[llvm] [SCEV] Try to prove no-wrap for AddRecs via BTC. (PR #131538)

Florian Hahn via llvm-commits llvm-commits at lists.llvm.org
Mon Jul 21 00:47:22 PDT 2025


================
@@ -5101,6 +5101,37 @@ ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
   return Result;
 }
 
+/// Return true if \p AR is known to not wrap via the loop's backedge-taken
+/// count.
+static SCEV::NoWrapFlags proveNoWrapViaBTC(const SCEVAddRecExpr *AR,
+                                           ScalarEvolution &SE) {
+  SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
+  if (AR->hasNoUnsignedWrap() && AR->hasNoSignedWrap())
+    return Result;
+
+  const Loop *L = AR->getLoop();
+  const SCEV *BTC = SE.getBackedgeTakenCount(L);
+  if (isa<SCEVCouldNotCompute>(BTC) ||
+      !match(AR->getStepRecurrence(SE), m_scev_One()))
+    return Result;
+
+  auto *WTy = SE.getWiderType(AR->getType(), BTC->getType());
+  // If AR's type is wider than BTC, we can zero extend BTC, otherwise bail out.
+  if (WTy != AR->getType())
+    return Result;
+
+  // AR has a step of 1, it is NUW/NSW if Start + BTC >= Start.
+  auto *Add = SE.getAddExpr(AR->getStart(), SE.getNoopOrZeroExtend(BTC, WTy));
----------------
fhahn wrote:

I left it as-is for now, in combination with a check that `Start + BTC` will not overflow (via `willNotOverflow`). For the more general `evaluateAtIteration`, I don't think we can easily check for overflow unfortunately. 

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


More information about the llvm-commits mailing list