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