[llvm] [InstCombine] Fold `X udiv Y` to `X lshr cttz(Y)` if Y is a power of 2 (PR #121386)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Thu Jan 9 08:14:27 PST 2025


================
@@ -1623,14 +1623,27 @@ Instruction *InstCombinerImpl::visitUDiv(BinaryOperator &I) {
     return Lshr;
   }
 
-  // Op1 udiv Op2 -> Op1 lshr log2(Op2), if log2() folds away.
-  if (takeLog2(Builder, Op1, /*Depth*/ 0, /*AssumeNonZero*/ true,
-               /*DoFold*/ false)) {
-    Value *Res = takeLog2(Builder, Op1, /*Depth*/ 0,
-                          /*AssumeNonZero*/ true, /*DoFold*/ true);
+  auto GetShiftableDenom = [&](Value *Denom) -> Value * {
+    // Op0 udiv Op1 -> Op0 lshr log2(Op1), if log2() folds away.
+    if (takeLog2(Builder, Denom, /*Depth=*/0, /*AssumeNonZero=*/true,
+                 /*DoFold=*/false))
+      return takeLog2(Builder, Denom, /*Depth=*/0, /*AssumeNonZero=*/true,
+                      /*DoFold=*/true);
+
+    // Op0 udiv Op1 -> Op0 lshr cttz(Op1), if Op1 is a power of 2.
+    if (isKnownToBeAPowerOfTwo(Denom, /*OrZero=*/true, /*Depth=*/0, &I))
+      // This will increase instruction count but it's okay
+      // since bitwise operations are substantially faster than
+      // division.
+      return Builder.CreateBinaryIntrinsic(Intrinsic::cttz, Denom,
+                                           Builder.getTrue());
+
+    return nullptr;
+  };
+
+  if (auto Res = GetShiftableDenom(Op1))
----------------
dtcxzyw wrote:

```suggestion
  if (auto *Res = GetShiftableDenom(Op1))
```

https://github.com/llvm/llvm-project/pull/121386


More information about the llvm-commits mailing list