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

Alex MacLean via llvm-commits llvm-commits at lists.llvm.org
Wed Jun 4 08:07:07 PDT 2025


================
@@ -564,6 +564,57 @@ Instruction *InstCombinerImpl::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
   return nullptr;
 }
 
+/// Try to fold a select to a min/max intrinsic. Many cases are already handled
+/// by matchDecomposedSelectPattern but here we handle the cases where more
+/// exensive modification of the IR is required.
+static Value *foldSelectICmpMinMax(const ICmpInst *Cmp, Value *TVal,
+                                   Value *FVal,
+                                   InstCombiner::BuilderTy &Builder,
+                                   const SimplifyQuery &SQ) {
+  const Value *CmpLHS = Cmp->getOperand(0);
+  const Value *CmpRHS = Cmp->getOperand(1);
+  ICmpInst::Predicate Pred = Cmp->getPredicate();
+
+  // (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.
+  if (CmpRHS == TVal) {
+    std::swap(CmpLHS, CmpRHS);
+    Pred = CmpInst::getSwappedPredicate(Pred);
+  }
+
+  if (CmpLHS == TVal) {
+    if (Pred == CmpInst::ICMP_SGT &&
+        match(FVal, m_NSWAddLike(m_Specific(CmpRHS), m_One()))) {
+      cast<Instruction>(FVal)->setHasNoUnsignedWrap(false);
----------------
AlexMaclean wrote:

@dtcxzyw Do you think it would be alright if I used `m_NSWAdd` instead of `m_NSWAddLike` to limit this transformation to adds for now? or should I handle disjoint ors by replacing them with an add instructions?

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


More information about the llvm-commits mailing list