Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

[Cranelift] fold bnot+iadd (#13201)

Bongjun Janga0dd8b3a6811
diff --git a/cranelift/codegen/src/opts/cprop.isle b/cranelift/codegen/src/opts/cprop.isle
index f40032dfbe..21533feb96 100644
--- a/cranelift/codegen/src/opts/cprop.isle
+++ b/cranelift/codegen/src/opts/cprop.isle
@@ -457,3 +457,8 @@
(decl ieee128_constant (Ieee128) Constant)
(extern constructor ieee128_constant ieee128_constant)
(extern extractor ieee128_constant ieee128_constant_extractor)
+
+;; a special case of ~a = -a - 1
+;; ~(x + y) = -(x + y) - 1 = (~x) - y = (~x) + (-y)
+;; bnot pushed to the leaf so that it not only canonicalzes the IR but also folds the constant y into -y
+(rule (simplify (bnot (fits_in_64 ty) (iadd ty x (iconst ty y)))) (iadd ty (bnot ty x) (iconst ty (imm64_neg ty y))))
diff --git a/cranelift/filetests/filetests/egraph/arithmetic.clif b/cranelift/filetests/filetests/egraph/arithmetic.clif
index b131428a6a..5e20ff39b4 100644
--- a/cranelift/filetests/filetests/egraph/arithmetic.clif
+++ b/cranelift/filetests/filetests/egraph/arithmetic.clif
@@ -439,3 +439,28 @@ block0(v0: i32):
; return v6
}
+;; ~(x + y) --> (~x) + (-y)
+function %bnot_iadd_const_i32(i32) -> i32 {
+block0(v0: i32):
+ v1 = iconst.i32 5
+ v2 = iadd v0, v1
+ v3 = bnot v2
+ return v3
+ ; check: v4 = bnot v0
+ ; check: v5 = iconst.i32 -5
+ ; check: v6 = iadd v4, v5
+ ; check: return v6
+}
+
+;; ~(x + y) --> (~x) + (-y)
+function %bnot_iadd_neg_const_i64(i64) -> i64 {
+block0(v0: i64):
+ v1 = iconst.i64 -7
+ v2 = iadd v0, v1
+ v3 = bnot v2
+ return v3
+ ; check: v4 = bnot v0
+ ; check: v5 = iconst.i64 7
+ ; check: v6 = iadd v4, v5
+ ; check: return v6
+}
diff --git a/cranelift/filetests/filetests/runtests/arithmetic.clif b/cranelift/filetests/filetests/runtests/arithmetic.clif
index f8a71620a1..95d734da23 100644
--- a/cranelift/filetests/filetests/runtests/arithmetic.clif
+++ b/cranelift/filetests/filetests/runtests/arithmetic.clif
@@ -1038,4 +1038,30 @@ block0(v0: i32, v1: i32):
}
; run: %test_ugt_x_umax(0, 0) == 0
-; run: %test_ugt_x_umax(1, 2) == 0
\ No newline at end of file
+; run: %test_ugt_x_umax(1, 2) == 0
+
+function %fold_bnot_iadd_const_i32_rt(i32) -> i32 fast {
+block0(v0: i32):
+ v1 = iconst.i32 5
+ v2 = iadd v0, v1
+ v3 = bnot v2
+ return v3
+}
+
+; run: %fold_bnot_iadd_const_i32_rt(0) == -6
+; run: %fold_bnot_iadd_const_i32_rt(7) == -13
+; run: %fold_bnot_iadd_const_i32_rt(-5) == -1
+; run: %fold_bnot_iadd_const_i32_rt(0x7fffffff) == 0x7ffffffb
+
+function %fold_bnot_iadd_neg_const_i64_rt(i64) -> i64 fast {
+block0(v0: i64):
+ v1 = iconst.i64 -7
+ v2 = iadd v0, v1
+ v3 = bnot v2
+ return v3
+}
+
+; run: %fold_bnot_iadd_neg_const_i64_rt(0) == 6
+; run: %fold_bnot_iadd_neg_const_i64_rt(7) == -1
+; run: %fold_bnot_iadd_neg_const_i64_rt(-1) == 7
+; run: %fold_bnot_iadd_neg_const_i64_rt(0x80000000_00000000) == 0x80000000_00000006