[llvm] [InstCombine] Fold mul (lshr exact (X, 2^N + 1)), N -> add (X , lshr (X, N)) (PR #95042)

via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 11 14:06:50 PDT 2024


================
@@ -255,6 +255,43 @@ Instruction *InstCombinerImpl::visitMul(BinaryOperator &I) {
     }
   }
 
+  {
+    // mul (lshr exact X, N), (2^N + 1) -> add (X , lshr (X, N))
+    Value *NewOp;
+    const APInt *ShiftC;
+    const APInt *MulAP;
+    if (match(&I, m_Mul(m_OneUse(m_CombineOr(
+                            m_LShr(m_Value(NewOp), m_APInt(ShiftC)),
+                            m_AShr(m_Value(NewOp), m_APInt(ShiftC)))),
+                        m_APInt(MulAP)))) {
+      if (BitWidth > 2 && (*MulAP - 1).isPowerOf2() &&
+          MulAP->logBase2() == ShiftC->getZExtValue()) {
+        BinaryOperator *OpBO = cast<BinaryOperator>(Op0);
+        if (OpBO->isExact()) {
+          Value *AddOp;
+          if (!HasNUW && !HasNUW)
+            AddOp = Builder.CreateFreeze(NewOp);
+          else
+            AddOp = NewOp;
+
+          Value *BinOp;
+          if (OpBO->getOpcode() == Instruction::LShr ||
+              (OpBO->getOpcode() == Instruction::AShr && HasNUW)) {
+            BinOp = Builder.CreateLShr(
+                AddOp, ConstantInt::get(Ty, ShiftC->getZExtValue()), "", true);
+          } else {
+            BinOp = Builder.CreateAShr(
+                AddOp, ConstantInt::get(Ty, ShiftC->getZExtValue()), "", true);
----------------
goldsteinn wrote:

comment the `true`.

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


More information about the llvm-commits mailing list