[llvm] [InstCombine] Optimize sub(sext(add(x, y)), sext(add(x, z))). (PR #144174)

Craig Topper via llvm-commits llvm-commits at lists.llvm.org
Fri Jun 13 18:03:36 PDT 2025


================
@@ -2807,6 +2807,62 @@ Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
   if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
     return Res;
 
+  // (sub[ nsw][ nuw] (sext (add nsw (X, Y)), sext (X))) --> (sext (Y))
+  {
+    Value *Add0;
+    if (match(Op0, m_SExt(m_Value(Add0))) &&
+        match(Add0, m_Add(m_Value(X), m_Value(Y))) &&
+        match(Op1, m_SExt(m_Specific(X)))) {
+      auto *OBO0 = cast<OverflowingBinaryOperator>(Add0);
+      if (OBO0->hasNoSignedWrap()) {
+        // Non-constant Y requires new SExt.
+        unsigned numOfNewInstrs = !isa<Constant>(Y) ? 1 : 0;
+        // Check if we can trade some of the old instructions for the new ones.
+        unsigned numOfDeadInstrs = 0;
+        numOfDeadInstrs += Op0->hasOneUse() ? 1 : 0;
+        numOfDeadInstrs += Op1->hasOneUse() ? 1 : 0;
+        numOfDeadInstrs += Add0->hasOneUse() ? 1 : 0;
+        if (numOfDeadInstrs >= numOfNewInstrs) {
+          Value *SExtY = Builder.CreateSExt(Y, I.getType());
+          return replaceInstUsesWith(I, SExtY);
+        }
+      }
+    }
+  }
+
+  // (sub[ nsw] (sext (add nsw (X, Y)), sext (add nsw (X, Z)))) -->
+  // --> (sub[ nsw] (sext (Y), sext(Z)))
+  {
+    Value *Z, *Add0, *Add1;
+    if (match(Op0, m_SExt(m_Value(Add0))) &&
+        match(Add0, m_Add(m_Value(X), m_Value(Y))) &&
----------------
topperc wrote:

m_NSWAdd?

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


More information about the llvm-commits mailing list