[llvm] [SCEV] Fix scMulExpr cost for multiply by -1 and power-of-2 (PR #191033)

via llvm-commits llvm-commits at lists.llvm.org
Wed Apr 8 12:32:17 PDT 2026


================
@@ -2023,12 +2023,26 @@ template<typename T> static InstructionCost costAndCollectOperands(
   case scAddExpr:
     Cost = ArithCost(Instruction::Add, S->getNumOperands() - 1);
     break;
-  case scMulExpr:
-    // TODO: this is a very pessimistic cost modelling for Mul,
-    // because of Bin Pow algorithm actually used by the expander,
-    // see SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
-    Cost = ArithCost(Instruction::Mul, S->getNumOperands() - 1);
+  case scMulExpr: {
+    // Match the actual expansion in visitMulExpr: multiply by -1 is
+    // expanded as a negate (sub 0, x), and multiply by a power of 2 is
+    // expanded as a shift.  Only handle the common two-operand case with a
+    // constant LHS; for everything else fall back to the pessimistic
+    // all-multiplies estimate.
+    // TODO: this is still pessimistic for the general case because of the
+    // Bin Pow algorithm actually used by the expander, see
+    // SCEVExpander::visitMulExpr(), ExpandOpBinPowN().
+    unsigned MulOpc = Instruction::Mul;
+    if (S->getNumOperands() == 2)
----------------
carlobertolli wrote:

This is a bit limiting but fit to the purpose of this patch.
For the future, we could look at (-1 * a * b) where the number of operands is 3 but we can still replace the first mul with a sub (or neg)

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


More information about the llvm-commits mailing list