[llvm] [InstCombine] Fold constant shift/mul into select arms for mul instruction (PR #196872)

Max Graey via llvm-commits llvm-commits at lists.llvm.org
Sun May 10 23:05:00 PDT 2026


================
@@ -331,6 +331,41 @@ Instruction *InstCombinerImpl::visitMul(BinaryOperator &I) {
   if (Value *FoldedMul = foldMulSelectToNegate(I, Builder))
     return replaceInstUsesWith(I, FoldedMul);
 
+  // (shl X, C1)*(select cond, C2, C3)--> X * (select cond, C2<<C1, C3<<C1)
+  // (mul X, C1)*(select cond, C2, C3)--> X * (select cond, C2*C1, C3*C1)
----------------
MaxGraey wrote:

You can easily add
```cpp
// (0 - X) * (select cond, C2, C3) -> X * (select cond, -C2, -C3)
// (fneg X) * (select cond, C2, C3) -> X * (select cond, -C2, -C3)
```
suboptimal: https://godbolt.org/z/WEo1PMf39
proofs: https://alive2.llvm.org/ce/z/47ZFVJ

Although this may be out of scope for this PR.

Another interesting observation: the order of the negated operands affects codegen, at least on x86. So this form more preferable for negated:

```llvm
  %mul = mul i32 %x, %sel.neg
```
instead of
```llvm
  %.neg = mul i32 %sel.neg, %x
```
This probably shouldn’t happen. Looks like a separate SelectionDAG PR.





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


More information about the llvm-commits mailing list