Skip to content

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

[Cranelift] `X * (1 << Y) --> X << Y` (#11522)

Bongjun Jangc5dcca75be44
diff --git a/cranelift/codegen/src/opts/arithmetic.isle b/cranelift/codegen/src/opts/arithmetic.isle
index 575dc2966a..d4aa06abae 100644
--- a/cranelift/codegen/src/opts/arithmetic.isle
+++ b/cranelift/codegen/src/opts/arithmetic.isle
@@ -328,3 +328,6 @@
;; (x + y) - (x | y) --> x & y
(rule (simplify (isub ty (iadd ty x y) (bor ty x y))) (band ty x y))
+
+;; x * (1 << y) == x << y
+(rule (simplify (imul ty x (ishl ty (iconst_s ty 1) y))) (ishl ty x y))
diff --git a/cranelift/filetests/filetests/egraph/arithmetic.clif b/cranelift/filetests/filetests/egraph/arithmetic.clif
index 7fdd27f982..e45a7e1b84 100644
--- a/cranelift/filetests/filetests/egraph/arithmetic.clif
+++ b/cranelift/filetests/filetests/egraph/arithmetic.clif
@@ -391,3 +391,15 @@ block0(v0: i32, v1: i32):
; check: v5 = band v0, v1
; check: return v5
}
+
+
+;; x * (1 << y) == x << y
+function %mul_shl(i32, i32) -> i32 {
+block0(v0: i32, v1: i32):
+ v2 = iconst.i32 1
+ v3 = ishl v2, v1
+ v4 = imul v0, v3
+ return v4
+ ; check: v5 = ishl v0, v1
+ ; check: return v5
+}
diff --git a/cranelift/filetests/filetests/runtests/arithmetic.clif b/cranelift/filetests/filetests/runtests/arithmetic.clif
index 3ef7d4628b..47e630c976 100644
--- a/cranelift/filetests/filetests/runtests/arithmetic.clif
+++ b/cranelift/filetests/filetests/runtests/arithmetic.clif
@@ -574,3 +574,17 @@ block0:
return v2
}
; run: %imul_big_constant() == 248153666
+
+
+;; x * (1 << y) should be optimized to x << y
+function %mul_one_shl(i32, i32) -> i32 {
+block0(v0: i32, v1: i32):
+ v2 = iconst.i32 1
+ v3 = ishl v2, v1
+ v4 = imul v0, v3
+ return v4
+}
+
+; run: %mul_one_shl(2, 3) == 16
+; run: %mul_one_shl(4, 5) == 128
+; run: %mul_one_shl(8, 6) == 512