1 //===-- InductiveRangeCheckElimination.cpp - ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
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
14 // len = < known positive >
15 // for (i = 0; i < n; i++) {
16 // if (0 <= i && i < len) {
19 // throw_out_of_bounds();
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
32 // throw_out_of_bounds();
35 // for (i = limit; i < n; i++) {
36 // if (0 <= i && i < len) {
39 // throw_out_of_bounds();
42 //===----------------------------------------------------------------------===//
44 #include "llvm/ADT/Optional.h"
45 #include "llvm/Analysis/BranchProbabilityInfo.h"
46 #include "llvm/Analysis/InstructionSimplify.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Analysis/LoopPass.h"
49 #include "llvm/Analysis/ScalarEvolution.h"
50 #include "llvm/Analysis/ScalarEvolutionExpander.h"
51 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
52 #include "llvm/Analysis/ValueTracking.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/Instructions.h"
57 #include "llvm/IR/Module.h"
58 #include "llvm/IR/PatternMatch.h"
59 #include "llvm/IR/ValueHandle.h"
60 #include "llvm/IR/Verifier.h"
61 #include "llvm/Pass.h"
62 #include "llvm/Support/Debug.h"
63 #include "llvm/Support/raw_ostream.h"
64 #include "llvm/Transforms/Scalar.h"
65 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
66 #include "llvm/Transforms/Utils/Cloning.h"
67 #include "llvm/Transforms/Utils/LoopUtils.h"
68 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
69 #include "llvm/Transforms/Utils/UnrollLoop.h"
73 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
76 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
79 static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
82 static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
83 cl::Hidden, cl::init(10));
85 #define DEBUG_TYPE "irce"
89 /// An inductive range check is conditional branch in a loop with
91 /// 1. a very cold successor (i.e. the branch jumps to that successor very
96 /// 2. a condition that is provably true for some contiguous range of values
97 /// taken by the containing loop's induction variable.
99 class InductiveRangeCheck {
100 // Classifies a range check
101 enum RangeCheckKind : unsigned {
102 // Range check of the form "0 <= I".
103 RANGE_CHECK_LOWER = 1,
105 // Range check of the form "I < L" where L is known positive.
106 RANGE_CHECK_UPPER = 2,
108 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
110 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
112 // Unrecognized range check condition.
113 RANGE_CHECK_UNKNOWN = (unsigned)-1
116 static StringRef rangeCheckKindToStr(RangeCheckKind);
118 const SCEV *Offset = nullptr;
119 const SCEV *Scale = nullptr;
120 Value *Length = nullptr;
121 Use *CheckUse = nullptr;
122 RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
124 static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
125 ScalarEvolution &SE, Value *&Index,
129 extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
130 SmallVectorImpl<InductiveRangeCheck> &Checks,
131 SmallPtrSetImpl<Value *> &Visited);
134 const SCEV *getOffset() const { return Offset; }
135 const SCEV *getScale() const { return Scale; }
136 Value *getLength() const { return Length; }
138 void print(raw_ostream &OS) const {
139 OS << "InductiveRangeCheck:\n";
140 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
150 OS << "\n CheckUse: ";
151 getCheckUse()->getUser()->print(OS);
152 OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
155 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
161 Use *getCheckUse() const { return CheckUse; }
163 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
164 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
171 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
172 assert(Begin->getType() == End->getType() && "ill-typed range!");
175 Type *getType() const { return Begin->getType(); }
176 const SCEV *getBegin() const { return Begin; }
177 const SCEV *getEnd() const { return End; }
180 /// This is the value the condition of the branch needs to evaluate to for the
181 /// branch to take the hot successor (see (1) above).
182 bool getPassingDirection() { return true; }
184 /// Computes a range for the induction variable (IndVar) in which the range
185 /// check is redundant and can be constant-folded away. The induction
186 /// variable is not required to be the canonical {0,+,1} induction variable.
187 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
188 const SCEVAddRecExpr *IndVar) const;
190 /// Parse out a set of inductive range checks from \p BI and append them to \p
193 /// NB! There may be conditions feeding into \p BI that aren't inductive range
194 /// checks, and hence don't end up in \p Checks.
196 extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
197 BranchProbabilityInfo &BPI,
198 SmallVectorImpl<InductiveRangeCheck> &Checks);
201 class InductiveRangeCheckElimination : public LoopPass {
204 InductiveRangeCheckElimination() : LoopPass(ID) {
205 initializeInductiveRangeCheckEliminationPass(
206 *PassRegistry::getPassRegistry());
209 void getAnalysisUsage(AnalysisUsage &AU) const override {
210 AU.addRequired<BranchProbabilityInfoWrapperPass>();
211 getLoopAnalysisUsage(AU);
214 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
217 char InductiveRangeCheckElimination::ID = 0;
220 INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
221 "Inductive range check elimination", false, false)
222 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
223 INITIALIZE_PASS_DEPENDENCY(LoopPass)
224 INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
225 "Inductive range check elimination", false, false)
227 StringRef InductiveRangeCheck::rangeCheckKindToStr(
228 InductiveRangeCheck::RangeCheckKind RCK) {
230 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
231 return "RANGE_CHECK_UNKNOWN";
233 case InductiveRangeCheck::RANGE_CHECK_UPPER:
234 return "RANGE_CHECK_UPPER";
236 case InductiveRangeCheck::RANGE_CHECK_LOWER:
237 return "RANGE_CHECK_LOWER";
239 case InductiveRangeCheck::RANGE_CHECK_BOTH:
240 return "RANGE_CHECK_BOTH";
243 llvm_unreachable("unknown range check type!");
246 /// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI` cannot
247 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
248 /// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value being
249 /// range checked, and set `Length` to the upper limit `Index` is being range
250 /// checked with if (and only if) the range check type is stronger or equal to
251 /// RANGE_CHECK_UPPER.
253 InductiveRangeCheck::RangeCheckKind
254 InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
255 ScalarEvolution &SE, Value *&Index,
258 auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
259 const SCEV *S = SE.getSCEV(V);
260 if (isa<SCEVCouldNotCompute>(S))
263 return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
264 SE.isKnownNonNegative(S);
267 using namespace llvm::PatternMatch;
269 ICmpInst::Predicate Pred = ICI->getPredicate();
270 Value *LHS = ICI->getOperand(0);
271 Value *RHS = ICI->getOperand(1);
275 return RANGE_CHECK_UNKNOWN;
277 case ICmpInst::ICMP_SLE:
280 case ICmpInst::ICMP_SGE:
281 if (match(RHS, m_ConstantInt<0>())) {
283 return RANGE_CHECK_LOWER;
285 return RANGE_CHECK_UNKNOWN;
287 case ICmpInst::ICMP_SLT:
290 case ICmpInst::ICMP_SGT:
291 if (match(RHS, m_ConstantInt<-1>())) {
293 return RANGE_CHECK_LOWER;
296 if (IsNonNegativeAndNotLoopVarying(LHS)) {
299 return RANGE_CHECK_UPPER;
301 return RANGE_CHECK_UNKNOWN;
303 case ICmpInst::ICMP_ULT:
306 case ICmpInst::ICMP_UGT:
307 if (IsNonNegativeAndNotLoopVarying(LHS)) {
310 return RANGE_CHECK_BOTH;
312 return RANGE_CHECK_UNKNOWN;
315 llvm_unreachable("default clause returns!");
318 void InductiveRangeCheck::extractRangeChecksFromCond(
319 Loop *L, ScalarEvolution &SE, Use &ConditionUse,
320 SmallVectorImpl<InductiveRangeCheck> &Checks,
321 SmallPtrSetImpl<Value *> &Visited) {
322 using namespace llvm::PatternMatch;
324 Value *Condition = ConditionUse.get();
325 if (!Visited.insert(Condition).second)
328 if (match(Condition, m_And(m_Value(), m_Value()))) {
329 SmallVector<InductiveRangeCheck, 8> SubChecks;
330 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
332 extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
335 if (SubChecks.size() == 2) {
336 // Handle a special case where we know how to merge two checks separately
337 // checking the upper and lower bounds into a full range check.
338 const auto &RChkA = SubChecks[0];
339 const auto &RChkB = SubChecks[1];
340 if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
341 RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale) {
343 // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
344 // But if one of them is a RANGE_CHECK_LOWER and the other is a
345 // RANGE_CHECK_UPPER (only possibility if they're different) then
346 // together they form a RANGE_CHECK_BOTH.
348 (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
349 SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
350 SubChecks[0].CheckUse = &ConditionUse;
352 // We updated one of the checks in place, now erase the other.
353 SubChecks.pop_back();
357 Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
361 ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
365 Value *Length = nullptr, *Index;
366 auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length);
367 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
370 const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
372 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
377 InductiveRangeCheck IRC;
379 IRC.Offset = IndexAddRec->getStart();
380 IRC.Scale = IndexAddRec->getStepRecurrence(SE);
381 IRC.CheckUse = &ConditionUse;
383 Checks.push_back(IRC);
386 void InductiveRangeCheck::extractRangeChecksFromBranch(
387 BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
388 SmallVectorImpl<InductiveRangeCheck> &Checks) {
390 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
393 BranchProbability LikelyTaken(15, 16);
395 if (BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
398 SmallPtrSet<Value *, 8> Visited;
399 InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
405 // Keeps track of the structure of a loop. This is similar to llvm::Loop,
406 // except that it is more lightweight and can track the state of a loop through
407 // changing and potentially invalid IR. This structure also formalizes the
408 // kinds of loops we can deal with -- ones that have a single latch that is also
409 // an exiting block *and* have a canonical induction variable.
410 struct LoopStructure {
416 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
417 // successor is `LatchExit', the exit block of the loop.
419 BasicBlock *LatchExit;
420 unsigned LatchBrExitIdx;
425 bool IndVarIncreasing;
428 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
429 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
430 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
432 template <typename M> LoopStructure map(M Map) const {
433 LoopStructure Result;
435 Result.Header = cast<BasicBlock>(Map(Header));
436 Result.Latch = cast<BasicBlock>(Map(Latch));
437 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
438 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
439 Result.LatchBrExitIdx = LatchBrExitIdx;
440 Result.IndVarNext = Map(IndVarNext);
441 Result.IndVarStart = Map(IndVarStart);
442 Result.LoopExitAt = Map(LoopExitAt);
443 Result.IndVarIncreasing = IndVarIncreasing;
447 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
448 BranchProbabilityInfo &BPI,
453 /// This class is used to constrain loops to run within a given iteration space.
454 /// The algorithm this class implements is given a Loop and a range [Begin,
455 /// End). The algorithm then tries to break out a "main loop" out of the loop
456 /// it is given in a way that the "main loop" runs with the induction variable
457 /// in a subset of [Begin, End). The algorithm emits appropriate pre and post
458 /// loops to run any remaining iterations. The pre loop runs any iterations in
459 /// which the induction variable is < Begin, and the post loop runs any
460 /// iterations in which the induction variable is >= End.
462 class LoopConstrainer {
463 // The representation of a clone of the original loop we started out with.
466 std::vector<BasicBlock *> Blocks;
468 // `Map` maps values in the clonee into values in the cloned version
469 ValueToValueMapTy Map;
471 // An instance of `LoopStructure` for the cloned loop
472 LoopStructure Structure;
475 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
476 // more details on what these fields mean.
477 struct RewrittenRangeInfo {
478 BasicBlock *PseudoExit;
479 BasicBlock *ExitSelector;
480 std::vector<PHINode *> PHIValuesAtPseudoExit;
484 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
487 // Calculated subranges we restrict the iteration space of the main loop to.
488 // See the implementation of `calculateSubRanges' for more details on how
489 // these fields are computed. `LowLimit` is None if there is no restriction
490 // on low end of the restricted iteration space of the main loop. `HighLimit`
491 // is None if there is no restriction on high end of the restricted iteration
492 // space of the main loop.
495 Optional<const SCEV *> LowLimit;
496 Optional<const SCEV *> HighLimit;
499 // A utility function that does a `replaceUsesOfWith' on the incoming block
500 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
501 // incoming block list with `ReplaceBy'.
502 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
503 BasicBlock *ReplaceBy);
505 // Compute a safe set of limits for the main loop to run in -- effectively the
506 // intersection of `Range' and the iteration space of the original loop.
507 // Return None if unable to compute the set of subranges.
509 Optional<SubRanges> calculateSubRanges() const;
511 // Clone `OriginalLoop' and return the result in CLResult. The IR after
512 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
513 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
514 // but there is no such edge.
516 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
518 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
519 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
520 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
521 // `OriginalHeaderCount'.
523 // If there are iterations left to execute, control is made to jump to
524 // `ContinuationBlock', otherwise they take the normal loop exit. The
525 // returned `RewrittenRangeInfo' object is populated as follows:
527 // .PseudoExit is a basic block that unconditionally branches to
528 // `ContinuationBlock'.
530 // .ExitSelector is a basic block that decides, on exit from the loop,
531 // whether to branch to the "true" exit or to `PseudoExit'.
533 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
534 // for each PHINode in the loop header on taking the pseudo exit.
536 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
537 // preheader because it is made to branch to the loop header only
541 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
543 BasicBlock *ContinuationBlock) const;
545 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
546 // function creates a new preheader for `LS' and returns it.
548 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
549 const char *Tag) const;
551 // `ContinuationBlockAndPreheader' was the continuation block for some call to
552 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
553 // This function rewrites the PHI nodes in `LS.Header' to start with the
555 void rewriteIncomingValuesForPHIs(
556 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
557 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
559 // Even though we do not preserve any passes at this time, we at least need to
560 // keep the parent loop structure consistent. The `LPPassManager' seems to
561 // verify this after running a loop pass. This function adds the list of
562 // blocks denoted by BBs to this loops parent loop if required.
563 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
565 // Some global state.
570 // Information about the original loop we started out with.
572 LoopInfo &OriginalLoopInfo;
573 const SCEV *LatchTakenCount;
574 BasicBlock *OriginalPreheader;
576 // The preheader of the main loop. This may or may not be different from
577 // `OriginalPreheader'.
578 BasicBlock *MainLoopPreheader;
580 // The range we need to run the main loop in.
581 InductiveRangeCheck::Range Range;
583 // The structure of the main loop (see comment at the beginning of this class
585 LoopStructure MainLoopStructure;
588 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
589 ScalarEvolution &SE, InductiveRangeCheck::Range R)
590 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
591 SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
592 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
593 MainLoopStructure(LS) {}
595 // Entry point for the algorithm. Returns true on success.
601 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
602 BasicBlock *ReplaceBy) {
603 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
604 if (PN->getIncomingBlock(i) == Block)
605 PN->setIncomingBlock(i, ReplaceBy);
608 static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
610 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
611 return SE.getSignedRange(S).contains(SMax) &&
612 SE.getUnsignedRange(S).contains(SMax);
615 static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
617 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
618 return SE.getSignedRange(S).contains(SMin) &&
619 SE.getUnsignedRange(S).contains(SMin);
622 Optional<LoopStructure>
623 LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
624 Loop &L, const char *&FailureReason) {
625 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
627 BasicBlock *Latch = L.getLoopLatch();
628 if (!L.isLoopExiting(Latch)) {
629 FailureReason = "no loop latch";
633 BasicBlock *Header = L.getHeader();
634 BasicBlock *Preheader = L.getLoopPreheader();
636 FailureReason = "no preheader";
640 BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
641 if (!LatchBr || LatchBr->isUnconditional()) {
642 FailureReason = "latch terminator not conditional branch";
646 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
648 BranchProbability ExitProbability =
649 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
651 if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
652 FailureReason = "short running loop, not profitable";
656 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
657 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
658 FailureReason = "latch terminator branch not conditional on integral icmp";
662 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
663 if (isa<SCEVCouldNotCompute>(LatchCount)) {
664 FailureReason = "could not compute latch count";
668 ICmpInst::Predicate Pred = ICI->getPredicate();
669 Value *LeftValue = ICI->getOperand(0);
670 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
671 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
673 Value *RightValue = ICI->getOperand(1);
674 const SCEV *RightSCEV = SE.getSCEV(RightValue);
676 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
677 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
678 if (isa<SCEVAddRecExpr>(RightSCEV)) {
679 std::swap(LeftSCEV, RightSCEV);
680 std::swap(LeftValue, RightValue);
681 Pred = ICmpInst::getSwappedPredicate(Pred);
683 FailureReason = "no add recurrences in the icmp";
688 auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
689 if (AR->getNoWrapFlags(SCEV::FlagNSW))
692 IntegerType *Ty = cast<IntegerType>(AR->getType());
693 IntegerType *WideTy =
694 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
696 const SCEVAddRecExpr *ExtendAfterOp =
697 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
699 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
700 const SCEV *ExtendedStep =
701 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
703 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
704 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
710 // We may have proved this when computing the sign extension above.
711 return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
714 auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
718 // Currently we only work with induction variables that have been proved to
719 // not wrap. This restriction can potentially be lifted in the future.
721 if (!HasNoSignedWrap(AR))
724 if (const SCEVConstant *StepExpr =
725 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
726 ConstantInt *StepCI = StepExpr->getValue();
727 if (StepCI->isOne() || StepCI->isMinusOne()) {
728 IsIncreasing = StepCI->isOne();
736 // `ICI` is interpreted as taking the backedge if the *next* value of the
737 // induction variable satisfies some constraint.
739 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
740 bool IsIncreasing = false;
741 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
742 FailureReason = "LHS in icmp not induction variable";
746 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
747 // TODO: generalize the predicates here to also match their unsigned variants.
749 bool FoundExpectedPred =
750 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
751 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
753 if (!FoundExpectedPred) {
754 FailureReason = "expected icmp slt semantically, found something else";
758 if (LatchBrExitIdx == 0) {
759 if (CanBeSMax(SE, RightSCEV)) {
760 // TODO: this restriction is easily removable -- we just have to
761 // remember that the icmp was an slt and not an sle.
762 FailureReason = "limit may overflow when coercing sle to slt";
766 IRBuilder<> B(Preheader->getTerminator());
767 RightValue = B.CreateAdd(RightValue, One);
771 bool FoundExpectedPred =
772 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
773 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
775 if (!FoundExpectedPred) {
776 FailureReason = "expected icmp sgt semantically, found something else";
780 if (LatchBrExitIdx == 0) {
781 if (CanBeSMin(SE, RightSCEV)) {
782 // TODO: this restriction is easily removable -- we just have to
783 // remember that the icmp was an sgt and not an sge.
784 FailureReason = "limit may overflow when coercing sge to sgt";
788 IRBuilder<> B(Preheader->getTerminator());
789 RightValue = B.CreateSub(RightValue, One);
793 const SCEV *StartNext = IndVarNext->getStart();
794 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
795 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
797 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
799 assert(SE.getLoopDisposition(LatchCount, &L) ==
800 ScalarEvolution::LoopInvariant &&
801 "loop variant exit count doesn't make sense!");
803 assert(!L.contains(LatchExit) && "expected an exit block!");
804 const DataLayout &DL = Preheader->getModule()->getDataLayout();
805 Value *IndVarStartV =
806 SCEVExpander(SE, DL, "irce")
807 .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
808 IndVarStartV->setName("indvar.start");
810 LoopStructure Result;
813 Result.Header = Header;
814 Result.Latch = Latch;
815 Result.LatchBr = LatchBr;
816 Result.LatchExit = LatchExit;
817 Result.LatchBrExitIdx = LatchBrExitIdx;
818 Result.IndVarStart = IndVarStartV;
819 Result.IndVarNext = LeftValue;
820 Result.IndVarIncreasing = IsIncreasing;
821 Result.LoopExitAt = RightValue;
823 FailureReason = nullptr;
828 Optional<LoopConstrainer::SubRanges>
829 LoopConstrainer::calculateSubRanges() const {
830 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
832 if (Range.getType() != Ty)
835 LoopConstrainer::SubRanges Result;
837 // I think we can be more aggressive here and make this nuw / nsw if the
838 // addition that feeds into the icmp for the latch's terminating branch is nuw
839 // / nsw. In any case, a wrapping 2's complement addition is safe.
840 ConstantInt *One = ConstantInt::get(Ty, 1);
841 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
842 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
844 bool Increasing = MainLoopStructure.IndVarIncreasing;
846 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
847 // range of values the induction variable takes.
849 const SCEV *Smallest = nullptr, *Greatest = nullptr;
855 // These two computations may sign-overflow. Here is why that is okay:
857 // We know that the induction variable does not sign-overflow on any
858 // iteration except the last one, and it starts at `Start` and ends at
859 // `End`, decrementing by one every time.
861 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
862 // induction variable is decreasing we know that that the smallest value
863 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
865 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
866 // that case, `Clamp` will always return `Smallest` and
867 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
868 // will be an empty range. Returning an empty range is always safe.
871 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
872 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
875 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
876 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
879 // In some cases we can prove that we don't need a pre or post loop
881 bool ProvablyNoPreloop =
882 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
883 if (!ProvablyNoPreloop)
884 Result.LowLimit = Clamp(Range.getBegin());
886 bool ProvablyNoPostLoop =
887 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
888 if (!ProvablyNoPostLoop)
889 Result.HighLimit = Clamp(Range.getEnd());
894 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
895 const char *Tag) const {
896 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
897 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
898 Result.Blocks.push_back(Clone);
899 Result.Map[BB] = Clone;
902 auto GetClonedValue = [&Result](Value *V) {
903 assert(V && "null values not in domain!");
904 auto It = Result.Map.find(V);
905 if (It == Result.Map.end())
907 return static_cast<Value *>(It->second);
910 Result.Structure = MainLoopStructure.map(GetClonedValue);
911 Result.Structure.Tag = Tag;
913 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
914 BasicBlock *ClonedBB = Result.Blocks[i];
915 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
917 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
919 for (Instruction &I : *ClonedBB)
920 RemapInstruction(&I, Result.Map,
921 RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
923 // Exit blocks will now have one more predecessor and their PHI nodes need
924 // to be edited to reflect that. No phi nodes need to be introduced because
925 // the loop is in LCSSA.
927 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
928 SBBI != SBBE; ++SBBI) {
930 if (OriginalLoop.contains(*SBBI))
931 continue; // not an exit block
933 for (Instruction &I : **SBBI) {
934 if (!isa<PHINode>(&I))
937 PHINode *PN = cast<PHINode>(&I);
938 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
939 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
945 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
946 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
947 BasicBlock *ContinuationBlock) const {
949 // We start with a loop with a single latch:
951 // +--------------------+
955 // +--------+-----------+
956 // | ----------------\
958 // +--------v----v------+ |
962 // +--------------------+ |
966 // +--------------------+ |
968 // | latch >----------/
970 // +-------v------------+
973 // | +--------------------+
975 // +---> original exit |
977 // +--------------------+
979 // We change the control flow to look like
982 // +--------------------+
984 // | preheader >-------------------------+
986 // +--------v-----------+ |
987 // | /-------------+ |
989 // +--------v--v--------+ | |
991 // | header | | +--------+ |
993 // +--------------------+ | | +-----v-----v-----------+
995 // | | | .pseudo.exit |
997 // | | +-----------v-----------+
1000 // | | +--------v-------------+
1001 // +--------------------+ | | | |
1002 // | | | | | ContinuationBlock |
1003 // | latch >------+ | | |
1004 // | | | +----------------------+
1005 // +---------v----------+ |
1008 // | +---------------^-----+
1010 // +-----> .exit.selector |
1012 // +----------v----------+
1014 // +--------------------+ |
1016 // | original exit <----+
1018 // +--------------------+
1021 RewrittenRangeInfo RRI;
1023 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1024 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
1025 &F, &*BBInsertLocation);
1026 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
1027 &*BBInsertLocation);
1029 BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
1030 bool Increasing = LS.IndVarIncreasing;
1032 IRBuilder<> B(PreheaderJump);
1034 // EnterLoopCond - is it okay to start executing this `LS'?
1035 Value *EnterLoopCond = Increasing
1036 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1037 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1039 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1040 PreheaderJump->eraseFromParent();
1042 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
1043 B.SetInsertPoint(LS.LatchBr);
1044 Value *TakeBackedgeLoopCond =
1045 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1046 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1047 Value *CondForBranch = LS.LatchBrExitIdx == 1
1048 ? TakeBackedgeLoopCond
1049 : B.CreateNot(TakeBackedgeLoopCond);
1051 LS.LatchBr->setCondition(CondForBranch);
1053 B.SetInsertPoint(RRI.ExitSelector);
1055 // IterationsLeft - are there any more iterations left, given the original
1056 // upper bound on the induction variable? If not, we branch to the "real"
1058 Value *IterationsLeft = Increasing
1059 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1060 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
1061 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1063 BranchInst *BranchToContinuation =
1064 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1066 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1067 // each of the PHI nodes in the loop header. This feeds into the initial
1068 // value of the same PHI nodes if/when we continue execution.
1069 for (Instruction &I : *LS.Header) {
1070 if (!isa<PHINode>(&I))
1073 PHINode *PN = cast<PHINode>(&I);
1075 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1076 BranchToContinuation);
1078 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1079 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1081 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1084 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1085 BranchToContinuation);
1086 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1087 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1089 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1090 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1091 for (Instruction &I : *LS.LatchExit) {
1092 if (PHINode *PN = dyn_cast<PHINode>(&I))
1093 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1101 void LoopConstrainer::rewriteIncomingValuesForPHIs(
1102 LoopStructure &LS, BasicBlock *ContinuationBlock,
1103 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1105 unsigned PHIIndex = 0;
1106 for (Instruction &I : *LS.Header) {
1107 if (!isa<PHINode>(&I))
1110 PHINode *PN = cast<PHINode>(&I);
1112 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1113 if (PN->getIncomingBlock(i) == ContinuationBlock)
1114 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1117 LS.IndVarStart = RRI.IndVarEnd;
1120 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1121 BasicBlock *OldPreheader,
1122 const char *Tag) const {
1124 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1125 BranchInst::Create(LS.Header, Preheader);
1127 for (Instruction &I : *LS.Header) {
1128 if (!isa<PHINode>(&I))
1131 PHINode *PN = cast<PHINode>(&I);
1132 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1133 replacePHIBlock(PN, OldPreheader, Preheader);
1139 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
1140 Loop *ParentLoop = OriginalLoop.getParentLoop();
1144 for (BasicBlock *BB : BBs)
1145 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
1148 bool LoopConstrainer::run() {
1149 BasicBlock *Preheader = nullptr;
1150 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1151 Preheader = OriginalLoop.getLoopPreheader();
1152 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1155 OriginalPreheader = Preheader;
1156 MainLoopPreheader = Preheader;
1158 Optional<SubRanges> MaybeSR = calculateSubRanges();
1159 if (!MaybeSR.hasValue()) {
1160 DEBUG(dbgs() << "irce: could not compute subranges\n");
1164 SubRanges SR = MaybeSR.getValue();
1165 bool Increasing = MainLoopStructure.IndVarIncreasing;
1167 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1169 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
1170 Instruction *InsertPt = OriginalPreheader->getTerminator();
1172 // It would have been better to make `PreLoop' and `PostLoop'
1173 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1175 ClonedLoop PreLoop, PostLoop;
1177 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1178 bool NeedsPostLoop =
1179 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1181 Value *ExitPreLoopAt = nullptr;
1182 Value *ExitMainLoopAt = nullptr;
1183 const SCEVConstant *MinusOneS =
1184 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1187 const SCEV *ExitPreLoopAtSCEV = nullptr;
1190 ExitPreLoopAtSCEV = *SR.LowLimit;
1192 if (CanBeSMin(SE, *SR.HighLimit)) {
1193 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1194 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1198 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1201 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1202 ExitPreLoopAt->setName("exit.preloop.at");
1205 if (NeedsPostLoop) {
1206 const SCEV *ExitMainLoopAtSCEV = nullptr;
1209 ExitMainLoopAtSCEV = *SR.HighLimit;
1211 if (CanBeSMin(SE, *SR.LowLimit)) {
1212 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1213 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1217 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1220 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1221 ExitMainLoopAt->setName("exit.mainloop.at");
1224 // We clone these ahead of time so that we don't have to deal with changing
1225 // and temporarily invalid IR as we transform the loops.
1227 cloneLoop(PreLoop, "preloop");
1229 cloneLoop(PostLoop, "postloop");
1231 RewrittenRangeInfo PreLoopRRI;
1234 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1235 PreLoop.Structure.Header);
1238 createPreheader(MainLoopStructure, Preheader, "mainloop");
1239 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1240 ExitPreLoopAt, MainLoopPreheader);
1241 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1245 BasicBlock *PostLoopPreheader = nullptr;
1246 RewrittenRangeInfo PostLoopRRI;
1248 if (NeedsPostLoop) {
1250 createPreheader(PostLoop.Structure, Preheader, "postloop");
1251 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1252 ExitMainLoopAt, PostLoopPreheader);
1253 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1257 BasicBlock *NewMainLoopPreheader =
1258 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1259 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1260 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1261 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1263 // Some of the above may be nullptr, filter them out before passing to
1264 // addToParentLoopIfNeeded.
1266 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
1268 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1269 addToParentLoopIfNeeded(PreLoop.Blocks);
1270 addToParentLoopIfNeeded(PostLoop.Blocks);
1275 /// Computes and returns a range of values for the induction variable (IndVar)
1276 /// in which the range check can be safely elided. If it cannot compute such a
1277 /// range, returns None.
1278 Optional<InductiveRangeCheck::Range>
1279 InductiveRangeCheck::computeSafeIterationSpace(
1280 ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
1281 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1282 // variable, that may or may not exist as a real llvm::Value in the loop) and
1283 // this inductive range check is a range check on the "C + D * I" ("C" is
1284 // getOffset() and "D" is getScale()). We rewrite the value being range
1285 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1286 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1287 // can be generalized as needed.
1289 // The actual inequalities we solve are of the form
1291 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1293 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1294 // and subtractions are twos-complement wrapping and comparisons are signed.
1298 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1299 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1300 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1303 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1304 // Hence 0 <= (IndVar + M) < L
1306 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1307 // 127, IndVar = 126 and L = -2 in an i8 world.
1309 if (!IndVar->isAffine())
1312 const SCEV *A = IndVar->getStart();
1313 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1317 const SCEV *C = getOffset();
1318 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1322 ConstantInt *ConstD = D->getValue();
1323 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1326 const SCEV *M = SE.getMinusSCEV(C, A);
1328 const SCEV *Begin = SE.getNegativeSCEV(M);
1329 const SCEV *UpperLimit = nullptr;
1331 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1332 // We can potentially do much better here.
1333 if (Value *V = getLength()) {
1334 UpperLimit = SE.getSCEV(V);
1336 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1337 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1338 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1341 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
1342 return InductiveRangeCheck::Range(Begin, End);
1345 static Optional<InductiveRangeCheck::Range>
1346 IntersectRange(ScalarEvolution &SE,
1347 const Optional<InductiveRangeCheck::Range> &R1,
1348 const InductiveRangeCheck::Range &R2) {
1351 auto &R1Value = R1.getValue();
1353 // TODO: we could widen the smaller range and have this work; but for now we
1354 // bail out to keep things simple.
1355 if (R1Value.getType() != R2.getType())
1358 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1359 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1361 return InductiveRangeCheck::Range(NewBegin, NewEnd);
1364 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1368 if (L->getBlocks().size() >= LoopSizeCutoff) {
1369 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1373 BasicBlock *Preheader = L->getLoopPreheader();
1375 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1379 LLVMContext &Context = Preheader->getContext();
1380 SmallVector<InductiveRangeCheck, 16> RangeChecks;
1381 ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1382 BranchProbabilityInfo &BPI =
1383 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
1385 for (auto BBI : L->getBlocks())
1386 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1387 InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1390 if (RangeChecks.empty())
1393 auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1394 OS << "irce: looking at loop "; L->print(OS);
1395 OS << "irce: loop has " << RangeChecks.size()
1396 << " inductive range checks: \n";
1397 for (InductiveRangeCheck &IRC : RangeChecks)
1401 DEBUG(PrintRecognizedRangeChecks(dbgs()));
1403 if (PrintRangeChecks)
1404 PrintRecognizedRangeChecks(errs());
1406 const char *FailureReason = nullptr;
1407 Optional<LoopStructure> MaybeLoopStructure =
1408 LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
1409 if (!MaybeLoopStructure.hasValue()) {
1410 DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1414 LoopStructure LS = MaybeLoopStructure.getValue();
1415 bool Increasing = LS.IndVarIncreasing;
1416 const SCEV *MinusOne =
1417 SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1418 const SCEVAddRecExpr *IndVar =
1419 cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1421 Optional<InductiveRangeCheck::Range> SafeIterRange;
1422 Instruction *ExprInsertPt = Preheader->getTerminator();
1424 SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
1426 IRBuilder<> B(ExprInsertPt);
1427 for (InductiveRangeCheck &IRC : RangeChecks) {
1428 auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
1429 if (Result.hasValue()) {
1430 auto MaybeSafeIterRange =
1431 IntersectRange(SE, SafeIterRange, Result.getValue());
1432 if (MaybeSafeIterRange.hasValue()) {
1433 RangeChecksToEliminate.push_back(IRC);
1434 SafeIterRange = MaybeSafeIterRange.getValue();
1439 if (!SafeIterRange.hasValue())
1442 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1443 SE, SafeIterRange.getValue());
1444 bool Changed = LC.run();
1447 auto PrintConstrainedLoopInfo = [L]() {
1448 dbgs() << "irce: in function ";
1449 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1450 dbgs() << "constrained ";
1454 DEBUG(PrintConstrainedLoopInfo());
1456 if (PrintChangedLoops)
1457 PrintConstrainedLoopInfo();
1459 // Optimize away the now-redundant range checks.
1461 for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1462 ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
1463 ? ConstantInt::getTrue(Context)
1464 : ConstantInt::getFalse(Context);
1465 IRC.getCheckUse()->set(FoldedRangeCheck);
1472 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1473 return new InductiveRangeCheckElimination;