blob: ea621ba66426c01f66d1b02c7429aed9bdb33393 [file] [log] [blame]
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001//===-- InductiveRangeCheckElimination.cpp - ------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9// The InductiveRangeCheckElimination pass splits a loop's iteration space into
10// three disjoint ranges. It does that in a way such that the loop running in
11// the middle loop provably does not need range checks. As an example, it will
12// convert
13//
14// len = < known positive >
15// for (i = 0; i < n; i++) {
16// if (0 <= i && i < len) {
17// do_something();
18// } else {
19// throw_out_of_bounds();
20// }
21// }
22//
23// to
24//
25// len = < known positive >
26// limit = smin(n, len)
27// // no first segment
28// for (i = 0; i < limit; i++) {
29// if (0 <= i && i < len) { // this check is fully redundant
30// do_something();
31// } else {
32// throw_out_of_bounds();
33// }
34// }
35// for (i = limit; i < n; i++) {
36// if (0 <= i && i < len) {
37// do_something();
38// } else {
39// throw_out_of_bounds();
40// }
41// }
42//===----------------------------------------------------------------------===//
43
44#include "llvm/ADT/Optional.h"
45
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
54#include "llvm/IR/Dominators.h"
55#include "llvm/IR/Function.h"
56#include "llvm/IR/Instructions.h"
57#include "llvm/IR/IRBuilder.h"
58#include "llvm/IR/Module.h"
59#include "llvm/IR/PatternMatch.h"
60#include "llvm/IR/ValueHandle.h"
61#include "llvm/IR/Verifier.h"
62
63#include "llvm/Support/Debug.h"
64
65#include "llvm/Transforms/Scalar.h"
66#include "llvm/Transforms/Utils/BasicBlockUtils.h"
67#include "llvm/Transforms/Utils/Cloning.h"
68#include "llvm/Transforms/Utils/LoopUtils.h"
69#include "llvm/Transforms/Utils/SimplifyIndVar.h"
70#include "llvm/Transforms/Utils/UnrollLoop.h"
71
72#include "llvm/Pass.h"
73
74#include <array>
75
76using namespace llvm;
77
78cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
79 cl::init(64));
80
81cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
82 cl::init(false));
83
84#define DEBUG_TYPE "irce"
85
86namespace {
87
88/// An inductive range check is conditional branch in a loop with
89///
90/// 1. a very cold successor (i.e. the branch jumps to that successor very
91/// rarely)
92///
93/// and
94///
95/// 2. a condition that is provably true for some range of values taken by the
96/// containing loop's induction variable.
97///
98/// Currently all inductive range checks are branches conditional on an
99/// expression of the form
100///
101/// 0 <= (Offset + Scale * I) < Length
102///
103/// where `I' is the canonical induction variable of a loop to which Offset and
104/// Scale are loop invariant, and Length is >= 0. Currently the 'false' branch
105/// is considered cold, looking at profiling data to verify that is a TODO.
106
107class InductiveRangeCheck {
108 const SCEV *Offset;
109 const SCEV *Scale;
110 Value *Length;
111 BranchInst *Branch;
112
113 InductiveRangeCheck() :
114 Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
115
116public:
117 const SCEV *getOffset() const { return Offset; }
118 const SCEV *getScale() const { return Scale; }
119 Value *getLength() const { return Length; }
120
121 void print(raw_ostream &OS) const {
122 OS << "InductiveRangeCheck:\n";
123 OS << " Offset: ";
124 Offset->print(OS);
125 OS << " Scale: ";
126 Scale->print(OS);
127 OS << " Length: ";
128 Length->print(OS);
129 OS << " Branch: ";
130 getBranch()->print(OS);
131 }
132
133#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
134 void dump() {
135 print(dbgs());
136 }
137#endif
138
139 BranchInst *getBranch() const { return Branch; }
140
Sanjoy Das351db052015-01-22 09:32:02 +0000141 /// Represents an signed integer range [Range.getBegin(), Range.getEnd()). If
142 /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
143
144 class Range {
145 Value *Begin;
146 Value *End;
147
148 public:
149 Range(Value *Begin, Value *End) : Begin(Begin), End(End) {
150 assert(Begin->getType() == End->getType() && "ill-typed range!");
151 }
152
153 Type *getType() const { return Begin->getType(); }
154 Value *getBegin() const { return Begin; }
155 Value *getEnd() const { return End; }
156 };
157
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000158 typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
159
160 /// This is the value the condition of the branch needs to evaluate to for the
161 /// branch to take the hot successor (see (1) above).
162 bool getPassingDirection() { return true; }
163
164 /// Computes a range for the induction variable in which the range check is
165 /// redundant and can be constant-folded away.
166 Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
167 IRBuilder<> &B) const;
168
169 /// Create an inductive range check out of BI if possible, else return
170 /// nullptr.
171 static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
172 Loop *L, ScalarEvolution &SE);
173};
174
175class InductiveRangeCheckElimination : public LoopPass {
176 InductiveRangeCheck::AllocatorTy Allocator;
177
178public:
179 static char ID;
180 InductiveRangeCheckElimination() : LoopPass(ID) {
181 initializeInductiveRangeCheckEliminationPass(
182 *PassRegistry::getPassRegistry());
183 }
184
185 void getAnalysisUsage(AnalysisUsage &AU) const override {
Chandler Carruth4f8f3072015-01-17 14:16:18 +0000186 AU.addRequired<LoopInfoWrapperPass>();
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000187 AU.addRequiredID(LoopSimplifyID);
188 AU.addRequiredID(LCSSAID);
189 AU.addRequired<ScalarEvolution>();
190 }
191
192 bool runOnLoop(Loop *L, LPPassManager &LPM) override;
193};
194
195char InductiveRangeCheckElimination::ID = 0;
196}
197
198INITIALIZE_PASS(InductiveRangeCheckElimination, "irce",
199 "Inductive range check elimination", false, false)
200
201static bool IsLowerBoundCheck(Value *Check, Value *&IndexV) {
202 using namespace llvm::PatternMatch;
203
204 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
205 Value *LHS = nullptr, *RHS = nullptr;
206
207 if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
208 return false;
209
210 switch (Pred) {
211 default:
212 return false;
213
214 case ICmpInst::ICMP_SLE:
215 std::swap(LHS, RHS);
216 // fallthrough
217 case ICmpInst::ICMP_SGE:
218 if (!match(RHS, m_ConstantInt<0>()))
219 return false;
220 IndexV = LHS;
221 return true;
222
223 case ICmpInst::ICMP_SLT:
224 std::swap(LHS, RHS);
225 // fallthrough
226 case ICmpInst::ICMP_SGT:
227 if (!match(RHS, m_ConstantInt<-1>()))
228 return false;
229 IndexV = LHS;
230 return true;
231 }
232}
233
234static bool IsUpperBoundCheck(Value *Check, Value *Index, Value *&UpperLimit) {
235 using namespace llvm::PatternMatch;
236
237 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
238 Value *LHS = nullptr, *RHS = nullptr;
239
240 if (!match(Check, m_ICmp(Pred, m_Value(LHS), m_Value(RHS))))
241 return false;
242
243 switch (Pred) {
244 default:
245 return false;
246
247 case ICmpInst::ICMP_SGT:
248 std::swap(LHS, RHS);
249 // fallthrough
250 case ICmpInst::ICMP_SLT:
251 if (LHS != Index)
252 return false;
253 UpperLimit = RHS;
254 return true;
255
256 case ICmpInst::ICMP_UGT:
257 std::swap(LHS, RHS);
258 // fallthrough
259 case ICmpInst::ICMP_ULT:
260 if (LHS != Index)
261 return false;
262 UpperLimit = RHS;
263 return true;
264 }
265}
266
267/// Split a condition into something semantically equivalent to (0 <= I <
268/// Limit), both comparisons signed and Len loop invariant on L and positive.
269/// On success, return true and set Index to I and UpperLimit to Limit. Return
270/// false on failure (we may still write to UpperLimit and Index on failure).
271/// It does not try to interpret I as a loop index.
272///
273static bool SplitRangeCheckCondition(Loop *L, ScalarEvolution &SE,
274 Value *Condition, const SCEV *&Index,
275 Value *&UpperLimit) {
276
277 // TODO: currently this catches some silly cases like comparing "%idx slt 1".
278 // Our transformations are still correct, but less likely to be profitable in
279 // those cases. We have to come up with some heuristics that pick out the
280 // range checks that are more profitable to clone a loop for. This function
281 // in general can be made more robust.
282
283 using namespace llvm::PatternMatch;
284
285 Value *A = nullptr;
286 Value *B = nullptr;
287 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
288
289 // In these early checks we assume that the matched UpperLimit is positive.
290 // We'll verify that fact later, before returning true.
291
292 if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
293 Value *IndexV = nullptr;
294 Value *ExpectedUpperBoundCheck = nullptr;
295
296 if (IsLowerBoundCheck(A, IndexV))
297 ExpectedUpperBoundCheck = B;
298 else if (IsLowerBoundCheck(B, IndexV))
299 ExpectedUpperBoundCheck = A;
300 else
301 return false;
302
303 if (!IsUpperBoundCheck(ExpectedUpperBoundCheck, IndexV, UpperLimit))
304 return false;
305
306 Index = SE.getSCEV(IndexV);
307
308 if (isa<SCEVCouldNotCompute>(Index))
309 return false;
310
311 } else if (match(Condition, m_ICmp(Pred, m_Value(A), m_Value(B)))) {
312 switch (Pred) {
313 default:
314 return false;
315
316 case ICmpInst::ICMP_SGT:
317 std::swap(A, B);
318 // fall through
319 case ICmpInst::ICMP_SLT:
320 UpperLimit = B;
321 Index = SE.getSCEV(A);
322 if (isa<SCEVCouldNotCompute>(Index) || !SE.isKnownNonNegative(Index))
323 return false;
324 break;
325
326 case ICmpInst::ICMP_UGT:
327 std::swap(A, B);
328 // fall through
329 case ICmpInst::ICMP_ULT:
330 UpperLimit = B;
331 Index = SE.getSCEV(A);
332 if (isa<SCEVCouldNotCompute>(Index))
333 return false;
334 break;
335 }
336 } else {
337 return false;
338 }
339
340 const SCEV *UpperLimitSCEV = SE.getSCEV(UpperLimit);
341 if (isa<SCEVCouldNotCompute>(UpperLimitSCEV) ||
342 !SE.isKnownNonNegative(UpperLimitSCEV))
343 return false;
344
345 if (SE.getLoopDisposition(UpperLimitSCEV, L) !=
346 ScalarEvolution::LoopInvariant) {
347 DEBUG(dbgs() << " in function: " << L->getHeader()->getParent()->getName()
348 << " ";
349 dbgs() << " UpperLimit is not loop invariant: "
350 << UpperLimit->getName() << "\n";);
351 return false;
352 }
353
354 return true;
355}
356
357InductiveRangeCheck *
358InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
359 Loop *L, ScalarEvolution &SE) {
360
361 if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
362 return nullptr;
363
364 Value *Length = nullptr;
365 const SCEV *IndexSCEV = nullptr;
366
367 if (!SplitRangeCheckCondition(L, SE, BI->getCondition(), IndexSCEV, Length))
368 return nullptr;
369
370 assert(IndexSCEV && Length && "contract with SplitRangeCheckCondition!");
371
372 const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
373 bool IsAffineIndex =
374 IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
375
376 if (!IsAffineIndex)
377 return nullptr;
378
379 InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
380 IRC->Length = Length;
381 IRC->Offset = IndexAddRec->getStart();
382 IRC->Scale = IndexAddRec->getStepRecurrence(SE);
383 IRC->Branch = BI;
384 return IRC;
385}
386
387static Value *MaybeSimplify(Value *V) {
388 if (Instruction *I = dyn_cast<Instruction>(V))
389 if (Value *Simplified = SimplifyInstruction(I))
390 return Simplified;
391 return V;
392}
393
394static Value *ConstructSMinOf(Value *X, Value *Y, IRBuilder<> &B) {
395 return MaybeSimplify(B.CreateSelect(B.CreateICmpSLT(X, Y), X, Y));
396}
397
398static Value *ConstructSMaxOf(Value *X, Value *Y, IRBuilder<> &B) {
399 return MaybeSimplify(B.CreateSelect(B.CreateICmpSGT(X, Y), X, Y));
400}
401
402namespace {
403
404/// This class is used to constrain loops to run within a given iteration space.
405/// The algorithm this class implements is given a Loop and a range [Begin,
406/// End). The algorithm then tries to break out a "main loop" out of the loop
407/// it is given in a way that the "main loop" runs with the induction variable
408/// in a subset of [Begin, End). The algorithm emits appropriate pre and post
409/// loops to run any remaining iterations. The pre loop runs any iterations in
410/// which the induction variable is < Begin, and the post loop runs any
411/// iterations in which the induction variable is >= End.
412///
413class LoopConstrainer {
414
415 // Keeps track of the structure of a loop. This is similar to llvm::Loop,
416 // except that it is more lightweight and can track the state of a loop
417 // through changing and potentially invalid IR. This structure also
418 // formalizes the kinds of loops we can deal with -- ones that have a single
419 // latch that is also an exiting block *and* have a canonical induction
420 // variable.
421 struct LoopStructure {
422 const char *Tag;
423
424 BasicBlock *Header;
425 BasicBlock *Latch;
426
427 // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
428 // successor is `LatchExit', the exit block of the loop.
429 BranchInst *LatchBr;
430 BasicBlock *LatchExit;
431 unsigned LatchBrExitIdx;
432
433 // The canonical induction variable. It's value is `CIVStart` on the 0th
434 // itertion and `CIVNext` for all iterations after that.
435 PHINode *CIV;
436 Value *CIVStart;
437 Value *CIVNext;
438
439 LoopStructure() : Tag(""), Header(nullptr), Latch(nullptr),
440 LatchBr(nullptr), LatchExit(nullptr),
441 LatchBrExitIdx(-1), CIV(nullptr),
442 CIVStart(nullptr), CIVNext(nullptr) { }
443
444 template <typename M> LoopStructure map(M Map) const {
445 LoopStructure Result;
446 Result.Tag = Tag;
447 Result.Header = cast<BasicBlock>(Map(Header));
448 Result.Latch = cast<BasicBlock>(Map(Latch));
449 Result.LatchBr = cast<BranchInst>(Map(LatchBr));
450 Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
451 Result.LatchBrExitIdx = LatchBrExitIdx;
452 Result.CIV = cast<PHINode>(Map(CIV));
453 Result.CIVNext = Map(CIVNext);
454 Result.CIVStart = Map(CIVStart);
455 return Result;
456 }
457 };
458
459 // The representation of a clone of the original loop we started out with.
460 struct ClonedLoop {
461 // The cloned blocks
462 std::vector<BasicBlock *> Blocks;
463
464 // `Map` maps values in the clonee into values in the cloned version
465 ValueToValueMapTy Map;
466
467 // An instance of `LoopStructure` for the cloned loop
468 LoopStructure Structure;
469 };
470
471 // Result of rewriting the range of a loop. See changeIterationSpaceEnd for
472 // more details on what these fields mean.
473 struct RewrittenRangeInfo {
474 BasicBlock *PseudoExit;
475 BasicBlock *ExitSelector;
476 std::vector<PHINode *> PHIValuesAtPseudoExit;
477
478 RewrittenRangeInfo() : PseudoExit(nullptr), ExitSelector(nullptr) { }
479 };
480
481 // Calculated subranges we restrict the iteration space of the main loop to.
482 // See the implementation of `calculateSubRanges' for more details on how
483 // these fields are computed. `ExitPreLoopAt' is `None' if we don't need a
484 // pre loop. `ExitMainLoopAt' is `None' if we don't need a post loop.
485 struct SubRanges {
486 Optional<Value *> ExitPreLoopAt;
487 Optional<Value *> ExitMainLoopAt;
488 };
489
490 // A utility function that does a `replaceUsesOfWith' on the incoming block
491 // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
492 // incoming block list with `ReplaceBy'.
493 static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
494 BasicBlock *ReplaceBy);
495
496 // Try to "parse" `OriginalLoop' and populate the various out parameters.
497 // Returns true on success, false on failure.
498 //
499 bool recognizeLoop(LoopStructure &LoopStructureOut,
500 const SCEV *&LatchCountOut, BasicBlock *&PreHeaderOut,
501 const char *&FailureReasonOut) const;
502
503 // Compute a safe set of limits for the main loop to run in -- effectively the
504 // intersection of `Range' and the iteration space of the original loop.
505 // Return the header count (1 + the latch taken count) in `HeaderCount'.
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000506 // Return None if unable to compute the set of subranges.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000507 //
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000508 Optional<SubRanges> calculateSubRanges(Value *&HeaderCount) const;
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000509
510 // Clone `OriginalLoop' and return the result in CLResult. The IR after
511 // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
512 // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
513 // but there is no such edge.
514 //
515 void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
516
517 // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
518 // iteration space of the rewritten loop ends at ExitLoopAt. The start of the
519 // iteration space is not changed. `ExitLoopAt' is assumed to be slt
520 // `OriginalHeaderCount'.
521 //
522 // If there are iterations left to execute, control is made to jump to
523 // `ContinuationBlock', otherwise they take the normal loop exit. The
524 // returned `RewrittenRangeInfo' object is populated as follows:
525 //
526 // .PseudoExit is a basic block that unconditionally branches to
527 // `ContinuationBlock'.
528 //
529 // .ExitSelector is a basic block that decides, on exit from the loop,
530 // whether to branch to the "true" exit or to `PseudoExit'.
531 //
532 // .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
533 // for each PHINode in the loop header on taking the pseudo exit.
534 //
535 // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
536 // preheader because it is made to branch to the loop header only
537 // conditionally.
538 //
539 RewrittenRangeInfo
540 changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
541 Value *ExitLoopAt,
542 BasicBlock *ContinuationBlock) const;
543
544 // The loop denoted by `LS' has `OldPreheader' as its preheader. This
545 // function creates a new preheader for `LS' and returns it.
546 //
547 BasicBlock *createPreheader(const LoopConstrainer::LoopStructure &LS,
548 BasicBlock *OldPreheader, const char *Tag) const;
549
550 // `ContinuationBlockAndPreheader' was the continuation block for some call to
551 // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
552 // This function rewrites the PHI nodes in `LS.Header' to start with the
553 // correct value.
554 void rewriteIncomingValuesForPHIs(
555 LoopConstrainer::LoopStructure &LS,
556 BasicBlock *ContinuationBlockAndPreheader,
557 const LoopConstrainer::RewrittenRangeInfo &RRI) const;
558
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 the iterator range [BlocksBegin, BlocksEnd) to this loops
563 // parent loop if required.
564 template<typename IteratorTy>
565 void addToParentLoopIfNeeded(IteratorTy BlocksBegin, IteratorTy BlocksEnd);
566
567 // Some global state.
568 Function &F;
569 LLVMContext &Ctx;
570 ScalarEvolution &SE;
571
572 // Information about the original loop we started out with.
573 Loop &OriginalLoop;
574 LoopInfo &OriginalLoopInfo;
575 const SCEV *LatchTakenCount;
576 BasicBlock *OriginalPreheader;
577 Value *OriginalHeaderCount;
578
579 // The preheader of the main loop. This may or may not be different from
580 // `OriginalPreheader'.
581 BasicBlock *MainLoopPreheader;
582
583 // The range we need to run the main loop in.
584 InductiveRangeCheck::Range Range;
585
586 // The structure of the main loop (see comment at the beginning of this class
587 // for a definition)
588 LoopStructure MainLoopStructure;
589
590public:
591 LoopConstrainer(Loop &L, LoopInfo &LI, ScalarEvolution &SE,
592 InductiveRangeCheck::Range R)
593 : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()), SE(SE),
594 OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
595 OriginalPreheader(nullptr), OriginalHeaderCount(nullptr),
596 MainLoopPreheader(nullptr), Range(R) { }
597
598 // Entry point for the algorithm. Returns true on success.
599 bool run();
600};
601
602}
603
604void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
605 BasicBlock *ReplaceBy) {
606 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
607 if (PN->getIncomingBlock(i) == Block)
608 PN->setIncomingBlock(i, ReplaceBy);
609}
610
611bool LoopConstrainer::recognizeLoop(LoopStructure &LoopStructureOut,
612 const SCEV *&LatchCountOut,
613 BasicBlock *&PreheaderOut,
614 const char *&FailureReason) const {
615 using namespace llvm::PatternMatch;
616
617 assert(OriginalLoop.isLoopSimplifyForm() &&
618 "should follow from addRequired<>");
619
620 BasicBlock *Latch = OriginalLoop.getLoopLatch();
621 if (!OriginalLoop.isLoopExiting(Latch)) {
622 FailureReason = "no loop latch";
623 return false;
624 }
625
626 PHINode *CIV = OriginalLoop.getCanonicalInductionVariable();
627 if (!CIV) {
628 FailureReason = "no CIV";
629 return false;
630 }
631
632 BasicBlock *Header = OriginalLoop.getHeader();
633 BasicBlock *Preheader = OriginalLoop.getLoopPreheader();
634 if (!Preheader) {
635 FailureReason = "no preheader";
636 return false;
637 }
638
639 Value *CIVNext = CIV->getIncomingValueForBlock(Latch);
640 Value *CIVStart = CIV->getIncomingValueForBlock(Preheader);
641
642 const SCEV *LatchCount = SE.getExitCount(&OriginalLoop, Latch);
643 if (isa<SCEVCouldNotCompute>(LatchCount)) {
644 FailureReason = "could not compute latch count";
645 return false;
646 }
647
648 // While SCEV does most of the analysis for us, we still have to
649 // modify the latch; and currently we can only deal with certain
650 // kinds of latches. This can be made more sophisticated as needed.
651
652 BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
653
654 if (!LatchBr || LatchBr->isUnconditional()) {
655 FailureReason = "latch terminator not conditional branch";
656 return false;
657 }
658
659 // Currently we only support a latch condition of the form:
660 //
661 // %condition = icmp slt %civNext, %limit
662 // br i1 %condition, label %header, label %exit
663
664 if (LatchBr->getSuccessor(0) != Header) {
665 FailureReason = "unknown latch form (header not first successor)";
666 return false;
667 }
668
669 Value *CIVComparedTo = nullptr;
670 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
671 if (!(match(LatchBr->getCondition(),
672 m_ICmp(Pred, m_Specific(CIVNext), m_Value(CIVComparedTo))) &&
673 Pred == ICmpInst::ICMP_SLT)) {
674 FailureReason = "unknown latch form (not slt)";
675 return false;
676 }
677
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000678 // IndVarSimplify will sometimes leave behind (in SCEV's cache) backedge-taken
679 // counts that are narrower than the canonical induction variable. These
680 // values are still accurate, and we could probably use them after sign/zero
681 // extension; but for now we just bail out of the transformation to keep
682 // things simple.
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000683 const SCEV *CIVComparedToSCEV = SE.getSCEV(CIVComparedTo);
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000684 if (isa<SCEVCouldNotCompute>(CIVComparedToSCEV) ||
685 CIVComparedToSCEV->getType() != LatchCount->getType()) {
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000686 FailureReason = "could not relate CIV to latch expression";
687 return false;
688 }
689
690 const SCEV *ShouldBeOne = SE.getMinusSCEV(CIVComparedToSCEV, LatchCount);
691 const SCEVConstant *SCEVOne = dyn_cast<SCEVConstant>(ShouldBeOne);
692 if (!SCEVOne || SCEVOne->getValue()->getValue() != 1) {
693 FailureReason = "unexpected header count in latch";
694 return false;
695 }
696
697 unsigned LatchBrExitIdx = 1;
698 BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
699
700 assert(SE.getLoopDisposition(LatchCount, &OriginalLoop) ==
701 ScalarEvolution::LoopInvariant &&
702 "loop variant exit count doesn't make sense!");
703
704 assert(!OriginalLoop.contains(LatchExit) && "expected an exit block!");
705
706 LoopStructureOut.Tag = "main";
707 LoopStructureOut.Header = Header;
708 LoopStructureOut.Latch = Latch;
709 LoopStructureOut.LatchBr = LatchBr;
710 LoopStructureOut.LatchExit = LatchExit;
711 LoopStructureOut.LatchBrExitIdx = LatchBrExitIdx;
712 LoopStructureOut.CIV = CIV;
713 LoopStructureOut.CIVNext = CIVNext;
714 LoopStructureOut.CIVStart = CIVStart;
715
716 LatchCountOut = LatchCount;
717 PreheaderOut = Preheader;
718 FailureReason = nullptr;
719
720 return true;
721}
722
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000723Optional<LoopConstrainer::SubRanges>
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000724LoopConstrainer::calculateSubRanges(Value *&HeaderCountOut) const {
725 IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
726
Sanjoy Das351db052015-01-22 09:32:02 +0000727 if (Range.getType() != Ty)
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +0000728 return None;
729
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000730 SCEVExpander Expander(SE, "irce");
731 Instruction *InsertPt = OriginalPreheader->getTerminator();
732
733 Value *LatchCountV =
734 MaybeSimplify(Expander.expandCodeFor(LatchTakenCount, Ty, InsertPt));
735
736 IRBuilder<> B(InsertPt);
737
738 LoopConstrainer::SubRanges Result;
739
740 // I think we can be more aggressive here and make this nuw / nsw if the
741 // addition that feeds into the icmp for the latch's terminating branch is nuw
742 // / nsw. In any case, a wrapping 2's complement addition is safe.
743 ConstantInt *One = ConstantInt::get(Ty, 1);
744 HeaderCountOut = MaybeSimplify(B.CreateAdd(LatchCountV, One, "header.count"));
745
Sanjoy Das351db052015-01-22 09:32:02 +0000746 const SCEV *RangeBegin = SE.getSCEV(Range.getBegin());
747 const SCEV *RangeEnd = SE.getSCEV(Range.getEnd());
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000748 const SCEV *HeaderCountSCEV = SE.getSCEV(HeaderCountOut);
749 const SCEV *Zero = SE.getConstant(Ty, 0);
750
751 // In some cases we can prove that we don't need a pre or post loop
752
753 bool ProvablyNoPreloop =
754 SE.isKnownPredicate(ICmpInst::ICMP_SLE, RangeBegin, Zero);
755 if (!ProvablyNoPreloop)
Sanjoy Das351db052015-01-22 09:32:02 +0000756 Result.ExitPreLoopAt = ConstructSMinOf(HeaderCountOut, Range.getBegin(), B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000757
758 bool ProvablyNoPostLoop =
759 SE.isKnownPredicate(ICmpInst::ICMP_SLE, HeaderCountSCEV, RangeEnd);
760 if (!ProvablyNoPostLoop)
Sanjoy Das351db052015-01-22 09:32:02 +0000761 Result.ExitMainLoopAt = ConstructSMinOf(HeaderCountOut, Range.getEnd(), B);
Sanjoy Dasa1837a32015-01-16 01:03:22 +0000762
763 return Result;
764}
765
766void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
767 const char *Tag) const {
768 for (BasicBlock *BB : OriginalLoop.getBlocks()) {
769 BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
770 Result.Blocks.push_back(Clone);
771 Result.Map[BB] = Clone;
772 }
773
774 auto GetClonedValue = [&Result](Value *V) {
775 assert(V && "null values not in domain!");
776 auto It = Result.Map.find(V);
777 if (It == Result.Map.end())
778 return V;
779 return static_cast<Value *>(It->second);
780 };
781
782 Result.Structure = MainLoopStructure.map(GetClonedValue);
783 Result.Structure.Tag = Tag;
784
785 for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
786 BasicBlock *ClonedBB = Result.Blocks[i];
787 BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
788
789 assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
790
791 for (Instruction &I : *ClonedBB)
792 RemapInstruction(&I, Result.Map,
793 RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
794
795 // Exit blocks will now have one more predecessor and their PHI nodes need
796 // to be edited to reflect that. No phi nodes need to be introduced because
797 // the loop is in LCSSA.
798
799 for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
800 SBBI != SBBE; ++SBBI) {
801
802 if (OriginalLoop.contains(*SBBI))
803 continue; // not an exit block
804
805 for (Instruction &I : **SBBI) {
806 if (!isa<PHINode>(&I))
807 break;
808
809 PHINode *PN = cast<PHINode>(&I);
810 Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
811 PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
812 }
813 }
814 }
815}
816
817LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
818 const LoopStructure &LS, BasicBlock *Preheader, Value *ExitLoopAt,
819 BasicBlock *ContinuationBlock) const {
820
821 // We start with a loop with a single latch:
822 //
823 // +--------------------+
824 // | |
825 // | preheader |
826 // | |
827 // +--------+-----------+
828 // | ----------------\
829 // | / |
830 // +--------v----v------+ |
831 // | | |
832 // | header | |
833 // | | |
834 // +--------------------+ |
835 // |
836 // ..... |
837 // |
838 // +--------------------+ |
839 // | | |
840 // | latch >----------/
841 // | |
842 // +-------v------------+
843 // |
844 // |
845 // | +--------------------+
846 // | | |
847 // +---> original exit |
848 // | |
849 // +--------------------+
850 //
851 // We change the control flow to look like
852 //
853 //
854 // +--------------------+
855 // | |
856 // | preheader >-------------------------+
857 // | | |
858 // +--------v-----------+ |
859 // | /-------------+ |
860 // | / | |
861 // +--------v--v--------+ | |
862 // | | | |
863 // | header | | +--------+ |
864 // | | | | | |
865 // +--------------------+ | | +-----v-----v-----------+
866 // | | | |
867 // | | | .pseudo.exit |
868 // | | | |
869 // | | +-----------v-----------+
870 // | | |
871 // ..... | | |
872 // | | +--------v-------------+
873 // +--------------------+ | | | |
874 // | | | | | ContinuationBlock |
875 // | latch >------+ | | |
876 // | | | +----------------------+
877 // +---------v----------+ |
878 // | |
879 // | |
880 // | +---------------^-----+
881 // | | |
882 // +-----> .exit.selector |
883 // | |
884 // +----------v----------+
885 // |
886 // +--------------------+ |
887 // | | |
888 // | original exit <----+
889 // | |
890 // +--------------------+
891 //
892
893 RewrittenRangeInfo RRI;
894
895 auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
896 RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
897 &F, BBInsertLocation);
898 RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
899 BBInsertLocation);
900
901 BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
902
903 IRBuilder<> B(PreheaderJump);
904
905 // EnterLoopCond - is it okay to start executing this `LS'?
906 Value *EnterLoopCond = B.CreateICmpSLT(LS.CIVStart, ExitLoopAt);
907 B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
908 PreheaderJump->eraseFromParent();
909
910 assert(LS.LatchBrExitIdx == 1 && "generalize this as needed!");
911
912 B.SetInsertPoint(LS.LatchBr);
913
914 // ContinueCond - is it okay to execute the next iteration in `LS'?
915 Value *ContinueCond = B.CreateICmpSLT(LS.CIVNext, ExitLoopAt);
916
917 LS.LatchBr->setCondition(ContinueCond);
918 assert(LS.LatchBr->getSuccessor(LS.LatchBrExitIdx) == LS.LatchExit &&
919 "invariant!");
920 LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
921
922 B.SetInsertPoint(RRI.ExitSelector);
923
924 // IterationsLeft - are there any more iterations left, given the original
925 // upper bound on the induction variable? If not, we branch to the "real"
926 // exit.
927 Value *IterationsLeft = B.CreateICmpSLT(LS.CIVNext, OriginalHeaderCount);
928 B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
929
930 BranchInst *BranchToContinuation =
931 BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
932
933 // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
934 // each of the PHI nodes in the loop header. This feeds into the initial
935 // value of the same PHI nodes if/when we continue execution.
936 for (Instruction &I : *LS.Header) {
937 if (!isa<PHINode>(&I))
938 break;
939
940 PHINode *PN = cast<PHINode>(&I);
941
942 PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
943 BranchToContinuation);
944
945 NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
946 NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
947 RRI.ExitSelector);
948 RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
949 }
950
951 // The latch exit now has a branch from `RRI.ExitSelector' instead of
952 // `LS.Latch'. The PHI nodes need to be updated to reflect that.
953 for (Instruction &I : *LS.LatchExit) {
954 if (PHINode *PN = dyn_cast<PHINode>(&I))
955 replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
956 else
957 break;
958 }
959
960 return RRI;
961}
962
963void LoopConstrainer::rewriteIncomingValuesForPHIs(
964 LoopConstrainer::LoopStructure &LS, BasicBlock *ContinuationBlock,
965 const LoopConstrainer::RewrittenRangeInfo &RRI) const {
966
967 unsigned PHIIndex = 0;
968 for (Instruction &I : *LS.Header) {
969 if (!isa<PHINode>(&I))
970 break;
971
972 PHINode *PN = cast<PHINode>(&I);
973
974 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
975 if (PN->getIncomingBlock(i) == ContinuationBlock)
976 PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
977 }
978
979 LS.CIVStart = LS.CIV->getIncomingValueForBlock(ContinuationBlock);
980}
981
982BasicBlock *
983LoopConstrainer::createPreheader(const LoopConstrainer::LoopStructure &LS,
984 BasicBlock *OldPreheader,
985 const char *Tag) const {
986
987 BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
988 BranchInst::Create(LS.Header, Preheader);
989
990 for (Instruction &I : *LS.Header) {
991 if (!isa<PHINode>(&I))
992 break;
993
994 PHINode *PN = cast<PHINode>(&I);
995 for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
996 replacePHIBlock(PN, OldPreheader, Preheader);
997 }
998
999 return Preheader;
1000}
1001
1002template<typename IteratorTy>
1003void LoopConstrainer::addToParentLoopIfNeeded(IteratorTy Begin,
1004 IteratorTy End) {
1005 Loop *ParentLoop = OriginalLoop.getParentLoop();
1006 if (!ParentLoop)
1007 return;
1008
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001009 for (; Begin != End; Begin++)
Chandler Carruth691addc2015-01-18 01:25:51 +00001010 ParentLoop->addBasicBlockToLoop(*Begin, OriginalLoopInfo);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001011}
1012
1013bool LoopConstrainer::run() {
1014 BasicBlock *Preheader = nullptr;
1015 const char *CouldNotProceedBecause = nullptr;
1016 if (!recognizeLoop(MainLoopStructure, LatchTakenCount, Preheader,
1017 CouldNotProceedBecause)) {
1018 DEBUG(dbgs() << "irce: could not recognize loop, " << CouldNotProceedBecause
1019 << "\n";);
1020 return false;
1021 }
1022
1023 OriginalPreheader = Preheader;
1024 MainLoopPreheader = Preheader;
1025
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001026 Optional<SubRanges> MaybeSR = calculateSubRanges(OriginalHeaderCount);
1027 if (!MaybeSR.hasValue()) {
1028 DEBUG(dbgs() << "irce: could not compute subranges\n");
1029 return false;
1030 }
1031 SubRanges SR = MaybeSR.getValue();
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001032
1033 // It would have been better to make `PreLoop' and `PostLoop'
1034 // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1035 // constructor.
1036 ClonedLoop PreLoop, PostLoop;
1037 bool NeedsPreLoop = SR.ExitPreLoopAt.hasValue();
1038 bool NeedsPostLoop = SR.ExitMainLoopAt.hasValue();
1039
1040 // We clone these ahead of time so that we don't have to deal with changing
1041 // and temporarily invalid IR as we transform the loops.
1042 if (NeedsPreLoop)
1043 cloneLoop(PreLoop, "preloop");
1044 if (NeedsPostLoop)
1045 cloneLoop(PostLoop, "postloop");
1046
1047 RewrittenRangeInfo PreLoopRRI;
1048
1049 if (NeedsPreLoop) {
1050 Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1051 PreLoop.Structure.Header);
1052
1053 MainLoopPreheader =
1054 createPreheader(MainLoopStructure, Preheader, "mainloop");
1055 PreLoopRRI =
1056 changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1057 SR.ExitPreLoopAt.getValue(), MainLoopPreheader);
1058 rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1059 PreLoopRRI);
1060 }
1061
1062 BasicBlock *PostLoopPreheader = nullptr;
1063 RewrittenRangeInfo PostLoopRRI;
1064
1065 if (NeedsPostLoop) {
1066 PostLoopPreheader =
1067 createPreheader(PostLoop.Structure, Preheader, "postloop");
1068 PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1069 SR.ExitMainLoopAt.getValue(),
1070 PostLoopPreheader);
1071 rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1072 PostLoopRRI);
1073 }
1074
1075 SmallVector<BasicBlock *, 6> NewBlocks;
1076 NewBlocks.push_back(PostLoopPreheader);
1077 NewBlocks.push_back(PreLoopRRI.PseudoExit);
1078 NewBlocks.push_back(PreLoopRRI.ExitSelector);
1079 NewBlocks.push_back(PostLoopRRI.PseudoExit);
1080 NewBlocks.push_back(PostLoopRRI.ExitSelector);
1081 if (MainLoopPreheader != Preheader)
1082 NewBlocks.push_back(MainLoopPreheader);
1083
1084 // Some of the above may be nullptr, filter them out before passing to
1085 // addToParentLoopIfNeeded.
1086 auto NewBlocksEnd = std::remove(NewBlocks.begin(), NewBlocks.end(), nullptr);
1087
1088 typedef SmallVector<BasicBlock *, 6>::iterator SmallVectItTy;
1089 typedef std::vector<BasicBlock *>::iterator StdVectItTy;
1090
1091 addToParentLoopIfNeeded<SmallVectItTy>(NewBlocks.begin(), NewBlocksEnd);
1092 addToParentLoopIfNeeded<StdVectItTy>(PreLoop.Blocks.begin(),
1093 PreLoop.Blocks.end());
1094 addToParentLoopIfNeeded<StdVectItTy>(PostLoop.Blocks.begin(),
1095 PostLoop.Blocks.end());
1096
1097 return true;
1098}
1099
1100/// Computes and returns a range of values for the induction variable in which
1101/// the range check can be safely elided. If it cannot compute such a range,
1102/// returns None.
1103Optional<InductiveRangeCheck::Range>
1104InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
1105 IRBuilder<> &B) const {
1106
1107 // Currently we support inequalities of the form:
1108 //
1109 // 0 <= Offset + 1 * CIV < L given L >= 0
1110 //
1111 // The inequality is satisfied by -Offset <= CIV < (L - Offset) [^1]. All
1112 // additions and subtractions are twos-complement wrapping and comparisons are
1113 // signed.
1114 //
1115 // Proof:
1116 //
1117 // If there exists CIV such that -Offset <= CIV < (L - Offset) then it
1118 // follows that -Offset <= (-Offset + L) [== Eq. 1]. Since L >= 0, if
1119 // (-Offset + L) sign-overflows then (-Offset + L) < (-Offset). Hence by
1120 // [Eq. 1], (-Offset + L) could not have overflown.
1121 //
1122 // This means CIV = t + (-Offset) for t in [0, L). Hence (CIV + Offset) =
1123 // t. Hence 0 <= (CIV + Offset) < L
1124
1125 // [^1]: Note that the solution does _not_ apply if L < 0; consider values
1126 // Offset = 127, CIV = 126 and L = -2 in an i8 world.
1127
1128 const SCEVConstant *ScaleC = dyn_cast<SCEVConstant>(getScale());
1129 if (!(ScaleC && ScaleC->getValue()->getValue() == 1)) {
1130 DEBUG(dbgs() << "irce: could not compute safe iteration space for:\n";
1131 print(dbgs()));
1132 return None;
1133 }
1134
1135 Value *OffsetV = SCEVExpander(SE, "safe.itr.space").expandCodeFor(
1136 getOffset(), getOffset()->getType(), B.GetInsertPoint());
1137 OffsetV = MaybeSimplify(OffsetV);
1138
1139 Value *Begin = MaybeSimplify(B.CreateNeg(OffsetV));
1140 Value *End = MaybeSimplify(B.CreateSub(getLength(), OffsetV));
1141
Sanjoy Das351db052015-01-22 09:32:02 +00001142 return InductiveRangeCheck::Range(Begin, End);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001143}
1144
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001145static Optional<InductiveRangeCheck::Range>
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001146IntersectRange(const Optional<InductiveRangeCheck::Range> &R1,
1147 const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1148 if (!R1.hasValue())
1149 return R2;
1150 auto &R1Value = R1.getValue();
1151
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001152 // TODO: we could widen the smaller range and have this work; but for now we
1153 // bail out to keep things simple.
Sanjoy Das351db052015-01-22 09:32:02 +00001154 if (R1Value.getType() != R2.getType())
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001155 return None;
1156
Sanjoy Das351db052015-01-22 09:32:02 +00001157 Value *NewMin = ConstructSMaxOf(R1Value.getBegin(), R2.getBegin(), B);
1158 Value *NewMax = ConstructSMinOf(R1Value.getEnd(), R2.getEnd(), B);
1159 return InductiveRangeCheck::Range(NewMin, NewMax);
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001160}
1161
1162bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1163 if (L->getBlocks().size() >= LoopSizeCutoff) {
1164 DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1165 return false;
1166 }
1167
1168 BasicBlock *Preheader = L->getLoopPreheader();
1169 if (!Preheader) {
1170 DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1171 return false;
1172 }
1173
1174 LLVMContext &Context = Preheader->getContext();
1175 InductiveRangeCheck::AllocatorTy IRCAlloc;
1176 SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1177 ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1178
1179 for (auto BBI : L->getBlocks())
1180 if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1181 if (InductiveRangeCheck *IRC =
1182 InductiveRangeCheck::create(IRCAlloc, TBI, L, SE))
1183 RangeChecks.push_back(IRC);
1184
1185 if (RangeChecks.empty())
1186 return false;
1187
1188 DEBUG(dbgs() << "irce: looking at loop "; L->print(dbgs());
1189 dbgs() << "irce: loop has " << RangeChecks.size()
1190 << " inductive range checks: \n";
1191 for (InductiveRangeCheck *IRC : RangeChecks)
1192 IRC->print(dbgs());
1193 );
1194
1195 Optional<InductiveRangeCheck::Range> SafeIterRange;
1196 Instruction *ExprInsertPt = Preheader->getTerminator();
1197
1198 SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1199
1200 IRBuilder<> B(ExprInsertPt);
1201 for (InductiveRangeCheck *IRC : RangeChecks) {
1202 auto Result = IRC->computeSafeIterationSpace(SE, B);
1203 if (Result.hasValue()) {
Sanjoy Dasd1fb13c2015-01-22 08:29:18 +00001204 auto MaybeSafeIterRange =
1205 IntersectRange(SafeIterRange, Result.getValue(), B);
1206 if (MaybeSafeIterRange.hasValue()) {
1207 RangeChecksToEliminate.push_back(IRC);
1208 SafeIterRange = MaybeSafeIterRange.getValue();
1209 }
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001210 }
1211 }
1212
1213 if (!SafeIterRange.hasValue())
1214 return false;
1215
Chandler Carruth4f8f3072015-01-17 14:16:18 +00001216 LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), SE,
1217 SafeIterRange.getValue());
Sanjoy Dasa1837a32015-01-16 01:03:22 +00001218 bool Changed = LC.run();
1219
1220 if (Changed) {
1221 auto PrintConstrainedLoopInfo = [L]() {
1222 dbgs() << "irce: in function ";
1223 dbgs() << L->getHeader()->getParent()->getName() << ": ";
1224 dbgs() << "constrained ";
1225 L->print(dbgs());
1226 };
1227
1228 DEBUG(PrintConstrainedLoopInfo());
1229
1230 if (PrintChangedLoops)
1231 PrintConstrainedLoopInfo();
1232
1233 // Optimize away the now-redundant range checks.
1234
1235 for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1236 ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1237 ? ConstantInt::getTrue(Context)
1238 : ConstantInt::getFalse(Context);
1239 IRC->getBranch()->setCondition(FoldedRangeCheck);
1240 }
1241 }
1242
1243 return Changed;
1244}
1245
1246Pass *llvm::createInductiveRangeCheckEliminationPass() {
1247 return new InductiveRangeCheckElimination;
1248}