diff --git a/llvm/lib/Analysis/ScalarEvolution.cpp b/llvm/lib/Analysis/ScalarEvolution.cpp --- a/llvm/lib/Analysis/ScalarEvolution.cpp +++ b/llvm/lib/Analysis/ScalarEvolution.cpp @@ -9662,9 +9662,14 @@ // Solve the general equation. const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(), getNegativeSCEV(Start), *this); - const SCEV *M = E == getCouldNotCompute() - ? E - : getConstant(getUnsignedRangeMax(E)); + + const SCEV *M = E; + if (E != getCouldNotCompute()) { + APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L)); + assert(MaxWithGuards.ule(getUnsignedRangeMax(E)) && + "applying loop guards unexpectedly pessimized max count"); + M = getConstant(MaxWithGuards); + } return ExitLimit(E, M, false, Predicates); } diff --git a/llvm/test/Analysis/ScalarEvolution/max-backedge-taken-count-guard-info-rewrite-expressions.ll b/llvm/test/Analysis/ScalarEvolution/max-backedge-taken-count-guard-info-rewrite-expressions.ll --- a/llvm/test/Analysis/ScalarEvolution/max-backedge-taken-count-guard-info-rewrite-expressions.ll +++ b/llvm/test/Analysis/ScalarEvolution/max-backedge-taken-count-guard-info-rewrite-expressions.ll @@ -67,9 +67,9 @@ ; Test case from PR52464. define i32 @rewrite_zext_icmp_ne(i32 %N) { ; CHECK-LABEL: Determining loop execution counts for: @rewrite_zext_icmp_ne -; CHECK-NEXT: Loop %loop: backedge-taken count is ((-4 + (4 * ((4 + (zext i32 (-1 + (zext i2 (trunc i32 %N to i2) to i32)) to i64)) /u 4))) /u 4) -; CHECK-NEXT: Loop %loop: max backedge-taken count is 1073741823 -; CHECK-NEXT: Loop %loop: Predicated backedge-taken count is ((-4 + (4 * ((4 + (zext i32 (-1 + (zext i2 (trunc i32 %N to i2) to i32)) to i64)) /u 4))) /u 4) +; CHECK-NEXT: Loop %loop: backedge-taken count is 0 +; CHECK-NEXT: Loop %loop: max backedge-taken count is 0 +; CHECK-NEXT: Loop %loop: Predicated backedge-taken count is 0 ; CHECK-NEXT: Predicates: ; CHECK-EMPTY: ; CHECK-NEXT: Loop %loop: Trip multiple is 1