[llvm] [InstCombine] Add optimization to combine adds through zext nneg, and add testcase (PR #157723)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Fri Sep 19 08:38:03 PDT 2025


================
@@ -1910,6 +1910,33 @@ Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
   if (Instruction *Res = foldBinOpOfSelectAndCastOfSelectCondition(I))
     return Res;
 
+  {
+    Value *X;
+    const APInt *C1, *C2;
+    if (match(&I, m_c_Add(m_NNegZExt(m_Add(m_Value(X), m_APInt(C1))),
+                          m_APInt(C2)))) {
+      // Check if inner constant C1 is negative C1 < 0 and outer constant C2 >=
+      // 0
+      if (!C1->isNegative() || C2->isNegative())
+        return nullptr;
+
+      APInt Sum = C1->sext(C2->getBitWidth()) + *C2;
+      APInt newSum = Sum.trunc(C1->getBitWidth());
+
+      if (newSum.sext(C2->getBitWidth()) != Sum)
+        return nullptr;
----------------
dtcxzyw wrote:

```suggestion
      if (!Sum.isSignedIntN(C1->getBitWidth()))
        return nullptr;
```


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


More information about the llvm-commits mailing list