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"
46 #include "llvm/Analysis/BranchProbabilityInfo.h"
47 #include "llvm/Analysis/InstructionSimplify.h"
48 #include "llvm/Analysis/LoopInfo.h"
49 #include "llvm/Analysis/LoopPass.h"
50 #include "llvm/Analysis/ScalarEvolution.h"
51 #include "llvm/Analysis/ScalarEvolutionExpander.h"
52 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
53 #include "llvm/Analysis/ValueTracking.h"
55 #include "llvm/IR/Dominators.h"
56 #include "llvm/IR/Function.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/IRBuilder.h"
59 #include "llvm/IR/Module.h"
60 #include "llvm/IR/PatternMatch.h"
61 #include "llvm/IR/ValueHandle.h"
62 #include "llvm/IR/Verifier.h"
64 #include "llvm/Support/Debug.h"
66 #include "llvm/Transforms/Scalar.h"
67 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
68 #include "llvm/Transforms/Utils/Cloning.h"
69 #include "llvm/Transforms/Utils/LoopUtils.h"
70 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
71 #include "llvm/Transforms/Utils/UnrollLoop.h"
73 #include "llvm/Pass.h"
79 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
82 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
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 range of values taken by the
97 /// containing loop's induction variable.
99 /// Currently all inductive range checks are branches conditional on an
100 /// expression of the form
102 /// 0 <= (Offset + Scale * I) < Length
104 /// where `I' is the canonical induction variable of a loop to which Offset and
105 /// Scale are loop invariant, and Length is >= 0. Currently the 'false' branch
106 /// is considered cold, looking at profiling data to verify that is a TODO.
108 class InductiveRangeCheck {
114 InductiveRangeCheck() :
115 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
118 const SCEV *getOffset() const { return Offset; }
119 const SCEV *getScale() const { return Scale; }
120 Value *getLength() const { return Length; }
122 void print(raw_ostream &OS) const {
123 OS << "InductiveRangeCheck:\n";
131 getBranch()->print(OS);
134 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
140 BranchInst *getBranch() const { return Branch; }
142 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
143 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
150 Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
151 assert(Begin->getType() == End->getType() && "ill-typed range!");
154 Type *getType() const { return Begin->getType(); }
155 const SCEV *getBegin() const { return Begin; }
156 const SCEV *getEnd() const { return End; }
159 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
161 /// This is the value the condition of the branch needs to evaluate to for the
162 /// branch to take the hot successor (see (1) above).
163 bool getPassingDirection() { return true; }
165 /// Computes a range for the induction variable in which the range check is
166 /// redundant and can be constant-folded away.
167 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
168 IRBuilder<> &B) const;
170 /// Create an inductive range check out of BI if possible, else return
172 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
173 Loop *L, ScalarEvolution &SE,
174 BranchProbabilityInfo &BPI);
177 class InductiveRangeCheckElimination : public LoopPass {
178 InductiveRangeCheck::AllocatorTy Allocator;
182 InductiveRangeCheckElimination() : LoopPass(ID) {
183 initializeInductiveRangeCheckEliminationPass(
184 *PassRegistry::getPassRegistry());
187 void getAnalysisUsage(AnalysisUsage &AU) const override {
188 AU.addRequired<LoopInfoWrapperPass>();
189 AU.addRequiredID(LoopSimplifyID);
190 AU.addRequiredID(LCSSAID);
191 AU.addRequired<ScalarEvolution>();
192 AU.addRequired<BranchProbabilityInfo>();
195 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
198 char InductiveRangeCheckElimination::ID = 0;
201 INITIALIZE_PASS(InductiveRangeCheckElimination, "irce",
202 "Inductive range check elimination", false, false)
204 static bool IsLowerBoundCheck(Value *Check, Value *&IndexV) {
205 using namespace llvm::PatternMatch;
207 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
208 Value *LHS = nullptr, *RHS = nullptr;
210 if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
217 case ICmpInst::ICMP_SLE:
220 case ICmpInst::ICMP_SGE:
221 if (!match(RHS, m_ConstantInt<0>()))
226 case ICmpInst::ICMP_SLT:
229 case ICmpInst::ICMP_SGT:
230 if (!match(RHS, m_ConstantInt<-1>()))
237 static bool IsUpperBoundCheck(Value *Check, Value *Index, Value *&UpperLimit) {
238 using namespace llvm::PatternMatch;
240 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
241 Value *LHS = nullptr, *RHS = nullptr;
243 if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
250 case ICmpInst::ICMP_SGT:
253 case ICmpInst::ICMP_SLT:
259 case ICmpInst::ICMP_UGT:
262 case ICmpInst::ICMP_ULT:
270 /// Split a condition into something semantically equivalent to (0 <= I <
271 /// Limit), both comparisons signed and Len loop invariant on L and positive.
272 /// On success, return true and set Index to I and UpperLimit to Limit. Return
273 /// false on failure (we may still write to UpperLimit and Index on failure).
274 /// It does not try to interpret I as a loop index.
276 static bool SplitRangeCheckCondition(Loop *L, ScalarEvolution &SE,
277 Value *Condition, const SCEV *&Index,
278 Value *&UpperLimit) {
280 // TODO: currently this catches some silly cases like comparing "%idx slt 1".
281 // Our transformations are still correct, but less likely to be profitable in
282 // those cases. We have to come up with some heuristics that pick out the
283 // range checks that are more profitable to clone a loop for. This function
284 // in general can be made more robust.
286 using namespace llvm::PatternMatch;
290 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
292 // In these early checks we assume that the matched UpperLimit is positive.
293 // We'll verify that fact later, before returning true.
295 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
296 Value *IndexV = nullptr;
297 Value *ExpectedUpperBoundCheck = nullptr;
299 if (IsLowerBoundCheck(A, IndexV))
300 ExpectedUpperBoundCheck = B;
301 else if (IsLowerBoundCheck(B, IndexV))
302 ExpectedUpperBoundCheck = A;
306 if (!IsUpperBoundCheck(ExpectedUpperBoundCheck, IndexV, UpperLimit))
309 Index = SE.getSCEV(IndexV);
311 if (isa<SCEVCouldNotCompute>(Index))
314 } else if (match(Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
319 case ICmpInst::ICMP_SGT:
322 case ICmpInst::ICMP_SLT:
324 Index = SE.getSCEV(A);
325 if (isa<SCEVCouldNotCompute>(Index) || !SE.isKnownNonNegative(Index))
329 case ICmpInst::ICMP_UGT:
332 case ICmpInst::ICMP_ULT:
334 Index = SE.getSCEV(A);
335 if (isa<SCEVCouldNotCompute>(Index))
343 const SCEV *UpperLimitSCEV = SE.getSCEV(UpperLimit);
344 if (isa<SCEVCouldNotCompute>(UpperLimitSCEV) ||
345 !SE.isKnownNonNegative(UpperLimitSCEV))
348 if (SE.getLoopDisposition(UpperLimitSCEV, L) !=
349 ScalarEvolution::LoopInvariant) {
350 DEBUG(dbgs() << " in function: " << L->getHeader()->getParent()->getName()
352 dbgs() << " UpperLimit is not loop invariant: "
353 << UpperLimit->getName() << "\n";);
361 InductiveRangeCheck *
362 InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
363 Loop *L, ScalarEvolution &SE,
364 BranchProbabilityInfo &BPI) {
366 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
369 BranchProbability LikelyTaken(15, 16);
371 if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
374 Value *Length = nullptr;
375 const SCEV *IndexSCEV = nullptr;
377 if (!SplitRangeCheckCondition(L, SE, BI->getCondition(), IndexSCEV, Length))
380 assert(IndexSCEV && Length && "contract with SplitRangeCheckCondition!");
382 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
384 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
389 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
390 IRC->Length = Length;
391 IRC->Offset = IndexAddRec->getStart();
392 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
399 /// This class is used to constrain loops to run within a given iteration space.
400 /// The algorithm this class implements is given a Loop and a range [Begin,
401 /// End). The algorithm then tries to break out a "main loop" out of the loop
402 /// it is given in a way that the "main loop" runs with the induction variable
403 /// in a subset of [Begin, End). The algorithm emits appropriate pre and post
404 /// loops to run any remaining iterations. The pre loop runs any iterations in
405 /// which the induction variable is < Begin, and the post loop runs any
406 /// iterations in which the induction variable is >= End.
408 class LoopConstrainer {
410 // Keeps track of the structure of a loop. This is similar to llvm::Loop,
411 // except that it is more lightweight and can track the state of a loop
412 // through changing and potentially invalid IR. This structure also
413 // formalizes the kinds of loops we can deal with -- ones that have a single
414 // latch that is also an exiting block *and* have a canonical induction
416 struct LoopStructure {
422 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
423 // successor is `LatchExit', the exit block of the loop.
425 BasicBlock *LatchExit;
426 unsigned LatchBrExitIdx;
428 // The canonical induction variable. It's value is `CIVStart` on the 0th
429 // itertion and `CIVNext` for all iterations after that.
434 LoopStructure() : Tag(""), Header(nullptr), Latch(nullptr),
435 LatchBr(nullptr), LatchExit(nullptr),
436 LatchBrExitIdx(-1), CIV(nullptr),
437 CIVStart(nullptr), CIVNext(nullptr) { }
439 template <typename M> LoopStructure map(M Map) const {
440 LoopStructure Result;
442 Result.Header = cast<BasicBlock>(Map(Header));
443 Result.Latch = cast<BasicBlock>(Map(Latch));
444 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
445 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
446 Result.LatchBrExitIdx = LatchBrExitIdx;
447 Result.CIV = cast<PHINode>(Map(CIV));
448 Result.CIVNext = Map(CIVNext);
449 Result.CIVStart = Map(CIVStart);
454 // The representation of a clone of the original loop we started out with.
457 std::vector<BasicBlock *> Blocks;
459 // `Map` maps values in the clonee into values in the cloned version
460 ValueToValueMapTy Map;
462 // An instance of `LoopStructure` for the cloned loop
463 LoopStructure Structure;
466 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
467 // more details on what these fields mean.
468 struct RewrittenRangeInfo {
469 BasicBlock *PseudoExit;
470 BasicBlock *ExitSelector;
471 std::vector<PHINode *> PHIValuesAtPseudoExit;
473 RewrittenRangeInfo() : PseudoExit(nullptr), ExitSelector(nullptr) { }
476 // Calculated subranges we restrict the iteration space of the main loop to.
477 // See the implementation of `calculateSubRanges' for more details on how
478 // these fields are computed. `ExitPreLoopAt' is `None' if we don't need a
479 // pre loop. `ExitMainLoopAt' is `None' if we don't need a post loop.
481 Optional<Value *> ExitPreLoopAt;
482 Optional<Value *> ExitMainLoopAt;
485 // A utility function that does a `replaceUsesOfWith' on the incoming block
486 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
487 // incoming block list with `ReplaceBy'.
488 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
489 BasicBlock *ReplaceBy);
491 // Try to "parse" `OriginalLoop' and populate the various out parameters.
492 // Returns true on success, false on failure.
494 bool recognizeLoop(LoopStructure &LoopStructureOut,
495 const SCEV *&LatchCountOut, BasicBlock *&PreHeaderOut,
496 const char *&FailureReasonOut) const;
498 // Compute a safe set of limits for the main loop to run in -- effectively the
499 // intersection of `Range' and the iteration space of the original loop.
500 // Return the header count (1 + the latch taken count) in `HeaderCount'.
501 // Return None if unable to compute the set of subranges.
503 Optional<SubRanges> calculateSubRanges(Value *&HeaderCount) const;
505 // Clone `OriginalLoop' and return the result in CLResult. The IR after
506 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
507 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
508 // but there is no such edge.
510 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
512 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
513 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
514 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
515 // `OriginalHeaderCount'.
517 // If there are iterations left to execute, control is made to jump to
518 // `ContinuationBlock', otherwise they take the normal loop exit. The
519 // returned `RewrittenRangeInfo' object is populated as follows:
521 // .PseudoExit is a basic block that unconditionally branches to
522 // `ContinuationBlock'.
524 // .ExitSelector is a basic block that decides, on exit from the loop,
525 // whether to branch to the "true" exit or to `PseudoExit'.
527 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
528 // for each PHINode in the loop header on taking the pseudo exit.
530 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
531 // preheader because it is made to branch to the loop header only
535 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
537 BasicBlock *ContinuationBlock) const;
539 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
540 // function creates a new preheader for `LS' and returns it.
542 BasicBlock *createPreheader(const LoopConstrainer::LoopStructure &LS,
543 BasicBlock *OldPreheader, const char *Tag) const;
545 // `ContinuationBlockAndPreheader' was the continuation block for some call to
546 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
547 // This function rewrites the PHI nodes in `LS.Header' to start with the
549 void rewriteIncomingValuesForPHIs(
550 LoopConstrainer::LoopStructure &LS,
551 BasicBlock *ContinuationBlockAndPreheader,
552 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
554 // Even though we do not preserve any passes at this time, we at least need to
555 // keep the parent loop structure consistent. The `LPPassManager' seems to
556 // verify this after running a loop pass. This function adds the list of
557 // blocks denoted by BBs to this loops parent loop if required.
558 void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
560 // Some global state.
565 // Information about the original loop we started out with.
567 LoopInfo &OriginalLoopInfo;
568 const SCEV *LatchTakenCount;
569 BasicBlock *OriginalPreheader;
570 Value *OriginalHeaderCount;
572 // The preheader of the main loop. This may or may not be different from
573 // `OriginalPreheader'.
574 BasicBlock *MainLoopPreheader;
576 // The range we need to run the main loop in.
577 InductiveRangeCheck::Range Range;
579 // The structure of the main loop (see comment at the beginning of this class
581 LoopStructure MainLoopStructure;
584 LoopConstrainer(Loop &L, LoopInfo &LI, ScalarEvolution &SE,
585 InductiveRangeCheck::Range R)
586 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), SE(SE),
587 OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
588 OriginalPreheader(nullptr), OriginalHeaderCount(nullptr),
589 MainLoopPreheader(nullptr), Range(R) { }
591 // Entry point for the algorithm. Returns true on success.
597 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
598 BasicBlock *ReplaceBy) {
599 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
600 if (PN->getIncomingBlock(i) == Block)
601 PN->setIncomingBlock(i, ReplaceBy);
604 bool LoopConstrainer::recognizeLoop(LoopStructure &LoopStructureOut,
605 const SCEV *&LatchCountOut,
606 BasicBlock *&PreheaderOut,
607 const char *&FailureReason) const {
608 using namespace llvm::PatternMatch;
610 assert(OriginalLoop.isLoopSimplifyForm() &&
611 "should follow from addRequired<>");
613 BasicBlock *Latch = OriginalLoop.getLoopLatch();
614 if (!OriginalLoop.isLoopExiting(Latch)) {
615 FailureReason = "no loop latch";
619 PHINode *CIV = OriginalLoop.getCanonicalInductionVariable();
621 FailureReason = "no CIV";
625 BasicBlock *Header = OriginalLoop.getHeader();
626 BasicBlock *Preheader = OriginalLoop.getLoopPreheader();
628 FailureReason = "no preheader";
632 Value *CIVNext = CIV->getIncomingValueForBlock(Latch);
633 Value *CIVStart = CIV->getIncomingValueForBlock(Preheader);
635 const SCEV *LatchCount = SE.getExitCount(&OriginalLoop, Latch);
636 if (isa<SCEVCouldNotCompute>(LatchCount)) {
637 FailureReason = "could not compute latch count";
641 // While SCEV does most of the analysis for us, we still have to
642 // modify the latch; and currently we can only deal with certain
643 // kinds of latches. This can be made more sophisticated as needed.
645 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
647 if (!LatchBr || LatchBr->isUnconditional()) {
648 FailureReason = "latch terminator not conditional branch";
652 // Currently we only support a latch condition of the form:
654 // %condition = icmp slt %civNext, %limit
655 // br i1 %condition, label %header, label %exit
657 if (LatchBr->getSuccessor(0) != Header) {
658 FailureReason = "unknown latch form (header not first successor)";
662 Value *CIVComparedTo = nullptr;
663 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
664 if (!(match(LatchBr->getCondition(),
665 m_ICmp(Pred, m_Specific(CIVNext), m_Value(CIVComparedTo))) &&
666 Pred == ICmpInst::ICMP_SLT)) {
667 FailureReason = "unknown latch form (not slt)";
671 // IndVarSimplify will sometimes leave behind (in SCEV's cache) backedge-taken
672 // counts that are narrower than the canonical induction variable. These
673 // values are still accurate, and we could probably use them after sign/zero
674 // extension; but for now we just bail out of the transformation to keep
676 const SCEV *CIVComparedToSCEV = SE.getSCEV(CIVComparedTo);
677 if (isa<SCEVCouldNotCompute>(CIVComparedToSCEV) ||
678 CIVComparedToSCEV->getType() != LatchCount->getType()) {
679 FailureReason = "could not relate CIV to latch expression";
683 const SCEV *ShouldBeOne = SE.getMinusSCEV(CIVComparedToSCEV, LatchCount);
684 const SCEVConstant *SCEVOne = dyn_cast<SCEVConstant>(ShouldBeOne);
685 if (!SCEVOne || SCEVOne->getValue()->getValue() != 1) {
686 FailureReason = "unexpected header count in latch";
690 unsigned LatchBrExitIdx = 1;
691 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
693 assert(SE.getLoopDisposition(LatchCount, &OriginalLoop) ==
694 ScalarEvolution::LoopInvariant &&
695 "loop variant exit count doesn't make sense!");
697 assert(!OriginalLoop.contains(LatchExit) && "expected an exit block!");
699 LoopStructureOut.Tag = "main";
700 LoopStructureOut.Header = Header;
701 LoopStructureOut.Latch = Latch;
702 LoopStructureOut.LatchBr = LatchBr;
703 LoopStructureOut.LatchExit = LatchExit;
704 LoopStructureOut.LatchBrExitIdx = LatchBrExitIdx;
705 LoopStructureOut.CIV = CIV;
706 LoopStructureOut.CIVNext = CIVNext;
707 LoopStructureOut.CIVStart = CIVStart;
709 LatchCountOut = LatchCount;
710 PreheaderOut = Preheader;
711 FailureReason = nullptr;
716 Optional<LoopConstrainer::SubRanges>
717 LoopConstrainer::calculateSubRanges(Value *&HeaderCountOut) const {
718 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
720 if (Range.getType() != Ty)
723 SCEVExpander Expander(SE, "irce");
724 Instruction *InsertPt = OriginalPreheader->getTerminator();
726 LoopConstrainer::SubRanges Result;
728 // I think we can be more aggressive here and make this nuw / nsw if the
729 // addition that feeds into the icmp for the latch's terminating branch is nuw
730 // / nsw. In any case, a wrapping 2's complement addition is safe.
731 ConstantInt *One = ConstantInt::get(Ty, 1);
732 const SCEV *HeaderCountSCEV = SE.getAddExpr(LatchTakenCount, SE.getSCEV(One));
733 HeaderCountOut = Expander.expandCodeFor(HeaderCountSCEV, Ty, InsertPt);
735 const SCEV *Zero = SE.getConstant(Ty, 0);
737 // In some cases we can prove that we don't need a pre or post loop
739 bool ProvablyNoPreloop =
740 SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Zero);
741 if (!ProvablyNoPreloop) {
742 const SCEV *ExitPreLoopAtSCEV =
743 SE.getSMinExpr(HeaderCountSCEV, Range.getBegin());
744 Result.ExitPreLoopAt =
745 Expander.expandCodeFor(ExitPreLoopAtSCEV, Ty, InsertPt);
748 bool ProvablyNoPostLoop =
749 SE.isKnownPredicate(ICmpInst::ICMP_SLE, HeaderCountSCEV, Range.getEnd());
750 if (!ProvablyNoPostLoop) {
751 const SCEV *ExitMainLoopAtSCEV =
752 SE.getSMinExpr(HeaderCountSCEV, Range.getEnd());
753 Result.ExitMainLoopAt =
754 Expander.expandCodeFor(ExitMainLoopAtSCEV, Ty, InsertPt);
760 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
761 const char *Tag) const {
762 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
763 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
764 Result.Blocks.push_back(Clone);
765 Result.Map[BB] = Clone;
768 auto GetClonedValue = [&Result](Value *V) {
769 assert(V && "null values not in domain!");
770 auto It = Result.Map.find(V);
771 if (It == Result.Map.end())
773 return static_cast<Value *>(It->second);
776 Result.Structure = MainLoopStructure.map(GetClonedValue);
777 Result.Structure.Tag = Tag;
779 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
780 BasicBlock *ClonedBB = Result.Blocks[i];
781 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
783 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
785 for (Instruction &I : *ClonedBB)
786 RemapInstruction(&I, Result.Map,
787 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
789 // Exit blocks will now have one more predecessor and their PHI nodes need
790 // to be edited to reflect that. No phi nodes need to be introduced because
791 // the loop is in LCSSA.
793 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
794 SBBI != SBBE; ++SBBI) {
796 if (OriginalLoop.contains(*SBBI))
797 continue; // not an exit block
799 for (Instruction &I : **SBBI) {
800 if (!isa<PHINode>(&I))
803 PHINode *PN = cast<PHINode>(&I);
804 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
805 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
811 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
812 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitLoopAt,
813 BasicBlock *ContinuationBlock) const {
815 // We start with a loop with a single latch:
817 // +--------------------+
821 // +--------+-----------+
822 // | ----------------\
824 // +--------v----v------+ |
828 // +--------------------+ |
832 // +--------------------+ |
834 // | latch >----------/
836 // +-------v------------+
839 // | +--------------------+
841 // +---> original exit |
843 // +--------------------+
845 // We change the control flow to look like
848 // +--------------------+
850 // | preheader >-------------------------+
852 // +--------v-----------+ |
853 // | /-------------+ |
855 // +--------v--v--------+ | |
857 // | header | | +--------+ |
859 // +--------------------+ | | +-----v-----v-----------+
861 // | | | .pseudo.exit |
863 // | | +-----------v-----------+
866 // | | +--------v-------------+
867 // +--------------------+ | | | |
868 // | | | | | ContinuationBlock |
869 // | latch >------+ | | |
870 // | | | +----------------------+
871 // +---------v----------+ |
874 // | +---------------^-----+
876 // +-----> .exit.selector |
878 // +----------v----------+
880 // +--------------------+ |
882 // | original exit <----+
884 // +--------------------+
887 RewrittenRangeInfo RRI;
889 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
890 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
891 &F, BBInsertLocation);
892 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
895 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
897 IRBuilder<> B(PreheaderJump);
899 // EnterLoopCond - is it okay to start executing this `LS'?
900 Value *EnterLoopCond = B.CreateICmpSLT(LS.CIVStart, ExitLoopAt);
901 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
902 PreheaderJump->eraseFromParent();
904 assert(LS.LatchBrExitIdx == 1 && "generalize this as needed!");
906 B.SetInsertPoint(LS.LatchBr);
908 // ContinueCond - is it okay to execute the next iteration in `LS'?
909 Value *ContinueCond = B.CreateICmpSLT(LS.CIVNext, ExitLoopAt);
911 LS.LatchBr->setCondition(ContinueCond);
912 assert(LS.LatchBr->getSuccessor(LS.LatchBrExitIdx) == LS.LatchExit &&
914 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
916 B.SetInsertPoint(RRI.ExitSelector);
918 // IterationsLeft - are there any more iterations left, given the original
919 // upper bound on the induction variable? If not, we branch to the "real"
921 Value *IterationsLeft = B.CreateICmpSLT(LS.CIVNext, OriginalHeaderCount);
922 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
924 BranchInst *BranchToContinuation =
925 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
927 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
928 // each of the PHI nodes in the loop header. This feeds into the initial
929 // value of the same PHI nodes if/when we continue execution.
930 for (Instruction &I : *LS.Header) {
931 if (!isa<PHINode>(&I))
934 PHINode *PN = cast<PHINode>(&I);
936 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
937 BranchToContinuation);
939 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
940 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
942 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
945 // The latch exit now has a branch from `RRI.ExitSelector' instead of
946 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
947 for (Instruction &I : *LS.LatchExit) {
948 if (PHINode *PN = dyn_cast<PHINode>(&I))
949 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
957 void LoopConstrainer::rewriteIncomingValuesForPHIs(
958 LoopConstrainer::LoopStructure &LS, BasicBlock *ContinuationBlock,
959 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
961 unsigned PHIIndex = 0;
962 for (Instruction &I : *LS.Header) {
963 if (!isa<PHINode>(&I))
966 PHINode *PN = cast<PHINode>(&I);
968 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
969 if (PN->getIncomingBlock(i) == ContinuationBlock)
970 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
973 LS.CIVStart = LS.CIV->getIncomingValueForBlock(ContinuationBlock);
977 LoopConstrainer::createPreheader(const LoopConstrainer::LoopStructure &LS,
978 BasicBlock *OldPreheader,
979 const char *Tag) const {
981 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
982 BranchInst::Create(LS.Header, Preheader);
984 for (Instruction &I : *LS.Header) {
985 if (!isa<PHINode>(&I))
988 PHINode *PN = cast<PHINode>(&I);
989 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
990 replacePHIBlock(PN, OldPreheader, Preheader);
996 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
997 Loop *ParentLoop = OriginalLoop.getParentLoop();
1001 for (BasicBlock *BB : BBs)
1002 ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
1005 bool LoopConstrainer::run() {
1006 BasicBlock *Preheader = nullptr;
1007 const char *CouldNotProceedBecause = nullptr;
1008 if (!recognizeLoop(MainLoopStructure, LatchTakenCount, Preheader,
1009 CouldNotProceedBecause)) {
1010 DEBUG(dbgs() << "irce: could not recognize loop, " << CouldNotProceedBecause
1015 OriginalPreheader = Preheader;
1016 MainLoopPreheader = Preheader;
1018 Optional<SubRanges> MaybeSR = calculateSubRanges(OriginalHeaderCount);
1019 if (!MaybeSR.hasValue()) {
1020 DEBUG(dbgs() << "irce: could not compute subranges\n");
1023 SubRanges SR = MaybeSR.getValue();
1025 // It would have been better to make `PreLoop' and `PostLoop'
1026 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1028 ClonedLoop PreLoop, PostLoop;
1029 bool NeedsPreLoop = SR.ExitPreLoopAt.hasValue();
1030 bool NeedsPostLoop = SR.ExitMainLoopAt.hasValue();
1032 // We clone these ahead of time so that we don't have to deal with changing
1033 // and temporarily invalid IR as we transform the loops.
1035 cloneLoop(PreLoop, "preloop");
1037 cloneLoop(PostLoop, "postloop");
1039 RewrittenRangeInfo PreLoopRRI;
1042 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1043 PreLoop.Structure.Header);
1046 createPreheader(MainLoopStructure, Preheader, "mainloop");
1048 changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1049 SR.ExitPreLoopAt.getValue(), MainLoopPreheader);
1050 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1054 BasicBlock *PostLoopPreheader = nullptr;
1055 RewrittenRangeInfo PostLoopRRI;
1057 if (NeedsPostLoop) {
1059 createPreheader(PostLoop.Structure, Preheader, "postloop");
1060 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1061 SR.ExitMainLoopAt.getValue(),
1063 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1067 BasicBlock *NewMainLoopPreheader =
1068 MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1069 BasicBlock *NewBlocks[] = {PostLoopPreheader, PreLoopRRI.PseudoExit,
1070 PreLoopRRI.ExitSelector, PostLoopRRI.PseudoExit,
1071 PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1073 // Some of the above may be nullptr, filter them out before passing to
1074 // addToParentLoopIfNeeded.
1076 std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
1078 addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1079 addToParentLoopIfNeeded(PreLoop.Blocks);
1080 addToParentLoopIfNeeded(PostLoop.Blocks);
1085 /// Computes and returns a range of values for the induction variable in which
1086 /// the range check can be safely elided. If it cannot compute such a range,
1088 Optional<InductiveRangeCheck::Range>
1089 InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
1090 IRBuilder<> &B) const {
1092 // Currently we support inequalities of the form:
1094 // 0 <= Offset + 1 * CIV < L given L >= 0
1096 // The inequality is satisfied by -Offset <= CIV < (L - Offset) [^1]. All
1097 // additions and subtractions are twos-complement wrapping and comparisons are
1102 // If there exists CIV such that -Offset <= CIV < (L - Offset) then it
1103 // follows that -Offset <= (-Offset + L) [== Eq. 1]. Since L >= 0, if
1104 // (-Offset + L) sign-overflows then (-Offset + L) < (-Offset). Hence by
1105 // [Eq. 1], (-Offset + L) could not have overflown.
1107 // This means CIV = t + (-Offset) for t in [0, L). Hence (CIV + Offset) =
1108 // t. Hence 0 <= (CIV + Offset) < L
1110 // [^1]: Note that the solution does _not_ apply if L < 0; consider values
1111 // Offset = 127, CIV = 126 and L = -2 in an i8 world.
1113 const SCEVConstant *ScaleC = dyn_cast<SCEVConstant>(getScale());
1114 if (!(ScaleC && ScaleC->getValue()->getValue() == 1)) {
1115 DEBUG(dbgs() << "irce: could not compute safe iteration space for:\n";
1120 const SCEV *Begin = SE.getNegativeSCEV(getOffset());
1121 const SCEV *End = SE.getMinusSCEV(SE.getSCEV(getLength()), getOffset());
1123 return InductiveRangeCheck::Range(Begin, End);
1126 static Optional<InductiveRangeCheck::Range>
1127 IntersectRange(ScalarEvolution &SE,
1128 const Optional<InductiveRangeCheck::Range> &R1,
1129 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1132 auto &R1Value = R1.getValue();
1134 // TODO: we could widen the smaller range and have this work; but for now we
1135 // bail out to keep things simple.
1136 if (R1Value.getType() != R2.getType())
1139 const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1140 const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1142 return InductiveRangeCheck::Range(NewBegin, NewEnd);
1145 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1146 if (L->getBlocks().size() >= LoopSizeCutoff) {
1147 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1151 BasicBlock *Preheader = L->getLoopPreheader();
1153 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1157 LLVMContext &Context = Preheader->getContext();
1158 InductiveRangeCheck::AllocatorTy IRCAlloc;
1159 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1160 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1161 BranchProbabilityInfo &BPI = getAnalysis<BranchProbabilityInfo>();
1163 for (auto BBI : L->getBlocks())
1164 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1165 if (InductiveRangeCheck *IRC =
1166 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
1167 RangeChecks.push_back(IRC);
1169 if (RangeChecks.empty())
1172 DEBUG(dbgs() << "irce: looking at loop "; L->print(dbgs());
1173 dbgs() << "irce: loop has " << RangeChecks.size()
1174 << " inductive range checks: \n";
1175 for (InductiveRangeCheck *IRC : RangeChecks)
1179 Optional<InductiveRangeCheck::Range> SafeIterRange;
1180 Instruction *ExprInsertPt = Preheader->getTerminator();
1182 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1184 IRBuilder<> B(ExprInsertPt);
1185 for (InductiveRangeCheck *IRC : RangeChecks) {
1186 auto Result = IRC->computeSafeIterationSpace(SE, B);
1187 if (Result.hasValue()) {
1188 auto MaybeSafeIterRange =
1189 IntersectRange(SE, SafeIterRange, Result.getValue(), B);
1190 if (MaybeSafeIterRange.hasValue()) {
1191 RangeChecksToEliminate.push_back(IRC);
1192 SafeIterRange = MaybeSafeIterRange.getValue();
1197 if (!SafeIterRange.hasValue())
1200 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), SE,
1201 SafeIterRange.getValue());
1202 bool Changed = LC.run();
1205 auto PrintConstrainedLoopInfo = [L]() {
1206 dbgs() << "irce: in function ";
1207 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1208 dbgs() << "constrained ";
1212 DEBUG(PrintConstrainedLoopInfo());
1214 if (PrintChangedLoops)
1215 PrintConstrainedLoopInfo();
1217 // Optimize away the now-redundant range checks.
1219 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1220 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1221 ? ConstantInt::getTrue(Context)
1222 : ConstantInt::getFalse(Context);
1223 IRC->getBranch()->setCondition(FoldedRangeCheck);
1230 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1231 return new InductiveRangeCheckElimination;