Skip to content

Conversation

fhahn
Copy link
Contributor

@fhahn fhahn commented Aug 27, 2025

Remove the fall-back to constant max BTC if the backedge-taken-count cannot be computed.

The constant max backedge-taken count is computed considering loop guards, so to avoid regressions we need to apply loop guards as needed.

Also remove the special handling for Mul in willNotOverflow, as this should not longer be needed after 9143746
(#155300).

@fhahn fhahn requested a review from annamthomas August 27, 2025 18:16
@fhahn fhahn requested a review from nikic as a code owner August 27, 2025 18:16
@llvmbot llvmbot added llvm:analysis Includes value tracking, cost tables and constant folding llvm:transforms labels Aug 27, 2025
@llvmbot
Copy link
Member

llvmbot commented Aug 27, 2025

@llvm/pr-subscribers-llvm-analysis

Author: Florian Hahn (fhahn)

Changes

Remove the fall-back to constant max BTC if the backedge-taken-count cannot be computed.

The constant max backedge-taken count is computed considering loop guards, so to avoid regressions we need to apply loop guards as needed.

Also remove the special handling for Mul in willNotOverflow, as this should not longer be needed after 9143746
(#155300).


Full diff: https://github.com/llvm/llvm-project/pull/155672.diff

5 Files Affected:

  • (modified) llvm/include/llvm/Analysis/LoopAccessAnalysis.h (+16-6)
  • (modified) llvm/lib/Analysis/Loads.cpp (+11-17)
  • (modified) llvm/lib/Analysis/LoopAccessAnalysis.cpp (+39-27)
  • (modified) llvm/lib/Analysis/ScalarEvolution.cpp (+3-11)
  • (modified) llvm/test/Transforms/LoopVectorize/vect.stats.ll (+1-1)
diff --git a/llvm/include/llvm/Analysis/LoopAccessAnalysis.h b/llvm/include/llvm/Analysis/LoopAccessAnalysis.h
index 92304edd67a44..52ab38583d5de 100644
--- a/llvm/include/llvm/Analysis/LoopAccessAnalysis.h
+++ b/llvm/include/llvm/Analysis/LoopAccessAnalysis.h
@@ -183,10 +183,12 @@ class MemoryDepChecker {
   MemoryDepChecker(PredicatedScalarEvolution &PSE, AssumptionCache *AC,
                    DominatorTree *DT, const Loop *L,
                    const DenseMap<Value *, const SCEV *> &SymbolicStrides,
-                   unsigned MaxTargetVectorWidthInBits)
+                   unsigned MaxTargetVectorWidthInBits,
+                   std::optional<ScalarEvolution::LoopGuards> &LoopGuards)
       : PSE(PSE), AC(AC), DT(DT), InnermostLoop(L),
         SymbolicStrides(SymbolicStrides),
-        MaxTargetVectorWidthInBits(MaxTargetVectorWidthInBits) {}
+        MaxTargetVectorWidthInBits(MaxTargetVectorWidthInBits),
+        LoopGuards(LoopGuards) {}
 
   /// Register the location (instructions are given increasing numbers)
   /// of a write access.
@@ -373,7 +375,7 @@ class MemoryDepChecker {
       PointerBounds;
 
   /// Cache for the loop guards of InnermostLoop.
-  std::optional<ScalarEvolution::LoopGuards> LoopGuards;
+  std::optional<ScalarEvolution::LoopGuards> &LoopGuards;
 
   /// Check whether there is a plausible dependence between the two
   /// accesses.
@@ -531,8 +533,9 @@ class RuntimePointerChecking {
           AliasSetId(AliasSetId), Expr(Expr), NeedsFreeze(NeedsFreeze) {}
   };
 
-  RuntimePointerChecking(MemoryDepChecker &DC, ScalarEvolution *SE)
-      : DC(DC), SE(SE) {}
+  RuntimePointerChecking(MemoryDepChecker &DC, ScalarEvolution *SE,
+                         std::optional<ScalarEvolution::LoopGuards> &LoopGuards)
+      : DC(DC), SE(SE), LoopGuards(LoopGuards) {}
 
   /// Reset the state of the pointer runtime information.
   void reset() {
@@ -646,6 +649,9 @@ class RuntimePointerChecking {
   /// Holds a pointer to the ScalarEvolution analysis.
   ScalarEvolution *SE;
 
+  /// Cache for the loop guards of the loop.
+  std::optional<ScalarEvolution::LoopGuards> &LoopGuards;
+
   /// Set of run-time checks required to establish independence of
   /// otherwise may-aliasing pointers in the loop.
   SmallVector<RuntimePointerCheck, 4> Checks;
@@ -821,6 +827,9 @@ class LoopAccessInfo {
 
   Loop *TheLoop;
 
+  /// Cache for the loop guards of TheLoop.
+  std::optional<ScalarEvolution::LoopGuards> LoopGuards;
+
   /// Determines whether we should generate partial runtime checks when not all
   /// memory accesses could be analyzed.
   bool AllowPartial;
@@ -938,7 +947,8 @@ LLVM_ABI std::pair<const SCEV *, const SCEV *> getStartAndEndForAccess(
     const SCEV *MaxBTC, ScalarEvolution *SE,
     DenseMap<std::pair<const SCEV *, Type *>,
              std::pair<const SCEV *, const SCEV *>> *PointerBounds,
-    DominatorTree *DT, AssumptionCache *AC);
+    DominatorTree *DT, AssumptionCache *AC,
+    std::optional<ScalarEvolution::LoopGuards> &LoopGuards);
 
 class LoopAccessInfoManager {
   /// The cache.
diff --git a/llvm/lib/Analysis/Loads.cpp b/llvm/lib/Analysis/Loads.cpp
index 7a8fbbd0fb919..0a68069374c64 100644
--- a/llvm/lib/Analysis/Loads.cpp
+++ b/llvm/lib/Analysis/Loads.cpp
@@ -26,10 +26,6 @@
 
 using namespace llvm;
 
-static cl::opt<bool>
-    UseSymbolicMaxBTCForDerefInLoop("use-symbolic-maxbtc-deref-loop",
-                                    cl::init(false));
-
 static bool isAligned(const Value *Base, Align Alignment,
                       const DataLayout &DL) {
   return Base->getPointerAlignment(DL) >= Alignment;
@@ -335,18 +331,10 @@ bool llvm::isDereferenceableAndAlignedInLoop(
                             : SE.getBackedgeTakenCount(L);
   if (isa<SCEVCouldNotCompute>(MaxBECount))
     return false;
-
-  if (isa<SCEVCouldNotCompute>(BECount) && !UseSymbolicMaxBTCForDerefInLoop) {
-    // TODO: Support symbolic max backedge taken counts for loops without
-    // computable backedge taken counts.
-    MaxBECount =
-        Predicates
-            ? SE.getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
-            : SE.getConstantMaxBackedgeTakenCount(L);
-  }
-
-  const auto &[AccessStart, AccessEnd] = getStartAndEndForAccess(
-      L, PtrScev, LI->getType(), BECount, MaxBECount, &SE, nullptr, &DT, AC);
+  std::optional<ScalarEvolution::LoopGuards> LoopGuards;
+  const auto &[AccessStart, AccessEnd] =
+      getStartAndEndForAccess(L, PtrScev, LI->getType(), BECount, MaxBECount,
+                              &SE, nullptr, &DT, AC, LoopGuards);
   if (isa<SCEVCouldNotCompute>(AccessStart) ||
       isa<SCEVCouldNotCompute>(AccessEnd))
     return false;
@@ -355,7 +343,13 @@ bool llvm::isDereferenceableAndAlignedInLoop(
   const SCEV *PtrDiff = SE.getMinusSCEV(AccessEnd, AccessStart);
   if (isa<SCEVCouldNotCompute>(PtrDiff))
     return false;
-  APInt MaxPtrDiff = SE.getUnsignedRangeMax(PtrDiff);
+
+  if (!LoopGuards)
+    LoopGuards.emplace(
+        ScalarEvolution::LoopGuards::collect(AddRec->getLoop(), SE));
+
+  APInt MaxPtrDiff =
+      SE.getUnsignedRangeMax(SE.applyLoopGuards(PtrDiff, *LoopGuards));
 
   Value *Base = nullptr;
   APInt AccessSize;
diff --git a/llvm/lib/Analysis/LoopAccessAnalysis.cpp b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
index 258fa982ed1d0..7b2f797311a62 100644
--- a/llvm/lib/Analysis/LoopAccessAnalysis.cpp
+++ b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
@@ -193,9 +193,8 @@ RuntimeCheckingPtrGroup::RuntimeCheckingPtrGroup(
 /// Returns \p A + \p B, if it is guaranteed not to unsigned wrap. Otherwise
 /// return nullptr. \p A and \p B must have the same type.
 static const SCEV *addSCEVNoOverflow(const SCEV *A, const SCEV *B,
-                                     ScalarEvolution &SE,
-                                     const Instruction *CtxI) {
-  if (!SE.willNotOverflow(Instruction::Add, /*IsSigned=*/false, A, B, CtxI))
+                                     ScalarEvolution &SE) {
+  if (!SE.willNotOverflow(Instruction::Add, /*IsSigned=*/false, A, B))
     return nullptr;
   return SE.getAddExpr(A, B);
 }
@@ -203,20 +202,19 @@ static const SCEV *addSCEVNoOverflow(const SCEV *A, const SCEV *B,
 /// Returns \p A * \p B, if it is guaranteed not to unsigned wrap. Otherwise
 /// return nullptr. \p A and \p B must have the same type.
 static const SCEV *mulSCEVOverflow(const SCEV *A, const SCEV *B,
-                                   ScalarEvolution &SE,
-                                   const Instruction *CtxI) {
-  if (!SE.willNotOverflow(Instruction::Mul, /*IsSigned=*/false, A, B, CtxI))
+                                   ScalarEvolution &SE) {
+  if (!SE.willNotOverflow(Instruction::Mul, /*IsSigned=*/false, A, B))
     return nullptr;
   return SE.getMulExpr(A, B);
 }
 
 /// Return true, if evaluating \p AR at \p MaxBTC cannot wrap, because \p AR at
 /// \p MaxBTC is guaranteed inbounds of the accessed object.
-static bool
-evaluatePtrAddRecAtMaxBTCWillNotWrap(const SCEVAddRecExpr *AR,
-                                     const SCEV *MaxBTC, const SCEV *EltSize,
-                                     ScalarEvolution &SE, const DataLayout &DL,
-                                     DominatorTree *DT, AssumptionCache *AC) {
+static bool evaluatePtrAddRecAtMaxBTCWillNotWrap(
+    const SCEVAddRecExpr *AR, const SCEV *MaxBTC, const SCEV *EltSize,
+    ScalarEvolution &SE, const DataLayout &DL, DominatorTree *DT,
+    AssumptionCache *AC,
+    std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
   auto *PointerBase = SE.getPointerBase(AR->getStart());
   auto *StartPtr = dyn_cast<SCEVUnknown>(PointerBase);
   if (!StartPtr)
@@ -234,12 +232,11 @@ evaluatePtrAddRecAtMaxBTCWillNotWrap(const SCEVAddRecExpr *AR,
   Type *WiderTy = SE.getWiderType(MaxBTC->getType(), Step->getType());
   const SCEV *DerefBytesSCEV = SE.getConstant(WiderTy, DerefBytes);
 
-  // Context which dominates the entire loop.
-  auto *CtxI = L->getLoopPredecessor()->getTerminator();
   // Check if we have a suitable dereferencable assumption we can use.
   if (!StartPtrV->canBeFreed()) {
     RetainedKnowledge DerefRK = getKnowledgeValidInContext(
-        StartPtrV, {Attribute::Dereferenceable}, *AC, CtxI, DT);
+        StartPtrV, {Attribute::Dereferenceable}, *AC,
+        L->getLoopPredecessor()->getTerminator(), DT);
     if (DerefRK) {
       DerefBytesSCEV = SE.getUMaxExpr(
           DerefBytesSCEV, SE.getConstant(WiderTy, DerefRK.ArgValue));
@@ -263,12 +260,20 @@ evaluatePtrAddRecAtMaxBTCWillNotWrap(const SCEVAddRecExpr *AR,
       SE.getMinusSCEV(AR->getStart(), StartPtr), WiderTy);
 
   const SCEV *OffsetAtLastIter =
-      mulSCEVOverflow(MaxBTC, SE.getAbsExpr(Step, /*IsNSW=*/false), SE, CtxI);
-  if (!OffsetAtLastIter)
-    return false;
+      mulSCEVOverflow(MaxBTC, SE.getAbsExpr(Step, /*IsNSW=*/false), SE);
+  if (!OffsetAtLastIter) {
+    // Re-try with constant max backedge-taken count if using the symbolic one
+    // failed.
+    MaxBTC = SE.getNoopOrZeroExtend(
+        SE.getConstantMaxBackedgeTakenCount(AR->getLoop()), WiderTy);
+    OffsetAtLastIter =
+        mulSCEVOverflow(MaxBTC, SE.getAbsExpr(Step, /*IsNSW=*/false), SE);
+    if (!OffsetAtLastIter)
+      return false;
+  }
 
   const SCEV *OffsetEndBytes = addSCEVNoOverflow(
-      OffsetAtLastIter, SE.getNoopOrZeroExtend(EltSize, WiderTy), SE, CtxI);
+      OffsetAtLastIter, SE.getNoopOrZeroExtend(EltSize, WiderTy), SE);
   if (!OffsetEndBytes)
     return false;
 
@@ -276,10 +281,15 @@ evaluatePtrAddRecAtMaxBTCWillNotWrap(const SCEVAddRecExpr *AR,
     // For positive steps, check if
     //  (AR->getStart() - StartPtr) + (MaxBTC  * Step) + EltSize <= DerefBytes,
     // while making sure none of the computations unsigned wrap themselves.
-    const SCEV *EndBytes =
-        addSCEVNoOverflow(StartOffset, OffsetEndBytes, SE, CtxI);
+    const SCEV *EndBytes = addSCEVNoOverflow(StartOffset, OffsetEndBytes, SE);
     if (!EndBytes)
       return false;
+
+    if (!LoopGuards)
+      LoopGuards.emplace(
+          ScalarEvolution::LoopGuards::collect(AR->getLoop(), SE));
+
+    EndBytes = SE.applyLoopGuards(EndBytes, *LoopGuards);
     return SE.isKnownPredicate(CmpInst::ICMP_ULE, EndBytes, DerefBytesSCEV);
   }
 
@@ -296,7 +306,8 @@ std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
     const SCEV *MaxBTC, ScalarEvolution *SE,
     DenseMap<std::pair<const SCEV *, Type *>,
              std::pair<const SCEV *, const SCEV *>> *PointerBounds,
-    DominatorTree *DT, AssumptionCache *AC) {
+    DominatorTree *DT, AssumptionCache *AC,
+    std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
   std::pair<const SCEV *, const SCEV *> *PtrBoundsPair;
   if (PointerBounds) {
     auto [Iter, Ins] = PointerBounds->insert(
@@ -332,7 +343,7 @@ std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
       // separately checks that accesses cannot not wrap, so unsigned max
       // represents an upper bound.
       if (evaluatePtrAddRecAtMaxBTCWillNotWrap(AR, MaxBTC, EltSizeSCEV, *SE, DL,
-                                               DT, AC)) {
+                                               DT, AC, LoopGuards)) {
         ScEnd = AR->evaluateAtIteration(MaxBTC, *SE);
       } else {
         ScEnd = SE->getAddExpr(
@@ -381,7 +392,7 @@ void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
   const SCEV *BTC = PSE.getBackedgeTakenCount();
   const auto &[ScStart, ScEnd] = getStartAndEndForAccess(
       Lp, PtrExpr, AccessTy, BTC, SymbolicMaxBTC, PSE.getSE(),
-      &DC.getPointerBounds(), DC.getDT(), DC.getAC());
+      &DC.getPointerBounds(), DC.getDT(), DC.getAC(), LoopGuards);
   assert(!isa<SCEVCouldNotCompute>(ScStart) &&
          !isa<SCEVCouldNotCompute>(ScEnd) &&
          "must be able to compute both start and end expressions");
@@ -1987,13 +1998,13 @@ bool MemoryDepChecker::areAccessesCompletelyBeforeOrAfter(const SCEV *Src,
   ScalarEvolution &SE = *PSE.getSE();
   const auto &[SrcStart_, SrcEnd_] =
       getStartAndEndForAccess(InnermostLoop, Src, SrcTy, BTC, SymbolicMaxBTC,
-                              &SE, &PointerBounds, DT, AC);
+                              &SE, &PointerBounds, DT, AC, LoopGuards);
   if (isa<SCEVCouldNotCompute>(SrcStart_) || isa<SCEVCouldNotCompute>(SrcEnd_))
     return false;
 
   const auto &[SinkStart_, SinkEnd_] =
       getStartAndEndForAccess(InnermostLoop, Sink, SinkTy, BTC, SymbolicMaxBTC,
-                              &SE, &PointerBounds, DT, AC);
+                              &SE, &PointerBounds, DT, AC, LoopGuards);
   if (isa<SCEVCouldNotCompute>(SinkStart_) ||
       isa<SCEVCouldNotCompute>(SinkEnd_))
     return false;
@@ -3040,8 +3051,9 @@ LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
         TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) * 2;
 
   DepChecker = std::make_unique<MemoryDepChecker>(
-      *PSE, AC, DT, L, SymbolicStrides, MaxTargetVectorWidthInBits);
-  PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE);
+      *PSE, AC, DT, L, SymbolicStrides, MaxTargetVectorWidthInBits, LoopGuards);
+  PtrRtChecking =
+      std::make_unique<RuntimePointerChecking>(*DepChecker, SE, LoopGuards);
   if (canAnalyzeLoop())
     CanVecMem = analyzeLoop(AA, LI, TLI, DT);
 }
diff --git a/llvm/lib/Analysis/ScalarEvolution.cpp b/llvm/lib/Analysis/ScalarEvolution.cpp
index aa2bcf7917537..e5e4dcfce3bd4 100644
--- a/llvm/lib/Analysis/ScalarEvolution.cpp
+++ b/llvm/lib/Analysis/ScalarEvolution.cpp
@@ -2338,23 +2338,15 @@ bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
   // Can we use context to prove the fact we need?
   if (!CtxI)
     return false;
+  // TODO: Support mul.
+  if (BinOp == Instruction::Mul)
+    return false;
   auto *RHSC = dyn_cast<SCEVConstant>(RHS);
   // TODO: Lift this limitation.
   if (!RHSC)
     return false;
   APInt C = RHSC->getAPInt();
   unsigned NumBits = C.getBitWidth();
-  if (BinOp == Instruction::Mul) {
-    // Multiplying by 0 or 1 never overflows
-    if (C.isZero() || C.isOne())
-      return true;
-    if (Signed)
-      return false;
-    APInt Limit = APInt::getMaxValue(NumBits).udiv(C);
-    // To avoid overflow, we need to make sure that LHS <= MAX / C.
-    return isKnownPredicateAt(ICmpInst::ICMP_ULE, LHS, getConstant(Limit),
-                              CtxI);
-  }
   bool IsSub = (BinOp == Instruction::Sub);
   bool IsNegativeConst = (Signed && C.isNegative());
   // Compute the direction and magnitude by which we need to check overflow.
diff --git a/llvm/test/Transforms/LoopVectorize/vect.stats.ll b/llvm/test/Transforms/LoopVectorize/vect.stats.ll
index f3695e6712952..e3240c8181519 100644
--- a/llvm/test/Transforms/LoopVectorize/vect.stats.ll
+++ b/llvm/test/Transforms/LoopVectorize/vect.stats.ll
@@ -1,4 +1,4 @@
-; RUN: opt < %s -passes=loop-vectorize -force-vector-interleave=4 -force-vector-width=4 -debug-only=loop-vectorize -enable-early-exit-vectorization -use-symbolic-maxbtc-deref-loop --disable-output -stats -S 2>&1 | FileCheck %s
+; RUN: opt < %s -passes=loop-vectorize -force-vector-interleave=4 -force-vector-width=4 -debug-only=loop-vectorize -enable-early-exit-vectorization --disable-output -stats -S 2>&1 | FileCheck %s
 ; REQUIRES: asserts
 
 ; We have 3 loops, two of them are vectorizable (with one being early-exit

@llvmbot
Copy link
Member

llvmbot commented Aug 27, 2025

@llvm/pr-subscribers-llvm-transforms

Author: Florian Hahn (fhahn)

Changes

Remove the fall-back to constant max BTC if the backedge-taken-count cannot be computed.

The constant max backedge-taken count is computed considering loop guards, so to avoid regressions we need to apply loop guards as needed.

Also remove the special handling for Mul in willNotOverflow, as this should not longer be needed after 9143746
(#155300).


Full diff: https://github.com/llvm/llvm-project/pull/155672.diff

5 Files Affected:

  • (modified) llvm/include/llvm/Analysis/LoopAccessAnalysis.h (+16-6)
  • (modified) llvm/lib/Analysis/Loads.cpp (+11-17)
  • (modified) llvm/lib/Analysis/LoopAccessAnalysis.cpp (+39-27)
  • (modified) llvm/lib/Analysis/ScalarEvolution.cpp (+3-11)
  • (modified) llvm/test/Transforms/LoopVectorize/vect.stats.ll (+1-1)
diff --git a/llvm/include/llvm/Analysis/LoopAccessAnalysis.h b/llvm/include/llvm/Analysis/LoopAccessAnalysis.h
index 92304edd67a44..52ab38583d5de 100644
--- a/llvm/include/llvm/Analysis/LoopAccessAnalysis.h
+++ b/llvm/include/llvm/Analysis/LoopAccessAnalysis.h
@@ -183,10 +183,12 @@ class MemoryDepChecker {
   MemoryDepChecker(PredicatedScalarEvolution &PSE, AssumptionCache *AC,
                    DominatorTree *DT, const Loop *L,
                    const DenseMap<Value *, const SCEV *> &SymbolicStrides,
-                   unsigned MaxTargetVectorWidthInBits)
+                   unsigned MaxTargetVectorWidthInBits,
+                   std::optional<ScalarEvolution::LoopGuards> &LoopGuards)
       : PSE(PSE), AC(AC), DT(DT), InnermostLoop(L),
         SymbolicStrides(SymbolicStrides),
-        MaxTargetVectorWidthInBits(MaxTargetVectorWidthInBits) {}
+        MaxTargetVectorWidthInBits(MaxTargetVectorWidthInBits),
+        LoopGuards(LoopGuards) {}
 
   /// Register the location (instructions are given increasing numbers)
   /// of a write access.
@@ -373,7 +375,7 @@ class MemoryDepChecker {
       PointerBounds;
 
   /// Cache for the loop guards of InnermostLoop.
-  std::optional<ScalarEvolution::LoopGuards> LoopGuards;
+  std::optional<ScalarEvolution::LoopGuards> &LoopGuards;
 
   /// Check whether there is a plausible dependence between the two
   /// accesses.
@@ -531,8 +533,9 @@ class RuntimePointerChecking {
           AliasSetId(AliasSetId), Expr(Expr), NeedsFreeze(NeedsFreeze) {}
   };
 
-  RuntimePointerChecking(MemoryDepChecker &DC, ScalarEvolution *SE)
-      : DC(DC), SE(SE) {}
+  RuntimePointerChecking(MemoryDepChecker &DC, ScalarEvolution *SE,
+                         std::optional<ScalarEvolution::LoopGuards> &LoopGuards)
+      : DC(DC), SE(SE), LoopGuards(LoopGuards) {}
 
   /// Reset the state of the pointer runtime information.
   void reset() {
@@ -646,6 +649,9 @@ class RuntimePointerChecking {
   /// Holds a pointer to the ScalarEvolution analysis.
   ScalarEvolution *SE;
 
+  /// Cache for the loop guards of the loop.
+  std::optional<ScalarEvolution::LoopGuards> &LoopGuards;
+
   /// Set of run-time checks required to establish independence of
   /// otherwise may-aliasing pointers in the loop.
   SmallVector<RuntimePointerCheck, 4> Checks;
@@ -821,6 +827,9 @@ class LoopAccessInfo {
 
   Loop *TheLoop;
 
+  /// Cache for the loop guards of TheLoop.
+  std::optional<ScalarEvolution::LoopGuards> LoopGuards;
+
   /// Determines whether we should generate partial runtime checks when not all
   /// memory accesses could be analyzed.
   bool AllowPartial;
@@ -938,7 +947,8 @@ LLVM_ABI std::pair<const SCEV *, const SCEV *> getStartAndEndForAccess(
     const SCEV *MaxBTC, ScalarEvolution *SE,
     DenseMap<std::pair<const SCEV *, Type *>,
              std::pair<const SCEV *, const SCEV *>> *PointerBounds,
-    DominatorTree *DT, AssumptionCache *AC);
+    DominatorTree *DT, AssumptionCache *AC,
+    std::optional<ScalarEvolution::LoopGuards> &LoopGuards);
 
 class LoopAccessInfoManager {
   /// The cache.
diff --git a/llvm/lib/Analysis/Loads.cpp b/llvm/lib/Analysis/Loads.cpp
index 7a8fbbd0fb919..0a68069374c64 100644
--- a/llvm/lib/Analysis/Loads.cpp
+++ b/llvm/lib/Analysis/Loads.cpp
@@ -26,10 +26,6 @@
 
 using namespace llvm;
 
-static cl::opt<bool>
-    UseSymbolicMaxBTCForDerefInLoop("use-symbolic-maxbtc-deref-loop",
-                                    cl::init(false));
-
 static bool isAligned(const Value *Base, Align Alignment,
                       const DataLayout &DL) {
   return Base->getPointerAlignment(DL) >= Alignment;
@@ -335,18 +331,10 @@ bool llvm::isDereferenceableAndAlignedInLoop(
                             : SE.getBackedgeTakenCount(L);
   if (isa<SCEVCouldNotCompute>(MaxBECount))
     return false;
-
-  if (isa<SCEVCouldNotCompute>(BECount) && !UseSymbolicMaxBTCForDerefInLoop) {
-    // TODO: Support symbolic max backedge taken counts for loops without
-    // computable backedge taken counts.
-    MaxBECount =
-        Predicates
-            ? SE.getPredicatedConstantMaxBackedgeTakenCount(L, *Predicates)
-            : SE.getConstantMaxBackedgeTakenCount(L);
-  }
-
-  const auto &[AccessStart, AccessEnd] = getStartAndEndForAccess(
-      L, PtrScev, LI->getType(), BECount, MaxBECount, &SE, nullptr, &DT, AC);
+  std::optional<ScalarEvolution::LoopGuards> LoopGuards;
+  const auto &[AccessStart, AccessEnd] =
+      getStartAndEndForAccess(L, PtrScev, LI->getType(), BECount, MaxBECount,
+                              &SE, nullptr, &DT, AC, LoopGuards);
   if (isa<SCEVCouldNotCompute>(AccessStart) ||
       isa<SCEVCouldNotCompute>(AccessEnd))
     return false;
@@ -355,7 +343,13 @@ bool llvm::isDereferenceableAndAlignedInLoop(
   const SCEV *PtrDiff = SE.getMinusSCEV(AccessEnd, AccessStart);
   if (isa<SCEVCouldNotCompute>(PtrDiff))
     return false;
-  APInt MaxPtrDiff = SE.getUnsignedRangeMax(PtrDiff);
+
+  if (!LoopGuards)
+    LoopGuards.emplace(
+        ScalarEvolution::LoopGuards::collect(AddRec->getLoop(), SE));
+
+  APInt MaxPtrDiff =
+      SE.getUnsignedRangeMax(SE.applyLoopGuards(PtrDiff, *LoopGuards));
 
   Value *Base = nullptr;
   APInt AccessSize;
diff --git a/llvm/lib/Analysis/LoopAccessAnalysis.cpp b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
index 258fa982ed1d0..7b2f797311a62 100644
--- a/llvm/lib/Analysis/LoopAccessAnalysis.cpp
+++ b/llvm/lib/Analysis/LoopAccessAnalysis.cpp
@@ -193,9 +193,8 @@ RuntimeCheckingPtrGroup::RuntimeCheckingPtrGroup(
 /// Returns \p A + \p B, if it is guaranteed not to unsigned wrap. Otherwise
 /// return nullptr. \p A and \p B must have the same type.
 static const SCEV *addSCEVNoOverflow(const SCEV *A, const SCEV *B,
-                                     ScalarEvolution &SE,
-                                     const Instruction *CtxI) {
-  if (!SE.willNotOverflow(Instruction::Add, /*IsSigned=*/false, A, B, CtxI))
+                                     ScalarEvolution &SE) {
+  if (!SE.willNotOverflow(Instruction::Add, /*IsSigned=*/false, A, B))
     return nullptr;
   return SE.getAddExpr(A, B);
 }
@@ -203,20 +202,19 @@ static const SCEV *addSCEVNoOverflow(const SCEV *A, const SCEV *B,
 /// Returns \p A * \p B, if it is guaranteed not to unsigned wrap. Otherwise
 /// return nullptr. \p A and \p B must have the same type.
 static const SCEV *mulSCEVOverflow(const SCEV *A, const SCEV *B,
-                                   ScalarEvolution &SE,
-                                   const Instruction *CtxI) {
-  if (!SE.willNotOverflow(Instruction::Mul, /*IsSigned=*/false, A, B, CtxI))
+                                   ScalarEvolution &SE) {
+  if (!SE.willNotOverflow(Instruction::Mul, /*IsSigned=*/false, A, B))
     return nullptr;
   return SE.getMulExpr(A, B);
 }
 
 /// Return true, if evaluating \p AR at \p MaxBTC cannot wrap, because \p AR at
 /// \p MaxBTC is guaranteed inbounds of the accessed object.
-static bool
-evaluatePtrAddRecAtMaxBTCWillNotWrap(const SCEVAddRecExpr *AR,
-                                     const SCEV *MaxBTC, const SCEV *EltSize,
-                                     ScalarEvolution &SE, const DataLayout &DL,
-                                     DominatorTree *DT, AssumptionCache *AC) {
+static bool evaluatePtrAddRecAtMaxBTCWillNotWrap(
+    const SCEVAddRecExpr *AR, const SCEV *MaxBTC, const SCEV *EltSize,
+    ScalarEvolution &SE, const DataLayout &DL, DominatorTree *DT,
+    AssumptionCache *AC,
+    std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
   auto *PointerBase = SE.getPointerBase(AR->getStart());
   auto *StartPtr = dyn_cast<SCEVUnknown>(PointerBase);
   if (!StartPtr)
@@ -234,12 +232,11 @@ evaluatePtrAddRecAtMaxBTCWillNotWrap(const SCEVAddRecExpr *AR,
   Type *WiderTy = SE.getWiderType(MaxBTC->getType(), Step->getType());
   const SCEV *DerefBytesSCEV = SE.getConstant(WiderTy, DerefBytes);
 
-  // Context which dominates the entire loop.
-  auto *CtxI = L->getLoopPredecessor()->getTerminator();
   // Check if we have a suitable dereferencable assumption we can use.
   if (!StartPtrV->canBeFreed()) {
     RetainedKnowledge DerefRK = getKnowledgeValidInContext(
-        StartPtrV, {Attribute::Dereferenceable}, *AC, CtxI, DT);
+        StartPtrV, {Attribute::Dereferenceable}, *AC,
+        L->getLoopPredecessor()->getTerminator(), DT);
     if (DerefRK) {
       DerefBytesSCEV = SE.getUMaxExpr(
           DerefBytesSCEV, SE.getConstant(WiderTy, DerefRK.ArgValue));
@@ -263,12 +260,20 @@ evaluatePtrAddRecAtMaxBTCWillNotWrap(const SCEVAddRecExpr *AR,
       SE.getMinusSCEV(AR->getStart(), StartPtr), WiderTy);
 
   const SCEV *OffsetAtLastIter =
-      mulSCEVOverflow(MaxBTC, SE.getAbsExpr(Step, /*IsNSW=*/false), SE, CtxI);
-  if (!OffsetAtLastIter)
-    return false;
+      mulSCEVOverflow(MaxBTC, SE.getAbsExpr(Step, /*IsNSW=*/false), SE);
+  if (!OffsetAtLastIter) {
+    // Re-try with constant max backedge-taken count if using the symbolic one
+    // failed.
+    MaxBTC = SE.getNoopOrZeroExtend(
+        SE.getConstantMaxBackedgeTakenCount(AR->getLoop()), WiderTy);
+    OffsetAtLastIter =
+        mulSCEVOverflow(MaxBTC, SE.getAbsExpr(Step, /*IsNSW=*/false), SE);
+    if (!OffsetAtLastIter)
+      return false;
+  }
 
   const SCEV *OffsetEndBytes = addSCEVNoOverflow(
-      OffsetAtLastIter, SE.getNoopOrZeroExtend(EltSize, WiderTy), SE, CtxI);
+      OffsetAtLastIter, SE.getNoopOrZeroExtend(EltSize, WiderTy), SE);
   if (!OffsetEndBytes)
     return false;
 
@@ -276,10 +281,15 @@ evaluatePtrAddRecAtMaxBTCWillNotWrap(const SCEVAddRecExpr *AR,
     // For positive steps, check if
     //  (AR->getStart() - StartPtr) + (MaxBTC  * Step) + EltSize <= DerefBytes,
     // while making sure none of the computations unsigned wrap themselves.
-    const SCEV *EndBytes =
-        addSCEVNoOverflow(StartOffset, OffsetEndBytes, SE, CtxI);
+    const SCEV *EndBytes = addSCEVNoOverflow(StartOffset, OffsetEndBytes, SE);
     if (!EndBytes)
       return false;
+
+    if (!LoopGuards)
+      LoopGuards.emplace(
+          ScalarEvolution::LoopGuards::collect(AR->getLoop(), SE));
+
+    EndBytes = SE.applyLoopGuards(EndBytes, *LoopGuards);
     return SE.isKnownPredicate(CmpInst::ICMP_ULE, EndBytes, DerefBytesSCEV);
   }
 
@@ -296,7 +306,8 @@ std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
     const SCEV *MaxBTC, ScalarEvolution *SE,
     DenseMap<std::pair<const SCEV *, Type *>,
              std::pair<const SCEV *, const SCEV *>> *PointerBounds,
-    DominatorTree *DT, AssumptionCache *AC) {
+    DominatorTree *DT, AssumptionCache *AC,
+    std::optional<ScalarEvolution::LoopGuards> &LoopGuards) {
   std::pair<const SCEV *, const SCEV *> *PtrBoundsPair;
   if (PointerBounds) {
     auto [Iter, Ins] = PointerBounds->insert(
@@ -332,7 +343,7 @@ std::pair<const SCEV *, const SCEV *> llvm::getStartAndEndForAccess(
       // separately checks that accesses cannot not wrap, so unsigned max
       // represents an upper bound.
       if (evaluatePtrAddRecAtMaxBTCWillNotWrap(AR, MaxBTC, EltSizeSCEV, *SE, DL,
-                                               DT, AC)) {
+                                               DT, AC, LoopGuards)) {
         ScEnd = AR->evaluateAtIteration(MaxBTC, *SE);
       } else {
         ScEnd = SE->getAddExpr(
@@ -381,7 +392,7 @@ void RuntimePointerChecking::insert(Loop *Lp, Value *Ptr, const SCEV *PtrExpr,
   const SCEV *BTC = PSE.getBackedgeTakenCount();
   const auto &[ScStart, ScEnd] = getStartAndEndForAccess(
       Lp, PtrExpr, AccessTy, BTC, SymbolicMaxBTC, PSE.getSE(),
-      &DC.getPointerBounds(), DC.getDT(), DC.getAC());
+      &DC.getPointerBounds(), DC.getDT(), DC.getAC(), LoopGuards);
   assert(!isa<SCEVCouldNotCompute>(ScStart) &&
          !isa<SCEVCouldNotCompute>(ScEnd) &&
          "must be able to compute both start and end expressions");
@@ -1987,13 +1998,13 @@ bool MemoryDepChecker::areAccessesCompletelyBeforeOrAfter(const SCEV *Src,
   ScalarEvolution &SE = *PSE.getSE();
   const auto &[SrcStart_, SrcEnd_] =
       getStartAndEndForAccess(InnermostLoop, Src, SrcTy, BTC, SymbolicMaxBTC,
-                              &SE, &PointerBounds, DT, AC);
+                              &SE, &PointerBounds, DT, AC, LoopGuards);
   if (isa<SCEVCouldNotCompute>(SrcStart_) || isa<SCEVCouldNotCompute>(SrcEnd_))
     return false;
 
   const auto &[SinkStart_, SinkEnd_] =
       getStartAndEndForAccess(InnermostLoop, Sink, SinkTy, BTC, SymbolicMaxBTC,
-                              &SE, &PointerBounds, DT, AC);
+                              &SE, &PointerBounds, DT, AC, LoopGuards);
   if (isa<SCEVCouldNotCompute>(SinkStart_) ||
       isa<SCEVCouldNotCompute>(SinkEnd_))
     return false;
@@ -3040,8 +3051,9 @@ LoopAccessInfo::LoopAccessInfo(Loop *L, ScalarEvolution *SE,
         TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) * 2;
 
   DepChecker = std::make_unique<MemoryDepChecker>(
-      *PSE, AC, DT, L, SymbolicStrides, MaxTargetVectorWidthInBits);
-  PtrRtChecking = std::make_unique<RuntimePointerChecking>(*DepChecker, SE);
+      *PSE, AC, DT, L, SymbolicStrides, MaxTargetVectorWidthInBits, LoopGuards);
+  PtrRtChecking =
+      std::make_unique<RuntimePointerChecking>(*DepChecker, SE, LoopGuards);
   if (canAnalyzeLoop())
     CanVecMem = analyzeLoop(AA, LI, TLI, DT);
 }
diff --git a/llvm/lib/Analysis/ScalarEvolution.cpp b/llvm/lib/Analysis/ScalarEvolution.cpp
index aa2bcf7917537..e5e4dcfce3bd4 100644
--- a/llvm/lib/Analysis/ScalarEvolution.cpp
+++ b/llvm/lib/Analysis/ScalarEvolution.cpp
@@ -2338,23 +2338,15 @@ bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
   // Can we use context to prove the fact we need?
   if (!CtxI)
     return false;
+  // TODO: Support mul.
+  if (BinOp == Instruction::Mul)
+    return false;
   auto *RHSC = dyn_cast<SCEVConstant>(RHS);
   // TODO: Lift this limitation.
   if (!RHSC)
     return false;
   APInt C = RHSC->getAPInt();
   unsigned NumBits = C.getBitWidth();
-  if (BinOp == Instruction::Mul) {
-    // Multiplying by 0 or 1 never overflows
-    if (C.isZero() || C.isOne())
-      return true;
-    if (Signed)
-      return false;
-    APInt Limit = APInt::getMaxValue(NumBits).udiv(C);
-    // To avoid overflow, we need to make sure that LHS <= MAX / C.
-    return isKnownPredicateAt(ICmpInst::ICMP_ULE, LHS, getConstant(Limit),
-                              CtxI);
-  }
   bool IsSub = (BinOp == Instruction::Sub);
   bool IsNegativeConst = (Signed && C.isNegative());
   // Compute the direction and magnitude by which we need to check overflow.
diff --git a/llvm/test/Transforms/LoopVectorize/vect.stats.ll b/llvm/test/Transforms/LoopVectorize/vect.stats.ll
index f3695e6712952..e3240c8181519 100644
--- a/llvm/test/Transforms/LoopVectorize/vect.stats.ll
+++ b/llvm/test/Transforms/LoopVectorize/vect.stats.ll
@@ -1,4 +1,4 @@
-; RUN: opt < %s -passes=loop-vectorize -force-vector-interleave=4 -force-vector-width=4 -debug-only=loop-vectorize -enable-early-exit-vectorization -use-symbolic-maxbtc-deref-loop --disable-output -stats -S 2>&1 | FileCheck %s
+; RUN: opt < %s -passes=loop-vectorize -force-vector-interleave=4 -force-vector-width=4 -debug-only=loop-vectorize -enable-early-exit-vectorization --disable-output -stats -S 2>&1 | FileCheck %s
 ; REQUIRES: asserts
 
 ; We have 3 loops, two of them are vectorizable (with one being early-exit

Comment on lines -2347 to -2357
if (BinOp == Instruction::Mul) {
// Multiplying by 0 or 1 never overflows
if (C.isZero() || C.isOne())
return true;
if (Signed)
return false;
APInt Limit = APInt::getMaxValue(NumBits).udiv(C);
// To avoid overflow, we need to make sure that LHS <= MAX / C.
return isKnownPredicateAt(ICmpInst::ICMP_ULE, LHS, getConstant(Limit),
CtxI);
}
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if we should leave the code in, for the current test cases, we get the expected results due to #155300

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had some cases downstream where I needed this code. I'll check if #155300 allows to get the test cases, but I think we can remove the code out unless it is exercised.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That would be great. If there are, could you add them?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my cases as well, #155300 was enough. We can remove this.

Comment on lines +265 to +270
// Re-try with constant max backedge-taken count if using the symbolic one
// failed.
MaxBTC = SE.getNoopOrZeroExtend(
SE.getConstantMaxBackedgeTakenCount(AR->getLoop()), WiderTy);
OffsetAtLastIter =
mulSCEVOverflow(MaxBTC, SE.getAbsExpr(Step, /*IsNSW=*/false), SE);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are some cases where we cannot apply loop guards effectively to MaxBTC (if it is an AddRec), but constant BTC computation uses them to get a tighter upper bound.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not use the CtxI above as done previously? Would that along with the mulSCEVOverflow change allow to get whats needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unfortunately that's not enough in some cases, for example https://github.com/llvm/llvm-project/blob/main/llvm/test/Transforms/LoopVectorize/single_early_exit.ll#L333 where the trip count of the inner loop depends on an induction from the outer loop

Copy link
Contributor

@annamthomas annamthomas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this! It handles more cases than what I had.
Why the LoopGuards is a better option than the isKnownPredicateAt? One is compile-time, but looking at the SCEV code, both are really similar (handling assumes/guards and dominating conditions).

Comment on lines -2347 to -2357
if (BinOp == Instruction::Mul) {
// Multiplying by 0 or 1 never overflows
if (C.isZero() || C.isOne())
return true;
if (Signed)
return false;
APInt Limit = APInt::getMaxValue(NumBits).udiv(C);
// To avoid overflow, we need to make sure that LHS <= MAX / C.
return isKnownPredicateAt(ICmpInst::ICMP_ULE, LHS, getConstant(Limit),
CtxI);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had some cases downstream where I needed this code. I'll check if #155300 allows to get the test cases, but I think we can remove the code out unless it is exercised.

Comment on lines +265 to +270
// Re-try with constant max backedge-taken count if using the symbolic one
// failed.
MaxBTC = SE.getNoopOrZeroExtend(
SE.getConstantMaxBackedgeTakenCount(AR->getLoop()), WiderTy);
OffsetAtLastIter =
mulSCEVOverflow(MaxBTC, SE.getAbsExpr(Step, /*IsNSW=*/false), SE);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why not use the CtxI above as done previously? Would that along with the mulSCEVOverflow change allow to get whats needed?

Remove the fall-back to constant max BTC if the backedge-taken-count
cannot be computed.

The constant max backedge-taken count is computed considering loop
guards, so to avoid regressions we need to apply loop guards as needed.

Also remove the special handling for Mul in willNotOverflow, as this
should not longer be needed after 9143746
(llvm#155300).
@fhahn fhahn force-pushed the laa-deref-guards-tc branch from 0caada9 to 23ce21c Compare September 2, 2025 12:55
@fhahn
Copy link
Contributor Author

fhahn commented Sep 2, 2025

ping :)

Copy link
Contributor

@annamthomas annamthomas left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Comment on lines -2347 to -2357
if (BinOp == Instruction::Mul) {
// Multiplying by 0 or 1 never overflows
if (C.isZero() || C.isOne())
return true;
if (Signed)
return false;
APInt Limit = APInt::getMaxValue(NumBits).udiv(C);
// To avoid overflow, we need to make sure that LHS <= MAX / C.
return isKnownPredicateAt(ICmpInst::ICMP_ULE, LHS, getConstant(Limit),
CtxI);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In my cases as well, #155300 was enough. We can remove this.

@fhahn fhahn merged commit 08001cf into llvm:main Sep 2, 2025
9 checks passed
@fhahn fhahn deleted the laa-deref-guards-tc branch September 2, 2025 17:58
llvm-sync bot pushed a commit to arm/arm-toolchain that referenced this pull request Sep 2, 2025
…cking deref. (#155672)

Remove the fall-back to constant max BTC if the backedge-taken-count
cannot be computed.

The constant max backedge-taken count is computed considering loop
guards, so to avoid regressions we need to apply loop guards as needed.

Also remove the special handling for Mul in willNotOverflow, as this
should not longer be needed after 9143746
(llvm/llvm-project#155300).

PR: llvm/llvm-project#155672
@thurstond
Copy link
Contributor

I think this might have broken the build (stage3/ubsan, https://lab.llvm.org/buildbot/#/builders/85/builds/12936). Could you please take a look?

FAILED: unittests/TextAPI/CMakeFiles/TextAPITests.dir/TextStubV3Tests.cpp.o 
/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm_build_ubsan/bin/clang++ -DGTEST_HAS_RTTI=0 -DLLVM_BUILD_STATIC -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_GLIBCXX_USE_CXX11_ABI=1 -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm_build2_ubsan/unittests/TextAPI -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/unittests/TextAPI -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm_build2_ubsan/include -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/third-party/unittest/googletest/include -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/third-party/unittest/googlemock/include -fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time -Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic -Wno-long-long -Wc++98-compat-extra-semi -Wimplicit-fallthrough -Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor -Wdelete-non-virtual-dtor -Wsuggest-override -Wstring-conversion -Wmisleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color -ffunction-sections -fdata-sections -O3 -DNDEBUG -std=c++17  -Wno-variadic-macros -Wno-gnu-zero-variadic-macro-arguments -fno-exceptions -funwind-tables -fno-rtti -UNDEBUG -Wno-suggest-override -MD -MT unittests/TextAPI/CMakeFiles/TextAPITests.dir/TextStubV3Tests.cpp.o -MF unittests/TextAPI/CMakeFiles/TextAPITests.dir/TextStubV3Tests.cpp.o.d -o unittests/TextAPI/CMakeFiles/TextAPITests.dir/TextStubV3Tests.cpp.o -c /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/unittests/TextAPI/TextStubV3Tests.cpp
Attempt to use a SCEVCouldNotCompute object!
UNREACHABLE executed at /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp:412!
PLEASE submit a bug report to https://github.com/llvm/llvm-project/issues/ and include the crash backtrace, preprocessed source, and associated run script.
Stack dump:
0.	Program arguments: /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm_build_ubsan/bin/clang++ -DGTEST_HAS_RTTI=0 -DLLVM_BUILD_STATIC -D_DEBUG -D_GLIBCXX_ASSERTIONS -D_GLIBCXX_USE_CXX11_ABI=1 -D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS -D__STDC_LIMIT_MACROS -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm_build2_ubsan/unittests/TextAPI -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/unittests/TextAPI -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm_build2_ubsan/include -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/third-party/unittest/googletest/include -I/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/third-party/unittest/googlemock/include -fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time -Werror=unguarded-availability-new -Wall -Wextra -Wno-unused-parameter -Wwrite-strings -Wcast-qual -Wmissing-field-initializers -pedantic -Wno-long-long -Wc++98-compat-extra-semi -Wimplicit-fallthrough -Wcovered-switch-default -Wno-noexcept-type -Wnon-virtual-dtor -Wdelete-non-virtual-dtor -Wsuggest-override -Wstring-conversion -Wmisleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color -ffunction-sections -fdata-sections -O3 -DNDEBUG -std=c++17 -Wno-variadic-macros -Wno-gnu-zero-variadic-macro-arguments -fno-exceptions -funwind-tables -fno-rtti -UNDEBUG -Wno-suggest-override -MD -MT unittests/TextAPI/CMakeFiles/TextAPITests.dir/TextStubV3Tests.cpp.o -MF unittests/TextAPI/CMakeFiles/TextAPITests.dir/TextStubV3Tests.cpp.o.d -o unittests/TextAPI/CMakeFiles/TextAPITests.dir/TextStubV3Tests.cpp.o -c /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/unittests/TextAPI/TextStubV3Tests.cpp
1.	<eof> parser at end of file
2.	Optimizer
3.	Running pass "function<eager-inv>(float2int,lower-constant-intrinsics,chr,loop(loop-rotate<header-duplication;no-prepare-for-lto>,loop-deletion),loop-distribute,inject-tli-mappings,loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>,infer-alignment,loop-load-elim,instcombine<max-iterations=1;no-verify-fixpoint>,simplifycfg<bonus-inst-threshold=1;forward-switch-cond;switch-range-to-icmp;switch-to-lookup;no-keep-loops;hoist-common-insts;no-hoist-loads-stores-with-cond-faulting;sink-common-insts;speculate-blocks;simplify-cond-branch;no-speculate-unpredictables>,slp-vectorizer,vector-combine,instcombine<max-iterations=1;no-verify-fixpoint>,loop-unroll<O3>,transform-warning,sroa<preserve-cfg>,infer-alignment,instcombine<max-iterations=1;no-verify-fixpoint>,loop-mssa(licm<allowspeculation>),alignment-from-assumptions,loop-sink,instsimplify,div-rem-pairs,tailcallelim,simplifycfg<bonus-inst-threshold=1;no-forward-switch-cond;switch-range-to-icmp;no-switch-to-lookup;keep-loops;no-hoist-common-insts;hoist-loads-stores-with-cond-faulting;no-sink-common-insts;speculate-blocks;simplify-cond-branch;speculate-unpredictables>)" on module "/home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/unittests/TextAPI/TextStubV3Tests.cpp"
4.	Running pass "loop-vectorize<no-interleave-forced-only;no-vectorize-forced-only;>" on function "_ZN5TBDv319TBDv3_ReadFile_Test8TestBodyEv"
 #0 0x0000bd17b5a7ef6c llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Support/Unix/Signals.inc:834:13
 #1 0x0000bd17b5a7be40 __cxx_atomic_store<CallbackAndCookie::Status> /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/libcxx_install_ubsan/include/c++/v1/__atomic/support/c11.h:68:3
 #2 0x0000bd17b5a7be40 store /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/libcxx_install_ubsan/include/c++/v1/__atomic/atomic.h:62:5
 #3 0x0000bd17b5a7be40 llvm::sys::RunSignalHandlers() /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Support/Signals.cpp:106:16
 #4 0x0000bd17b59ac530 (anonymous namespace)::CrashRecoveryContextImpl::HandleCrash(int, unsigned long) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Support/CrashRecoveryContext.cpp:73:5
 #5 0x0000bd17b59ac80c CrashRecoverySignalHandler(int) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Support/CrashRecoveryContext.cpp:391:1
 #6 0x0000e8f43d7378f8 (linux-vdso.so.1+0x8f8)
 #7 0x0000e8f43d127608 (/lib/aarch64-linux-gnu/libc.so.6+0x87608)
 #8 0x0000e8f43d0dcb3c raise (/lib/aarch64-linux-gnu/libc.so.6+0x3cb3c)
 #9 0x0000e8f43d0c7e00 abort (/lib/aarch64-linux-gnu/libc.so.6+0x27e00)
#10 0x0000bd17b59b846c operator<< /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/Support/raw_ostream.h:235:17
#11 0x0000bd17b59b846c operator<< /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/Support/raw_ostream.h:258:18
#12 0x0000bd17b59b846c llvm::llvm_unreachable_internal(char const*, char const*, unsigned int) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Support/ErrorHandling.cpp:242:12
#13 0x0000bd17b46660fc llvm::SCEV::getType() const /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp:412:5
#14 0x0000bd17b4686364 llvm::ScalarEvolution::getNoopOrZeroExtend(llvm::SCEV const*, llvm::Type*) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Analysis/ScalarEvolution.cpp:4748:20
#15 0x0000bd17b455fe84 evaluatePtrAddRecAtMaxBTCWillNotWrap /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Analysis/LoopAccessAnalysis.cpp:0:17
#16 0x0000bd17b455fe84 llvm::getStartAndEndForAccess(llvm::Loop const*, llvm::SCEV const*, llvm::Type*, llvm::SCEV const*, llvm::SCEV const*, llvm::ScalarEvolution*, llvm::DenseMap<std::__1::pair<llvm::SCEV const*, llvm::Type*>, std::__1::pair<llvm::SCEV const*, llvm::SCEV const*>, llvm::DenseMapInfo<std::__1::pair<llvm::SCEV const*, llvm::Type*>, void>, llvm::detail::DenseMapPair<std::__1::pair<llvm::SCEV const*, llvm::Type*>, std::__1::pair<llvm::SCEV const*, llvm::SCEV const*>>>*, llvm::DominatorTree*, llvm::AssumptionCache*, std::__1::optional<llvm::ScalarEvolution::LoopGuards>&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Analysis/LoopAccessAnalysis.cpp:345:11
#17 0x0000bd17b4557dd0 llvm::isDereferenceableAndAlignedInLoop(llvm::LoadInst*, llvm::Loop*, llvm::ScalarEvolution&, llvm::DominatorTree&, llvm::AssumptionCache*, llvm::SmallVectorImpl<llvm::SCEVPredicate const*>*) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Analysis/Loads.cpp:336:7
#18 0x0000bd17b736bf00 llvm::LoopVectorizationLegality::canVectorizeWithIfConvert() /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp:1554:58
#19 0x0000bd17b736db3c llvm::LoopVectorizationLegality::canVectorize(bool) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorizationLegality.cpp:1844:22
#20 0x0000bd17b7253bc0 llvm::LoopVectorizePass::processLoop(llvm::Loop*) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp:9912:7
#21 0x0000bd17b725e304 llvm::LoopVectorizePass::runImpl(llvm::Function&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp:10335:27
#22 0x0000bd17b725eb58 llvm::LoopVectorizePass::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp:10372:32
#23 0x0000bd17b5266ee4 llvm::PassManager<llvm::Function, llvm::AnalysisManager<llvm::Function>>::run(llvm::Function&, llvm::AnalysisManager<llvm::Function>&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/IR/PassManagerImpl.h:80:8
#24 0x0000bd17b526be10 llvm::ModuleToFunctionPassAdaptor::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/IR/PassManager.cpp:132:23
#25 0x0000bd17b5266070 llvm::PassManager<llvm::Module, llvm::AnalysisManager<llvm::Module>>::run(llvm::Module&, llvm::AnalysisManager<llvm::Module>&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/IR/PassManagerImpl.h:80:8
#26 0x0000bd17b64cf26c isSmall /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/ADT/SmallPtrSet.h:248:33
#27 0x0000bd17b64cf26c ~SmallPtrSetImplBase /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/ADT/SmallPtrSet.h:89:10
#28 0x0000bd17b64cf26c ~PreservedAnalyses /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/IR/Analysis.h:112:7
#29 0x0000bd17b64cf26c (anonymous namespace)::EmitAssemblyHelper::RunOptimizationPipeline(clang::BackendAction, std::__1::unique_ptr<llvm::raw_pwrite_stream, std::__1::default_delete<llvm::raw_pwrite_stream>>&, std::__1::unique_ptr<llvm::ToolOutputFile, std::__1::default_delete<llvm::ToolOutputFile>>&, clang::BackendConsumer*) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/CodeGen/BackendUtil.cpp:1203:5
#30 0x0000bd17b64c615c RunCodegenPipeline /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/CodeGen/BackendUtil.cpp:1215:23
#31 0x0000bd17b64c615c emitAssembly /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/CodeGen/BackendUtil.cpp:1277:3
#32 0x0000bd17b64c615c clang::emitBackendOutput(clang::CompilerInstance&, clang::CodeGenOptions&, llvm::StringRef, llvm::Module*, clang::BackendAction, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>, std::__1::unique_ptr<llvm::raw_pwrite_stream, std::__1::default_delete<llvm::raw_pwrite_stream>>, clang::BackendConsumer*) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/CodeGen/BackendUtil.cpp:1442:13
#33 0x0000bd17b64dc634 reset /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/libcxx_install_ubsan/include/c++/v1/__memory/unique_ptr.h:287:21
#34 0x0000bd17b64dc634 ~unique_ptr /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/libcxx_install_ubsan/include/c++/v1/__memory/unique_ptr.h:259:71
#35 0x0000bd17b64dc634 clang::BackendConsumer::HandleTranslationUnit(clang::ASTContext&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/CodeGen/CodeGenAction.cpp:316:3
#36 0x0000bd17b8742ffc clang::ParseAST(clang::Sema&, bool, bool) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/Parse/ParseAST.cpp:127:16
#37 0x0000bd17b6af2c9c clang::FrontendAction::Execute() /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/Frontend/FrontendAction.cpp:1314:10
#38 0x0000bd17b6a56d84 getPtr /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/Support/Error.h:278:42
#39 0x0000bd17b6a56d84 operator bool /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/Support/Error.h:241:16
#40 0x0000bd17b6a56d84 clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/Frontend/CompilerInstance.cpp:1066:23
#41 0x0000bd17b6c55dd4 clang::ExecuteCompilerInvocation(clang::CompilerInstance*) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp:302:25
#42 0x0000bd17b22075d0 cc1_main(llvm::ArrayRef<char const*>, char const*, void*) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/tools/driver/cc1_main.cpp:297:15
#43 0x0000bd17b2201d94 ExecuteCC1Tool(llvm::SmallVectorImpl<char const*>&, llvm::ToolContext const&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/tools/driver/driver.cpp:223:12
#44 0x0000bd17b68ef2fc operator() /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/Driver/Job.cpp:436:30
#45 0x0000bd17b68ef2fc void llvm::function_ref<void ()>::callback_fn<clang::driver::CC1Command::Execute(llvm::ArrayRef<std::__1::optional<llvm::StringRef>>, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>*, bool*) const::$_0>(long) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/ADT/STLFunctionalExtras.h:46:12
#46 0x0000bd17b59ac3f0 operator() /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/ADT/STLFunctionalExtras.h:0:12
#47 0x0000bd17b59ac3f0 llvm::CrashRecoveryContext::RunSafely(llvm::function_ref<void ()>) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/lib/Support/CrashRecoveryContext.cpp:426:3
#48 0x0000bd17b68ed3f0 clang::driver::CC1Command::Execute(llvm::ArrayRef<std::__1::optional<llvm::StringRef>>, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>>*, bool*) const /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/Driver/Job.cpp:436:7
#49 0x0000bd17b689a010 operator bool /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/libcxx_install_ubsan/include/c++/v1/__functional/function.h:309:75
#50 0x0000bd17b689a010 operator bool /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/libcxx_install_ubsan/include/c++/v1/__functional/function.h:677:93
#51 0x0000bd17b689a010 clang::driver::Compilation::ExecuteCommand(clang::driver::Command const&, clang::driver::Command const*&, bool) const /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/Driver/Compilation.cpp:197:7
#52 0x0000bd17b689a2a4 clang::driver::Compilation::ExecuteJobs(clang::driver::JobList const&, llvm::SmallVectorImpl<std::__1::pair<int, clang::driver::Command const*>>&, bool) const /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/Driver/Compilation.cpp:246:13
#53 0x0000bd17b68b7248 empty /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/ADT/SmallVector.h:82:46
#54 0x0000bd17b68b7248 clang::driver::Driver::ExecuteCompilation(clang::driver::Compilation&, llvm::SmallVectorImpl<std::__1::pair<int, clang::driver::Command const*>>&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/lib/Driver/Driver.cpp:2244:23
#55 0x0000bd17b2200d00 size /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/ADT/SmallVector.h:79:32
#56 0x0000bd17b2200d00 end /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/llvm/include/llvm/ADT/SmallVector.h:270:37
#57 0x0000bd17b2200d00 clang_main(int, char**, llvm::ToolContext const&) /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm-project/clang/tools/driver/driver.cpp:406:24
#58 0x0000bd17b2218888 main /home/b/sanitizer-aarch64-linux-bootstrap-ubsan/build/llvm_build_ubsan/tools/clang/tools/driver/clang-driver.cpp:17:10

fhahn added a commit that referenced this pull request Sep 2, 2025
…ng deref. (#155672)"

This reverts commit 08001cf.

This triggers an assertion in some build configs, e.g.
 https://lab.llvm.org/buildbot/#/builders/24/builds/12211
@fhahn
Copy link
Contributor Author

fhahn commented Sep 2, 2025

thanks, should already be reverted

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
llvm:analysis Includes value tracking, cost tables and constant folding llvm:transforms
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants