[llvm] [SCCP] Relax two-instruction range checks (PR #158495)

Andreas Jonson via llvm-commits llvm-commits at lists.llvm.org
Mon Sep 15 10:02:25 PDT 2025


================
@@ -284,6 +286,54 @@ static Value *simplifyInstruction(SCCPSolver &Solver,
     return Sub;
   }
 
+  // Relax range checks.
+  if (auto *ICmp = dyn_cast<ICmpInst>(&Inst)) {
+    Value *X;
+    auto MatchTwoInstructionExactRangeCheck =
+        [&]() -> std::optional<ConstantRange> {
+      const APInt *RHSC;
+      if (!match(ICmp->getOperand(1), m_APInt(RHSC)))
+        return std::nullopt;
+
+      Value *LHS = ICmp->getOperand(0);
+      ICmpInst::Predicate Pred = ICmp->getPredicate();
+      const APInt *Offset;
+      if (match(LHS, m_OneUse(m_AddLike(m_Value(X), m_APInt(Offset)))))
+        return ConstantRange::makeExactICmpRegion(Pred, *RHSC).sub(*Offset);
+      // Match icmp eq/ne X & NegPow2, C
+      if (ICmp->isEquality()) {
+        const APInt *Mask;
+        if (match(LHS, m_OneUse(m_And(m_Value(X), m_NegatedPower2(Mask)))) &&
+            RHSC->countr_zero() >= Mask->countr_zero()) {
+          ConstantRange CR(*RHSC, *RHSC - *Mask);
+          return Pred == ICmpInst::ICMP_EQ ? CR : CR.inverse();
+        }
+      }
+      return std::nullopt;
+    };
+
+    if (auto CR = MatchTwoInstructionExactRangeCheck()) {
+      ConstantRange LRange = GetRange(X);
+      if (LRange.isFullSet())
+        return nullptr;
+      auto NewCR = CR->exactUnionWith(LRange.inverse());
+      if (!NewCR)
----------------
andjo403 wrote:

do we also want to check the intersection with LRange as if there only is two values it is possible to have EQ/NE predicate instead? eg if relax_range_check had the argument range [0,4) instead of [0,5)

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


More information about the llvm-commits mailing list