Enzyme main
Loading...
Searching...
No Matches
MustExitScalarEvolution.cpp
Go to the documentation of this file.
1
2//===- MustExitScalarEvolution.cpp - ScalarEvolution assuming loops
3// terminate-=//
4//
5// Enzyme Project
6//
7// Part of the Enzyme Project, under the Apache License v2.0 with LLVM
8// Exceptions. See https://llvm.org/LICENSE.txt for license information.
9// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
10//
11// If using this code in an academic setting, please cite the following:
12// @incollection{enzymeNeurips,
13// title = {Instead of Rewriting Foreign Code for Machine Learning,
14// Automatically Synthesize Fast Gradients},
15// author = {Moses, William S. and Churavy, Valentin},
16// booktitle = {Advances in Neural Information Processing Systems 33},
17// year = {2020},
18// note = {To appear in},
19// }
20//
21//===----------------------------------------------------------------------===//
22//
23// This file defines MustExitScalarEvolution, a subclass of ScalarEvolution
24// that assumes that all loops terminate (and don't loop forever).
25//
26//===----------------------------------------------------------------------===//
27
29#include "FunctionUtils.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/Analysis/LoopInfo.h"
32#include "llvm/Analysis/ScalarEvolution.h"
33
34#include <type_traits>
35
36#ifdef __clang__
37#pragma clang diagnostic push
38#pragma clang diagnostic ignored "-Wunused-variable"
39#else
40#pragma GCC diagnostic push
41#pragma GCC diagnostic ignored "-Wunused-variable"
42#endif
43
44#if LLVM_VERSION_MAJOR <= 22
45#define SCEVUse const SCEV *
46#endif
47
48using namespace llvm;
49
51 return true;
52}
53
55 const Loop *L, Value *ExitCond, bool ExitIfTrue, bool ControlsExit,
56 bool AllowPredicates) {
57 ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
58 return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
59 ControlsExit, AllowPredicates);
60}
61
63 llvm::TargetLibraryInfo &TLI,
64 llvm::AssumptionCache &AC,
65 llvm::DominatorTree &DT,
66 llvm::LoopInfo &LI)
67 : ScalarEvolution(F, TLI, AC, DT, LI),
68 GuaranteedUnreachable(getGuaranteedUnreachable(&F)) {}
69
71 const Loop *L, BasicBlock *ExitingBlock, bool AllowPredicates) {
72
73 SmallVector<BasicBlock *, 8> ExitingBlocks;
74 L->getExitingBlocks(ExitingBlocks);
75 for (auto &ExitingBlock : ExitingBlocks) {
76 BasicBlock *Exit = nullptr;
77 for (auto *SBB : successors(ExitingBlock)) {
78 if (!L->contains(SBB)) {
79 if (GuaranteedUnreachable.count(SBB))
80 continue;
81 Exit = SBB;
82 break;
83 }
84 }
85 if (!Exit)
86 ExitingBlock = nullptr;
87 }
88 ExitingBlocks.erase(
89 std::remove(ExitingBlocks.begin(), ExitingBlocks.end(), nullptr),
90 ExitingBlocks.end());
91
92 assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
93 // If our exiting block does not dominate the latch, then its connection with
94 // loop's exit limit may be far from trivial.
95 const BasicBlock *Latch = L->getLoopLatch();
96 if (!Latch || !DT.dominates(ExitingBlock, Latch))
97 return getCouldNotCompute();
98
99 bool IsOnlyExit = ExitingBlocks.size() == 1;
100 auto *Term = ExitingBlock->getTerminator();
101 if (Instruction *BI =
102 (isAnyBranch(Term) ? cast<Instruction>(Term) : nullptr)) {
103 assert(isConditionalBranch(BI) && "If unconditional, it can't be in loop!");
104 bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
105 assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
106 "It should have one successor in loop and one exit block!");
107 // Proceed to the next level to examine the exit condition expression.
108 return computeExitLimitFromCond(L, getBranchCondition(BI), ExitIfTrue,
109 /*ControlsExit=*/IsOnlyExit,
110 AllowPredicates);
111 }
112
113 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
114 // For switch, make sure that there is a single exit from the loop.
115 BasicBlock *Exit = nullptr;
116 for (auto *SBB : successors(ExitingBlock))
117 if (!L->contains(SBB)) {
118 if (GuaranteedUnreachable.count(SBB))
119 continue;
120 if (Exit) // Multiple exit successors.
121 return getCouldNotCompute();
122 Exit = SBB;
123 }
124 assert(Exit && "Exiting block must have at least one exit");
125 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
126 /*ControlsExit=*/IsOnlyExit);
127 }
128
129 return getCouldNotCompute();
130}
131
132ScalarEvolution::ExitLimit
134 const Loop *L, SwitchInst *Switch, BasicBlock *ExitingBlock,
135 bool ControlsOnlyExit) {
136 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
137
138 // Give up if the exit is the default dest of a switch.
139 if (Switch->getDefaultDest() == ExitingBlock)
140 return getCouldNotCompute();
141
142 ///! If we're guaranteed unreachable, the default dest does not matter.
143 if (!GuaranteedUnreachable.count(Switch->getDefaultDest()))
144 assert(L->contains(Switch->getDefaultDest()) &&
145 "Default case must not exit the loop!");
146 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
147 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
148
149 // while (X != Y) --> while (X-Y != 0)
150 ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsOnlyExit);
151 if (EL.hasAnyInfo())
152 return EL;
153
154 return getCouldNotCompute();
155}
156
157ScalarEvolution::ExitLimit
159 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
160 bool ControlsExit, bool AllowPredicates) {
161
162 if (auto MaybeEL =
163 Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
164 return *MaybeEL;
165
166 ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
167 ControlsExit, AllowPredicates);
168 Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
169 return EL;
170}
171
172ScalarEvolution::ExitLimit
174 ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
175 bool ControlsExit, bool AllowPredicates) {
176 // Check if the controlling expression for this loop is an And or Or.
177 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
178 if (BO->getOpcode() == Instruction::And) {
179 // Recurse on the operands of the and.
180 bool EitherMayExit = !ExitIfTrue;
181 ExitLimit EL0 = computeExitLimitFromCondCached(
182 Cache, L, BO->getOperand(0), ExitIfTrue,
183 ControlsExit && !EitherMayExit, AllowPredicates);
184 ExitLimit EL1 = computeExitLimitFromCondCached(
185 Cache, L, BO->getOperand(1), ExitIfTrue,
186 ControlsExit && !EitherMayExit, AllowPredicates);
187 const SCEV *BECount = getCouldNotCompute();
188 const SCEV *MaxBECount = getCouldNotCompute();
189 if (EitherMayExit) {
190 // Both conditions must be true for the loop to continue executing.
191 // Choose the less conservative count.
192 if (EL0.ExactNotTaken == getCouldNotCompute() ||
193 EL1.ExactNotTaken == getCouldNotCompute())
194 BECount = getCouldNotCompute();
195 else
196 BECount =
197 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
198#if LLVM_VERSION_MAJOR >= 16
199 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
200 MaxBECount = EL1.ConstantMaxNotTaken;
201 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
202 MaxBECount = EL0.ConstantMaxNotTaken;
203 else
204 MaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
205 EL1.ConstantMaxNotTaken);
206 } else {
207 // Both conditions must be true at the same time for the loop to exit.
208 // For now, be conservative.
209 if (EL0.ConstantMaxNotTaken == EL1.ConstantMaxNotTaken)
210 MaxBECount = EL0.ConstantMaxNotTaken;
211 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
212 BECount = EL0.ExactNotTaken;
213 }
214#else
215 if (EL0.MaxNotTaken == getCouldNotCompute())
216 MaxBECount = EL1.MaxNotTaken;
217 else if (EL1.MaxNotTaken == getCouldNotCompute())
218 MaxBECount = EL0.MaxNotTaken;
219 else
220 MaxBECount =
221 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
222 } else {
223 // Both conditions must be true at the same time for the loop to exit.
224 // For now, be conservative.
225 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
226 MaxBECount = EL0.MaxNotTaken;
227 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
228 BECount = EL0.ExactNotTaken;
229 }
230#endif
231 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
232 // to be more aggressive when computing BECount than when computing
233 // MaxBECount. In these cases it is possible for EL0.ExactNotTaken and
234 // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
235 // EL1.ConstantMaxNotTaken to not.
236 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
237 !isa<SCEVCouldNotCompute>(BECount))
238 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
239
240#if LLVM_VERSION_MAJOR >= 20
241 return ExitLimit(BECount, MaxBECount, MaxBECount, false,
242 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
243#elif LLVM_VERSION_MAJOR >= 16
244 return ExitLimit(BECount, MaxBECount, MaxBECount, false,
245 {&EL0.Predicates, &EL1.Predicates});
246#else
247 return ExitLimit(BECount, MaxBECount, false,
248 {&EL0.Predicates, &EL1.Predicates});
249#endif
250 }
251 if (BO->getOpcode() == Instruction::Or) {
252 // Recurse on the operands of the or.
253 bool EitherMayExit = ExitIfTrue;
254 ExitLimit EL0 = computeExitLimitFromCondCached(
255 Cache, L, BO->getOperand(0), ExitIfTrue,
256 ControlsExit && !EitherMayExit, AllowPredicates);
257 ExitLimit EL1 = computeExitLimitFromCondCached(
258 Cache, L, BO->getOperand(1), ExitIfTrue,
259 ControlsExit && !EitherMayExit, AllowPredicates);
260 const SCEV *BECount = getCouldNotCompute();
261 const SCEV *MaxBECount = getCouldNotCompute();
262 if (EitherMayExit) {
263 // Both conditions must be false for the loop to continue executing.
264 // Choose the less conservative count.
265 if (EL0.ExactNotTaken == getCouldNotCompute() ||
266 EL1.ExactNotTaken == getCouldNotCompute())
267 BECount = getCouldNotCompute();
268 else
269 BECount =
270 getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken);
271#if LLVM_VERSION_MAJOR >= 16
272 if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
273 MaxBECount = EL1.ConstantMaxNotTaken;
274 else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
275 MaxBECount = EL0.ConstantMaxNotTaken;
276 else
277 MaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
278 EL1.ConstantMaxNotTaken);
279 } else {
280 // Both conditions must be false at the same time for the loop to exit.
281 // For now, be conservative.
282 if (EL0.ConstantMaxNotTaken == EL1.ConstantMaxNotTaken)
283 MaxBECount = EL0.ConstantMaxNotTaken;
284 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
285 BECount = EL0.ExactNotTaken;
286 }
287#if LLVM_VERSION_MAJOR >= 20
288 return ExitLimit(BECount, MaxBECount, MaxBECount, false,
289 {ArrayRef(EL0.Predicates), ArrayRef(EL1.Predicates)});
290#else
291 return ExitLimit(BECount, MaxBECount, MaxBECount, false,
292 {&EL0.Predicates, &EL1.Predicates});
293#endif
294#else
295 if (EL0.MaxNotTaken == getCouldNotCompute())
296 MaxBECount = EL1.MaxNotTaken;
297 else if (EL1.MaxNotTaken == getCouldNotCompute())
298 MaxBECount = EL0.MaxNotTaken;
299 else
300 MaxBECount =
301 getUMinFromMismatchedTypes(EL0.MaxNotTaken, EL1.MaxNotTaken);
302 } else {
303 // Both conditions must be false at the same time for the loop to exit.
304 // For now, be conservative.
305 if (EL0.MaxNotTaken == EL1.MaxNotTaken)
306 MaxBECount = EL0.MaxNotTaken;
307 if (EL0.ExactNotTaken == EL1.ExactNotTaken)
308 BECount = EL0.ExactNotTaken;
309 }
310 return ExitLimit(BECount, MaxBECount, false,
311 {&EL0.Predicates, &EL1.Predicates});
312#endif
313 }
314 }
315
316 // With an icmp, it may be feasible to compute an exact backedge-taken count.
317 // Proceed to the next level to examine the icmp.
318 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
319 ExitLimit EL =
320 computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
321 if (EL.hasFullInfo() || !AllowPredicates)
322 return EL;
323
324 // Try again, but use SCEV predicates this time.
325 return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
326 /*AllowPredicates=*/true);
327 }
328
329 // Check for a constant condition. These are normally stripped out by
330 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
331 // preserve the CFG and is temporarily leaving constant conditions
332 // in place.
333 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
334 if (ExitIfTrue == !CI->getZExtValue())
335 // The backedge is always taken.
336 return getCouldNotCompute();
337 else
338 // The backedge is never taken.
339 return getZero(CI->getType());
340 }
341
342 // If it's not an integer or pointer comparison then compute it the hard way.
343 return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
344}
345
347 const Loop *L, ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsExit,
348 bool AllowPredicates) {
349 // If the condition was exit on true, convert the condition to exit on false
350#if LLVM_VERSION_MAJOR >= 20
351 llvm::CmpPredicate Pred = ExitCond->getPredicate();
352#else
353 auto Pred = ExitCond->getPredicate();
354#endif
355 if (ExitIfTrue)
356 Pred = ExitCond->getInversePredicate();
357 const auto OriginalPred = Pred;
358
359#if LLVM_VERSION_MAJOR < 14
360 // Handle common loops like: for (X = "string"; *X; ++X)
361 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
362 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
363 ExitLimit ItCnt = computeLoadConstantCompareExitLimit(LI, RHS, L, Pred);
364 if (ItCnt.hasAnyInfo())
365 return ItCnt;
366 }
367#endif
368
369 SCEVUse LHS = getSCEV(ExitCond->getOperand(0));
370 SCEVUse RHS = getSCEV(ExitCond->getOperand(1));
371
372#define PROP_PHI(LHS) \
373 if (auto un = dyn_cast<SCEVUnknown>(LHS)) { \
374 if (auto pn = dyn_cast_or_null<PHINode>(un->getValue())) { \
375 const SCEV *sc = nullptr; \
376 bool failed = false; \
377 for (auto &a : pn->incoming_values()) { \
378 auto subsc = getSCEV(a); \
379 if (sc == nullptr) { \
380 sc = subsc; \
381 continue; \
382 } \
383 if (subsc != sc) { \
384 failed = true; \
385 break; \
386 } \
387 } \
388 if (!failed) { \
389 LHS = sc; \
390 } \
391 } \
392 }
393 PROP_PHI(LHS)
394 PROP_PHI(RHS)
395
396 // Try to evaluate any dependencies out of the loop.
397 LHS = getSCEVAtScope(LHS, L);
398 RHS = getSCEVAtScope(RHS, L);
399
400 // At this point, we would like to compute how many iterations of the
401 // loop the predicate will return true for these inputs.
402 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
403 // If there is a loop-invariant, force it into the RHS.
404 std::swap(LHS, RHS);
405 Pred = ICmpInst::getSwappedPredicate(Pred);
406 }
407
408 // Simplify the operands before analyzing them.
409 (void)SimplifyICmpOperands(Pred, LHS, RHS);
410
411 // If we have a comparison of a chrec against a constant, try to use value
412 // ranges to answer this query.
413 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
414 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
415 if (AddRec->getLoop() == L) {
416 // Form the constant range.
417 ConstantRange CompRange =
418 ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
419
420 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
421 if (!isa<SCEVCouldNotCompute>(Ret))
422 return Ret;
423 }
424
425 switch (Pred) {
426 case ICmpInst::ICMP_NE: { // while (X != Y)
427 // Convert to: while (X-Y != 0)
428 ExitLimit EL =
429 howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit, AllowPredicates);
430 if (EL.hasAnyInfo())
431 return EL;
432 break;
433 }
434 case ICmpInst::ICMP_EQ: { // while (X == Y)
435 // Convert to: while (X-Y == 0)
436 ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
437 if (EL.hasAnyInfo())
438 return EL;
439 break;
440 }
441 case ICmpInst::ICMP_SLT:
442 case ICmpInst::ICMP_ULT:
443 case ICmpInst::ICMP_SLE:
444 case ICmpInst::ICMP_ULE: { // while (X < Y)
445 bool IsSigned = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
446
447 if (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_ULE) {
448 if (!isa<IntegerType>(RHS->getType()))
449 break;
450 SmallVector<SCEVUse, 2> sv = {
451 RHS,
452 getConstant(ConstantInt::get(cast<IntegerType>(RHS->getType()), 1))};
453 // Since this is not an infinite loop by induction, RHS cannot be
454 // int_max/uint_max Therefore adding 1 does not wrap.
455 if (IsSigned)
456 RHS = getAddExpr(sv, SCEV::FlagNSW);
457 else
458 RHS = getAddExpr(sv, SCEV::FlagNUW);
459 }
460 ExitLimit EL =
461 howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit, AllowPredicates);
462 if (EL.hasAnyInfo())
463 return EL;
464 break;
465 }
466 case ICmpInst::ICMP_SGT:
467 case ICmpInst::ICMP_UGT:
468 case ICmpInst::ICMP_SGE:
469 case ICmpInst::ICMP_UGE: { // while (X > Y)
470 bool IsSigned = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
471 if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_UGE) {
472 if (!isa<IntegerType>(RHS->getType()))
473 break;
474 SmallVector<SCEVUse, 2> sv = {
475 RHS,
476 getConstant(ConstantInt::get(cast<IntegerType>(RHS->getType()), -1,
477 /*IsSigned*/ true))};
478 // Since this is not an infinite loop by induction, RHS cannot be
479 // int_min/uint_min Therefore subtracting 1 does not wrap.
480 if (IsSigned)
481 RHS = getAddExpr(sv, SCEV::FlagNSW);
482 else
483 RHS = getAddExpr(sv, SCEV::FlagNUW);
484 }
485#if LLVM_VERSION_MAJOR >= 24
486 ExitLimit EL = ScalarEvolution::howManyLessThans(
487 LHS, RHS, L, IsSigned, /*Invert=*/true, ControlsExit, AllowPredicates);
488#else
489 ExitLimit EL = howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
490 AllowPredicates);
491#endif
492 if (EL.hasAnyInfo())
493 return EL;
494 break;
495 }
496 default:
497 break;
498 }
499
500 auto *ExhaustiveCount = computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
501
502 if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
503 return ExhaustiveCount;
504
505 return computeShiftCompareExitLimit(ExitCond->getOperand(0),
506 ExitCond->getOperand(1), L, OriginalPred);
507}
508
509#if LLVM_VERSION_MAJOR >= 13
510static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
511 ICmpInst::Predicate *Pred,
512 ScalarEvolution *SE) {
513 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
514 if (SE->isKnownPositive(Step)) {
515 *Pred = ICmpInst::ICMP_SLT;
516 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
517 SE->getSignedRangeMax(Step));
518 }
519 if (SE->isKnownNegative(Step)) {
520 *Pred = ICmpInst::ICMP_SGT;
521 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
522 SE->getSignedRangeMin(Step));
523 }
524 return nullptr;
525}
526static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
527 ICmpInst::Predicate *Pred,
528 ScalarEvolution *SE) {
529 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
530 *Pred = ICmpInst::ICMP_ULT;
531
532 return SE->getConstant(APInt::getMinValue(BitWidth) -
533 SE->getUnsignedRangeMax(Step));
534}
535
536// The type of SCEV's wrap flags: SCEVWrapFlags, SCEVNoWrapFlags or
537// SCEVFlags, depending on the LLVM version. Taken from a flag constant, which
538// all versions provide, rather than from an LLVM version check, as the type
539// was renamed several times during LLVM 24's development.
540using WrapFlagsTy = std::remove_cv_t<decltype(SCEV::FlagNSW)>;
541
542namespace {
543
544struct ExtendOpTraitsBase {
545#if LLVM_VERSION_MAJOR >= 24
546 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(SCEVUse, Type *,
547 unsigned);
548#else
549 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
550 unsigned);
551#endif
552};
553
554// Used to make code generic over signed and unsigned overflow.
555template <typename ExtendOp> struct ExtendOpTraits {
556 // Members present:
557 //
558 // static const WrapFlagsTy WrapType;
559 //
560 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
561 //
562 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
563 // ICmpInst::Predicate *Pred,
564 // ScalarEvolution *SE);
565};
566
567template <>
568struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
569 static const WrapFlagsTy WrapType = SCEV::FlagNSW;
570
571 static const GetExtendExprTy GetExtendExpr;
572
573 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
574 ICmpInst::Predicate *Pred,
575 ScalarEvolution *SE) {
576 return getSignedOverflowLimitForStep(Step, Pred, SE);
577 }
578};
579
580const ExtendOpTraitsBase::GetExtendExprTy
581 ExtendOpTraits<SCEVSignExtendExpr>::GetExtendExpr =
582 &ScalarEvolution::getSignExtendExpr;
583
584template <>
585struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
586 static const WrapFlagsTy WrapType = SCEV::FlagNUW;
587
588 static const GetExtendExprTy GetExtendExpr;
589
590 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
591 ICmpInst::Predicate *Pred,
592 ScalarEvolution *SE) {
593 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
594 }
595};
596
597const ExtendOpTraitsBase::GetExtendExprTy
598 ExtendOpTraits<SCEVZeroExtendExpr>::GetExtendExpr =
599 &ScalarEvolution::getZeroExtendExpr;
600
601} // end anonymous namespace
602
603static bool hasFlags(WrapFlagsTy Flags, WrapFlagsTy TestFlags) {
604 return TestFlags == ScalarEvolution::maskFlags(Flags, TestFlags);
605};
606
607template <typename ExtendOpTy>
608static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
609 ScalarEvolution *SE, unsigned Depth) {
610 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
611 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
612
613 const Loop *L = AR->getLoop();
614 const SCEV *Start = AR->getStart();
615 const SCEV *Step = AR->getStepRecurrence(*SE);
616
617 // Check for a simple looking step prior to loop entry.
618 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
619 if (!SA)
620 return nullptr;
621
622 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
623 // subtraction is expensive. For this purpose, perform a quick and dirty
624 // difference, by checking for Step in the operand list.
625 SmallVector<SCEVUse, 4> DiffOps;
626 for (const SCEV *Op : SA->operands())
627 if (Op != Step)
628 DiffOps.push_back(Op);
629
630 if (DiffOps.size() == SA->getNumOperands())
631 return nullptr;
632
633 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
634 // `Step`:
635
636 // 1. NSW/NUW flags on the step increment.
637 auto PreStartFlags =
638 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
639 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
640 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
641#if LLVM_VERSION_MAJOR >= 24
642 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagNone));
643#else
644 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
645#endif
646
647 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
648 // "S+X does not sign/unsign-overflow".
649 //
650
651 const SCEV *BECount = SE->getBackedgeTakenCount(L);
652#if LLVM_VERSION_MAJOR >= 23
653 if (PreAR && any(PreAR->getNoWrapFlags(WrapType)) &&
654 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
655 return PreStart;
656#else
657 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
658 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
659 return PreStart;
660#endif
661
662 // 2. Direct overflow check on the step operation's expression.
663 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
664 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
665 const SCEV *OperandExtendedStart =
666 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
667 (SE->*GetExtendExpr)(Step, WideTy, Depth));
668 if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
669#if LLVM_VERSION_MAJOR >= 23
670 if (PreAR && any(AR->getNoWrapFlags(WrapType)))
671#else
672 if (PreAR && AR->getNoWrapFlags(WrapType))
673#endif
674 {
675 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
676 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
677 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
678 SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
679 }
680 return PreStart;
681 }
682
683 // 3. Loop precondition.
684 ICmpInst::Predicate Pred;
685 const SCEV *OverflowLimit =
686 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
687
688 if (OverflowLimit &&
689 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
690 return PreStart;
691
692 return nullptr;
693}
694
695template <typename ExtendOpTy>
696static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
697 ScalarEvolution *SE, unsigned Depth) {
698 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
699
700 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
701 if (!PreStart)
702 return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
703
704 return SE->getAddExpr(
705 (SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty, Depth),
706 (SE->*GetExtendExpr)(PreStart, Ty, Depth));
707}
708
709static WrapFlagsTy StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
710 const ArrayRef<const SCEV *> Ops,
711 WrapFlagsTy Flags) {
712 using namespace std::placeholders;
713
714 using OBO = OverflowingBinaryOperator;
715
716 bool CanAnalyze =
717 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
718 (void)CanAnalyze;
719 assert(CanAnalyze && "don't call from other places!");
720
721 auto SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
722 WrapFlagsTy SignOrUnsignWrap =
723 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
724
725 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
726 auto IsKnownNonNegative = [&](const SCEV *S) {
727 return SE->isKnownNonNegative(S);
728 };
729
730 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
731 Flags = ScalarEvolution::setFlags(Flags, (WrapFlagsTy)SignOrUnsignMask);
732
733 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
734
735 if (SignOrUnsignWrap != SignOrUnsignMask &&
736 (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
737 isa<SCEVConstant>(Ops[0])) {
738
739 auto Opcode = [&] {
740 switch (Type) {
741 case scAddExpr:
742 return Instruction::Add;
743 case scMulExpr:
744 return Instruction::Mul;
745 default:
746 llvm_unreachable("Unexpected SCEV op.");
747 }
748 }();
749
750 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
751
752 // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
753 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
754 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
755 Opcode, C, OBO::NoSignedWrap);
756 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
757 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
758 }
759
760 // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
761 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
762 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
763 Opcode, C, OBO::NoUnsignedWrap);
764 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
765 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
766 }
767 }
768
769 // <0,+,nonnegative><nw> is also nuw
770 // TODO: Add corresponding nsw case
771 if (Type == scAddRecExpr && hasFlags(Flags, SCEV::FlagNW) &&
772 !hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 && Ops[0]->isZero() &&
773 IsKnownNonNegative(Ops[1]))
774 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
775
776 // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
777 if (Type == scMulExpr && !hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2) {
778 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
779 if (UDiv->getOperand(1) == Ops[1])
780 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
781 if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
782 if (UDiv->getOperand(1) == Ops[0])
783 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
784 }
785
786 return Flags;
787}
788
789ScalarEvolution::ExitLimit MustExitScalarEvolution::howManyLessThans(
790 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
791 bool ControlsExit, bool AllowPredicates) {
792#if LLVM_VERSION_MAJOR >= 20
793 SmallVector<const SCEVPredicate *, 4> Predicates;
794#else
795 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
796#endif
797
798 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
799 bool PredicatedIV = false;
800
801 auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
802 // Can we prove this loop *must* be UB if overflow of IV occurs?
803 // Reasoning goes as follows:
804 // * Suppose the IV did self wrap.
805 // * If Stride evenly divides the iteration space, then once wrap
806 // occurs, the loop must revisit the same values.
807 // * We know that RHS is invariant, and that none of those values
808 // caused this exit to be taken previously. Thus, this exit is
809 // dynamically dead.
810 // * If this is the sole exit, then a dead exit implies the loop
811 // must be infinite if there are no abnormal exits.
812 // * If the loop were infinite, then it must either not be mustprogress
813 // or have side effects. Otherwise, it must be UB.
814 // * It can't (by assumption), be UB so we have contradicted our
815 // premise and can conclude the IV did not in fact self-wrap.
816 if (!isLoopInvariant(RHS, L))
817 return false;
818
819 auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
820 if (!StrideC || !StrideC->getAPInt().isPowerOf2())
821 return false;
822
823 if (!ControlsExit || !loopHasNoAbnormalExits(L))
824 return false;
825
826 return loopIsFiniteByAssumption(L);
827 };
828
829 if (!IV) {
830 if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
831 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
832 if (AR && AR->getLoop() == L && AR->isAffine()) {
833 auto Flags = AR->getNoWrapFlags();
834 if (!hasFlags(Flags, SCEV::FlagNW) && canAssumeNoSelfWrap(AR)) {
835 Flags = setFlags(Flags, SCEV::FlagNW);
836
837 SmallVector<const SCEV *, 4> Operands{AR->operands()};
838 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
839
840 setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
841 }
842 if (AR->hasNoUnsignedWrap()) {
843 // Emulate what getZeroExtendExpr would have done during construction
844 // if we'd been able to infer the fact just above at that time.
845 const SCEV *Step = AR->getStepRecurrence(*this);
846 Type *Ty = ZExt->getType();
847 auto S = getAddRecExpr(
848 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
849 getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
850 IV = dyn_cast<SCEVAddRecExpr>(S);
851 }
852 }
853 }
854 }
855
856 if (!IV && AllowPredicates) {
857 // Try to make this an AddRec using runtime tests, in the first X
858 // iterations of this loop, where X is the SCEV expression found by the
859 // algorithm below.
860 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
861 PredicatedIV = true;
862 }
863
864 // Avoid weird loops
865 if (!IV || IV->getLoop() != L || !IV->isAffine())
866 return getCouldNotCompute();
867
868 // A precondition of this method is that the condition being analyzed
869 // reaches an exiting branch which dominates the latch. Given that, we can
870 // assume that an increment which violates the nowrap specification and
871 // produces poison must cause undefined behavior when the resulting poison
872 // value is branched upon and thus we can conclude that the backedge is
873 // taken no more often than would be required to produce that poison value.
874 // Note that a well defined loop can exit on the iteration which violates
875 // the nowrap specification if there is another exit (either explicit or
876 // implicit/exceptional) which causes the loop to execute before the
877 // exiting instruction we're analyzing would trigger UB.
878 auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
879
880#if LLVM_VERSION_MAJOR >= 23
881 bool NoWrap = ControlsExit && any(IV->getNoWrapFlags(WrapType));
882#else
883 bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
884#endif
885
886 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
887
888 const SCEV *Stride = IV->getStepRecurrence(*this);
889
890 bool PositiveStride = isKnownPositive(Stride);
891
892 // Avoid negative or zero stride values.
893 if (!PositiveStride) {
894 // We can compute the correct backedge taken count for loops with unknown
895 // strides if we can prove that the loop is not an infinite loop with side
896 // effects. Here's the loop structure we are trying to handle -
897 //
898 // i = start
899 // do {
900 // A[i] = i;
901 // i += s;
902 // } while (i < end);
903 //
904 // The backedge taken count for such loops is evaluated as -
905 // (max(end, start + stride) - start - 1) /u stride
906 //
907 // The additional preconditions that we need to check to prove correctness
908 // of the above formula is as follows -
909 //
910 // a) IV is either nuw or nsw depending upon signedness (indicated by the
911 // NoWrap flag).
912 // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
913 // no side effects within the loop)
914 // c) loop has a single static exit (with no abnormal exits)
915 //
916 // Precondition a) implies that if the stride is negative, this is a single
917 // trip loop. The backedge taken count formula reduces to zero in this case.
918 //
919 // Precondition b) and c) combine to imply that if rhs is invariant in L,
920 // then a zero stride means the backedge can't be taken without executing
921 // undefined behavior.
922 //
923 // The positive stride case is the same as isKnownPositive(Stride) returning
924 // true (original behavior of the function).
925 //
926 if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
927 !loopHasNoAbnormalExits(L)) {
928 return getCouldNotCompute();
929 }
930
931 // This bailout is protecting the logic in computeMaxBECountForLT which
932 // has not yet been sufficiently auditted or tested with negative strides.
933 // We used to filter out all known-non-positive cases here, we're in the
934 // process of being less restrictive bit by bit.
935 if (IsSigned && isKnownNonPositive(Stride))
936 return getCouldNotCompute();
937
938 if (!isKnownNonZero(Stride)) {
939 // If we have a step of zero, and RHS isn't invariant in L, we don't know
940 // if it might eventually be greater than start and if so, on which
941 // iteration. We can't even produce a useful upper bound.
942 if (!isLoopInvariant(RHS, L))
943 return getCouldNotCompute();
944
945 // We allow a potentially zero stride, but we need to divide by stride
946 // below. Since the loop can't be infinite and this check must control
947 // the sole exit, we can infer the exit must be taken on the first
948 // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
949 // we know the numerator in the divides below must be zero, so we can
950 // pick an arbitrary non-zero value for the denominator (e.g. stride)
951 // and produce the right result.
952 // FIXME: Handle the case where Stride is poison?
953 auto wouldZeroStrideBeUB = [&]() {
954 // Proof by contradiction. Suppose the stride were zero. If we can
955 // prove that the backedge *is* taken on the first iteration, then since
956 // we know this condition controls the sole exit, we must have an
957 // infinite loop. We can't have a (well defined) infinite loop per
958 // check just above.
959 // Note: The (Start - Stride) term is used to get the start' term from
960 // (start' + stride,+,stride). Remember that we only care about the
961 // result of this expression when stride == 0 at runtime.
962 auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
963 return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
964 };
965 if (!wouldZeroStrideBeUB()) {
966 Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
967 }
968 }
969 } else if (!Stride->isOne() && !NoWrap) {
970 auto isUBOnWrap = [&]() {
971 // From no-self-wrap, we need to then prove no-(un)signed-wrap. This
972 // follows trivially from the fact that every (un)signed-wrapped, but
973 // not self-wrapped value must be LT than the last value before
974 // (un)signed wrap. Since we know that last value didn't exit, nor
975 // will any smaller one.
976 return canAssumeNoSelfWrap(IV);
977 };
978
979 // Avoid proven overflow cases: this will ensure that the backedge taken
980 // count will not generate any unsigned overflow. Relaxed no-overflow
981 // conditions exploit NoWrapFlags, allowing to optimize in presence of
982 // undefined behaviors like the case of C language.
983 if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
984 return getCouldNotCompute();
985 }
986
987 // On all paths just preceding, we established the following invariant:
988 // IV can be assumed not to overflow up to and including the exiting
989 // iteration. We proved this in one of two ways:
990 // 1) We can show overflow doesn't occur before the exiting iteration
991 // 1a) canIVOverflowOnLT, and b) step of one
992 // 2) We can show that if overflow occurs, the loop must execute UB
993 // before any possible exit.
994 // Note that we have not yet proved RHS invariant (in general).
995
996 const SCEV *Start = IV->getStart();
997
998 // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
999 // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
1000 // Use integer-typed versions for actual computation; we can't subtract
1001 // pointers in general.
1002 const SCEV *OrigStart = Start;
1003 const SCEV *OrigRHS = RHS;
1004#if LLVM_VERSION_MAJOR >= 24
1005 if (Start->getType()->isPointerTy()) {
1006 Start = getPtrToAddrExpr(Start);
1007 if (isa<SCEVCouldNotCompute>(Start))
1008 return Start;
1009 }
1010 if (RHS->getType()->isPointerTy()) {
1011 RHS = getPtrToAddrExpr(RHS);
1012 if (isa<SCEVCouldNotCompute>(RHS))
1013 return RHS;
1014 }
1015#else
1016 if (Start->getType()->isPointerTy()) {
1017 Start = getLosslessPtrToIntExpr(Start);
1018 if (isa<SCEVCouldNotCompute>(Start))
1019 return Start;
1020 }
1021 if (RHS->getType()->isPointerTy()) {
1022 RHS = getLosslessPtrToIntExpr(RHS);
1023 if (isa<SCEVCouldNotCompute>(RHS))
1024 return RHS;
1025 }
1026#endif
1027
1028 // When the RHS is not invariant, we do not know the end bound of the loop and
1029 // cannot calculate the ExactBECount needed by ExitLimit. However, we can
1030 // calculate the MaxBECount, given the start, stride and max value for the end
1031 // bound of the loop (RHS), and the fact that IV does not overflow (which is
1032 // checked above).
1033 if (!isLoopInvariant(RHS, L)) {
1034#if LLVM_VERSION_MAJOR >= 24
1035 const SCEV *MaxBECount = computeMaxBECountForLT(
1036 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned,
1037 /*Invert=*/false);
1038#else
1039 const SCEV *MaxBECount = computeMaxBECountForLT(
1040 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
1041#endif
1042#if LLVM_VERSION_MAJOR >= 16
1043 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
1044 MaxBECount, false /*MaxOrZero*/, Predicates);
1045#else
1046 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
1047 false /*MaxOrZero*/, Predicates);
1048#endif
1049 }
1050
1051 // We use the expression (max(End,Start)-Start)/Stride to describe the
1052 // backedge count, as if the backedge is taken at least once max(End,Start)
1053 // is End and so the result is as above, and if not max(End,Start) is Start
1054 // so we get a backedge count of zero.
1055 const SCEV *BECount = nullptr;
1056 auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
1057 assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
1058 assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
1059 assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
1060 // Can we prove (max(RHS,Start) > Start - Stride?
1061 if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
1062 isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
1063 // In this case, we can use a refined formula for computing backedge taken
1064 // count. The general formula remains:
1065 // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
1066 // We want to use the alternate formula:
1067 // "((End - 1) - (Start - Stride)) /u Stride"
1068 // Let's do a quick case analysis to show these are equivalent under
1069 // our precondition that max(RHS,Start) > Start - Stride.
1070 // * For RHS <= Start, the backedge-taken count must be zero.
1071 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
1072 // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
1073 // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
1074 // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing
1075 // this to the stride of 1 case.
1076 // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
1077 // "((End - 1) - (Start - Stride)) /u Stride" reduces to
1078 // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
1079 // "((RHS - (Start - Stride) - 1) /u Stride".
1080 // Our preconditions trivially imply no overflow in that form.
1081 const SCEV *MinusOne = getMinusOne(Stride->getType());
1082 const SCEV *Numerator =
1083 getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
1084 BECount = getUDivExpr(Numerator, Stride);
1085 }
1086
1087 const SCEV *BECountIfBackedgeTaken = nullptr;
1088 if (!BECount) {
1089 auto canProveRHSGreaterThanEqualStart = [&]() {
1090 auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1091 if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
1092 return true;
1093
1094 // (RHS > Start - 1) implies RHS >= Start.
1095 // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
1096 // "Start - 1" doesn't overflow.
1097 // * For signed comparison, if Start - 1 does overflow, it's equal
1098 // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
1099 // * For unsigned comparison, if Start - 1 does overflow, it's equal
1100 // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
1101 //
1102 // FIXME: Should isLoopEntryGuardedByCond do this for us?
1103 auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1104 auto StartMinusOne =
1105 getAddExpr(OrigStart, getMinusOne(OrigStart->getType()));
1106 return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
1107 };
1108
1109 // If we know that RHS >= Start in the context of loop, then we know that
1110 // max(RHS, Start) = RHS at this point.
1111 const SCEV *End;
1112 if (canProveRHSGreaterThanEqualStart()) {
1113 End = RHS;
1114 } else {
1115 // If RHS < Start, the backedge will be taken zero times. So in
1116 // general, we can write the backedge-taken count as:
1117 //
1118 // RHS >= Start ? ceil(RHS - Start) / Stride : 0
1119 //
1120 // We convert it to the following to make it more convenient for SCEV:
1121 //
1122 // ceil(max(RHS, Start) - Start) / Stride
1123 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
1124
1125 // See what would happen if we assume the backedge is taken. This is
1126 // used to compute MaxBECount.
1127 BECountIfBackedgeTaken =
1128 getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
1129 }
1130
1131 // At this point, we know:
1132 //
1133 // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
1134 // 2. The index variable doesn't overflow.
1135 //
1136 // Therefore, we know N exists such that
1137 // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
1138 // doesn't overflow.
1139 //
1140 // Using this information, try to prove whether the addition in
1141 // "(Start - End) + (Stride - 1)" has unsigned overflow.
1142 const SCEV *One = getOne(Stride->getType());
1143 bool MayAddOverflow = [&] {
1144 if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
1145 if (StrideC->getAPInt().isPowerOf2()) {
1146 // Suppose Stride is a power of two, and Start/End are unsigned
1147 // integers. Let UMAX be the largest representable unsigned
1148 // integer.
1149 //
1150 // By the preconditions of this function, we know
1151 // "(Start + Stride * N) >= End", and this doesn't overflow.
1152 // As a formula:
1153 //
1154 // End <= (Start + Stride * N) <= UMAX
1155 //
1156 // Subtracting Start from all the terms:
1157 //
1158 // End - Start <= Stride * N <= UMAX - Start
1159 //
1160 // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
1161 //
1162 // End - Start <= Stride * N <= UMAX
1163 //
1164 // Stride * N is a multiple of Stride. Therefore,
1165 //
1166 // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
1167 //
1168 // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
1169 // Therefore, UMAX mod Stride == Stride - 1. So we can write:
1170 //
1171 // End - Start <= Stride * N <= UMAX - Stride - 1
1172 //
1173 // Dropping the middle term:
1174 //
1175 // End - Start <= UMAX - Stride - 1
1176 //
1177 // Adding Stride - 1 to both sides:
1178 //
1179 // (End - Start) + (Stride - 1) <= UMAX
1180 //
1181 // In other words, the addition doesn't have unsigned overflow.
1182 //
1183 // A similar proof works if we treat Start/End as signed values.
1184 // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
1185 // use signed max instead of unsigned max. Note that we're trying
1186 // to prove a lack of unsigned overflow in either case.
1187 return false;
1188 }
1189 }
1190 if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
1191 // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
1192 // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
1193 // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
1194 //
1195 // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
1196 return false;
1197 }
1198 return true;
1199 }();
1200
1201 const SCEV *Delta = getMinusSCEV(End, Start);
1202 if (!MayAddOverflow) {
1203 // floor((D + (S - 1)) / S)
1204 // We prefer this formulation if it's legal because it's fewer operations.
1205 BECount =
1206 getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
1207 } else {
1208 BECount = getUDivCeilSCEV(Delta, Stride);
1209 }
1210 }
1211
1212 const SCEV *MaxBECount;
1213 bool MaxOrZero = false;
1214 if (isa<SCEVConstant>(BECount)) {
1215 MaxBECount = BECount;
1216 } else if (BECountIfBackedgeTaken &&
1217 isa<SCEVConstant>(BECountIfBackedgeTaken)) {
1218 // If we know exactly how many times the backedge will be taken if it's
1219 // taken at least once, then the backedge count will either be that or
1220 // zero.
1221 MaxBECount = BECountIfBackedgeTaken;
1222 MaxOrZero = true;
1223 } else {
1224#if LLVM_VERSION_MAJOR >= 24
1225 MaxBECount = computeMaxBECountForLT(
1226 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned,
1227 /*Invert=*/false);
1228#else
1229 MaxBECount = computeMaxBECountForLT(
1230 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
1231#endif
1232 }
1233
1234 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
1235 !isa<SCEVCouldNotCompute>(BECount))
1236 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
1237#if LLVM_VERSION_MAJOR >= 16
1238 return ExitLimit(BECount, MaxBECount, MaxBECount, MaxOrZero, Predicates);
1239#else
1240 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
1241#endif
1242}
1243#else
1245 const SCEV *LHS, const SCEV *RHS, const Loop *L, bool IsSigned,
1246 bool ControlsExit, bool AllowPredicates) {
1247 SmallPtrSet<const SCEVPredicate *, 4> Predicates;
1248
1249 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
1250
1251 if (!IV && AllowPredicates) {
1252 // Try to make this an AddRec using runtime tests, in the first X
1253 // iterations of this loop, where X is the SCEV expression found by the
1254 // algorithm below.
1255 IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
1256 }
1257
1258 // Avoid weird loops
1259 if (!IV || IV->getLoop() != L || !IV->isAffine())
1260 return getCouldNotCompute();
1261
1262 bool NoWrap = ControlsExit && true; // changed this to assume no wrap for inc
1263 // IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
1264
1265 const SCEV *Stride = IV->getStepRecurrence(*this);
1266
1267 bool PositiveStride = isKnownPositive(Stride);
1268
1269 // Avoid negative or zero stride values.
1270 if (!PositiveStride) {
1271 // We can compute the correct backedge taken count for loops with unknown
1272 // strides if we can prove that the loop is not an infinite loop with side
1273 // effects. Here's the loop structure we are trying to handle -
1274 //
1275 // i = start
1276 // do {
1277 // A[i] = i;
1278 // i += s;
1279 // } while (i < end);
1280 //
1281 // The backedge taken count for such loops is evaluated as -
1282 // (max(end, start + stride) - start - 1) /u stride
1283 //
1284 // The additional preconditions that we need to check to prove correctness
1285 // of the above formula is as follows -
1286 //
1287 // a) IV is either nuw or nsw depending upon signedness (indicated by the
1288 // NoWrap flag).
1289 // b) loop is single exit with no side effects. // dont need this
1290 //
1291 //
1292 // Precondition a) implies that if the stride is negative, this is a single
1293 // trip loop. The backedge taken count formula reduces to zero in this case.
1294 //
1295 // Precondition b) implies that the unknown stride cannot be zero otherwise
1296 // we have UB.
1297 //
1298 // The positive stride case is the same as isKnownPositive(Stride) returning
1299 // true (original behavior of the function).
1300 //
1301 // We want to make sure that the stride is truly unknown as there are edge
1302 // cases where ScalarEvolution propagates no wrap flags to the
1303 // post-increment/decrement IV even though the increment/decrement operation
1304 // itself is wrapping. The computed backedge taken count may be wrong in
1305 // such cases. This is prevented by checking that the stride is not known to
1306 // be either positive or non-positive. For example, no wrap flags are
1307 // propagated to the post-increment IV of this loop with a trip count of 2 -
1308 //
1309 // unsigned char i;
1310 // for(i=127; i<128; i+=129)
1311 // A[i] = i;
1312 //
1313 if (!NoWrap) // THIS LINE CHANGED
1314 return getCouldNotCompute();
1315 } else if (!Stride->isOne() &&
1316 doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
1317 // Avoid proven overflow cases: this will ensure that the backedge taken
1318 // count will not generate any unsigned overflow. Relaxed no-overflow
1319 // conditions exploit NoWrapFlags, allowing to optimize in presence of
1320 // undefined behaviors like the case of C language.
1321 return getCouldNotCompute();
1322
1323 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1324 const SCEV *Start = IV->getStart();
1325 const SCEV *End = RHS;
1326 // When the RHS is not invariant, we do not know the end bound of the loop and
1327 // cannot calculate the ExactBECount needed by ExitLimit. However, we can
1328 // calculate the MaxBECount, given the start, stride and max value for the end
1329 // bound of the loop (RHS), and the fact that IV does not overflow (which is
1330 // checked above).
1331 if (!isLoopInvariant(RHS, L)) {
1332 const SCEV *MaxBECount = computeMaxBECountForLT(
1333 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
1334 return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
1335 false /*MaxOrZero*/, Predicates);
1336 }
1337 // If the backedge is taken at least once, then it will be taken
1338 // (End-Start)/Stride times (rounded up to a multiple of Stride), where Start
1339 // is the LHS value of the less-than comparison the first time it is evaluated
1340 // and End is the RHS.
1341 const SCEV *BECountIfBackedgeTaken =
1342 computeBECount(getMinusSCEV(End, Start), Stride, false);
1343 // If the loop entry is guarded by the result of the backedge test of the
1344 // first loop iteration, then we know the backedge will be taken at least
1345 // once and so the backedge taken count is as above. If not then we use the
1346 // expression (max(End,Start)-Start)/Stride to describe the backedge count,
1347 // as if the backedge is taken at least once max(End,Start) is End and so the
1348 // result is as above, and if not max(End,Start) is Start so we get a backedge
1349 // count of zero.
1350 const SCEV *BECount;
1351 if (isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
1352 BECount = BECountIfBackedgeTaken;
1353 else {
1354 End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
1355 BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
1356 }
1357
1358 const SCEV *MaxBECount;
1359 bool MaxOrZero = false;
1360 if (isa<SCEVConstant>(BECount))
1361 MaxBECount = BECount;
1362 else if (isa<SCEVConstant>(BECountIfBackedgeTaken)) {
1363 // If we know exactly how many times the backedge will be taken if it's
1364 // taken at least once, then the backedge count will either be that or
1365 // zero.
1366 MaxBECount = BECountIfBackedgeTaken;
1367 MaxOrZero = true;
1368 } else {
1369 MaxBECount = computeMaxBECountForLT(
1370 Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
1371 }
1372
1373 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
1374 !isa<SCEVCouldNotCompute>(BECount))
1375 MaxBECount = getConstant(getUnsignedRangeMax(BECount));
1376
1377 return ExitLimit(BECount, MaxBECount, MaxOrZero, Predicates);
1378}
1379
1380#ifdef __clang__
1381#pragma clang diagnostic pop
1382#else
1383#pragma GCC diagnostic pop
1384#endif
1385
1386#endif
static llvm::SmallPtrSet< llvm::BasicBlock *, 4 > getGuaranteedUnreachable(llvm::Function *F)
#define PROP_PHI(LHS)
#define SCEVUse
static bool isConditionalBranch(const llvm::Value *V)
Definition Utils.h:65
static llvm::Value * getBranchCondition(llvm::Value *V)
The condition of a branch isConditionalBranch says yes to.
Definition Utils.h:100
static bool isAnyBranch(const llvm::Value *V)
Definition Utils.h:57
ScalarEvolution::ExitLimit howManyLessThans(const llvm::SCEV *LHS, const llvm::SCEV *RHS, const llvm::Loop *L, bool IsSigned, bool ControlsExit, bool AllowPredicates)
llvm::SmallPtrSet< llvm::BasicBlock *, 4 > GuaranteedUnreachable
ScalarEvolution::ExitLimit computeExitLimitFromICmp(const llvm::Loop *L, llvm::ICmpInst *ExitCond, bool ExitIfTrue, bool ControlsExit, bool AllowPredicates=false)
ScalarEvolution::ExitLimit computeExitLimitFromCond(const llvm::Loop *L, llvm::Value *ExitCond, bool ExitIfTrue, bool ControlsExit, bool AllowPredicates)
ScalarEvolution::ExitLimit computeExitLimitFromSingleExitSwitch(const llvm::Loop *L, llvm::SwitchInst *Switch, llvm::BasicBlock *ExitingBB, bool IsSubExpr)
ScalarEvolution::ExitLimit computeExitLimit(const llvm::Loop *L, llvm::BasicBlock *ExitingBlock, bool AllowPredicates)
ScalarEvolution::ExitLimit computeExitLimitFromCondCached(ExitLimitCacheTy &Cache, const llvm::Loop *L, llvm::Value *ExitCond, bool ExitIfTrue, bool ControlsExit, bool AllowPredicates)
ScalarEvolution::ExitLimit computeExitLimitFromCondImpl(ExitLimitCacheTy &Cache, const llvm::Loop *L, llvm::Value *ExitCond, bool ExitIfTrue, bool ControlsExit, bool AllowPredicates)
MustExitScalarEvolution(llvm::Function &F, llvm::TargetLibraryInfo &TLI, llvm::AssumptionCache &AC, llvm::DominatorTree &DT, llvm::LoopInfo &LI)
bool loopIsFiniteByAssumption(const llvm::Loop *L)