1//===- InductiveRangeCheckElimination.cpp - -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// The InductiveRangeCheckElimination pass splits a loop's iteration space into
10// three disjoint ranges. It does that in a way such that the loop running in
11// the middle loop provably does not need range checks. As an example, it will
12// convert
13//
14// len = < known positive >
15// for (i = 0; i < n; i++) {
16// if (0 <= i && i < len) {
17// do_something();
18// } else {
19// throw_out_of_bounds();
20// }
21// }
22//
23// to
24//
25// len = < known positive >
26// limit = smin(n, len)
27// // no first segment
28// for (i = 0; i < limit; i++) {
29// if (0 <= i && i < len) { // this check is fully redundant
30// do_something();
31// } else {
32// throw_out_of_bounds();
33// }
34// }
35// for (i = limit; i < n; i++) {
36// if (0 <= i && i < len) {
37// do_something();
38// } else {
39// throw_out_of_bounds();
40// }
41// }
42//
43//===----------------------------------------------------------------------===//
44
45#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
46#include "llvm/ADT/APInt.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/PriorityWorklist.h"
49#include "llvm/ADT/SmallPtrSet.h"
50#include "llvm/ADT/SmallVector.h"
51#include "llvm/ADT/StringRef.h"
52#include "llvm/ADT/Twine.h"
53#include "llvm/Analysis/BlockFrequencyInfo.h"
54#include "llvm/Analysis/BranchProbabilityInfo.h"
55#include "llvm/Analysis/CycleAnalysis.h"
56#include "llvm/Analysis/LoopAnalysisManager.h"
57#include "llvm/Analysis/LoopInfo.h"
58#include "llvm/Analysis/ScalarEvolution.h"
59#include "llvm/Analysis/ScalarEvolutionExpressions.h"
60#include "llvm/IR/BasicBlock.h"
61#include "llvm/IR/CFG.h"
62#include "llvm/IR/Constants.h"
63#include "llvm/IR/DerivedTypes.h"
64#include "llvm/IR/Dominators.h"
65#include "llvm/IR/Function.h"
66#include "llvm/IR/IRBuilder.h"
67#include "llvm/IR/InstrTypes.h"
68#include "llvm/IR/Instructions.h"
69#include "llvm/IR/Metadata.h"
70#include "llvm/IR/Module.h"
71#include "llvm/IR/PatternMatch.h"
72#include "llvm/IR/Type.h"
73#include "llvm/IR/Use.h"
74#include "llvm/IR/User.h"
75#include "llvm/IR/Value.h"
76#include "llvm/Support/BranchProbability.h"
77#include "llvm/Support/Casting.h"
78#include "llvm/Support/CommandLine.h"
79#include "llvm/Support/Compiler.h"
80#include "llvm/Support/Debug.h"
81#include "llvm/Support/ErrorHandling.h"
82#include "llvm/Support/raw_ostream.h"
83#include "llvm/Transforms/Utils/BasicBlockUtils.h"
84#include "llvm/Transforms/Utils/Cloning.h"
85#include "llvm/Transforms/Utils/LoopConstrainer.h"
86#include "llvm/Transforms/Utils/LoopSimplify.h"
87#include "llvm/Transforms/Utils/LoopUtils.h"
88#include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
89#include "llvm/Transforms/Utils/ValueMapper.h"
90#include <algorithm>
91#include <cassert>
92#include <optional>
93#include <utility>
94
95using namespace llvm;
96using namespace llvm::PatternMatch;
97
98static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
99 cl::init(Val: 64));
100
101static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
102 cl::init(Val: false));
103
104static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
105 cl::init(Val: false));
106
107static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
108 cl::Hidden, cl::init(Val: false));
109
110static cl::opt<unsigned> MinEliminatedChecks("irce-min-eliminated-checks",
111 cl::Hidden, cl::init(Val: 10));
112
113static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
114 cl::Hidden, cl::init(Val: true));
115
116static cl::opt<bool> AllowNarrowLatchCondition(
117 "irce-allow-narrow-latch", cl::Hidden, cl::init(Val: true),
118 cl::desc("If set to true, IRCE may eliminate wide range checks in loops "
119 "with narrow latch condition."));
120
121static cl::opt<unsigned> MaxTypeSizeForOverflowCheck(
122 "irce-max-type-size-for-overflow-check", cl::Hidden, cl::init(Val: 32),
123 cl::desc(
124 "Maximum size of range check type for which can be produced runtime "
125 "overflow check of its limit's computation"));
126
127static cl::opt<bool>
128 PrintScaledBoundaryRangeChecks("irce-print-scaled-boundary-range-checks",
129 cl::Hidden, cl::init(Val: false));
130
131#define DEBUG_TYPE "irce"
132
133namespace {
134
135/// An inductive range check is conditional branch in a loop with a condition
136/// that is provably true for some contiguous range of values taken by the
137/// containing loop's induction variable.
138///
139class InductiveRangeCheck {
140
141 const SCEV *Begin = nullptr;
142 const SCEV *Step = nullptr;
143 const SCEV *End = nullptr;
144 Use *CheckUse = nullptr;
145
146 static bool parseRangeCheckICmp(Loop *L, ICmpInst *ICI, ScalarEvolution &SE,
147 const SCEVAddRecExpr *&Index,
148 const SCEV *&End);
149
150 static void
151 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
152 SmallVectorImpl<InductiveRangeCheck> &Checks,
153 SmallPtrSetImpl<Value *> &Visited);
154
155 static bool parseIvAgaisntLimit(Loop *L, Value *LHS, Value *RHS,
156 ICmpInst::Predicate Pred, ScalarEvolution &SE,
157 const SCEVAddRecExpr *&Index,
158 const SCEV *&End);
159
160 static bool reassociateSubLHS(Loop *L, Value *VariantLHS, Value *InvariantRHS,
161 ICmpInst::Predicate Pred, ScalarEvolution &SE,
162 const SCEVAddRecExpr *&Index, const SCEV *&End);
163
164public:
165 const SCEV *getBegin() const { return Begin; }
166 const SCEV *getStep() const { return Step; }
167 const SCEV *getEnd() const { return End; }
168
169 void print(raw_ostream &OS) const {
170 OS << "InductiveRangeCheck:\n";
171 OS << " Begin: ";
172 Begin->print(OS);
173 OS << " Step: ";
174 Step->print(OS);
175 OS << " End: ";
176 End->print(OS);
177 OS << "\n CheckUse: ";
178 getCheckUse()->getUser()->print(O&: OS);
179 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
180 }
181
182 LLVM_DUMP_METHOD
183 void dump() {
184 print(OS&: dbgs());
185 }
186
187 Use *getCheckUse() const { return CheckUse; }
188
189 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
190 /// R.getEnd() le R.getBegin(), then R denotes the empty range.
191
192 class Range {
193 const SCEV *Begin;
194 const SCEV *End;
195
196 public:
197 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
198 assert(Begin->getType() == End->getType() && "ill-typed range!");
199 }
200
201 Type *getType() const { return Begin->getType(); }
202 const SCEV *getBegin() const { return Begin; }
203 const SCEV *getEnd() const { return End; }
204 bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
205 if (Begin == End)
206 return true;
207 if (IsSigned)
208 return SE.isKnownPredicate(Pred: ICmpInst::ICMP_SGE, LHS: Begin, RHS: End);
209 else
210 return SE.isKnownPredicate(Pred: ICmpInst::ICMP_UGE, LHS: Begin, RHS: End);
211 }
212 };
213
214 /// This is the value the condition of the branch needs to evaluate to for the
215 /// branch to take the hot successor (see (1) above).
216 bool getPassingDirection() { return true; }
217
218 /// Computes a range for the induction variable (IndVar) in which the range
219 /// check is redundant and can be constant-folded away. The induction
220 /// variable is not required to be the canonical {0,+,1} induction variable.
221 std::optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
222 const SCEVAddRecExpr *IndVar,
223 bool IsLatchSigned) const;
224
225 /// Parse out a set of inductive range checks from \p BI and append them to \p
226 /// Checks.
227 ///
228 /// NB! There may be conditions feeding into \p BI that aren't inductive range
229 /// checks, and hence don't end up in \p Checks.
230 static void extractRangeChecksFromBranch(
231 CondBrInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI,
232 std::optional<uint64_t> EstimatedTripCount,
233 SmallVectorImpl<InductiveRangeCheck> &Checks, bool &Changed);
234};
235
236class InductiveRangeCheckElimination {
237 ScalarEvolution &SE;
238 BranchProbabilityInfo *BPI;
239 DominatorTree &DT;
240 LoopInfo &LI;
241
242 using GetBFIFunc = llvm::function_ref<llvm::BlockFrequencyInfo &()>;
243 GetBFIFunc GetBFI;
244
245 // Returns the estimated number of iterations based on block frequency info if
246 // available, or on branch probability info. Nullopt is returned if the number
247 // of iterations cannot be estimated.
248 std::optional<uint64_t> estimatedTripCount(const Loop &L);
249
250public:
251 InductiveRangeCheckElimination(ScalarEvolution &SE,
252 BranchProbabilityInfo *BPI, DominatorTree &DT,
253 LoopInfo &LI, GetBFIFunc GetBFI = nullptr)
254 : SE(SE), BPI(BPI), DT(DT), LI(LI), GetBFI(GetBFI) {}
255
256 bool run(Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop);
257};
258
259} // end anonymous namespace
260
261/// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
262/// be interpreted as a range check, return false. Otherwise set `Index` to the
263/// SCEV being range checked, and set `End` to the upper or lower limit `Index`
264/// is being range checked.
265bool InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
266 ScalarEvolution &SE,
267 const SCEVAddRecExpr *&Index,
268 const SCEV *&End) {
269 auto IsLoopInvariant = [&SE, L](Value *V) {
270 return SE.isLoopInvariant(S: SE.getSCEV(V), L);
271 };
272
273 ICmpInst::Predicate Pred = ICI->getPredicate();
274 Value *LHS = ICI->getOperand(i_nocapture: 0);
275 Value *RHS = ICI->getOperand(i_nocapture: 1);
276
277 if (!LHS->getType()->isIntegerTy())
278 return false;
279
280 // Canonicalize to the `Index Pred Invariant` comparison
281 if (IsLoopInvariant(LHS)) {
282 std::swap(a&: LHS, b&: RHS);
283 Pred = CmpInst::getSwappedPredicate(pred: Pred);
284 } else if (!IsLoopInvariant(RHS))
285 // Both LHS and RHS are loop variant
286 return false;
287
288 if (parseIvAgaisntLimit(L, LHS, RHS, Pred, SE, Index, End))
289 return true;
290
291 if (reassociateSubLHS(L, VariantLHS: LHS, InvariantRHS: RHS, Pred, SE, Index, End))
292 return true;
293
294 // TODO: support ReassociateAddLHS
295 return false;
296}
297
298// Try to parse range check in the form of "IV vs Limit"
299bool InductiveRangeCheck::parseIvAgaisntLimit(Loop *L, Value *LHS, Value *RHS,
300 ICmpInst::Predicate Pred,
301 ScalarEvolution &SE,
302 const SCEVAddRecExpr *&Index,
303 const SCEV *&End) {
304
305 auto SIntMaxSCEV = [&](Type *T) {
306 unsigned BitWidth = cast<IntegerType>(Val: T)->getBitWidth();
307 return SE.getConstant(Val: APInt::getSignedMaxValue(numBits: BitWidth));
308 };
309
310 const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Val: SE.getSCEV(V: LHS));
311 if (!AddRec)
312 return false;
313
314 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
315 // We can potentially do much better here.
316 // If we want to adjust upper bound for the unsigned range check as we do it
317 // for signed one, we will need to pick Unsigned max
318 switch (Pred) {
319 default:
320 return false;
321
322 case ICmpInst::ICMP_SGE:
323 if (match(V: RHS, P: m_ConstantInt<0>())) {
324 Index = AddRec;
325 End = SIntMaxSCEV(Index->getType());
326 return true;
327 }
328 return false;
329
330 case ICmpInst::ICMP_SGT:
331 if (match(V: RHS, P: m_ConstantInt<-1>())) {
332 Index = AddRec;
333 End = SIntMaxSCEV(Index->getType());
334 return true;
335 }
336 return false;
337
338 case ICmpInst::ICMP_SLT:
339 case ICmpInst::ICMP_ULT:
340 Index = AddRec;
341 End = SE.getSCEV(V: RHS);
342 return true;
343
344 case ICmpInst::ICMP_SLE:
345 case ICmpInst::ICMP_ULE:
346 const SCEV *One = SE.getOne(Ty: RHS->getType());
347 const SCEV *RHSS = SE.getSCEV(V: RHS);
348 bool Signed = Pred == ICmpInst::ICMP_SLE;
349 if (SE.willNotOverflow(BinOp: Instruction::BinaryOps::Add, Signed, LHS: RHSS, RHS: One)) {
350 Index = AddRec;
351 End = SE.getAddExpr(LHS: RHSS, RHS: One);
352 return true;
353 }
354 return false;
355 }
356
357 llvm_unreachable("default clause returns!");
358}
359
360// Try to parse range check in the form of "IV - Offset vs Limit" or "Offset -
361// IV vs Limit"
362bool InductiveRangeCheck::reassociateSubLHS(
363 Loop *L, Value *VariantLHS, Value *InvariantRHS, ICmpInst::Predicate Pred,
364 ScalarEvolution &SE, const SCEVAddRecExpr *&Index, const SCEV *&End) {
365 Value *LHS, *RHS;
366 if (!match(V: VariantLHS, P: m_Sub(L: m_Value(V&: LHS), R: m_Value(V&: RHS))))
367 return false;
368
369 const SCEV *IV = SE.getSCEV(V: LHS);
370 const SCEV *Offset = SE.getSCEV(V: RHS);
371 const SCEV *Limit = SE.getSCEV(V: InvariantRHS);
372
373 bool OffsetSubtracted = false;
374 if (SE.isLoopInvariant(S: IV, L))
375 // "Offset - IV vs Limit"
376 std::swap(a&: IV, b&: Offset);
377 else if (SE.isLoopInvariant(S: Offset, L))
378 // "IV - Offset vs Limit"
379 OffsetSubtracted = true;
380 else
381 return false;
382
383 const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Val: IV);
384 if (!AddRec)
385 return false;
386
387 // In order to turn "IV - Offset < Limit" into "IV < Limit + Offset", we need
388 // to be able to freely move values from left side of inequality to right side
389 // (just as in normal linear arithmetics). Overflows make things much more
390 // complicated, so we want to avoid this.
391 //
392 // Let's prove that the initial subtraction doesn't overflow with all IV's
393 // values from the safe range constructed for that check.
394 //
395 // [Case 1] IV - Offset < Limit
396 // It doesn't overflow if:
397 // SINT_MIN <= IV - Offset <= SINT_MAX
398 // In terms of scaled SINT we need to prove:
399 // SINT_MIN + Offset <= IV <= SINT_MAX + Offset
400 // Safe range will be constructed:
401 // 0 <= IV < Limit + Offset
402 // It means that 'IV - Offset' doesn't underflow, because:
403 // SINT_MIN + Offset < 0 <= IV
404 // and doesn't overflow:
405 // IV < Limit + Offset <= SINT_MAX + Offset
406 //
407 // [Case 2] Offset - IV > Limit
408 // It doesn't overflow if:
409 // SINT_MIN <= Offset - IV <= SINT_MAX
410 // In terms of scaled SINT we need to prove:
411 // -SINT_MIN >= IV - Offset >= -SINT_MAX
412 // Offset - SINT_MIN >= IV >= Offset - SINT_MAX
413 // Safe range will be constructed:
414 // 0 <= IV < Offset - Limit
415 // It means that 'Offset - IV' doesn't underflow, because
416 // Offset - SINT_MAX < 0 <= IV
417 // and doesn't overflow:
418 // IV < Offset - Limit <= Offset - SINT_MIN
419 //
420 // For the computed upper boundary of the IV's range (Offset +/- Limit) we
421 // don't know exactly whether it overflows or not. So if we can't prove this
422 // fact at compile time, we scale boundary computations to a wider type with
423 // the intention to add runtime overflow check.
424
425 auto getExprScaledIfOverflow = [&](Instruction::BinaryOps BinOp,
426 const SCEV *LHS,
427 const SCEV *RHS) -> const SCEV * {
428 const SCEV *(ScalarEvolution::*Operation)(SCEVUse, SCEVUse,
429 SCEV::NoWrapFlags, unsigned);
430 switch (BinOp) {
431 default:
432 llvm_unreachable("Unsupported binary op");
433 case Instruction::Add:
434 Operation = &ScalarEvolution::getAddExpr;
435 break;
436 case Instruction::Sub:
437 Operation = &ScalarEvolution::getMinusSCEV;
438 break;
439 }
440
441 if (SE.willNotOverflow(BinOp, Signed: ICmpInst::isSigned(Pred), LHS, RHS,
442 CtxI: cast<Instruction>(Val: VariantLHS)))
443 return (SE.*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0);
444
445 // We couldn't prove that the expression does not overflow.
446 // Than scale it to a wider type to check overflow at runtime.
447 auto *Ty = cast<IntegerType>(Val: LHS->getType());
448 if (Ty->getBitWidth() > MaxTypeSizeForOverflowCheck)
449 return nullptr;
450
451 auto WideTy = IntegerType::get(C&: Ty->getContext(), NumBits: Ty->getBitWidth() * 2);
452 return (SE.*Operation)(SE.getSignExtendExpr(Op: LHS, Ty: WideTy),
453 SE.getSignExtendExpr(Op: RHS, Ty: WideTy), SCEV::FlagAnyWrap,
454 0);
455 };
456
457 if (OffsetSubtracted)
458 // "IV - Offset < Limit" -> "IV" < Offset + Limit
459 Limit = getExprScaledIfOverflow(Instruction::BinaryOps::Add, Offset, Limit);
460 else {
461 // "Offset - IV > Limit" -> "IV" < Offset - Limit
462 Limit = getExprScaledIfOverflow(Instruction::BinaryOps::Sub, Offset, Limit);
463 Pred = ICmpInst::getSwappedPredicate(pred: Pred);
464 }
465
466 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
467 // "Expr <= Limit" -> "Expr < Limit + 1"
468 if (Pred == ICmpInst::ICMP_SLE && Limit)
469 Limit = getExprScaledIfOverflow(Instruction::BinaryOps::Add, Limit,
470 SE.getOne(Ty: Limit->getType()));
471 if (Limit) {
472 Index = AddRec;
473 End = Limit;
474 return true;
475 }
476 }
477 return false;
478}
479
480void InductiveRangeCheck::extractRangeChecksFromCond(
481 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
482 SmallVectorImpl<InductiveRangeCheck> &Checks,
483 SmallPtrSetImpl<Value *> &Visited) {
484 Value *Condition = ConditionUse.get();
485 if (!Visited.insert(Ptr: Condition).second)
486 return;
487
488 // TODO: Do the same for OR, XOR, NOT etc?
489 if (match(V: Condition, P: m_LogicalAnd(L: m_Value(), R: m_Value()))) {
490 extractRangeChecksFromCond(L, SE, ConditionUse&: cast<User>(Val: Condition)->getOperandUse(i: 0),
491 Checks, Visited);
492 extractRangeChecksFromCond(L, SE, ConditionUse&: cast<User>(Val: Condition)->getOperandUse(i: 1),
493 Checks, Visited);
494 return;
495 }
496
497 ICmpInst *ICI = dyn_cast<ICmpInst>(Val: Condition);
498 if (!ICI)
499 return;
500
501 const SCEV *End = nullptr;
502 const SCEVAddRecExpr *IndexAddRec = nullptr;
503 if (!parseRangeCheckICmp(L, ICI, SE, Index&: IndexAddRec, End))
504 return;
505
506 assert(IndexAddRec && "IndexAddRec was not computed");
507 assert(End && "End was not computed");
508
509 if ((IndexAddRec->getLoop() != L) || !IndexAddRec->isAffine())
510 return;
511
512 InductiveRangeCheck IRC;
513 IRC.End = End;
514 IRC.Begin = IndexAddRec->getStart();
515 IRC.Step = IndexAddRec->getStepRecurrence(SE);
516 IRC.CheckUse = &ConditionUse;
517 Checks.push_back(Elt: IRC);
518}
519
520void InductiveRangeCheck::extractRangeChecksFromBranch(
521 CondBrInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo *BPI,
522 std::optional<uint64_t> EstimatedTripCount,
523 SmallVectorImpl<InductiveRangeCheck> &Checks, bool &Changed) {
524 if (BI->getParent() == L->getLoopLatch())
525 return;
526
527 unsigned IndexLoopSucc = L->contains(BB: BI->getSuccessor(i: 0)) ? 0 : 1;
528 assert(L->contains(BI->getSuccessor(IndexLoopSucc)) &&
529 "No edges coming to loop?");
530
531 if (!SkipProfitabilityChecks && BPI) {
532 auto SuccessProbability =
533 BPI->getEdgeProbability(Src: BI->getParent(), IndexInSuccessors: IndexLoopSucc);
534 if (EstimatedTripCount) {
535 auto EstimatedEliminatedChecks =
536 SuccessProbability.scale(Num: *EstimatedTripCount);
537 if (EstimatedEliminatedChecks < MinEliminatedChecks) {
538 LLVM_DEBUG(dbgs() << "irce: could not prove profitability for branch "
539 << *BI << ": "
540 << "estimated eliminated checks too low "
541 << EstimatedEliminatedChecks << "\n";);
542 return;
543 }
544 } else {
545 BranchProbability LikelyTaken(15, 16);
546 if (SuccessProbability < LikelyTaken) {
547 LLVM_DEBUG(dbgs() << "irce: could not prove profitability for branch "
548 << *BI << ": "
549 << "could not estimate trip count "
550 << "and branch success probability too low "
551 << SuccessProbability << "\n";);
552 return;
553 }
554 }
555 }
556
557 // IRCE expects branch's true edge comes to loop. Invert branch for opposite
558 // case.
559 if (IndexLoopSucc != 0) {
560 IRBuilder<> Builder(BI);
561 InvertBranch(PBI: BI, Builder);
562 if (BPI)
563 BPI->swapSuccEdgesProbabilities(Src: BI->getParent());
564 Changed = true;
565 }
566
567 SmallPtrSet<Value *, 8> Visited;
568 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, ConditionUse&: BI->getOperandUse(i: 0),
569 Checks, Visited);
570}
571
572/// If the type of \p S matches with \p Ty, return \p S. Otherwise, return
573/// signed or unsigned extension of \p S to type \p Ty.
574static const SCEV *NoopOrExtend(const SCEV *S, Type *Ty, ScalarEvolution &SE,
575 bool Signed) {
576 return Signed ? SE.getNoopOrSignExtend(V: S, Ty) : SE.getNoopOrZeroExtend(V: S, Ty);
577}
578
579// Compute a safe set of limits for the main loop to run in -- effectively the
580// intersection of `Range' and the iteration space of the original loop.
581// Return std::nullopt if unable to compute the set of subranges.
582static std::optional<LoopConstrainer::SubRanges>
583calculateSubRanges(ScalarEvolution &SE, const Loop &L,
584 InductiveRangeCheck::Range &Range,
585 const LoopStructure &MainLoopStructure) {
586 auto *RTy = cast<IntegerType>(Val: Range.getType());
587 // We only support wide range checks and narrow latches.
588 if (!AllowNarrowLatchCondition && RTy != MainLoopStructure.ExitCountTy)
589 return std::nullopt;
590 if (RTy->getBitWidth() < MainLoopStructure.ExitCountTy->getBitWidth())
591 return std::nullopt;
592
593 LoopConstrainer::SubRanges Result;
594
595 bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
596 // I think we can be more aggressive here and make this nuw / nsw if the
597 // addition that feeds into the icmp for the latch's terminating branch is nuw
598 // / nsw. In any case, a wrapping 2's complement addition is safe.
599 const SCEV *Start = NoopOrExtend(S: SE.getSCEV(V: MainLoopStructure.IndVarStart),
600 Ty: RTy, SE, Signed: IsSignedPredicate);
601 const SCEV *End = NoopOrExtend(S: SE.getSCEV(V: MainLoopStructure.LoopExitAt), Ty: RTy,
602 SE, Signed: IsSignedPredicate);
603
604 bool Increasing = MainLoopStructure.IndVarIncreasing;
605
606 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
607 // [Smallest, GreatestSeen] is the range of values the induction variable
608 // takes.
609
610 const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
611
612 const SCEV *One = SE.getOne(Ty: RTy);
613 if (Increasing) {
614 Smallest = Start;
615 Greatest = End;
616 // No overflow, because the range [Smallest, GreatestSeen] is not empty.
617 GreatestSeen = SE.getMinusSCEV(LHS: End, RHS: One);
618 } else {
619 // These two computations may sign-overflow. Here is why that is okay:
620 //
621 // We know that the induction variable does not sign-overflow on any
622 // iteration except the last one, and it starts at `Start` and ends at
623 // `End`, decrementing by one every time.
624 //
625 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
626 // induction variable is decreasing we know that the smallest value
627 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
628 //
629 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
630 // that case, `Clamp` will always return `Smallest` and
631 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
632 // will be an empty range. Returning an empty range is always safe.
633
634 Smallest = SE.getAddExpr(LHS: End, RHS: One);
635 Greatest = SE.getAddExpr(LHS: Start, RHS: One);
636 GreatestSeen = Start;
637 }
638
639 auto Clamp = [&SE, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
640 return IsSignedPredicate
641 ? SE.getSMaxExpr(LHS: Smallest, RHS: SE.getSMinExpr(LHS: Greatest, RHS: S))
642 : SE.getUMaxExpr(LHS: Smallest, RHS: SE.getUMinExpr(LHS: Greatest, RHS: S));
643 };
644
645 // In some cases we can prove that we don't need a pre or post loop.
646 ICmpInst::Predicate PredLE =
647 IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
648 ICmpInst::Predicate PredLT =
649 IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
650
651 bool ProvablyNoPreloop =
652 SE.isKnownPredicate(Pred: PredLE, LHS: Range.getBegin(), RHS: Smallest);
653 if (!ProvablyNoPreloop)
654 Result.LowLimit = Clamp(Range.getBegin());
655
656 bool ProvablyNoPostLoop =
657 SE.isKnownPredicate(Pred: PredLT, LHS: GreatestSeen, RHS: Range.getEnd());
658 if (!ProvablyNoPostLoop)
659 Result.HighLimit = Clamp(Range.getEnd());
660
661 return Result;
662}
663
664/// Computes and returns a range of values for the induction variable (IndVar)
665/// in which the range check can be safely elided. If it cannot compute such a
666/// range, returns std::nullopt.
667std::optional<InductiveRangeCheck::Range>
668InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
669 const SCEVAddRecExpr *IndVar,
670 bool IsLatchSigned) const {
671 // We can deal when types of latch check and range checks don't match in case
672 // if latch check is more narrow.
673 auto *IVType = dyn_cast<IntegerType>(Val: IndVar->getType());
674 auto *RCType = dyn_cast<IntegerType>(Val: getBegin()->getType());
675 auto *EndType = dyn_cast<IntegerType>(Val: getEnd()->getType());
676 // Do not work with pointer types.
677 if (!IVType || !RCType)
678 return std::nullopt;
679 if (IVType->getBitWidth() > RCType->getBitWidth())
680 return std::nullopt;
681
682 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
683 // variable, that may or may not exist as a real llvm::Value in the loop) and
684 // this inductive range check is a range check on the "C + D * I" ("C" is
685 // getBegin() and "D" is getStep()). We rewrite the value being range
686 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
687 //
688 // The actual inequalities we solve are of the form
689 //
690 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
691 //
692 // Here L stands for upper limit of the safe iteration space.
693 // The inequality is satisfied by (0 - M) <= IndVar < (L - M). To avoid
694 // overflows when calculating (0 - M) and (L - M) we, depending on type of
695 // IV's iteration space, limit the calculations by borders of the iteration
696 // space. For example, if IndVar is unsigned, (0 - M) overflows for any M > 0.
697 // If we figured out that "anything greater than (-M) is safe", we strengthen
698 // this to "everything greater than 0 is safe", assuming that values between
699 // -M and 0 just do not exist in unsigned iteration space, and we don't want
700 // to deal with overflown values.
701
702 if (!IndVar->isAffine())
703 return std::nullopt;
704
705 const SCEV *A = NoopOrExtend(S: IndVar->getStart(), Ty: RCType, SE, Signed: IsLatchSigned);
706 const SCEVConstant *B = dyn_cast<SCEVConstant>(
707 Val: NoopOrExtend(S: IndVar->getStepRecurrence(SE), Ty: RCType, SE, Signed: IsLatchSigned));
708 if (!B)
709 return std::nullopt;
710 assert(!B->isZero() && "Recurrence with zero step?");
711
712 const SCEV *C = getBegin();
713 const SCEVConstant *D = dyn_cast<SCEVConstant>(Val: getStep());
714 if (D != B)
715 return std::nullopt;
716
717 assert(!D->getValue()->isZero() && "Recurrence with zero step?");
718 unsigned BitWidth = RCType->getBitWidth();
719 const SCEV *SIntMax = SE.getConstant(Val: APInt::getSignedMaxValue(numBits: BitWidth));
720 const SCEV *SIntMin = SE.getConstant(Val: APInt::getSignedMinValue(numBits: BitWidth));
721
722 // Subtract Y from X so that it does not go through border of the IV
723 // iteration space. Mathematically, it is equivalent to:
724 //
725 // ClampedSubtract(X, Y) = min(max(X - Y, INT_MIN), INT_MAX). [1]
726 //
727 // In [1], 'X - Y' is a mathematical subtraction (result is not bounded to
728 // any width of bit grid). But after we take min/max, the result is
729 // guaranteed to be within [INT_MIN, INT_MAX].
730 //
731 // In [1], INT_MAX and INT_MIN are respectively signed and unsigned max/min
732 // values, depending on type of latch condition that defines IV iteration
733 // space.
734 auto ClampedSubtract = [&](const SCEV *X, const SCEV *Y) {
735 // FIXME: The current implementation assumes that X is in [0, SINT_MAX].
736 // This is required to ensure that SINT_MAX - X does not overflow signed and
737 // that X - Y does not overflow unsigned if Y is negative. Can we lift this
738 // restriction and make it work for negative X either?
739 if (IsLatchSigned) {
740 // X is a number from signed range, Y is interpreted as signed.
741 // Even if Y is SINT_MAX, (X - Y) does not reach SINT_MIN. So the only
742 // thing we should care about is that we didn't cross SINT_MAX.
743 // So, if Y is positive, we subtract Y safely.
744 // Rule 1: Y > 0 ---> Y.
745 // If 0 <= -Y <= (SINT_MAX - X), we subtract Y safely.
746 // Rule 2: Y >=s (X - SINT_MAX) ---> Y.
747 // If 0 <= (SINT_MAX - X) < -Y, we can only subtract (X - SINT_MAX).
748 // Rule 3: Y <s (X - SINT_MAX) ---> (X - SINT_MAX).
749 // It gives us smax(Y, X - SINT_MAX) to subtract in all cases.
750 const SCEV *XMinusSIntMax = SE.getMinusSCEV(LHS: X, RHS: SIntMax);
751 return SE.getMinusSCEV(LHS: X, RHS: SE.getSMaxExpr(LHS: Y, RHS: XMinusSIntMax),
752 Flags: SCEV::FlagNSW);
753 } else
754 // X is a number from unsigned range, Y is interpreted as signed.
755 // Even if Y is SINT_MIN, (X - Y) does not reach UINT_MAX. So the only
756 // thing we should care about is that we didn't cross zero.
757 // So, if Y is negative, we subtract Y safely.
758 // Rule 1: Y <s 0 ---> Y.
759 // If 0 <= Y <= X, we subtract Y safely.
760 // Rule 2: Y <=s X ---> Y.
761 // If 0 <= X < Y, we should stop at 0 and can only subtract X.
762 // Rule 3: Y >s X ---> X.
763 // It gives us smin(X, Y) to subtract in all cases.
764 return SE.getMinusSCEV(LHS: X, RHS: SE.getSMinExpr(LHS: X, RHS: Y), Flags: SCEV::FlagNUW);
765 };
766 const SCEV *M = SE.getMinusSCEV(LHS: C, RHS: A);
767 const SCEV *Zero = SE.getZero(Ty: M->getType());
768
769 // This function returns SCEV equal to 1 if X is non-negative 0 otherwise.
770 auto SCEVCheckNonNegative = [&](const SCEV *X) {
771 const Loop *L = IndVar->getLoop();
772 const SCEV *Zero = SE.getZero(Ty: X->getType());
773 const SCEV *One = SE.getOne(Ty: X->getType());
774 // Can we trivially prove that X is a non-negative or negative value?
775 if (isKnownNonNegativeInLoop(S: X, L, SE))
776 return One;
777 else if (isKnownNegativeInLoop(S: X, L, SE))
778 return Zero;
779 // If not, we will have to figure it out during the execution.
780 // Function smax(smin(X, 0), -1) + 1 equals to 1 if X >= 0 and 0 if X < 0.
781 const SCEV *NegOne = SE.getNegativeSCEV(V: One);
782 return SE.getAddExpr(LHS: SE.getSMaxExpr(LHS: SE.getSMinExpr(LHS: X, RHS: Zero), RHS: NegOne), RHS: One);
783 };
784
785 // This function returns SCEV equal to 1 if X will not overflow in terms of
786 // range check type, 0 otherwise.
787 auto SCEVCheckWillNotOverflow = [&](const SCEV *X) {
788 // X doesn't overflow if SINT_MAX >= X.
789 // Then if (SINT_MAX - X) >= 0, X doesn't overflow
790 const SCEV *SIntMaxExt = SE.getSignExtendExpr(Op: SIntMax, Ty: X->getType());
791 const SCEV *OverflowCheck =
792 SCEVCheckNonNegative(SE.getMinusSCEV(LHS: SIntMaxExt, RHS: X));
793
794 // X doesn't underflow if X >= SINT_MIN.
795 // Then if (X - SINT_MIN) >= 0, X doesn't underflow
796 const SCEV *SIntMinExt = SE.getSignExtendExpr(Op: SIntMin, Ty: X->getType());
797 const SCEV *UnderflowCheck =
798 SCEVCheckNonNegative(SE.getMinusSCEV(LHS: X, RHS: SIntMinExt));
799
800 return SE.getMulExpr(LHS: OverflowCheck, RHS: UnderflowCheck);
801 };
802
803 // FIXME: Current implementation of ClampedSubtract implicitly assumes that
804 // X is non-negative (in sense of a signed value). We need to re-implement
805 // this function in a way that it will correctly handle negative X as well.
806 // We use it twice: for X = 0 everything is fine, but for X = getEnd() we can
807 // end up with a negative X and produce wrong results. So currently we ensure
808 // that if getEnd() is negative then both ends of the safe range are zero.
809 // Note that this may pessimize elimination of unsigned range checks against
810 // negative values.
811 const SCEV *REnd = getEnd();
812 const SCEV *EndWillNotOverflow = SE.getOne(Ty: RCType);
813
814 auto PrintRangeCheck = [&](raw_ostream &OS) {
815 auto L = IndVar->getLoop();
816 OS << "irce: in function ";
817 OS << L->getHeader()->getParent()->getName();
818 OS << ", in ";
819 L->print(OS);
820 OS << "there is range check with scaled boundary:\n";
821 print(OS);
822 };
823
824 if (EndType->getBitWidth() > RCType->getBitWidth()) {
825 assert(EndType->getBitWidth() == RCType->getBitWidth() * 2);
826 if (PrintScaledBoundaryRangeChecks)
827 PrintRangeCheck(errs());
828 // End is computed with extended type but will be truncated to a narrow one
829 // type of range check. Therefore we need a check that the result will not
830 // overflow in terms of narrow type.
831 EndWillNotOverflow =
832 SE.getTruncateExpr(Op: SCEVCheckWillNotOverflow(REnd), Ty: RCType);
833 REnd = SE.getTruncateExpr(Op: REnd, Ty: RCType);
834 }
835
836 const SCEV *RuntimeChecks =
837 SE.getMulExpr(LHS: SCEVCheckNonNegative(REnd), RHS: EndWillNotOverflow);
838 const SCEV *Begin = SE.getMulExpr(LHS: ClampedSubtract(Zero, M), RHS: RuntimeChecks);
839 const SCEV *End = SE.getMulExpr(LHS: ClampedSubtract(REnd, M), RHS: RuntimeChecks);
840
841 return InductiveRangeCheck::Range(Begin, End);
842}
843
844static std::optional<InductiveRangeCheck::Range>
845IntersectSignedRange(ScalarEvolution &SE,
846 const std::optional<InductiveRangeCheck::Range> &R1,
847 const InductiveRangeCheck::Range &R2) {
848 if (R2.isEmpty(SE, /* IsSigned */ true))
849 return std::nullopt;
850 if (!R1)
851 return R2;
852 auto &R1Value = *R1;
853 // We never return empty ranges from this function, and R1 is supposed to be
854 // a result of intersection. Thus, R1 is never empty.
855 assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
856 "We should never have empty R1!");
857
858 // TODO: we could widen the smaller range and have this work; but for now we
859 // bail out to keep things simple.
860 if (R1Value.getType() != R2.getType())
861 return std::nullopt;
862
863 const SCEV *NewBegin = SE.getSMaxExpr(LHS: R1Value.getBegin(), RHS: R2.getBegin());
864 const SCEV *NewEnd = SE.getSMinExpr(LHS: R1Value.getEnd(), RHS: R2.getEnd());
865
866 // If the resulting range is empty, just return std::nullopt.
867 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
868 if (Ret.isEmpty(SE, /* IsSigned */ true))
869 return std::nullopt;
870 return Ret;
871}
872
873static std::optional<InductiveRangeCheck::Range>
874IntersectUnsignedRange(ScalarEvolution &SE,
875 const std::optional<InductiveRangeCheck::Range> &R1,
876 const InductiveRangeCheck::Range &R2) {
877 if (R2.isEmpty(SE, /* IsSigned */ false))
878 return std::nullopt;
879 if (!R1)
880 return R2;
881 auto &R1Value = *R1;
882 // We never return empty ranges from this function, and R1 is supposed to be
883 // a result of intersection. Thus, R1 is never empty.
884 assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
885 "We should never have empty R1!");
886
887 // TODO: we could widen the smaller range and have this work; but for now we
888 // bail out to keep things simple.
889 if (R1Value.getType() != R2.getType())
890 return std::nullopt;
891
892 const SCEV *NewBegin = SE.getUMaxExpr(LHS: R1Value.getBegin(), RHS: R2.getBegin());
893 const SCEV *NewEnd = SE.getUMinExpr(LHS: R1Value.getEnd(), RHS: R2.getEnd());
894
895 // If the resulting range is empty, just return std::nullopt.
896 auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
897 if (Ret.isEmpty(SE, /* IsSigned */ false))
898 return std::nullopt;
899 return Ret;
900}
901
902PreservedAnalyses IRCEPass::run(Function &F, FunctionAnalysisManager &AM) {
903 auto &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
904 LoopInfo &LI = AM.getResult<LoopAnalysis>(IR&: F);
905 // There are no loops in the function. Return before computing other expensive
906 // analyses.
907 if (LI.empty())
908 return PreservedAnalyses::all();
909 auto &SE = AM.getResult<ScalarEvolutionAnalysis>(IR&: F);
910 auto &BPI = AM.getResult<BranchProbabilityAnalysis>(IR&: F);
911
912 // Get BFI analysis result on demand. Please note that modification of
913 // CFG invalidates this analysis and we should handle it.
914 auto getBFI = [&F, &AM ]()->BlockFrequencyInfo & {
915 return AM.getResult<BlockFrequencyAnalysis>(IR&: F);
916 };
917 InductiveRangeCheckElimination IRCE(SE, &BPI, DT, LI, { getBFI });
918
919 bool Changed = false;
920 {
921 bool CFGChanged = false;
922 for (const auto &L : LI) {
923 CFGChanged |= simplifyLoop(L, DT: &DT, LI: &LI, SE: &SE, AC: nullptr, MSSAU: nullptr,
924 /*PreserveLCSSA=*/false);
925 Changed |= formLCSSARecursively(L&: *L, DT, LI: &LI, SE: &SE);
926 }
927 Changed |= CFGChanged;
928
929 if (CFGChanged && !SkipProfitabilityChecks) {
930 PreservedAnalyses PA = PreservedAnalyses::all();
931 PA.abandon<CycleAnalysis>();
932 PA.abandon<BlockFrequencyAnalysis>();
933 AM.invalidate(IR&: F, PA);
934 }
935 }
936
937 SmallPriorityWorklist<Loop *, 4> Worklist;
938 appendLoopsToWorklist(LI, Worklist);
939 auto LPMAddNewLoop = [&Worklist](Loop *NL, bool IsSubloop) {
940 if (!IsSubloop)
941 appendLoopsToWorklist(*NL, Worklist);
942 };
943
944 while (!Worklist.empty()) {
945 Loop *L = Worklist.pop_back_val();
946 if (IRCE.run(L, LPMAddNewLoop)) {
947 Changed = true;
948 if (!SkipProfitabilityChecks) {
949 PreservedAnalyses PA = PreservedAnalyses::all();
950 PA.abandon<CycleAnalysis>();
951 PA.abandon<BlockFrequencyAnalysis>();
952 AM.invalidate(IR&: F, PA);
953 }
954 }
955 }
956
957 if (!Changed)
958 return PreservedAnalyses::all();
959 return getLoopPassPreservedAnalyses();
960}
961
962std::optional<uint64_t>
963InductiveRangeCheckElimination::estimatedTripCount(const Loop &L) {
964 if (GetBFI) {
965 BlockFrequencyInfo &BFI = GetBFI();
966 uint64_t hFreq = BFI.getBlockFreq(BB: L.getHeader()).getFrequency();
967 uint64_t phFreq = BFI.getBlockFreq(BB: L.getLoopPreheader()).getFrequency();
968 if (phFreq == 0 || hFreq == 0)
969 return std::nullopt;
970 return {hFreq / phFreq};
971 }
972
973 if (!BPI)
974 return std::nullopt;
975
976 auto *Latch = L.getLoopLatch();
977 if (!Latch)
978 return std::nullopt;
979 auto *LatchBr = dyn_cast<CondBrInst>(Val: Latch->getTerminator());
980 if (!LatchBr)
981 return std::nullopt;
982
983 auto LatchBrExitIdx = LatchBr->getSuccessor(i: 0) == L.getHeader() ? 1 : 0;
984 BranchProbability ExitProbability =
985 BPI->getEdgeProbability(Src: Latch, IndexInSuccessors: LatchBrExitIdx);
986 if (ExitProbability.isUnknown() || ExitProbability.isZero())
987 return std::nullopt;
988
989 return {ExitProbability.scaleByInverse(Num: 1)};
990}
991
992bool InductiveRangeCheckElimination::run(
993 Loop *L, function_ref<void(Loop *, bool)> LPMAddNewLoop) {
994 if (L->getBlocks().size() >= LoopSizeCutoff) {
995 LLVM_DEBUG(dbgs() << "irce: giving up constraining loop, too large\n");
996 return false;
997 }
998
999 BasicBlock *Preheader = L->getLoopPreheader();
1000 if (!Preheader) {
1001 LLVM_DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1002 return false;
1003 }
1004
1005 auto EstimatedTripCount = estimatedTripCount(L: *L);
1006 if (!SkipProfitabilityChecks && EstimatedTripCount &&
1007 *EstimatedTripCount < MinEliminatedChecks) {
1008 LLVM_DEBUG(dbgs() << "irce: could not prove profitability: "
1009 << "the estimated number of iterations is "
1010 << *EstimatedTripCount << "\n");
1011 return false;
1012 }
1013
1014 LLVMContext &Context = Preheader->getContext();
1015 SmallVector<InductiveRangeCheck, 16> RangeChecks;
1016 bool Changed = false;
1017
1018 for (auto *BBI : L->getBlocks())
1019 if (CondBrInst *TBI = dyn_cast<CondBrInst>(Val: BBI->getTerminator()))
1020 InductiveRangeCheck::extractRangeChecksFromBranch(
1021 BI: TBI, L, SE, BPI, EstimatedTripCount, Checks&: RangeChecks, Changed);
1022
1023 if (RangeChecks.empty())
1024 return Changed;
1025
1026 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1027 OS << "irce: looking at loop "; L->print(OS);
1028 OS << "irce: loop has " << RangeChecks.size()
1029 << " inductive range checks: \n";
1030 for (InductiveRangeCheck &IRC : RangeChecks)
1031 IRC.print(OS);
1032 };
1033
1034 LLVM_DEBUG(PrintRecognizedRangeChecks(dbgs()));
1035
1036 if (PrintRangeChecks)
1037 PrintRecognizedRangeChecks(errs());
1038
1039 const char *FailureReason = nullptr;
1040 SCEVExpander LoopStructureExpander(SE, "loop-constrainer");
1041 SCEVExpanderCleaner LoopStructureExpanderCleaner(LoopStructureExpander);
1042 std::optional<LoopStructure> MaybeLoopStructure =
1043 LoopStructure::parseLoopStructure(Expander&: LoopStructureExpander, L&: *L,
1044 AllowUnsignedLatchCond: AllowUnsignedLatchCondition,
1045 FailureReason);
1046 if (!MaybeLoopStructure) {
1047 LLVM_DEBUG(dbgs() << "irce: could not parse loop structure: "
1048 << FailureReason << "\n";);
1049 return Changed;
1050 }
1051 LoopStructure LS = *MaybeLoopStructure;
1052 const SCEVAddRecExpr *IndVar =
1053 cast<SCEVAddRecExpr>(Val: SE.getMinusSCEV(LHS: SE.getSCEV(V: LS.IndVarBase), RHS: SE.getSCEV(V: LS.IndVarStep)));
1054
1055 std::optional<InductiveRangeCheck::Range> SafeIterRange;
1056
1057 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
1058 // Basing on the type of latch predicate, we interpret the IV iteration range
1059 // as signed or unsigned range. We use different min/max functions (signed or
1060 // unsigned) when intersecting this range with safe iteration ranges implied
1061 // by range checks.
1062 auto IntersectRange =
1063 LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
1064
1065 for (InductiveRangeCheck &IRC : RangeChecks) {
1066 auto Result = IRC.computeSafeIterationSpace(SE, IndVar,
1067 IsLatchSigned: LS.IsSignedPredicate);
1068 if (Result) {
1069 auto MaybeSafeIterRange = IntersectRange(SE, SafeIterRange, *Result);
1070 if (MaybeSafeIterRange) {
1071 assert(!MaybeSafeIterRange->isEmpty(SE, LS.IsSignedPredicate) &&
1072 "We should never return empty ranges!");
1073 RangeChecksToEliminate.push_back(Elt: IRC);
1074 SafeIterRange = *MaybeSafeIterRange;
1075 }
1076 }
1077 }
1078
1079 if (!SafeIterRange)
1080 return Changed;
1081
1082 std::optional<LoopConstrainer::SubRanges> MaybeSR =
1083 calculateSubRanges(SE, L: *L, Range&: *SafeIterRange, MainLoopStructure: LS);
1084 if (!MaybeSR) {
1085 LLVM_DEBUG(dbgs() << "irce: could not compute subranges\n");
1086 return Changed;
1087 }
1088
1089 LoopConstrainer LC(*L, LI, LPMAddNewLoop, LS, SE, DT,
1090 SafeIterRange->getBegin()->getType(), *MaybeSR);
1091
1092 if (LC.run()) {
1093 LoopStructureExpanderCleaner.markResultUsed();
1094 LS.IndVarStart->setName("indvar.start");
1095 Changed = true;
1096
1097 auto PrintConstrainedLoopInfo = [L]() {
1098 dbgs() << "irce: in function ";
1099 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1100 dbgs() << "constrained ";
1101 L->print(OS&: dbgs());
1102 };
1103
1104 LLVM_DEBUG(PrintConstrainedLoopInfo());
1105
1106 if (PrintChangedLoops)
1107 PrintConstrainedLoopInfo();
1108
1109 // Optimize away the now-redundant range checks.
1110
1111 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1112 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
1113 ? ConstantInt::getTrue(Context)
1114 : ConstantInt::getFalse(Context);
1115 IRC.getCheckUse()->set(FoldedRangeCheck);
1116 }
1117 }
1118
1119 return Changed;
1120}
1121