[IRCE] Add comments, NFC.
[oota-llvm.git] / lib / Transforms / Scalar / InductiveRangeCheckElimination.cpp
1 //===-- 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/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"
54
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"
63
64 #include "llvm/Support/Debug.h"
65
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"
72
73 #include "llvm/Pass.h"
74
75 #include <array>
76
77 using namespace llvm;
78
79 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
80                                         cl::init(64));
81
82 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
83                                        cl::init(false));
84
85 static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
86                                           cl::Hidden, cl::init(10));
87
88 #define DEBUG_TYPE "irce"
89
90 namespace {
91
92 /// An inductive range check is conditional branch in a loop with
93 ///
94 ///  1. a very cold successor (i.e. the branch jumps to that successor very
95 ///     rarely)
96 ///
97 ///  and
98 ///
99 ///  2. a condition that is provably true for some contiguous range of values
100 ///     taken by the containing loop's induction variable.
101 ///
102 class InductiveRangeCheck {
103   // Classifies a range check
104   enum RangeCheckKind {
105     // Range check of the form "0 <= I".
106     RANGE_CHECK_LOWER = 1,
107
108     // Range check of the form "I < L" where L is known positive.
109     RANGE_CHECK_UPPER = 2,
110
111     // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
112     // conditions.
113     RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
114
115     // Unrecognized range check condition.
116     RANGE_CHECK_UNKNOWN = (unsigned)-1
117   };
118
119   static const char *rangeCheckKindToStr(RangeCheckKind);
120
121   const SCEV *Offset;
122   const SCEV *Scale;
123   Value *Length;
124   BranchInst *Branch;
125   RangeCheckKind Kind;
126
127   static RangeCheckKind parseRangeCheckICmp(ICmpInst *ICI, ScalarEvolution &SE,
128                                             Value *&Index, Value *&Length);
129
130   static InductiveRangeCheck::RangeCheckKind
131   parseRangeCheck(Loop *L, ScalarEvolution &SE, Value *Condition,
132                   const SCEV *&Index, Value *&UpperLimit);
133
134   InductiveRangeCheck() :
135     Offset(nullptr), Scale(nullptr), Length(nullptr), Branch(nullptr) { }
136
137 public:
138   const SCEV *getOffset() const { return Offset; }
139   const SCEV *getScale() const { return Scale; }
140   Value *getLength() const { return Length; }
141
142   void print(raw_ostream &OS) const {
143     OS << "InductiveRangeCheck:\n";
144     OS << "  Kind: " << rangeCheckKindToStr(Kind) << "\n";
145     OS << "  Offset: ";
146     Offset->print(OS);
147     OS << "  Scale: ";
148     Scale->print(OS);
149     OS << "  Length: ";
150     if (Length)
151       Length->print(OS);
152     else
153       OS << "(null)";
154     OS << "\n  Branch: ";
155     getBranch()->print(OS);
156     OS << "\n";
157   }
158
159 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
160   void dump() {
161     print(dbgs());
162   }
163 #endif
164
165   BranchInst *getBranch() const { return Branch; }
166
167   /// Represents an signed integer range [Range.getBegin(), Range.getEnd()).  If
168   /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
169
170   class Range {
171     const SCEV *Begin;
172     const SCEV *End;
173
174   public:
175     Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
176       assert(Begin->getType() == End->getType() && "ill-typed range!");
177     }
178
179     Type *getType() const { return Begin->getType(); }
180     const SCEV *getBegin() const { return Begin; }
181     const SCEV *getEnd() const { return End; }
182   };
183
184   typedef SpecificBumpPtrAllocator<InductiveRangeCheck> AllocatorTy;
185
186   /// This is the value the condition of the branch needs to evaluate to for the
187   /// branch to take the hot successor (see (1) above).
188   bool getPassingDirection() { return true; }
189
190   /// Computes a range for the induction variable (IndVar) in which the range
191   /// check is redundant and can be constant-folded away.  The induction
192   /// variable is not required to be the canonical {0,+,1} induction variable.
193   Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
194                                             const SCEVAddRecExpr *IndVar,
195                                             IRBuilder<> &B) const;
196
197   /// Create an inductive range check out of BI if possible, else return
198   /// nullptr.
199   static InductiveRangeCheck *create(AllocatorTy &Alloc, BranchInst *BI,
200                                      Loop *L, ScalarEvolution &SE,
201                                      BranchProbabilityInfo &BPI);
202 };
203
204 class InductiveRangeCheckElimination : public LoopPass {
205   InductiveRangeCheck::AllocatorTy Allocator;
206
207 public:
208   static char ID;
209   InductiveRangeCheckElimination() : LoopPass(ID) {
210     initializeInductiveRangeCheckEliminationPass(
211         *PassRegistry::getPassRegistry());
212   }
213
214   void getAnalysisUsage(AnalysisUsage &AU) const override {
215     AU.addRequired<LoopInfoWrapperPass>();
216     AU.addRequiredID(LoopSimplifyID);
217     AU.addRequiredID(LCSSAID);
218     AU.addRequired<ScalarEvolution>();
219     AU.addRequired<BranchProbabilityInfo>();
220   }
221
222   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
223 };
224
225 char InductiveRangeCheckElimination::ID = 0;
226 }
227
228 INITIALIZE_PASS(InductiveRangeCheckElimination, "irce",
229                 "Inductive range check elimination", false, false)
230
231 const char *InductiveRangeCheck::rangeCheckKindToStr(
232     InductiveRangeCheck::RangeCheckKind RCK) {
233   switch (RCK) {
234   case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
235     return "RANGE_CHECK_UNKNOWN";
236
237   case InductiveRangeCheck::RANGE_CHECK_UPPER:
238     return "RANGE_CHECK_UPPER";
239
240   case InductiveRangeCheck::RANGE_CHECK_LOWER:
241     return "RANGE_CHECK_LOWER";
242
243   case InductiveRangeCheck::RANGE_CHECK_BOTH:
244     return "RANGE_CHECK_BOTH";
245   }
246
247   llvm_unreachable("unknown range check type!");
248 }
249
250 /// Parse a single ICmp instruction, `ICI`, into a range check.  If `ICI`
251 /// cannot
252 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
253 /// `Index` and `Length` to `nullptr`.  Otherwise set `Index` to the value
254 /// being
255 /// range checked, and set `Length` to the upper limit `Index` is being range
256 /// checked with if (and only if) the range check type is stronger or equal to
257 /// RANGE_CHECK_UPPER.
258 ///
259 InductiveRangeCheck::RangeCheckKind
260 InductiveRangeCheck::parseRangeCheckICmp(ICmpInst *ICI, ScalarEvolution &SE,
261                                          Value *&Index, Value *&Length) {
262
263   using namespace llvm::PatternMatch;
264
265   ICmpInst::Predicate Pred = ICI->getPredicate();
266   Value *LHS = ICI->getOperand(0);
267   Value *RHS = ICI->getOperand(1);
268
269   switch (Pred) {
270   default:
271     return RANGE_CHECK_UNKNOWN;
272
273   case ICmpInst::ICMP_SLE:
274     std::swap(LHS, RHS);
275   // fallthrough
276   case ICmpInst::ICMP_SGE:
277     if (match(RHS, m_ConstantInt<0>())) {
278       Index = LHS;
279       return RANGE_CHECK_LOWER;
280     }
281     return RANGE_CHECK_UNKNOWN;
282
283   case ICmpInst::ICMP_SLT:
284     std::swap(LHS, RHS);
285   // fallthrough
286   case ICmpInst::ICMP_SGT:
287     if (match(RHS, m_ConstantInt<-1>())) {
288       Index = LHS;
289       return RANGE_CHECK_LOWER;
290     }
291
292     if (SE.isKnownNonNegative(SE.getSCEV(LHS))) {
293       Index = RHS;
294       Length = LHS;
295       return RANGE_CHECK_UPPER;
296     }
297     return RANGE_CHECK_UNKNOWN;
298
299   case ICmpInst::ICMP_ULT:
300     std::swap(LHS, RHS);
301   // fallthrough
302   case ICmpInst::ICMP_UGT:
303     if (SE.isKnownNonNegative(SE.getSCEV(LHS))) {
304       Index = RHS;
305       Length = LHS;
306       return RANGE_CHECK_BOTH;
307     }
308     return RANGE_CHECK_UNKNOWN;
309   }
310
311   llvm_unreachable("default clause returns!");
312 }
313
314 /// Parses an arbitrary condition into a range check.  `Length` is set only if
315 /// the range check is recognized to be `RANGE_CHECK_UPPER` or stronger.
316 InductiveRangeCheck::RangeCheckKind
317 InductiveRangeCheck::parseRangeCheck(Loop *L, ScalarEvolution &SE,
318                                      Value *Condition, const SCEV *&Index,
319                                      Value *&Length) {
320   using namespace llvm::PatternMatch;
321
322   Value *A = nullptr;
323   Value *B = nullptr;
324
325   if (match(Condition, m_And(m_Value(A), m_Value(B)))) {
326     Value *IndexA = nullptr, *IndexB = nullptr;
327     Value *LengthA = nullptr, *LengthB = nullptr;
328     ICmpInst *ICmpA = dyn_cast<ICmpInst>(A), *ICmpB = dyn_cast<ICmpInst>(B);
329
330     if (!ICmpA || !ICmpB)
331       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
332
333     auto RCKindA = parseRangeCheckICmp(ICmpA, SE, IndexA, LengthA);
334     auto RCKindB = parseRangeCheckICmp(ICmpB, SE, IndexB, LengthB);
335
336     if (RCKindA == InductiveRangeCheck::RANGE_CHECK_UNKNOWN ||
337         RCKindB == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
338       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
339
340     if (IndexA != IndexB)
341       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
342
343     if (LengthA != nullptr && LengthB != nullptr && LengthA != LengthB)
344       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
345
346     Index = SE.getSCEV(IndexA);
347     if (isa<SCEVCouldNotCompute>(Index))
348       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
349
350     Length = LengthA == nullptr ? LengthB : LengthA;
351
352     return (InductiveRangeCheck::RangeCheckKind)(RCKindA | RCKindB);
353   }
354
355   if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
356     Value *IndexVal = nullptr;
357
358     auto RCKind = parseRangeCheckICmp(ICI, SE, IndexVal, Length);
359
360     if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
361       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
362
363     Index = SE.getSCEV(IndexVal);
364     if (isa<SCEVCouldNotCompute>(Index))
365       return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
366
367     return RCKind;
368   }
369
370   return InductiveRangeCheck::RANGE_CHECK_UNKNOWN;
371 }
372
373
374 InductiveRangeCheck *
375 InductiveRangeCheck::create(InductiveRangeCheck::AllocatorTy &A, BranchInst *BI,
376                             Loop *L, ScalarEvolution &SE,
377                             BranchProbabilityInfo &BPI) {
378
379   if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
380     return nullptr;
381
382   BranchProbability LikelyTaken(15, 16);
383
384   if (BPI.getEdgeProbability(BI->getParent(), (unsigned) 0) < LikelyTaken)
385     return nullptr;
386
387   Value *Length = nullptr;
388   const SCEV *IndexSCEV = nullptr;
389
390   auto RCKind = InductiveRangeCheck::parseRangeCheck(L, SE, BI->getCondition(),
391                                                      IndexSCEV, Length);
392
393   if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
394     return nullptr;
395
396   assert(IndexSCEV && "contract with SplitRangeCheckCondition!");
397   assert(!(RCKind & InductiveRangeCheck::RANGE_CHECK_UPPER) ||
398          Length && "contract with SplitRangeCheckCondition!");
399
400   const SCEVAddRecExpr *IndexAddRec = dyn_cast<SCEVAddRecExpr>(IndexSCEV);
401   bool IsAffineIndex =
402       IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
403
404   if (!IsAffineIndex)
405     return nullptr;
406
407   InductiveRangeCheck *IRC = new (A.Allocate()) InductiveRangeCheck;
408   IRC->Length = Length;
409   IRC->Offset = IndexAddRec->getStart();
410   IRC->Scale = IndexAddRec->getStepRecurrence(SE);
411   IRC->Branch = BI;
412   IRC->Kind = RCKind;
413   return IRC;
414 }
415
416 namespace {
417
418 // Keeps track of the structure of a loop.  This is similar to llvm::Loop,
419 // except that it is more lightweight and can track the state of a loop through
420 // changing and potentially invalid IR.  This structure also formalizes the
421 // kinds of loops we can deal with -- ones that have a single latch that is also
422 // an exiting block *and* have a canonical induction variable.
423 struct LoopStructure {
424   const char *Tag;
425
426   BasicBlock *Header;
427   BasicBlock *Latch;
428
429   // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
430   // successor is `LatchExit', the exit block of the loop.
431   BranchInst *LatchBr;
432   BasicBlock *LatchExit;
433   unsigned LatchBrExitIdx;
434
435   Value *IndVarNext;
436   Value *IndVarStart;
437   Value *LoopExitAt;
438   bool IndVarIncreasing;
439
440   LoopStructure()
441       : Tag(""), Header(nullptr), Latch(nullptr), LatchBr(nullptr),
442         LatchExit(nullptr), LatchBrExitIdx(-1), IndVarNext(nullptr),
443         IndVarStart(nullptr), LoopExitAt(nullptr), IndVarIncreasing(false) {}
444
445   template <typename M> LoopStructure map(M Map) const {
446     LoopStructure Result;
447     Result.Tag = Tag;
448     Result.Header = cast<BasicBlock>(Map(Header));
449     Result.Latch = cast<BasicBlock>(Map(Latch));
450     Result.LatchBr = cast<BranchInst>(Map(LatchBr));
451     Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
452     Result.LatchBrExitIdx = LatchBrExitIdx;
453     Result.IndVarNext = Map(IndVarNext);
454     Result.IndVarStart = Map(IndVarStart);
455     Result.LoopExitAt = Map(LoopExitAt);
456     Result.IndVarIncreasing = IndVarIncreasing;
457     return Result;
458   }
459
460   static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
461                                                     BranchProbabilityInfo &BPI,
462                                                     Loop &,
463                                                     const char *&);
464 };
465
466 /// This class is used to constrain loops to run within a given iteration space.
467 /// The algorithm this class implements is given a Loop and a range [Begin,
468 /// End).  The algorithm then tries to break out a "main loop" out of the loop
469 /// it is given in a way that the "main loop" runs with the induction variable
470 /// in a subset of [Begin, End).  The algorithm emits appropriate pre and post
471 /// loops to run any remaining iterations.  The pre loop runs any iterations in
472 /// which the induction variable is < Begin, and the post loop runs any
473 /// iterations in which the induction variable is >= End.
474 ///
475 class LoopConstrainer {
476   // The representation of a clone of the original loop we started out with.
477   struct ClonedLoop {
478     // The cloned blocks
479     std::vector<BasicBlock *> Blocks;
480
481     // `Map` maps values in the clonee into values in the cloned version
482     ValueToValueMapTy Map;
483
484     // An instance of `LoopStructure` for the cloned loop
485     LoopStructure Structure;
486   };
487
488   // Result of rewriting the range of a loop.  See changeIterationSpaceEnd for
489   // more details on what these fields mean.
490   struct RewrittenRangeInfo {
491     BasicBlock *PseudoExit;
492     BasicBlock *ExitSelector;
493     std::vector<PHINode *> PHIValuesAtPseudoExit;
494     PHINode *IndVarEnd;
495
496     RewrittenRangeInfo()
497         : PseudoExit(nullptr), ExitSelector(nullptr), IndVarEnd(nullptr) {}
498   };
499
500   // Calculated subranges we restrict the iteration space of the main loop to.
501   // See the implementation of `calculateSubRanges' for more details on how
502   // these fields are computed.  `LowLimit` is None if there is no restriction
503   // on low end of the restricted iteration space of the main loop.  `HighLimit`
504   // is None if there is no restriction on high end of the restricted iteration
505   // space of the main loop.
506
507   struct SubRanges {
508     Optional<const SCEV *> LowLimit;
509     Optional<const SCEV *> HighLimit;
510   };
511
512   // A utility function that does a `replaceUsesOfWith' on the incoming block
513   // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
514   // incoming block list with `ReplaceBy'.
515   static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
516                               BasicBlock *ReplaceBy);
517
518   // Compute a safe set of limits for the main loop to run in -- effectively the
519   // intersection of `Range' and the iteration space of the original loop.
520   // Return None if unable to compute the set of subranges.
521   //
522   Optional<SubRanges> calculateSubRanges() const;
523
524   // Clone `OriginalLoop' and return the result in CLResult.  The IR after
525   // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
526   // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
527   // but there is no such edge.
528   //
529   void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
530
531   // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
532   // iteration space of the rewritten loop ends at ExitLoopAt.  The start of the
533   // iteration space is not changed.  `ExitLoopAt' is assumed to be slt
534   // `OriginalHeaderCount'.
535   //
536   // If there are iterations left to execute, control is made to jump to
537   // `ContinuationBlock', otherwise they take the normal loop exit.  The
538   // returned `RewrittenRangeInfo' object is populated as follows:
539   //
540   //  .PseudoExit is a basic block that unconditionally branches to
541   //      `ContinuationBlock'.
542   //
543   //  .ExitSelector is a basic block that decides, on exit from the loop,
544   //      whether to branch to the "true" exit or to `PseudoExit'.
545   //
546   //  .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
547   //      for each PHINode in the loop header on taking the pseudo exit.
548   //
549   // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
550   // preheader because it is made to branch to the loop header only
551   // conditionally.
552   //
553   RewrittenRangeInfo
554   changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
555                           Value *ExitLoopAt,
556                           BasicBlock *ContinuationBlock) const;
557
558   // The loop denoted by `LS' has `OldPreheader' as its preheader.  This
559   // function creates a new preheader for `LS' and returns it.
560   //
561   BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
562                               const char *Tag) const;
563
564   // `ContinuationBlockAndPreheader' was the continuation block for some call to
565   // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
566   // This function rewrites the PHI nodes in `LS.Header' to start with the
567   // correct value.
568   void rewriteIncomingValuesForPHIs(
569       LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
570       const LoopConstrainer::RewrittenRangeInfo &RRI) const;
571
572   // Even though we do not preserve any passes at this time, we at least need to
573   // keep the parent loop structure consistent.  The `LPPassManager' seems to
574   // verify this after running a loop pass.  This function adds the list of
575   // blocks denoted by BBs to this loops parent loop if required.
576   void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
577
578   // Some global state.
579   Function &F;
580   LLVMContext &Ctx;
581   ScalarEvolution &SE;
582
583   // Information about the original loop we started out with.
584   Loop &OriginalLoop;
585   LoopInfo &OriginalLoopInfo;
586   const SCEV *LatchTakenCount;
587   BasicBlock *OriginalPreheader;
588
589   // The preheader of the main loop.  This may or may not be different from
590   // `OriginalPreheader'.
591   BasicBlock *MainLoopPreheader;
592
593   // The range we need to run the main loop in.
594   InductiveRangeCheck::Range Range;
595
596   // The structure of the main loop (see comment at the beginning of this class
597   // for a definition)
598   LoopStructure MainLoopStructure;
599
600 public:
601   LoopConstrainer(Loop &L, LoopInfo &LI, const LoopStructure &LS,
602                   ScalarEvolution &SE, InductiveRangeCheck::Range R)
603       : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
604         SE(SE), OriginalLoop(L), OriginalLoopInfo(LI), LatchTakenCount(nullptr),
605         OriginalPreheader(nullptr), MainLoopPreheader(nullptr), Range(R),
606         MainLoopStructure(LS) {}
607
608   // Entry point for the algorithm.  Returns true on success.
609   bool run();
610 };
611
612 }
613
614 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
615                                       BasicBlock *ReplaceBy) {
616   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
617     if (PN->getIncomingBlock(i) == Block)
618       PN->setIncomingBlock(i, ReplaceBy);
619 }
620
621 static bool CanBeSMax(ScalarEvolution &SE, const SCEV *S) {
622   APInt SMax =
623       APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
624   return SE.getSignedRange(S).contains(SMax) &&
625          SE.getUnsignedRange(S).contains(SMax);
626 }
627
628 static bool CanBeSMin(ScalarEvolution &SE, const SCEV *S) {
629   APInt SMin =
630       APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth());
631   return SE.getSignedRange(S).contains(SMin) &&
632          SE.getUnsignedRange(S).contains(SMin);
633 }
634
635 Optional<LoopStructure>
636 LoopStructure::parseLoopStructure(ScalarEvolution &SE, BranchProbabilityInfo &BPI,
637                                   Loop &L, const char *&FailureReason) {
638   assert(L.isLoopSimplifyForm() && "should follow from addRequired<>");
639
640   BasicBlock *Latch = L.getLoopLatch();
641   if (!L.isLoopExiting(Latch)) {
642     FailureReason = "no loop latch";
643     return None;
644   }
645
646   BasicBlock *Header = L.getHeader();
647   BasicBlock *Preheader = L.getLoopPreheader();
648   if (!Preheader) {
649     FailureReason = "no preheader";
650     return None;
651   }
652
653   BranchInst *LatchBr = dyn_cast<BranchInst>(&*Latch->rbegin());
654   if (!LatchBr || LatchBr->isUnconditional()) {
655     FailureReason = "latch terminator not conditional branch";
656     return None;
657   }
658
659   unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
660
661   BranchProbability ExitProbability =
662     BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
663
664   if (ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
665     FailureReason = "short running loop, not profitable";
666     return None;
667   }
668
669   ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
670   if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
671     FailureReason = "latch terminator branch not conditional on integral icmp";
672     return None;
673   }
674
675   const SCEV *LatchCount = SE.getExitCount(&L, Latch);
676   if (isa<SCEVCouldNotCompute>(LatchCount)) {
677     FailureReason = "could not compute latch count";
678     return None;
679   }
680
681   ICmpInst::Predicate Pred = ICI->getPredicate();
682   Value *LeftValue = ICI->getOperand(0);
683   const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
684   IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
685
686   Value *RightValue = ICI->getOperand(1);
687   const SCEV *RightSCEV = SE.getSCEV(RightValue);
688
689   // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
690   if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
691     if (isa<SCEVAddRecExpr>(RightSCEV)) {
692       std::swap(LeftSCEV, RightSCEV);
693       std::swap(LeftValue, RightValue);
694       Pred = ICmpInst::getSwappedPredicate(Pred);
695     } else {
696       FailureReason = "no add recurrences in the icmp";
697       return None;
698     }
699   }
700
701   auto IsInductionVar = [&SE](const SCEVAddRecExpr *AR, bool &IsIncreasing) {
702     if (!AR->isAffine())
703       return false;
704
705     IntegerType *Ty = cast<IntegerType>(AR->getType());
706     IntegerType *WideTy =
707         IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
708
709     // Currently we only work with induction variables that have been proved to
710     // not wrap.  This restriction can potentially be lifted in the future.
711
712     const SCEVAddRecExpr *ExtendAfterOp =
713         dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
714     if (!ExtendAfterOp)
715       return false;
716
717     const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
718     const SCEV *ExtendedStep =
719         SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
720
721     bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
722                         ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
723
724     if (!NoSignedWrap)
725       return false;
726
727     if (const SCEVConstant *StepExpr =
728             dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
729       ConstantInt *StepCI = StepExpr->getValue();
730       if (StepCI->isOne() || StepCI->isMinusOne()) {
731         IsIncreasing = StepCI->isOne();
732         return true;
733       }
734     }
735
736     return false;
737   };
738
739   // `ICI` is interpreted as taking the backedge if the *next* value of the
740   // induction variable satisfies some constraint.
741
742   const SCEVAddRecExpr *IndVarNext = cast<SCEVAddRecExpr>(LeftSCEV);
743   bool IsIncreasing = false;
744   if (!IsInductionVar(IndVarNext, IsIncreasing)) {
745     FailureReason = "LHS in icmp not induction variable";
746     return None;
747   }
748
749   ConstantInt *One = ConstantInt::get(IndVarTy, 1);
750   // TODO: generalize the predicates here to also match their unsigned variants.
751   if (IsIncreasing) {
752     bool FoundExpectedPred =
753         (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 1) ||
754         (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 0);
755
756     if (!FoundExpectedPred) {
757       FailureReason = "expected icmp slt semantically, found something else";
758       return None;
759     }
760
761     if (LatchBrExitIdx == 0) {
762       if (CanBeSMax(SE, RightSCEV)) {
763         // TODO: this restriction is easily removable -- we just have to
764         // remember that the icmp was an slt and not an sle.
765         FailureReason = "limit may overflow when coercing sle to slt";
766         return None;
767       }
768
769       IRBuilder<> B(&*Preheader->rbegin());
770       RightValue = B.CreateAdd(RightValue, One);
771     }
772
773   } else {
774     bool FoundExpectedPred =
775         (Pred == ICmpInst::ICMP_SGT && LatchBrExitIdx == 1) ||
776         (Pred == ICmpInst::ICMP_SLT && LatchBrExitIdx == 0);
777
778     if (!FoundExpectedPred) {
779       FailureReason = "expected icmp sgt semantically, found something else";
780       return None;
781     }
782
783     if (LatchBrExitIdx == 0) {
784       if (CanBeSMin(SE, RightSCEV)) {
785         // TODO: this restriction is easily removable -- we just have to
786         // remember that the icmp was an sgt and not an sge.
787         FailureReason = "limit may overflow when coercing sge to sgt";
788         return None;
789       }
790
791       IRBuilder<> B(&*Preheader->rbegin());
792       RightValue = B.CreateSub(RightValue, One);
793     }
794   }
795
796   const SCEV *StartNext = IndVarNext->getStart();
797   const SCEV *Addend = SE.getNegativeSCEV(IndVarNext->getStepRecurrence(SE));
798   const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
799
800   BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
801
802   assert(SE.getLoopDisposition(LatchCount, &L) ==
803              ScalarEvolution::LoopInvariant &&
804          "loop variant exit count doesn't make sense!");
805
806   assert(!L.contains(LatchExit) && "expected an exit block!");
807   const DataLayout &DL = Preheader->getModule()->getDataLayout();
808   Value *IndVarStartV =
809       SCEVExpander(SE, DL, "irce")
810           .expandCodeFor(IndVarStart, IndVarTy, &*Preheader->rbegin());
811   IndVarStartV->setName("indvar.start");
812
813   LoopStructure Result;
814
815   Result.Tag = "main";
816   Result.Header = Header;
817   Result.Latch = Latch;
818   Result.LatchBr = LatchBr;
819   Result.LatchExit = LatchExit;
820   Result.LatchBrExitIdx = LatchBrExitIdx;
821   Result.IndVarStart = IndVarStartV;
822   Result.IndVarNext = LeftValue;
823   Result.IndVarIncreasing = IsIncreasing;
824   Result.LoopExitAt = RightValue;
825
826   FailureReason = nullptr;
827
828   return Result;
829 }
830
831 Optional<LoopConstrainer::SubRanges>
832 LoopConstrainer::calculateSubRanges() const {
833   IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
834
835   if (Range.getType() != Ty)
836     return None;
837
838   LoopConstrainer::SubRanges Result;
839
840   // I think we can be more aggressive here and make this nuw / nsw if the
841   // addition that feeds into the icmp for the latch's terminating branch is nuw
842   // / nsw.  In any case, a wrapping 2's complement addition is safe.
843   ConstantInt *One = ConstantInt::get(Ty, 1);
844   const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
845   const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
846
847   bool Increasing = MainLoopStructure.IndVarIncreasing;
848
849   // We compute `Smallest` and `Greatest` such that [Smallest, Greatest) is the
850   // range of values the induction variable takes.
851
852   const SCEV *Smallest = nullptr, *Greatest = nullptr;
853
854   if (Increasing) {
855     Smallest = Start;
856     Greatest = End;
857   } else {
858     // These two computations may sign-overflow.  Here is why that is okay:
859     //
860     // We know that the induction variable does not sign-overflow on any
861     // iteration except the last one, and it starts at `Start` and ends at
862     // `End`, decrementing by one every time.
863     //
864     //  * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
865     //    induction variable is decreasing we know that that the smallest value
866     //    the loop body is actually executed with is `INT_SMIN` == `Smallest`.
867     //
868     //  * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`.  In
869     //    that case, `Clamp` will always return `Smallest` and
870     //    [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
871     //    will be an empty range.  Returning an empty range is always safe.
872     //
873
874     Smallest = SE.getAddExpr(End, SE.getSCEV(One));
875     Greatest = SE.getAddExpr(Start, SE.getSCEV(One));
876   }
877
878   auto Clamp = [this, Smallest, Greatest](const SCEV *S) {
879     return SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S));
880   };
881
882   // In some cases we can prove that we don't need a pre or post loop
883
884   bool ProvablyNoPreloop =
885       SE.isKnownPredicate(ICmpInst::ICMP_SLE, Range.getBegin(), Smallest);
886   if (!ProvablyNoPreloop)
887     Result.LowLimit = Clamp(Range.getBegin());
888
889   bool ProvablyNoPostLoop =
890       SE.isKnownPredicate(ICmpInst::ICMP_SLE, Greatest, Range.getEnd());
891   if (!ProvablyNoPostLoop)
892     Result.HighLimit = Clamp(Range.getEnd());
893
894   return Result;
895 }
896
897 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
898                                 const char *Tag) const {
899   for (BasicBlock *BB : OriginalLoop.getBlocks()) {
900     BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
901     Result.Blocks.push_back(Clone);
902     Result.Map[BB] = Clone;
903   }
904
905   auto GetClonedValue = [&Result](Value *V) {
906     assert(V && "null values not in domain!");
907     auto It = Result.Map.find(V);
908     if (It == Result.Map.end())
909       return V;
910     return static_cast<Value *>(It->second);
911   };
912
913   Result.Structure = MainLoopStructure.map(GetClonedValue);
914   Result.Structure.Tag = Tag;
915
916   for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
917     BasicBlock *ClonedBB = Result.Blocks[i];
918     BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
919
920     assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
921
922     for (Instruction &I : *ClonedBB)
923       RemapInstruction(&I, Result.Map,
924                        RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
925
926     // Exit blocks will now have one more predecessor and their PHI nodes need
927     // to be edited to reflect that.  No phi nodes need to be introduced because
928     // the loop is in LCSSA.
929
930     for (auto SBBI = succ_begin(OriginalBB), SBBE = succ_end(OriginalBB);
931          SBBI != SBBE; ++SBBI) {
932
933       if (OriginalLoop.contains(*SBBI))
934         continue; // not an exit block
935
936       for (Instruction &I : **SBBI) {
937         if (!isa<PHINode>(&I))
938           break;
939
940         PHINode *PN = cast<PHINode>(&I);
941         Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
942         PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
943       }
944     }
945   }
946 }
947
948 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
949     const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
950     BasicBlock *ContinuationBlock) const {
951
952   // We start with a loop with a single latch:
953   //
954   //    +--------------------+
955   //    |                    |
956   //    |     preheader      |
957   //    |                    |
958   //    +--------+-----------+
959   //             |      ----------------\
960   //             |     /                |
961   //    +--------v----v------+          |
962   //    |                    |          |
963   //    |      header        |          |
964   //    |                    |          |
965   //    +--------------------+          |
966   //                                    |
967   //            .....                   |
968   //                                    |
969   //    +--------------------+          |
970   //    |                    |          |
971   //    |       latch        >----------/
972   //    |                    |
973   //    +-------v------------+
974   //            |
975   //            |
976   //            |   +--------------------+
977   //            |   |                    |
978   //            +--->   original exit    |
979   //                |                    |
980   //                +--------------------+
981   //
982   // We change the control flow to look like
983   //
984   //
985   //    +--------------------+
986   //    |                    |
987   //    |     preheader      >-------------------------+
988   //    |                    |                         |
989   //    +--------v-----------+                         |
990   //             |    /-------------+                  |
991   //             |   /              |                  |
992   //    +--------v--v--------+      |                  |
993   //    |                    |      |                  |
994   //    |      header        |      |   +--------+     |
995   //    |                    |      |   |        |     |
996   //    +--------------------+      |   |  +-----v-----v-----------+
997   //                                |   |  |                       |
998   //                                |   |  |     .pseudo.exit      |
999   //                                |   |  |                       |
1000   //                                |   |  +-----------v-----------+
1001   //                                |   |              |
1002   //            .....               |   |              |
1003   //                                |   |     +--------v-------------+
1004   //    +--------------------+      |   |     |                      |
1005   //    |                    |      |   |     |   ContinuationBlock  |
1006   //    |       latch        >------+   |     |                      |
1007   //    |                    |          |     +----------------------+
1008   //    +---------v----------+          |
1009   //              |                     |
1010   //              |                     |
1011   //              |     +---------------^-----+
1012   //              |     |                     |
1013   //              +----->    .exit.selector   |
1014   //                    |                     |
1015   //                    +----------v----------+
1016   //                               |
1017   //     +--------------------+    |
1018   //     |                    |    |
1019   //     |   original exit    <----+
1020   //     |                    |
1021   //     +--------------------+
1022   //
1023
1024   RewrittenRangeInfo RRI;
1025
1026   auto BBInsertLocation = std::next(Function::iterator(LS.Latch));
1027   RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
1028                                         &F, BBInsertLocation);
1029   RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
1030                                       BBInsertLocation);
1031
1032   BranchInst *PreheaderJump = cast<BranchInst>(&*Preheader->rbegin());
1033   bool Increasing = LS.IndVarIncreasing;
1034
1035   IRBuilder<> B(PreheaderJump);
1036
1037   // EnterLoopCond - is it okay to start executing this `LS'?
1038   Value *EnterLoopCond = Increasing
1039                              ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1040                              : B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt);
1041
1042   B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1043   PreheaderJump->eraseFromParent();
1044
1045   LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
1046   B.SetInsertPoint(LS.LatchBr);
1047   Value *TakeBackedgeLoopCond =
1048       Increasing ? B.CreateICmpSLT(LS.IndVarNext, ExitSubloopAt)
1049                  : B.CreateICmpSGT(LS.IndVarNext, ExitSubloopAt);
1050   Value *CondForBranch = LS.LatchBrExitIdx == 1
1051                              ? TakeBackedgeLoopCond
1052                              : B.CreateNot(TakeBackedgeLoopCond);
1053
1054   LS.LatchBr->setCondition(CondForBranch);
1055
1056   B.SetInsertPoint(RRI.ExitSelector);
1057
1058   // IterationsLeft - are there any more iterations left, given the original
1059   // upper bound on the induction variable?  If not, we branch to the "real"
1060   // exit.
1061   Value *IterationsLeft = Increasing
1062                               ? B.CreateICmpSLT(LS.IndVarNext, LS.LoopExitAt)
1063                               : B.CreateICmpSGT(LS.IndVarNext, LS.LoopExitAt);
1064   B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1065
1066   BranchInst *BranchToContinuation =
1067       BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1068
1069   // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1070   // each of the PHI nodes in the loop header.  This feeds into the initial
1071   // value of the same PHI nodes if/when we continue execution.
1072   for (Instruction &I : *LS.Header) {
1073     if (!isa<PHINode>(&I))
1074       break;
1075
1076     PHINode *PN = cast<PHINode>(&I);
1077
1078     PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1079                                       BranchToContinuation);
1080
1081     NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1082     NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1083                         RRI.ExitSelector);
1084     RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1085   }
1086
1087   RRI.IndVarEnd = PHINode::Create(LS.IndVarNext->getType(), 2, "indvar.end",
1088                                   BranchToContinuation);
1089   RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1090   RRI.IndVarEnd->addIncoming(LS.IndVarNext, RRI.ExitSelector);
1091
1092   // The latch exit now has a branch from `RRI.ExitSelector' instead of
1093   // `LS.Latch'.  The PHI nodes need to be updated to reflect that.
1094   for (Instruction &I : *LS.LatchExit) {
1095     if (PHINode *PN = dyn_cast<PHINode>(&I))
1096       replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1097     else
1098       break;
1099   }
1100
1101   return RRI;
1102 }
1103
1104 void LoopConstrainer::rewriteIncomingValuesForPHIs(
1105     LoopStructure &LS, BasicBlock *ContinuationBlock,
1106     const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1107
1108   unsigned PHIIndex = 0;
1109   for (Instruction &I : *LS.Header) {
1110     if (!isa<PHINode>(&I))
1111       break;
1112
1113     PHINode *PN = cast<PHINode>(&I);
1114
1115     for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1116       if (PN->getIncomingBlock(i) == ContinuationBlock)
1117         PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1118   }
1119
1120   LS.IndVarStart = RRI.IndVarEnd;
1121 }
1122
1123 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1124                                              BasicBlock *OldPreheader,
1125                                              const char *Tag) const {
1126
1127   BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1128   BranchInst::Create(LS.Header, Preheader);
1129
1130   for (Instruction &I : *LS.Header) {
1131     if (!isa<PHINode>(&I))
1132       break;
1133
1134     PHINode *PN = cast<PHINode>(&I);
1135     for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1136       replacePHIBlock(PN, OldPreheader, Preheader);
1137   }
1138
1139   return Preheader;
1140 }
1141
1142 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
1143   Loop *ParentLoop = OriginalLoop.getParentLoop();
1144   if (!ParentLoop)
1145     return;
1146
1147   for (BasicBlock *BB : BBs)
1148     ParentLoop->addBasicBlockToLoop(BB, OriginalLoopInfo);
1149 }
1150
1151 bool LoopConstrainer::run() {
1152   BasicBlock *Preheader = nullptr;
1153   LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1154   Preheader = OriginalLoop.getLoopPreheader();
1155   assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1156          "preconditions!");
1157
1158   OriginalPreheader = Preheader;
1159   MainLoopPreheader = Preheader;
1160
1161   Optional<SubRanges> MaybeSR = calculateSubRanges();
1162   if (!MaybeSR.hasValue()) {
1163     DEBUG(dbgs() << "irce: could not compute subranges\n");
1164     return false;
1165   }
1166
1167   SubRanges SR = MaybeSR.getValue();
1168   bool Increasing = MainLoopStructure.IndVarIncreasing;
1169   IntegerType *IVTy =
1170       cast<IntegerType>(MainLoopStructure.IndVarNext->getType());
1171
1172   SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
1173   Instruction *InsertPt = OriginalPreheader->getTerminator();
1174
1175   // It would have been better to make `PreLoop' and `PostLoop'
1176   // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1177   // constructor.
1178   ClonedLoop PreLoop, PostLoop;
1179   bool NeedsPreLoop =
1180       Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1181   bool NeedsPostLoop =
1182       Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1183
1184   Value *ExitPreLoopAt = nullptr;
1185   Value *ExitMainLoopAt = nullptr;
1186   const SCEVConstant *MinusOneS =
1187       cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1188
1189   if (NeedsPreLoop) {
1190     const SCEV *ExitPreLoopAtSCEV = nullptr;
1191
1192     if (Increasing)
1193       ExitPreLoopAtSCEV = *SR.LowLimit;
1194     else {
1195       if (CanBeSMin(SE, *SR.HighLimit)) {
1196         DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1197                      << "preloop exit limit.  HighLimit = " << *(*SR.HighLimit)
1198                      << "\n");
1199         return false;
1200       }
1201       ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1202     }
1203
1204     ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1205     ExitPreLoopAt->setName("exit.preloop.at");
1206   }
1207
1208   if (NeedsPostLoop) {
1209     const SCEV *ExitMainLoopAtSCEV = nullptr;
1210
1211     if (Increasing)
1212       ExitMainLoopAtSCEV = *SR.HighLimit;
1213     else {
1214       if (CanBeSMin(SE, *SR.LowLimit)) {
1215         DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1216                      << "mainloop exit limit.  LowLimit = " << *(*SR.LowLimit)
1217                      << "\n");
1218         return false;
1219       }
1220       ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1221     }
1222
1223     ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1224     ExitMainLoopAt->setName("exit.mainloop.at");
1225   }
1226
1227   // We clone these ahead of time so that we don't have to deal with changing
1228   // and temporarily invalid IR as we transform the loops.
1229   if (NeedsPreLoop)
1230     cloneLoop(PreLoop, "preloop");
1231   if (NeedsPostLoop)
1232     cloneLoop(PostLoop, "postloop");
1233
1234   RewrittenRangeInfo PreLoopRRI;
1235
1236   if (NeedsPreLoop) {
1237     Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1238                                                   PreLoop.Structure.Header);
1239
1240     MainLoopPreheader =
1241         createPreheader(MainLoopStructure, Preheader, "mainloop");
1242     PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1243                                          ExitPreLoopAt, MainLoopPreheader);
1244     rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1245                                  PreLoopRRI);
1246   }
1247
1248   BasicBlock *PostLoopPreheader = nullptr;
1249   RewrittenRangeInfo PostLoopRRI;
1250
1251   if (NeedsPostLoop) {
1252     PostLoopPreheader =
1253         createPreheader(PostLoop.Structure, Preheader, "postloop");
1254     PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1255                                           ExitMainLoopAt, PostLoopPreheader);
1256     rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1257                                  PostLoopRRI);
1258   }
1259
1260   BasicBlock *NewMainLoopPreheader =
1261       MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1262   BasicBlock *NewBlocks[] = {PostLoopPreheader,        PreLoopRRI.PseudoExit,
1263                              PreLoopRRI.ExitSelector,  PostLoopRRI.PseudoExit,
1264                              PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1265
1266   // Some of the above may be nullptr, filter them out before passing to
1267   // addToParentLoopIfNeeded.
1268   auto NewBlocksEnd =
1269       std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
1270
1271   addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1272   addToParentLoopIfNeeded(PreLoop.Blocks);
1273   addToParentLoopIfNeeded(PostLoop.Blocks);
1274
1275   return true;
1276 }
1277
1278 /// Computes and returns a range of values for the induction variable (IndVar)
1279 /// in which the range check can be safely elided.  If it cannot compute such a
1280 /// range, returns None.
1281 Optional<InductiveRangeCheck::Range>
1282 InductiveRangeCheck::computeSafeIterationSpace(ScalarEvolution &SE,
1283                                                const SCEVAddRecExpr *IndVar,
1284                                                IRBuilder<> &) const {
1285   // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1286   // variable, that may or may not exist as a real llvm::Value in the loop) and
1287   // this inductive range check is a range check on the "C + D * I" ("C" is
1288   // getOffset() and "D" is getScale()).  We rewrite the value being range
1289   // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1290   // Currently we support this only for "B" = "D" = { 1 or -1 }, but the code
1291   // can be generalized as needed.
1292   //
1293   // The actual inequalities we solve are of the form
1294   //
1295   //   0 <= M + 1 * IndVar < L given L >= 0  (i.e. N == 1)
1296   //
1297   // The inequality is satisfied by -M <= IndVar < (L - M) [^1].  All additions
1298   // and subtractions are twos-complement wrapping and comparisons are signed.
1299   //
1300   // Proof:
1301   //
1302   //   If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1303   //   that -M <= (-M + L) [== Eq. 1].  Since L >= 0, if (-M + L) sign-overflows
1304   //   then (-M + L) < (-M).  Hence by [Eq. 1], (-M + L) could not have
1305   //   overflown.
1306   //
1307   //   This means IndVar = t + (-M) for t in [0, L).  Hence (IndVar + M) = t.
1308   //   Hence 0 <= (IndVar + M) < L
1309
1310   // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1311   // 127, IndVar = 126 and L = -2 in an i8 world.
1312
1313   if (!IndVar->isAffine())
1314     return None;
1315
1316   const SCEV *A = IndVar->getStart();
1317   const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1318   if (!B)
1319     return None;
1320
1321   const SCEV *C = getOffset();
1322   const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1323   if (D != B)
1324     return None;
1325
1326   ConstantInt *ConstD = D->getValue();
1327   if (!(ConstD->isMinusOne() || ConstD->isOne()))
1328     return None;
1329
1330   const SCEV *M = SE.getMinusSCEV(C, A);
1331
1332   const SCEV *Begin = SE.getNegativeSCEV(M);
1333   const SCEV *UpperLimit = nullptr;
1334
1335   // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1336   // We can potentially do much better here.
1337   if (Value *V = getLength()) {
1338     UpperLimit = SE.getSCEV(V);
1339   } else {
1340     assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1341     unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1342     UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1343   }
1344
1345   const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
1346   return InductiveRangeCheck::Range(Begin, End);
1347 }
1348
1349 static Optional<InductiveRangeCheck::Range>
1350 IntersectRange(ScalarEvolution &SE,
1351                const Optional<InductiveRangeCheck::Range> &R1,
1352                const InductiveRangeCheck::Range &R2, IRBuilder<> &B) {
1353   if (!R1.hasValue())
1354     return R2;
1355   auto &R1Value = R1.getValue();
1356
1357   // TODO: we could widen the smaller range and have this work; but for now we
1358   // bail out to keep things simple.
1359   if (R1Value.getType() != R2.getType())
1360     return None;
1361
1362   const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1363   const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1364
1365   return InductiveRangeCheck::Range(NewBegin, NewEnd);
1366 }
1367
1368 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1369   if (L->getBlocks().size() >= LoopSizeCutoff) {
1370     DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1371     return false;
1372   }
1373
1374   BasicBlock *Preheader = L->getLoopPreheader();
1375   if (!Preheader) {
1376     DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1377     return false;
1378   }
1379
1380   LLVMContext &Context = Preheader->getContext();
1381   InductiveRangeCheck::AllocatorTy IRCAlloc;
1382   SmallVector<InductiveRangeCheck *, 16> RangeChecks;
1383   ScalarEvolution &SE = getAnalysis<ScalarEvolution>();
1384   BranchProbabilityInfo &BPI = getAnalysis<BranchProbabilityInfo>();
1385
1386   for (auto BBI : L->getBlocks())
1387     if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1388       if (InductiveRangeCheck *IRC =
1389           InductiveRangeCheck::create(IRCAlloc, TBI, L, SE, BPI))
1390         RangeChecks.push_back(IRC);
1391
1392   if (RangeChecks.empty())
1393     return false;
1394
1395   DEBUG(dbgs() << "irce: looking at loop "; L->print(dbgs());
1396         dbgs() << "irce: loop has " << RangeChecks.size()
1397                << " inductive range checks: \n";
1398         for (InductiveRangeCheck *IRC : RangeChecks)
1399           IRC->print(dbgs());
1400     );
1401
1402   const char *FailureReason = nullptr;
1403   Optional<LoopStructure> MaybeLoopStructure =
1404       LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
1405   if (!MaybeLoopStructure.hasValue()) {
1406     DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1407                  << "\n";);
1408     return false;
1409   }
1410   LoopStructure LS = MaybeLoopStructure.getValue();
1411   bool Increasing = LS.IndVarIncreasing;
1412   const SCEV *MinusOne =
1413       SE.getConstant(LS.IndVarNext->getType(), Increasing ? -1 : 1, true);
1414   const SCEVAddRecExpr *IndVar =
1415       cast<SCEVAddRecExpr>(SE.getAddExpr(SE.getSCEV(LS.IndVarNext), MinusOne));
1416
1417   Optional<InductiveRangeCheck::Range> SafeIterRange;
1418   Instruction *ExprInsertPt = Preheader->getTerminator();
1419
1420   SmallVector<InductiveRangeCheck *, 4> RangeChecksToEliminate;
1421
1422   IRBuilder<> B(ExprInsertPt);
1423   for (InductiveRangeCheck *IRC : RangeChecks) {
1424     auto Result = IRC->computeSafeIterationSpace(SE, IndVar, B);
1425     if (Result.hasValue()) {
1426       auto MaybeSafeIterRange =
1427         IntersectRange(SE, SafeIterRange, Result.getValue(), B);
1428       if (MaybeSafeIterRange.hasValue()) {
1429         RangeChecksToEliminate.push_back(IRC);
1430         SafeIterRange = MaybeSafeIterRange.getValue();
1431       }
1432     }
1433   }
1434
1435   if (!SafeIterRange.hasValue())
1436     return false;
1437
1438   LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LS,
1439                      SE, SafeIterRange.getValue());
1440   bool Changed = LC.run();
1441
1442   if (Changed) {
1443     auto PrintConstrainedLoopInfo = [L]() {
1444       dbgs() << "irce: in function ";
1445       dbgs() << L->getHeader()->getParent()->getName() << ": ";
1446       dbgs() << "constrained ";
1447       L->print(dbgs());
1448     };
1449
1450     DEBUG(PrintConstrainedLoopInfo());
1451
1452     if (PrintChangedLoops)
1453       PrintConstrainedLoopInfo();
1454
1455     // Optimize away the now-redundant range checks.
1456
1457     for (InductiveRangeCheck *IRC : RangeChecksToEliminate) {
1458       ConstantInt *FoldedRangeCheck = IRC->getPassingDirection()
1459                                           ? ConstantInt::getTrue(Context)
1460                                           : ConstantInt::getFalse(Context);
1461       IRC->getBranch()->setCondition(FoldedRangeCheck);
1462     }
1463   }
1464
1465   return Changed;
1466 }
1467
1468 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1469   return new InductiveRangeCheckElimination;
1470 }