[llvm] [DAGCombiner] Fix the "subtraction if above a constant threshold" transform (PR #140042)

Simon Pilgrim via llvm-commits llvm-commits at lists.llvm.org
Thu May 15 05:03:32 PDT 2025


================
@@ -12136,15 +12136,19 @@ SDValue DAGCombiner::visitSELECT(SDNode *N) {
     if (SDValue NewSel = SimplifySelect(DL, N0, N1, N2))
       return NewSel;
 
-    // (select (ugt x, C), (add x, ~C), x) -> (umin (add x, ~C), x)
+    // (select (ugt x, C), (add x, ~C), x) -> (umin x, (add x, ~C))
     // (select (ult x, C), x, (add x, -C)) -> (umin x, (add x, -C))
     APInt C;
     if (sd_match(Cond1, m_ConstInt(C)) && hasUMin(VT)) {
+      APInt AddC;
       if ((CC == ISD::SETUGT && Cond0 == N2 &&
-           sd_match(N1, m_Add(m_Specific(N2), m_SpecificInt(~C)))) ||
+           sd_match(N1, m_Add(m_Specific(N2), m_ConstInt(AddC))) &&
+           AddC == ~C) ||
           (CC == ISD::SETULT && Cond0 == N1 &&
-           sd_match(N2, m_Add(m_Specific(N1), m_SpecificInt(-C)))))
-        return DAG.getNode(ISD::UMIN, DL, VT, N1, N2);
+           sd_match(N2, m_Add(m_Specific(N1), m_ConstInt(AddC))) && AddC == -C))
+        return DAG.getNode(ISD::UMIN, DL, VT, Cond0,
+                           DAG.getNode(ISD::ADD, DL, VT, Cond0,
+                                       DAG.getConstant(AddC, DL, VT)));
----------------
RKSimon wrote:

It might be cleaner just to split these and then do:
```
if (CC == ISD::SETULT && Cond0 == N1 &&
    sd_match(N2, m_Add(m_Specific(N1), m_SpecificInt(-C))))
 return DAG.getNode(ISD::UMIN, DL, VT, Cond0, DAG.getNode(ISD::ADD, DL, VT, Cond0,
                                    DAG.getConstant(-C, DL, VT)));
```
etc.

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


More information about the llvm-commits mailing list