Skip to content

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

cranelift: bitops folding added (#12715)

Hyunbin Kimdfc36b61915f
diff --git a/cranelift/codegen/src/opts/bitops.isle b/cranelift/codegen/src/opts/bitops.isle
index df947c9205..ee8af0f4ac 100644
--- a/cranelift/codegen/src/opts/bitops.isle
+++ b/cranelift/codegen/src/opts/bitops.isle
@@ -235,3 +235,15 @@
(rule (simplify (bor ty (bnot ty (bxor ty x y)) (band ty y x))) (bnot ty (bxor ty x y)))
(rule (simplify (bor ty (band ty y x) (bnot ty (bxor ty y x)))) (bnot ty (bxor ty x y)))
(rule (simplify (bor ty (bnot ty (bxor ty y x)) (band ty y x))) (bnot ty (bxor ty x y)))
+
+; (x | y) + (-y) --> x & ~y
+(rule (simplify (iadd ty (bor ty x y) (ineg ty y)))
+ (band ty x (bnot ty y)))
+(rule (simplify (iadd ty (ineg ty y) (bor ty x y)))
+ (band ty x (bnot ty y)))
+(rule (simplify (iadd ty (bor ty y x) (ineg ty y)))
+ (band ty x (bnot ty y)))
+(rule (simplify (iadd ty (ineg ty y) (bor ty y x)))
+ (band ty x (bnot ty y)))
+
+
diff --git a/cranelift/filetests/filetests/egraph/fold-bitops.clif b/cranelift/filetests/filetests/egraph/fold-bitops.clif
index 3784c01f90..4c4a9e14ab 100644
--- a/cranelift/filetests/filetests/egraph/fold-bitops.clif
+++ b/cranelift/filetests/filetests/egraph/fold-bitops.clif
@@ -89,4 +89,21 @@ block0(v0: i32, v1: i32):
; v6 = bxor v1, v0
; v7 = bnot v6
; return v7
-; }
\ No newline at end of file
+; }
+
+;; (iadd ty (bor ty x y) (ineg ty y)) -> (band ty x (bnot ty y))
+function %test_iadd_bor_ineg(i32, i32) -> i32 fast {
+block0(v0: i32, v1: i32):
+ v2 = bor v0, v1
+ v3 = ineg v1
+ v4 = iadd v2, v3
+ return v4
+}
+
+; function %test_iadd_bor_ineg(i32, i32) -> i32 fast {
+; block0(v0: i32, v1: i32):
+; v2 = bor v0, v1
+; v7 = isub v2, v1
+; return v7
+; }
+
diff --git a/cranelift/filetests/filetests/runtests/bitops.clif b/cranelift/filetests/filetests/runtests/bitops.clif
index 473bf81a6b..b79dc40ada 100644
--- a/cranelift/filetests/filetests/runtests/bitops.clif
+++ b/cranelift/filetests/filetests/runtests/bitops.clif
@@ -244,4 +244,17 @@ block0(v0: i32, v1: i32):
; run: %test_bor_band_bnot_bxor(0, 0) == 0xffffffff
; run: %test_bor_band_bnot_bxor(1, 1) == 0xffffffff
; run: %test_bor_band_bnot_bxor(0, 1) == 0xfffffffe
-; run: %test_bor_band_bnot_bxor(2, 1) == 0xfffffffc
\ No newline at end of file
+; run: %test_bor_band_bnot_bxor(2, 1) == 0xfffffffc
+
+function %test_iadd_bor_ineg(i32, i32) -> i32 fast {
+block0(v0: i32, v1: i32):
+ v2 = bor v0, v1
+ v3 = ineg v1
+ v4 = iadd v2, v3
+ return v4
+}
+
+; run: %test_iadd_bor_ineg(0, 0) == 0
+; run: %test_iadd_bor_ineg(1, 1) == 0
+; run: %test_iadd_bor_ineg(2, 1) == 2
+; run: %test_iadd_bor_ineg(0xffffffff, 0) == -1
\ No newline at end of file