[llvm] [ValueTracking] Fold max/min when incrementing/decrementing by 1 (PR #142466)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Tue Jun 3 08:06:40 PDT 2025


================
@@ -8388,6 +8388,31 @@ static SelectPatternResult matchMinMax(CmpInst::Predicate Pred,
     }
   }
 
+  // (X > Y) ? X : (Y - 1) ==> MIN(X, Y - 1)
+  // (X < Y) ? X : (Y + 1) ==> MAX(X, Y + 1)
+  // This transformation is valid when overflow corresponding to the sign of
+  // the comparison is poison and we must drop the non-matching overflow flag.
+  // Note: that the UMIN case is not possible as we canonicalize to addition.
+  if (CmpLHS == TrueVal) {
+    if (Pred == CmpInst::ICMP_SGT &&
+        match(FalseVal, m_NSWAddLike(m_Specific(CmpRHS), m_One()))) {
+      cast<Instruction>(FalseVal)->setHasNoUnsignedWrap(false);
----------------
nikic wrote:

You can't modify IR in ValueTracking. You'll have to add separate patterns for these in InstCombine. (Or add an out-argument indicating that the caller should clear flags, but I don't think that would be better in this case.)

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


More information about the llvm-commits mailing list