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"
74 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
77 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
80 static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
83 static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
84 cl::Hidden, cl::init(10));
86 #define DEBUG_TYPE "irce"
90 /// An inductive range check is conditional branch in a loop with
92 /// 1. a very cold successor (i.e. the branch jumps to that successor very
97 /// 2. a condition that is provably true for some contiguous range of values
98 /// taken by the containing loop's induction variable.
100 class InductiveRangeCheck {
101 // Classifies a range check
102 enum RangeCheckKind : unsigned {
103 // Range check of the form "0 <= I".
104 RANGE_CHECK_LOWER = 1,
106 // Range check of the form "I < L" where L is known positive.
107 RANGE_CHECK_UPPER = 2,
109 // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
111 RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
113 // Unrecognized range check condition.
114 RANGE_CHECK_UNKNOWN = (unsigned)-1
117 static const char *rangeCheckKindToStr(RangeCheckKind);
125 static RangeCheckKind parseRangeCheckICmp(ICmpInst *ICI, ScalarEvolution &SE,
126 Value *&Index, Value *&Length);
128 static InductiveRangeCheck::RangeCheckKind
129 parseRangeCheck(Loop *L, ScalarEvolution &SE, Value *Condition,
130 const SCEV *&Index, Value *&UpperLimit);
132 InductiveRangeCheck() :
133 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
136 const SCEV *getOffset() const { return Offset; }
137 const SCEV *getScale() const { return Scale; }
138 Value *getLength() const { return Length; }
140 void print(raw_ostream &OS) const {
141 OS << "InductiveRangeCheck:\n";
142 OS << " Kind: " << rangeCheckKindToStr(Kind) << "\n";
153 getBranch()->print(OS);
157 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
163 BranchInst *getBranch() const { return Branch; }
165 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
166 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
173 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
174 assert(Begin->getType() == End->getType() && "ill-typed range!");
177 Type *getType() const { return Begin->getType(); }
178 const SCEV *getBegin() const { return Begin; }
179 const SCEV *getEnd() const { return End; }
182 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
184 /// This is the value the condition of the branch needs to evaluate to for the
185 /// branch to take the hot successor (see (1) above).
186 bool getPassingDirection() { return true; }
188 /// Computes a range for the induction variable (IndVar) in which the range
189 /// check is redundant and can be constant-folded away. The induction
190 /// variable is not required to be the canonical {0,+,1} induction variable.
191 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
192 const SCEVAddRecExpr *IndVar,
193 IRBuilder<> &B) const;
195 /// Create an inductive range check out of BI if possible, else return
197 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
198 Loop *L, ScalarEvolution &SE,
199 BranchProbabilityInfo &BPI);
202 class InductiveRangeCheckElimination : public LoopPass {
203 InductiveRangeCheck::AllocatorTy Allocator;
207 InductiveRangeCheckElimination() : LoopPass(ID) {
208 initializeInductiveRangeCheckEliminationPass(
209 *PassRegistry::getPassRegistry());
212 void getAnalysisUsage(AnalysisUsage &AU) const override {
213 AU.addRequired<LoopInfoWrapperPass>();
214 AU.addRequiredID(LoopSimplifyID);
215 AU.addRequiredID(LCSSAID);
216 AU.addRequired<ScalarEvolution>();
217 AU.addRequired<BranchProbabilityInfo>();
220 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
223 char InductiveRangeCheckElimination::ID = 0;
226 INITIALIZE_PASS(InductiveRangeCheckElimination, "irce",
227 "Inductive range check elimination", false, false)
229 const char *InductiveRangeCheck::rangeCheckKindToStr(
230 InductiveRangeCheck::RangeCheckKind RCK) {
232 case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
233 return "RANGE_CHECK_UNKNOWN";
235 case InductiveRangeCheck::RANGE_CHECK_UPPER:
236 return "RANGE_CHECK_UPPER";
238 case InductiveRangeCheck::RANGE_CHECK_LOWER:
239 return "RANGE_CHECK_LOWER";
241 case InductiveRangeCheck::RANGE_CHECK_BOTH:
242 return "RANGE_CHECK_BOTH";
245 llvm_unreachable("unknown range check type!");
248 /// Parse a single ICmp instruction, `ICI`, into a range check. If `ICI`
250 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
251 /// `Index` and `Length` to `nullptr`. Otherwise set `Index` to the value
253 /// range checked, and set `Length` to the upper limit `Index` is being range
254 /// checked with if (and only if) the range check type is stronger or equal to
255 /// RANGE_CHECK_UPPER.
257 InductiveRangeCheck::RangeCheckKind
258 InductiveRangeCheck::parseRangeCheckICmp(ICmpInst *ICI, ScalarEvolution &SE,
259 Value *&Index, Value *&Length) {
261 using namespace llvm::PatternMatch;
263 ICmpInst::Predicate Pred = ICI->getPredicate();
264 Value *LHS = ICI->getOperand(0);
265 Value *RHS = ICI->getOperand(1);
269 return RANGE_CHECK_UNKNOWN;
271 case ICmpInst::ICMP_SLE:
274 case ICmpInst::ICMP_SGE:
275 if (match(RHS, m_ConstantInt<0>())) {
277 return RANGE_CHECK_LOWER;
279 return RANGE_CHECK_UNKNOWN;
281 case ICmpInst::ICMP_SLT:
284 case ICmpInst::ICMP_SGT:
285 if (match(RHS, m_ConstantInt<-1>())) {
287 return RANGE_CHECK_LOWER;
290 if (SE.isKnownNonNegative(SE.getSCEV(LHS))) {
293 return RANGE_CHECK_UPPER;
295 return RANGE_CHECK_UNKNOWN;
297 case ICmpInst::ICMP_ULT:
300 case ICmpInst::ICMP_UGT:
301 if (SE.isKnownNonNegative(SE.getSCEV(LHS))) {
304 return RANGE_CHECK_BOTH;
306 return RANGE_CHECK_UNKNOWN;
309 llvm_unreachable("default clause returns!");
312 /// Parses an arbitrary condition into a range check. `Length` is set only if
313 /// the range check is recognized to be `RANGE_CHECK_UPPER` or stronger.
314 InductiveRangeCheck::RangeCheckKind
315 InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
316 Value *Condition, const SCEV *&Index,
318 using namespace llvm::PatternMatch;
323 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
324 Value *IndexA = nullptr, *IndexB = nullptr;
325 Value *LengthA = nullptr, *LengthB = nullptr;
326 ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
328 if (!ICmpA || !ICmpB)
329 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
331 auto RCKindA = parseRangeCheckICmp(ICmpA, SE, IndexA, LengthA);
332 auto RCKindB = parseRangeCheckICmp(ICmpB, SE, IndexB, LengthB);
334 if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
335 RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
336 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
338 if (IndexA != IndexB)
339 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
341 if (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB)
342 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
344 Index = SE.getSCEV(IndexA);
345 if (isa<SCEVCouldNotCompute>(Index))
346 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
348 Length = LengthA == nullptr ? LengthB : LengthA;
350 return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
353 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
354 Value *IndexVal = nullptr;
356 auto RCKind = parseRangeCheckICmp(ICI, SE, IndexVal, Length);
358 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
359 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
361 Index = SE.getSCEV(IndexVal);
362 if (isa<SCEVCouldNotCompute>(Index))
363 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
368 return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
372 InductiveRangeCheck *
373 InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
374 Loop *L, ScalarEvolution &SE,
375 BranchProbabilityInfo &BPI) {
377 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
380 BranchProbability LikelyTaken(15, 16);
382 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
385 Value *Length = nullptr;
386 const SCEV *IndexSCEV = nullptr;
388 auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
391 if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
394 assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
395 assert((!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) || Length) &&
396 "contract with SplitRangeCheckCondition!");
398 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
400 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
405 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
406 IRC->Length = Length;
407 IRC->Offset = IndexAddRec->getStart();
408 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
416 // Keeps track of the structure of a loop. This is similar to llvm::Loop,
417 // except that it is more lightweight and can track the state of a loop through
418 // changing and potentially invalid IR. This structure also formalizes the
419 // kinds of loops we can deal with -- ones that have a single latch that is also
420 // an exiting block *and* have a canonical induction variable.
421 struct LoopStructure {
427 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
428 // successor is `LatchExit', the exit block of the loop.
430 BasicBlock *LatchExit;
431 unsigned LatchBrExitIdx;
436 bool IndVarIncreasing;
439 : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
440 LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
441 IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
443 template <typename M> LoopStructure map(M Map) const {
444 LoopStructure Result;
446 Result.Header = cast<BasicBlock>(Map(Header));
447 Result.Latch = cast<BasicBlock>(Map(Latch));
448 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
449 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
450 Result.LatchBrExitIdx = LatchBrExitIdx;
451 Result.IndVarNext = Map(IndVarNext);
452 Result.IndVarStart = Map(IndVarStart);
453 Result.LoopExitAt = Map(LoopExitAt);
454 Result.IndVarIncreasing = IndVarIncreasing;
458 static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
459 BranchProbabilityInfo &BPI,
464 /// This class is used to constrain loops to run within a given iteration space.
465 /// The algorithm this class implements is given a Loop and a range [Begin,
466 /// End). The algorithm then tries to break out a "main loop" out of the loop
467 /// it is given in a way that the "main loop" runs with the induction variable
468 /// in a subset of [Begin, End). The algorithm emits appropriate pre and post
469 /// loops to run any remaining iterations. The pre loop runs any iterations in
470 /// which the induction variable is < Begin, and the post loop runs any
471 /// iterations in which the induction variable is >= End.
473 class LoopConstrainer {
474 // The representation of a clone of the original loop we started out with.
477 std::vector<BasicBlock *> Blocks;
479 // `Map` maps values in the clonee into values in the cloned version
480 ValueToValueMapTy Map;
482 // An instance of `LoopStructure` for the cloned loop
483 LoopStructure Structure;
486 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
487 // more details on what these fields mean.
488 struct RewrittenRangeInfo {
489 BasicBlock *PseudoExit;
490 BasicBlock *ExitSelector;
491 std::vector<PHINode *> PHIValuesAtPseudoExit;
495 : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
498 // Calculated subranges we restrict the iteration space of the main loop to.
499 // See the implementation of `calculateSubRanges' for more details on how
500 // these fields are computed. `LowLimit` is None if there is no restriction
501 // on low end of the restricted iteration space of the main loop. `HighLimit`
502 // is None if there is no restriction on high end of the restricted iteration
503 // space of the main loop.
506 Optional<const SCEV *> LowLimit;
507 Optional<const SCEV *> HighLimit;
510 // A utility function that does a `replaceUsesOfWith' on the incoming block
511 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
512 // incoming block list with `ReplaceBy'.
513 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
514 BasicBlock *ReplaceBy);
516 // Compute a safe set of limits for the main loop to run in -- effectively the
517 // intersection of `Range' and the iteration space of the original loop.
518 // Return None if unable to compute the set of subranges.
520 Optional<SubRanges> calculateSubRanges() const;
522 // Clone `OriginalLoop' and return the result in CLResult. The IR after
523 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
524 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
525 // but there is no such edge.
527 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
529 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
530 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
531 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
532 // `OriginalHeaderCount'.
534 // If there are iterations left to execute, control is made to jump to
535 // `ContinuationBlock', otherwise they take the normal loop exit. The
536 // returned `RewrittenRangeInfo' object is populated as follows:
538 // .PseudoExit is a basic block that unconditionally branches to
539 // `ContinuationBlock'.
541 // .ExitSelector is a basic block that decides, on exit from the loop,
542 // whether to branch to the "true" exit or to `PseudoExit'.
544 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
545 // for each PHINode in the loop header on taking the pseudo exit.
547 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
548 // preheader because it is made to branch to the loop header only
552 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
554 BasicBlock *ContinuationBlock) const;
556 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
557 // function creates a new preheader for `LS' and returns it.
559 BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
560 const char *Tag) const;
562 // `ContinuationBlockAndPreheader' was the continuation block for some call to
563 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
564 // This function rewrites the PHI nodes in `LS.Header' to start with the
566 void rewriteIncomingValuesForPHIs(
567 LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
568 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
570 // Even though we do not preserve any passes at this time, we at least need to
571 // keep the parent loop structure consistent. The `LPPassManager' seems to
572 // verify this after running a loop pass. This function adds the list of
573 // blocks denoted by BBs to this loops parent loop if required.
574 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
576 // Some global state.
581 // Information about the original loop we started out with.
583 LoopInfo &OriginalLoopInfo;
584 const SCEV *LatchTakenCount;
585 BasicBlock *OriginalPreheader;
587 // The preheader of the main loop. This may or may not be different from
588 // `OriginalPreheader'.
589 BasicBlock *MainLoopPreheader;
591 // The range we need to run the main loop in.
592 InductiveRangeCheck::Range Range;
594 // The structure of the main loop (see comment at the beginning of this class
596 LoopStructure MainLoopStructure;
599 LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
600 ScalarEvolution &SE, InductiveRangeCheck::Range R)
601 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
602 SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
603 OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
604 MainLoopStructure(LS) {}
606 // Entry point for the algorithm. Returns true on success.
612 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
613 BasicBlock *ReplaceBy) {
614 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
615 if (PN->getIncomingBlock(i) == Block)
616 PN->setIncomingBlock(i, ReplaceBy);
619 static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
621 APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
622 return SE.getSignedRange(S).contains(SMax) &&
623 SE.getUnsignedRange(S).contains(SMax);
626 static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
628 APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
629 return SE.getSignedRange(S).contains(SMin) &&
630 SE.getUnsignedRange(S).contains(SMin);
633 Optional<LoopStructure>
634 LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
635 Loop &L, const char *&FailureReason) {
636 assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
638 BasicBlock *Latch = L.getLoopLatch();
639 if (!L.isLoopExiting(Latch)) {
640 FailureReason = "no loop latch";
644 BasicBlock *Header = L.getHeader();
645 BasicBlock *Preheader = L.getLoopPreheader();
647 FailureReason = "no preheader";
651 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
652 if (!LatchBr || LatchBr->isUnconditional()) {
653 FailureReason = "latch terminator not conditional branch";
657 unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
659 BranchProbability ExitProbability =
660 BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
662 if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
663 FailureReason = "short running loop, not profitable";
667 ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
668 if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
669 FailureReason = "latch terminator branch not conditional on integral icmp";
673 const SCEV *LatchCount = SE.getExitCount(&L, Latch);
674 if (isa<SCEVCouldNotCompute>(LatchCount)) {
675 FailureReason = "could not compute latch count";
679 ICmpInst::Predicate Pred = ICI->getPredicate();
680 Value *LeftValue = ICI->getOperand(0);
681 const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
682 IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
684 Value *RightValue = ICI->getOperand(1);
685 const SCEV *RightSCEV = SE.getSCEV(RightValue);
687 // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
688 if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
689 if (isa<SCEVAddRecExpr>(RightSCEV)) {
690 std::swap(LeftSCEV, RightSCEV);
691 std::swap(LeftValue, RightValue);
692 Pred = ICmpInst::getSwappedPredicate(Pred);
694 FailureReason = "no add recurrences in the icmp";
699 auto IsInductionVar = [&SE](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
703 IntegerType *Ty = cast<IntegerType>(AR->getType());
704 IntegerType *WideTy =
705 IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
707 // Currently we only work with induction variables that have been proved to
708 // not wrap. This restriction can potentially be lifted in the future.
710 const SCEVAddRecExpr *ExtendAfterOp =
711 dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
715 const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
716 const SCEV *ExtendedStep =
717 SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
719 bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
720 ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
725 if (const SCEVConstant *StepExpr =
726 dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
727 ConstantInt *StepCI = StepExpr->getValue();
728 if (StepCI->isOne() || StepCI->isMinusOne()) {
729 IsIncreasing = StepCI->isOne();
737 // `ICI` is interpreted as taking the backedge if the *next* value of the
738 // induction variable satisfies some constraint.
740 const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
741 bool IsIncreasing = false;
742 if (!IsInductionVar(IndVarNext, IsIncreasing)) {
743 FailureReason = "LHS in icmp not induction variable";
747 ConstantInt *One = ConstantInt::get(IndVarTy, 1);
748 // TODO: generalize the predicates here to also match their unsigned variants.
750 bool FoundExpectedPred =
751 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
752 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
754 if (!FoundExpectedPred) {
755 FailureReason = "expected icmp slt semantically, found something else";
759 if (LatchBrExitIdx == 0) {
760 if (CanBeSMax(SE, RightSCEV)) {
761 // TODO: this restriction is easily removable -- we just have to
762 // remember that the icmp was an slt and not an sle.
763 FailureReason = "limit may overflow when coercing sle to slt";
767 IRBuilder<> B(&*Preheader->rbegin());
768 RightValue = B.CreateAdd(RightValue, One);
772 bool FoundExpectedPred =
773 (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
774 (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
776 if (!FoundExpectedPred) {
777 FailureReason = "expected icmp sgt semantically, found something else";
781 if (LatchBrExitIdx == 0) {
782 if (CanBeSMin(SE, RightSCEV)) {
783 // TODO: this restriction is easily removable -- we just have to
784 // remember that the icmp was an sgt and not an sge.
785 FailureReason = "limit may overflow when coercing sge to sgt";
789 IRBuilder<> B(&*Preheader->rbegin());
790 RightValue = B.CreateSub(RightValue, One);
794 const SCEV *StartNext = IndVarNext->getStart();
795 const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
796 const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
798 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
800 assert(SE.getLoopDisposition(LatchCount, &L) ==
801 ScalarEvolution::LoopInvariant &&
802 "loop variant exit count doesn't make sense!");
804 assert(!L.contains(LatchExit) && "expected an exit block!");
805 const DataLayout &DL = Preheader->getModule()->getDataLayout();
806 Value *IndVarStartV =
807 SCEVExpander(SE, DL, "irce")
808 .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
809 IndVarStartV->setName("indvar.start");
811 LoopStructure Result;
814 Result.Header = Header;
815 Result.Latch = Latch;
816 Result.LatchBr = LatchBr;
817 Result.LatchExit = LatchExit;
818 Result.LatchBrExitIdx = LatchBrExitIdx;
819 Result.IndVarStart = IndVarStartV;
820 Result.IndVarNext = LeftValue;
821 Result.IndVarIncreasing = IsIncreasing;
822 Result.LoopExitAt = RightValue;
824 FailureReason = nullptr;
829 Optional<LoopConstrainer::SubRanges>
830 LoopConstrainer::calculateSubRanges() const {
831 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
833 if (Range.getType() != Ty)
836 LoopConstrainer::SubRanges Result;
838 // I think we can be more aggressive here and make this nuw / nsw if the
839 // addition that feeds into the icmp for the latch's terminating branch is nuw
840 // / nsw. In any case, a wrapping 2's complement addition is safe.
841 ConstantInt *One = ConstantInt::get(Ty, 1);
842 const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
843 const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
845 bool Increasing = MainLoopStructure.IndVarIncreasing;
847 // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
848 // range of values the induction variable takes.
850 const SCEV *Smallest = nullptr, *Greatest = nullptr;
856 // These two computations may sign-overflow. Here is why that is okay:
858 // We know that the induction variable does not sign-overflow on any
859 // iteration except the last one, and it starts at `Start` and ends at
860 // `End`, decrementing by one every time.
862 // * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
863 // induction variable is decreasing we know that that the smallest value
864 // the loop body is actually executed with is `INT_SMIN` == `Smallest`.
866 // * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`. In
867 // that case, `Clamp` will always return `Smallest` and
868 // [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
869 // will be an empty range. Returning an empty range is always safe.
872 Smallest = SE.getAddExpr(End, SE.getSCEV(One));
873 Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
876 auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
877 return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
880 // In some cases we can prove that we don't need a pre or post loop
882 bool ProvablyNoPreloop =
883 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
884 if (!ProvablyNoPreloop)
885 Result.LowLimit = Clamp(Range.getBegin());
887 bool ProvablyNoPostLoop =
888 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
889 if (!ProvablyNoPostLoop)
890 Result.HighLimit = Clamp(Range.getEnd());
895 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
896 const char *Tag) const {
897 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
898 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
899 Result.Blocks.push_back(Clone);
900 Result.Map[BB] = Clone;
903 auto GetClonedValue = [&Result](Value *V) {
904 assert(V && "null values not in domain!");
905 auto It = Result.Map.find(V);
906 if (It == Result.Map.end())
908 return static_cast<Value *>(It->second);
911 Result.Structure = MainLoopStructure.map(GetClonedValue);
912 Result.Structure.Tag = Tag;
914 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
915 BasicBlock *ClonedBB = Result.Blocks[i];
916 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
918 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
920 for (Instruction &I : *ClonedBB)
921 RemapInstruction(&I, Result.Map,
922 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
924 // Exit blocks will now have one more predecessor and their PHI nodes need
925 // to be edited to reflect that. No phi nodes need to be introduced because
926 // the loop is in LCSSA.
928 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
929 SBBI != SBBE; ++SBBI) {
931 if (OriginalLoop.contains(*SBBI))
932 continue; // not an exit block
934 for (Instruction &I : **SBBI) {
935 if (!isa<PHINode>(&I))
938 PHINode *PN = cast<PHINode>(&I);
939 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
940 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
946 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
947 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
948 BasicBlock *ContinuationBlock) const {
950 // We start with a loop with a single latch:
952 // +--------------------+
956 // +--------+-----------+
957 // | ----------------\
959 // +--------v----v------+ |
963 // +--------------------+ |
967 // +--------------------+ |
969 // | latch >----------/
971 // +-------v------------+
974 // | +--------------------+
976 // +---> original exit |
978 // +--------------------+
980 // We change the control flow to look like
983 // +--------------------+
985 // | preheader >-------------------------+
987 // +--------v-----------+ |
988 // | /-------------+ |
990 // +--------v--v--------+ | |
992 // | header | | +--------+ |
994 // +--------------------+ | | +-----v-----v-----------+
996 // | | | .pseudo.exit |
998 // | | +-----------v-----------+
1001 // | | +--------v-------------+
1002 // +--------------------+ | | | |
1003 // | | | | | ContinuationBlock |
1004 // | latch >------+ | | |
1005 // | | | +----------------------+
1006 // +---------v----------+ |
1009 // | +---------------^-----+
1011 // +-----> .exit.selector |
1013 // +----------v----------+
1015 // +--------------------+ |
1017 // | original exit <----+
1019 // +--------------------+
1022 RewrittenRangeInfo RRI;
1024 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1025 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
1026 &F, BBInsertLocation);
1027 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
1030 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
1031 bool Increasing = LS.IndVarIncreasing;
1033 IRBuilder<> B(PreheaderJump);
1035 // EnterLoopCond - is it okay to start executing this `LS'?
1036 Value *EnterLoopCond = Increasing
1037 ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1038 : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1040 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1041 PreheaderJump->eraseFromParent();
1043 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
1044 B.SetInsertPoint(LS.LatchBr);
1045 Value *TakeBackedgeLoopCond =
1046 Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1047 : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1048 Value *CondForBranch = LS.LatchBrExitIdx == 1
1049 ? TakeBackedgeLoopCond
1050 : B.CreateNot(TakeBackedgeLoopCond);
1052 LS.LatchBr->setCondition(CondForBranch);
1054 B.SetInsertPoint(RRI.ExitSelector);
1056 // IterationsLeft - are there any more iterations left, given the original
1057 // upper bound on the induction variable? If not, we branch to the "real"
1059 Value *IterationsLeft = Increasing
1060 ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1061 : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
1062 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1064 BranchInst *BranchToContinuation =
1065 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1067 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1068 // each of the PHI nodes in the loop header. This feeds into the initial
1069 // value of the same PHI nodes if/when we continue execution.
1070 for (Instruction &I : *LS.Header) {
1071 if (!isa<PHINode>(&I))
1074 PHINode *PN = cast<PHINode>(&I);
1076 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1077 BranchToContinuation);
1079 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1080 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1082 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1085 RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1086 BranchToContinuation);
1087 RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1088 RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1090 // The latch exit now has a branch from `RRI.ExitSelector' instead of
1091 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
1092 for (Instruction &I : *LS.LatchExit) {
1093 if (PHINode *PN = dyn_cast<PHINode>(&I))
1094 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1102 void LoopConstrainer::rewriteIncomingValuesForPHIs(
1103 LoopStructure &LS, BasicBlock *ContinuationBlock,
1104 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1106 unsigned PHIIndex = 0;
1107 for (Instruction &I : *LS.Header) {
1108 if (!isa<PHINode>(&I))
1111 PHINode *PN = cast<PHINode>(&I);
1113 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1114 if (PN->getIncomingBlock(i) == ContinuationBlock)
1115 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1118 LS.IndVarStart = RRI.IndVarEnd;
1121 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1122 BasicBlock *OldPreheader,
1123 const char *Tag) const {
1125 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1126 BranchInst::Create(LS.Header, Preheader);
1128 for (Instruction &I : *LS.Header) {
1129 if (!isa<PHINode>(&I))
1132 PHINode *PN = cast<PHINode>(&I);
1133 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1134 replacePHIBlock(PN, OldPreheader, Preheader);
1140 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
1141 Loop *ParentLoop = OriginalLoop.getParentLoop();
1145 for (BasicBlock *BB : BBs)
1146 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
1149 bool LoopConstrainer::run() {
1150 BasicBlock *Preheader = nullptr;
1151 LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1152 Preheader = OriginalLoop.getLoopPreheader();
1153 assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1156 OriginalPreheader = Preheader;
1157 MainLoopPreheader = Preheader;
1159 Optional<SubRanges> MaybeSR = calculateSubRanges();
1160 if (!MaybeSR.hasValue()) {
1161 DEBUG(dbgs() << "irce: could not compute subranges\n");
1165 SubRanges SR = MaybeSR.getValue();
1166 bool Increasing = MainLoopStructure.IndVarIncreasing;
1168 cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1170 SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
1171 Instruction *InsertPt = OriginalPreheader->getTerminator();
1173 // It would have been better to make `PreLoop' and `PostLoop'
1174 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1176 ClonedLoop PreLoop, PostLoop;
1178 Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1179 bool NeedsPostLoop =
1180 Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1182 Value *ExitPreLoopAt = nullptr;
1183 Value *ExitMainLoopAt = nullptr;
1184 const SCEVConstant *MinusOneS =
1185 cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1188 const SCEV *ExitPreLoopAtSCEV = nullptr;
1191 ExitPreLoopAtSCEV = *SR.LowLimit;
1193 if (CanBeSMin(SE, *SR.HighLimit)) {
1194 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1195 << "preloop exit limit. HighLimit = " << *(*SR.HighLimit)
1199 ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1202 ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1203 ExitPreLoopAt->setName("exit.preloop.at");
1206 if (NeedsPostLoop) {
1207 const SCEV *ExitMainLoopAtSCEV = nullptr;
1210 ExitMainLoopAtSCEV = *SR.HighLimit;
1212 if (CanBeSMin(SE, *SR.LowLimit)) {
1213 DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1214 << "mainloop exit limit. LowLimit = " << *(*SR.LowLimit)
1218 ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1221 ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1222 ExitMainLoopAt->setName("exit.mainloop.at");
1225 // We clone these ahead of time so that we don't have to deal with changing
1226 // and temporarily invalid IR as we transform the loops.
1228 cloneLoop(PreLoop, "preloop");
1230 cloneLoop(PostLoop, "postloop");
1232 RewrittenRangeInfo PreLoopRRI;
1235 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1236 PreLoop.Structure.Header);
1239 createPreheader(MainLoopStructure, Preheader, "mainloop");
1240 PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1241 ExitPreLoopAt, MainLoopPreheader);
1242 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1246 BasicBlock *PostLoopPreheader = nullptr;
1247 RewrittenRangeInfo PostLoopRRI;
1249 if (NeedsPostLoop) {
1251 createPreheader(PostLoop.Structure, Preheader, "postloop");
1252 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1253 ExitMainLoopAt, PostLoopPreheader);
1254 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1258 BasicBlock *NewMainLoopPreheader =
1259 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1260 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1261 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1262 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1264 // Some of the above may be nullptr, filter them out before passing to
1265 // addToParentLoopIfNeeded.
1267 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
1269 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1270 addToParentLoopIfNeeded(PreLoop.Blocks);
1271 addToParentLoopIfNeeded(PostLoop.Blocks);
1276 /// Computes and returns a range of values for the induction variable (IndVar)
1277 /// in which the range check can be safely elided. If it cannot compute such a
1278 /// range, returns None.
1279 Optional<InductiveRangeCheck::Range>
1280 InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
1281 const SCEVAddRecExpr *IndVar,
1282 IRBuilder<> &) const {
1283 // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1284 // variable, that may or may not exist as a real llvm::Value in the loop) and
1285 // this inductive range check is a range check on the "C + D * I" ("C" is
1286 // getOffset() and "D" is getScale()). We rewrite the value being range
1287 // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1288 // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1289 // can be generalized as needed.
1291 // The actual inequalities we solve are of the form
1293 // 0 <= M + 1 * IndVar < L given L >= 0 (i.e. N == 1)
1295 // The inequality is satisfied by -M <= IndVar < (L - M) [^1]. All additions
1296 // and subtractions are twos-complement wrapping and comparisons are signed.
1300 // If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1301 // that -M <= (-M + L) [== Eq. 1]. Since L >= 0, if (-M + L) sign-overflows
1302 // then (-M + L) < (-M). Hence by [Eq. 1], (-M + L) could not have
1305 // This means IndVar = t + (-M) for t in [0, L). Hence (IndVar + M) = t.
1306 // Hence 0 <= (IndVar + M) < L
1308 // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1309 // 127, IndVar = 126 and L = -2 in an i8 world.
1311 if (!IndVar->isAffine())
1314 const SCEV *A = IndVar->getStart();
1315 const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1319 const SCEV *C = getOffset();
1320 const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1324 ConstantInt *ConstD = D->getValue();
1325 if (!(ConstD->isMinusOne() || ConstD->isOne()))
1328 const SCEV *M = SE.getMinusSCEV(C, A);
1330 const SCEV *Begin = SE.getNegativeSCEV(M);
1331 const SCEV *UpperLimit = nullptr;
1333 // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1334 // We can potentially do much better here.
1335 if (Value *V = getLength()) {
1336 UpperLimit = SE.getSCEV(V);
1338 assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1339 unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1340 UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1343 const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
1344 return InductiveRangeCheck::Range(Begin, End);
1347 static Optional<InductiveRangeCheck::Range>
1348 IntersectRange(ScalarEvolution &SE,
1349 const Optional<InductiveRangeCheck::Range> &R1,
1350 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1353 auto &R1Value = R1.getValue();
1355 // TODO: we could widen the smaller range and have this work; but for now we
1356 // bail out to keep things simple.
1357 if (R1Value.getType() != R2.getType())
1360 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1361 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1363 return InductiveRangeCheck::Range(NewBegin, NewEnd);
1366 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1367 if (L->getBlocks().size() >= LoopSizeCutoff) {
1368 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1372 BasicBlock *Preheader = L->getLoopPreheader();
1374 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1378 LLVMContext &Context = Preheader->getContext();
1379 InductiveRangeCheck::AllocatorTy IRCAlloc;
1380 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1381 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1382 BranchProbabilityInfo &BPI = getAnalysis<BranchProbabilityInfo>();
1384 for (auto BBI : L->getBlocks())
1385 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1386 if (InductiveRangeCheck *IRC =
1387 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
1388 RangeChecks.push_back(IRC);
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, B);
1429 if (Result.hasValue()) {
1430 auto MaybeSafeIterRange =
1431 IntersectRange(SE, SafeIterRange, Result.getValue(), B);
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->getBranch()->setCondition(FoldedRangeCheck);
1472 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1473 return new InductiveRangeCheckElimination;