Skip to content

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

Add bitops optimization rules (#14234)

Zijian1bc38a14178e
diff --git a/cranelift/codegen/src/opts/bitops.isle b/cranelift/codegen/src/opts/bitops.isle
index 7c58bbadc0..4557c3748b 100644
--- a/cranelift/codegen/src/opts/bitops.isle
+++ b/cranelift/codegen/src/opts/bitops.isle
@@ -778,3 +778,9 @@
(rule (simplify (band ty (band ty x y) (band ty y z))) (band ty (band ty y x) z))
(rule (simplify (band ty (band ty x y) (band ty z x))) (band ty (band ty x y) z))
(rule (simplify (band ty (band ty x y) (band ty z y))) (band ty (band ty y x) z))
+
+;; popcnt(bswap(x)) == popcnt(x)
+(rule (simplify (popcnt ty (bswap ty x))) (popcnt ty x))
+
+;; popcnt(bitrev(x)) == popcnt(x)
+(rule (simplify (popcnt ty (bitrev ty x))) (popcnt ty x))
diff --git a/cranelift/codegen/src/opts/shifts.isle b/cranelift/codegen/src/opts/shifts.isle
index cbeef501c0..af5d44f0e9 100644
--- a/cranelift/codegen/src/opts/shifts.isle
+++ b/cranelift/codegen/src/opts/shifts.isle
@@ -311,6 +311,7 @@
(rotl ty x (iconst_u kty (u64_and k (ty_shift_mask ty)))))
(rule (simplify (band ty (ishl ty x z) (ishl ty y z))) (ishl ty (band ty x y) z))
+(rule (simplify (bor ty (ishl ty x z) (ishl ty y z))) (ishl ty (bor ty x y) z))
(rule (simplify (isub ty (ishl ty x z) (ishl ty y z))) (ishl ty (isub ty x y) z))
(rule (simplify (iadd ty (ishl ty x z) (ishl ty y z))) (ishl ty (iadd ty x y) z))
diff --git a/cranelift/filetests/filetests/egraph/bitops.clif b/cranelift/filetests/filetests/egraph/bitops.clif
index 54f53e2a7a..9403627424 100644
--- a/cranelift/filetests/filetests/egraph/bitops.clif
+++ b/cranelift/filetests/filetests/egraph/bitops.clif
@@ -1292,3 +1292,23 @@ block0(v0: i32, v1: i32):
; check: v5 = band v0, v4
; check: return v5
}
+
+;; popcnt(bswap(x)) -> popcnt(x)
+function %test_popcnt_bswap_i32(i32) -> i32 fast {
+block0(v0: i32):
+ v1 = bswap v0
+ v2 = popcnt v1
+ return v2
+ ; check: v3 = popcnt v0
+ ; check: return v3
+}
+
+;; popcnt(bitrev(x)) -> popcnt(x)
+function %test_popcnt_bitrev_i32(i32) -> i32 fast {
+block0(v0: i32):
+ v1 = bitrev v0
+ v2 = popcnt v1
+ return v2
+ ; check: v3 = popcnt v0
+ ; check: return v3
+}
diff --git a/cranelift/filetests/filetests/egraph/shifts.clif b/cranelift/filetests/filetests/egraph/shifts.clif
index 7f37f298d6..6667bc7f62 100644
--- a/cranelift/filetests/filetests/egraph/shifts.clif
+++ b/cranelift/filetests/filetests/egraph/shifts.clif
@@ -681,3 +681,15 @@ block0(v0: i32, v1: i32, v2: i32):
; check: v7 = band v1, v6
; check: return v7
}
+
+;; (x << z) | (y << z) -> (x | y) << z
+function %test_bor_ishl_ishl_i32(i32, i32, i32) -> i32 fast {
+block0(v0: i32, v1: i32, v2: i32):
+ v3 = ishl v0, v2
+ v4 = ishl v1, v2
+ v5 = bor v3, v4
+ return v5
+ ; check: v6 = bor v0, v1
+ ; check: v7 = ishl v6, v2
+ ; check: return v7
+}