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 //
10 // The InductiveRangeCheckElimination pass splits a loop's iteration space into
11 // three disjoint ranges.  It does that in a way such that the loop running in
12 // the middle loop provably does not need range checks. As an example, it will
13 // convert
14 //
15 //   len = < known positive >
16 //   for (i = 0; i < n; i++) {
17 //     if (0 <= i && i < len) {
18 //       do_something();
19 //     } else {
20 //       throw_out_of_bounds();
21 //     }
22 //   }
23 //
24 // to
25 //
26 //   len = < known positive >
27 //   limit = smin(n, len)
28 //   // no first segment
29 //   for (i = 0; i < limit; i++) {
30 //     if (0 <= i && i < len) { // this check is fully redundant
31 //       do_something();
32 //     } else {
33 //       throw_out_of_bounds();
34 //     }
35 //   }
36 //   for (i = limit; i < n; i++) {
37 //     if (0 <= i && i < len) {
38 //       do_something();
39 //     } else {
40 //       throw_out_of_bounds();
41 //     }
42 //   }
43 //
44 //===----------------------------------------------------------------------===//
45 
46 #include "llvm/ADT/APInt.h"
47 #include "llvm/ADT/ArrayRef.h"
48 #include "llvm/ADT/None.h"
49 #include "llvm/ADT/Optional.h"
50 #include "llvm/ADT/SmallPtrSet.h"
51 #include "llvm/ADT/SmallVector.h"
52 #include "llvm/ADT/StringRef.h"
53 #include "llvm/ADT/Twine.h"
54 #include "llvm/Analysis/BranchProbabilityInfo.h"
55 #include "llvm/Analysis/LoopInfo.h"
56 #include "llvm/Analysis/LoopPass.h"
57 #include "llvm/Analysis/ScalarEvolution.h"
58 #include "llvm/Analysis/ScalarEvolutionExpander.h"
59 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
60 #include "llvm/IR/BasicBlock.h"
61 #include "llvm/IR/CFG.h"
62 #include "llvm/IR/Constants.h"
63 #include "llvm/IR/DerivedTypes.h"
64 #include "llvm/IR/Dominators.h"
65 #include "llvm/IR/Function.h"
66 #include "llvm/IR/IRBuilder.h"
67 #include "llvm/IR/InstrTypes.h"
68 #include "llvm/IR/Instructions.h"
69 #include "llvm/IR/Metadata.h"
70 #include "llvm/IR/Module.h"
71 #include "llvm/IR/PatternMatch.h"
72 #include "llvm/IR/Type.h"
73 #include "llvm/IR/Use.h"
74 #include "llvm/IR/User.h"
75 #include "llvm/IR/Value.h"
76 #include "llvm/Pass.h"
77 #include "llvm/Support/BranchProbability.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/raw_ostream.h"
84 #include "llvm/Transforms/Scalar.h"
85 #include "llvm/Transforms/Utils/Cloning.h"
86 #include "llvm/Transforms/Utils/LoopSimplify.h"
87 #include "llvm/Transforms/Utils/LoopUtils.h"
88 #include "llvm/Transforms/Utils/ValueMapper.h"
89 #include <algorithm>
90 #include <cassert>
91 #include <iterator>
92 #include <limits>
93 #include <utility>
94 #include <vector>
95 
96 using namespace llvm;
97 using namespace llvm::PatternMatch;
98 
99 static cl::opt<unsigned> LoopSizeCutoff("irce-loop-size-cutoff", cl::Hidden,
100                                         cl::init(64));
101 
102 static cl::opt<bool> PrintChangedLoops("irce-print-changed-loops", cl::Hidden,
103                                        cl::init(false));
104 
105 static cl::opt<bool> PrintRangeChecks("irce-print-range-checks", cl::Hidden,
106                                       cl::init(false));
107 
108 static cl::opt<int> MaxExitProbReciprocal("irce-max-exit-prob-reciprocal",
109                                           cl::Hidden, cl::init(10));
110 
111 static cl::opt<bool> SkipProfitabilityChecks("irce-skip-profitability-checks",
112                                              cl::Hidden, cl::init(false));
113 
114 static cl::opt<bool> AllowUnsignedLatchCondition("irce-allow-unsigned-latch",
115                                                  cl::Hidden, cl::init(true));
116 
117 static const char *ClonedLoopTag = "irce.loop.clone";
118 
119 #define DEBUG_TYPE "irce"
120 
121 namespace {
122 
123 /// An inductive range check is conditional branch in a loop with
124 ///
125 ///  1. a very cold successor (i.e. the branch jumps to that successor very
126 ///     rarely)
127 ///
128 ///  and
129 ///
130 ///  2. a condition that is provably true for some contiguous range of values
131 ///     taken by the containing loop's induction variable.
132 ///
133 class InductiveRangeCheck {
134   // Classifies a range check
135   enum RangeCheckKind : unsigned {
136     // Range check of the form "0 <= I".
137     RANGE_CHECK_LOWER = 1,
138 
139     // Range check of the form "I < L" where L is known positive.
140     RANGE_CHECK_UPPER = 2,
141 
142     // The logical and of the RANGE_CHECK_LOWER and RANGE_CHECK_UPPER
143     // conditions.
144     RANGE_CHECK_BOTH = RANGE_CHECK_LOWER | RANGE_CHECK_UPPER,
145 
146     // Unrecognized range check condition.
147     RANGE_CHECK_UNKNOWN = (unsigned)-1
148   };
149 
150   static StringRef rangeCheckKindToStr(RangeCheckKind);
151 
152   const SCEV *Offset = nullptr;
153   const SCEV *Scale = nullptr;
154   Value *Length = nullptr;
155   Use *CheckUse = nullptr;
156   RangeCheckKind Kind = RANGE_CHECK_UNKNOWN;
157   bool IsSigned = true;
158 
159   static RangeCheckKind parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
160                                             ScalarEvolution &SE, Value *&Index,
161                                             Value *&Length, bool &IsSigned);
162 
163   static void
164   extractRangeChecksFromCond(Loop *L, ScalarEvolution &SE, Use &ConditionUse,
165                              SmallVectorImpl<InductiveRangeCheck> &Checks,
166                              SmallPtrSetImpl<Value *> &Visited);
167 
168 public:
169   const SCEV *getOffset() const { return Offset; }
170   const SCEV *getScale() const { return Scale; }
171   Value *getLength() const { return Length; }
172   bool isSigned() const { return IsSigned; }
173 
174   void print(raw_ostream &OS) const {
175     OS << "InductiveRangeCheck:\n";
176     OS << "  Kind: " << rangeCheckKindToStr(Kind) << "\n";
177     OS << "  Offset: ";
178     Offset->print(OS);
179     OS << "  Scale: ";
180     Scale->print(OS);
181     OS << "  Length: ";
182     if (Length)
183       Length->print(OS);
184     else
185       OS << "(null)";
186     OS << "\n  CheckUse: ";
187     getCheckUse()->getUser()->print(OS);
188     OS << " Operand: " << getCheckUse()->getOperandNo() << "\n";
189   }
190 
191   LLVM_DUMP_METHOD
192   void dump() {
193     print(dbgs());
194   }
195 
196   Use *getCheckUse() const { return CheckUse; }
197 
198   /// Represents an signed integer range [Range.getBegin(), Range.getEnd()).  If
199   /// R.getEnd() sle R.getBegin(), then R denotes the empty range.
200 
201   class Range {
202     const SCEV *Begin;
203     const SCEV *End;
204 
205   public:
206     Range(const SCEV *Begin, const SCEV *End) : Begin(Begin), End(End) {
207       assert(Begin->getType() == End->getType() && "ill-typed range!");
208     }
209 
210     Type *getType() const { return Begin->getType(); }
211     const SCEV *getBegin() const { return Begin; }
212     const SCEV *getEnd() const { return End; }
213     bool isEmpty(ScalarEvolution &SE, bool IsSigned) const {
214       if (Begin == End)
215         return true;
216       if (IsSigned)
217         return SE.isKnownPredicate(ICmpInst::ICMP_SGE, Begin, End);
218       else
219         return SE.isKnownPredicate(ICmpInst::ICMP_UGE, Begin, End);
220     }
221   };
222 
223   /// This is the value the condition of the branch needs to evaluate to for the
224   /// branch to take the hot successor (see (1) above).
225   bool getPassingDirection() { return true; }
226 
227   /// Computes a range for the induction variable (IndVar) in which the range
228   /// check is redundant and can be constant-folded away.  The induction
229   /// variable is not required to be the canonical {0,+,1} induction variable.
230   Optional<Range> computeSafeIterationSpace(ScalarEvolution &SE,
231                                             const SCEVAddRecExpr *IndVar) const;
232 
233   /// Parse out a set of inductive range checks from \p BI and append them to \p
234   /// Checks.
235   ///
236   /// NB! There may be conditions feeding into \p BI that aren't inductive range
237   /// checks, and hence don't end up in \p Checks.
238   static void
239   extractRangeChecksFromBranch(BranchInst *BI, Loop *L, ScalarEvolution &SE,
240                                BranchProbabilityInfo &BPI,
241                                SmallVectorImpl<InductiveRangeCheck> &Checks);
242 };
243 
244 class InductiveRangeCheckElimination : public LoopPass {
245 public:
246   static char ID;
247 
248   InductiveRangeCheckElimination() : LoopPass(ID) {
249     initializeInductiveRangeCheckEliminationPass(
250         *PassRegistry::getPassRegistry());
251   }
252 
253   void getAnalysisUsage(AnalysisUsage &AU) const override {
254     AU.addRequired<BranchProbabilityInfoWrapperPass>();
255     getLoopAnalysisUsage(AU);
256   }
257 
258   bool runOnLoop(Loop *L, LPPassManager &LPM) override;
259 };
260 
261 } // end anonymous namespace
262 
263 char InductiveRangeCheckElimination::ID = 0;
264 
265 INITIALIZE_PASS_BEGIN(InductiveRangeCheckElimination, "irce",
266                       "Inductive range check elimination", false, false)
267 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
268 INITIALIZE_PASS_DEPENDENCY(LoopPass)
269 INITIALIZE_PASS_END(InductiveRangeCheckElimination, "irce",
270                     "Inductive range check elimination", false, false)
271 
272 StringRef InductiveRangeCheck::rangeCheckKindToStr(
273     InductiveRangeCheck::RangeCheckKind RCK) {
274   switch (RCK) {
275   case InductiveRangeCheck::RANGE_CHECK_UNKNOWN:
276     return "RANGE_CHECK_UNKNOWN";
277 
278   case InductiveRangeCheck::RANGE_CHECK_UPPER:
279     return "RANGE_CHECK_UPPER";
280 
281   case InductiveRangeCheck::RANGE_CHECK_LOWER:
282     return "RANGE_CHECK_LOWER";
283 
284   case InductiveRangeCheck::RANGE_CHECK_BOTH:
285     return "RANGE_CHECK_BOTH";
286   }
287 
288   llvm_unreachable("unknown range check type!");
289 }
290 
291 /// Parse a single ICmp instruction, `ICI`, into a range check.  If `ICI` cannot
292 /// be interpreted as a range check, return `RANGE_CHECK_UNKNOWN` and set
293 /// `Index` and `Length` to `nullptr`.  Otherwise set `Index` to the value being
294 /// range checked, and set `Length` to the upper limit `Index` is being range
295 /// checked with if (and only if) the range check type is stronger or equal to
296 /// RANGE_CHECK_UPPER.
297 InductiveRangeCheck::RangeCheckKind
298 InductiveRangeCheck::parseRangeCheckICmp(Loop *L, ICmpInst *ICI,
299                                          ScalarEvolution &SE, Value *&Index,
300                                          Value *&Length, bool &IsSigned) {
301   auto IsNonNegativeAndNotLoopVarying = [&SE, L](Value *V) {
302     const SCEV *S = SE.getSCEV(V);
303     if (isa<SCEVCouldNotCompute>(S))
304       return false;
305 
306     return SE.getLoopDisposition(S, L) == ScalarEvolution::LoopInvariant &&
307            SE.isKnownNonNegative(S);
308   };
309 
310   ICmpInst::Predicate Pred = ICI->getPredicate();
311   Value *LHS = ICI->getOperand(0);
312   Value *RHS = ICI->getOperand(1);
313 
314   switch (Pred) {
315   default:
316     return RANGE_CHECK_UNKNOWN;
317 
318   case ICmpInst::ICMP_SLE:
319     std::swap(LHS, RHS);
320     LLVM_FALLTHROUGH;
321   case ICmpInst::ICMP_SGE:
322     IsSigned = true;
323     if (match(RHS, m_ConstantInt<0>())) {
324       Index = LHS;
325       return RANGE_CHECK_LOWER;
326     }
327     return RANGE_CHECK_UNKNOWN;
328 
329   case ICmpInst::ICMP_SLT:
330     std::swap(LHS, RHS);
331     LLVM_FALLTHROUGH;
332   case ICmpInst::ICMP_SGT:
333     IsSigned = true;
334     if (match(RHS, m_ConstantInt<-1>())) {
335       Index = LHS;
336       return RANGE_CHECK_LOWER;
337     }
338 
339     if (IsNonNegativeAndNotLoopVarying(LHS)) {
340       Index = RHS;
341       Length = LHS;
342       return RANGE_CHECK_UPPER;
343     }
344     return RANGE_CHECK_UNKNOWN;
345 
346   case ICmpInst::ICMP_ULT:
347     std::swap(LHS, RHS);
348     LLVM_FALLTHROUGH;
349   case ICmpInst::ICMP_UGT:
350     IsSigned = false;
351     if (IsNonNegativeAndNotLoopVarying(LHS)) {
352       Index = RHS;
353       Length = LHS;
354       return RANGE_CHECK_BOTH;
355     }
356     return RANGE_CHECK_UNKNOWN;
357   }
358 
359   llvm_unreachable("default clause returns!");
360 }
361 
362 void InductiveRangeCheck::extractRangeChecksFromCond(
363     Loop *L, ScalarEvolution &SE, Use &ConditionUse,
364     SmallVectorImpl<InductiveRangeCheck> &Checks,
365     SmallPtrSetImpl<Value *> &Visited) {
366   Value *Condition = ConditionUse.get();
367   if (!Visited.insert(Condition).second)
368     return;
369 
370   if (match(Condition, m_And(m_Value(), m_Value()))) {
371     SmallVector<InductiveRangeCheck, 8> SubChecks;
372     extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(0),
373                                SubChecks, Visited);
374     extractRangeChecksFromCond(L, SE, cast<User>(Condition)->getOperandUse(1),
375                                SubChecks, Visited);
376 
377     if (SubChecks.size() == 2) {
378       // Handle a special case where we know how to merge two checks separately
379       // checking the upper and lower bounds into a full range check.
380       const auto &RChkA = SubChecks[0];
381       const auto &RChkB = SubChecks[1];
382       if ((RChkA.Length == RChkB.Length || !RChkA.Length || !RChkB.Length) &&
383           RChkA.Offset == RChkB.Offset && RChkA.Scale == RChkB.Scale &&
384           RChkA.IsSigned == RChkB.IsSigned) {
385         // If RChkA.Kind == RChkB.Kind then we just found two identical checks.
386         // But if one of them is a RANGE_CHECK_LOWER and the other is a
387         // RANGE_CHECK_UPPER (only possibility if they're different) then
388         // together they form a RANGE_CHECK_BOTH.
389         SubChecks[0].Kind =
390             (InductiveRangeCheck::RangeCheckKind)(RChkA.Kind | RChkB.Kind);
391         SubChecks[0].Length = RChkA.Length ? RChkA.Length : RChkB.Length;
392         SubChecks[0].CheckUse = &ConditionUse;
393         SubChecks[0].IsSigned = RChkA.IsSigned;
394 
395         // We updated one of the checks in place, now erase the other.
396         SubChecks.pop_back();
397       }
398     }
399 
400     Checks.insert(Checks.end(), SubChecks.begin(), SubChecks.end());
401     return;
402   }
403 
404   ICmpInst *ICI = dyn_cast<ICmpInst>(Condition);
405   if (!ICI)
406     return;
407 
408   Value *Length = nullptr, *Index;
409   bool IsSigned;
410   auto RCKind = parseRangeCheckICmp(L, ICI, SE, Index, Length, IsSigned);
411   if (RCKind == InductiveRangeCheck::RANGE_CHECK_UNKNOWN)
412     return;
413 
414   const auto *IndexAddRec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Index));
415   bool IsAffineIndex =
416       IndexAddRec && (IndexAddRec->getLoop() == L) && IndexAddRec->isAffine();
417 
418   if (!IsAffineIndex)
419     return;
420 
421   InductiveRangeCheck IRC;
422   IRC.Length = Length;
423   IRC.Offset = IndexAddRec->getStart();
424   IRC.Scale = IndexAddRec->getStepRecurrence(SE);
425   IRC.CheckUse = &ConditionUse;
426   IRC.Kind = RCKind;
427   IRC.IsSigned = IsSigned;
428   Checks.push_back(IRC);
429 }
430 
431 void InductiveRangeCheck::extractRangeChecksFromBranch(
432     BranchInst *BI, Loop *L, ScalarEvolution &SE, BranchProbabilityInfo &BPI,
433     SmallVectorImpl<InductiveRangeCheck> &Checks) {
434   if (BI->isUnconditional() || BI->getParent() == L->getLoopLatch())
435     return;
436 
437   BranchProbability LikelyTaken(15, 16);
438 
439   if (!SkipProfitabilityChecks &&
440       BPI.getEdgeProbability(BI->getParent(), (unsigned)0) < LikelyTaken)
441     return;
442 
443   SmallPtrSet<Value *, 8> Visited;
444   InductiveRangeCheck::extractRangeChecksFromCond(L, SE, BI->getOperandUse(0),
445                                                   Checks, Visited);
446 }
447 
448 // Add metadata to the loop L to disable loop optimizations. Callers need to
449 // confirm that optimizing loop L is not beneficial.
450 static void DisableAllLoopOptsOnLoop(Loop &L) {
451   // We do not care about any existing loopID related metadata for L, since we
452   // are setting all loop metadata to false.
453   LLVMContext &Context = L.getHeader()->getContext();
454   // Reserve first location for self reference to the LoopID metadata node.
455   MDNode *Dummy = MDNode::get(Context, {});
456   MDNode *DisableUnroll = MDNode::get(
457       Context, {MDString::get(Context, "llvm.loop.unroll.disable")});
458   Metadata *FalseVal =
459       ConstantAsMetadata::get(ConstantInt::get(Type::getInt1Ty(Context), 0));
460   MDNode *DisableVectorize = MDNode::get(
461       Context,
462       {MDString::get(Context, "llvm.loop.vectorize.enable"), FalseVal});
463   MDNode *DisableLICMVersioning = MDNode::get(
464       Context, {MDString::get(Context, "llvm.loop.licm_versioning.disable")});
465   MDNode *DisableDistribution= MDNode::get(
466       Context,
467       {MDString::get(Context, "llvm.loop.distribute.enable"), FalseVal});
468   MDNode *NewLoopID =
469       MDNode::get(Context, {Dummy, DisableUnroll, DisableVectorize,
470                             DisableLICMVersioning, DisableDistribution});
471   // Set operand 0 to refer to the loop id itself.
472   NewLoopID->replaceOperandWith(0, NewLoopID);
473   L.setLoopID(NewLoopID);
474 }
475 
476 namespace {
477 
478 // Keeps track of the structure of a loop.  This is similar to llvm::Loop,
479 // except that it is more lightweight and can track the state of a loop through
480 // changing and potentially invalid IR.  This structure also formalizes the
481 // kinds of loops we can deal with -- ones that have a single latch that is also
482 // an exiting block *and* have a canonical induction variable.
483 struct LoopStructure {
484   const char *Tag = "";
485 
486   BasicBlock *Header = nullptr;
487   BasicBlock *Latch = nullptr;
488 
489   // `Latch's terminator instruction is `LatchBr', and it's `LatchBrExitIdx'th
490   // successor is `LatchExit', the exit block of the loop.
491   BranchInst *LatchBr = nullptr;
492   BasicBlock *LatchExit = nullptr;
493   unsigned LatchBrExitIdx = std::numeric_limits<unsigned>::max();
494 
495   // The loop represented by this instance of LoopStructure is semantically
496   // equivalent to:
497   //
498   // intN_ty inc = IndVarIncreasing ? 1 : -1;
499   // pred_ty predicate = IndVarIncreasing ? ICMP_SLT : ICMP_SGT;
500   //
501   // for (intN_ty iv = IndVarStart; predicate(iv, LoopExitAt); iv = IndVarBase)
502   //   ... body ...
503 
504   Value *IndVarBase = nullptr;
505   Value *IndVarStart = nullptr;
506   Value *IndVarStep = nullptr;
507   Value *LoopExitAt = nullptr;
508   bool IndVarIncreasing = false;
509   bool IsSignedPredicate = true;
510 
511   LoopStructure() = default;
512 
513   template <typename M> LoopStructure map(M Map) const {
514     LoopStructure Result;
515     Result.Tag = Tag;
516     Result.Header = cast<BasicBlock>(Map(Header));
517     Result.Latch = cast<BasicBlock>(Map(Latch));
518     Result.LatchBr = cast<BranchInst>(Map(LatchBr));
519     Result.LatchExit = cast<BasicBlock>(Map(LatchExit));
520     Result.LatchBrExitIdx = LatchBrExitIdx;
521     Result.IndVarBase = Map(IndVarBase);
522     Result.IndVarStart = Map(IndVarStart);
523     Result.IndVarStep = Map(IndVarStep);
524     Result.LoopExitAt = Map(LoopExitAt);
525     Result.IndVarIncreasing = IndVarIncreasing;
526     Result.IsSignedPredicate = IsSignedPredicate;
527     return Result;
528   }
529 
530   static Optional<LoopStructure> parseLoopStructure(ScalarEvolution &,
531                                                     BranchProbabilityInfo &BPI,
532                                                     Loop &,
533                                                     const char *&);
534 };
535 
536 /// This class is used to constrain loops to run within a given iteration space.
537 /// The algorithm this class implements is given a Loop and a range [Begin,
538 /// End).  The algorithm then tries to break out a "main loop" out of the loop
539 /// it is given in a way that the "main loop" runs with the induction variable
540 /// in a subset of [Begin, End).  The algorithm emits appropriate pre and post
541 /// loops to run any remaining iterations.  The pre loop runs any iterations in
542 /// which the induction variable is < Begin, and the post loop runs any
543 /// iterations in which the induction variable is >= End.
544 class LoopConstrainer {
545   // The representation of a clone of the original loop we started out with.
546   struct ClonedLoop {
547     // The cloned blocks
548     std::vector<BasicBlock *> Blocks;
549 
550     // `Map` maps values in the clonee into values in the cloned version
551     ValueToValueMapTy Map;
552 
553     // An instance of `LoopStructure` for the cloned loop
554     LoopStructure Structure;
555   };
556 
557   // Result of rewriting the range of a loop.  See changeIterationSpaceEnd for
558   // more details on what these fields mean.
559   struct RewrittenRangeInfo {
560     BasicBlock *PseudoExit = nullptr;
561     BasicBlock *ExitSelector = nullptr;
562     std::vector<PHINode *> PHIValuesAtPseudoExit;
563     PHINode *IndVarEnd = nullptr;
564 
565     RewrittenRangeInfo() = default;
566   };
567 
568   // Calculated subranges we restrict the iteration space of the main loop to.
569   // See the implementation of `calculateSubRanges' for more details on how
570   // these fields are computed.  `LowLimit` is None if there is no restriction
571   // on low end of the restricted iteration space of the main loop.  `HighLimit`
572   // is None if there is no restriction on high end of the restricted iteration
573   // space of the main loop.
574 
575   struct SubRanges {
576     Optional<const SCEV *> LowLimit;
577     Optional<const SCEV *> HighLimit;
578   };
579 
580   // A utility function that does a `replaceUsesOfWith' on the incoming block
581   // set of a `PHINode' -- replaces instances of `Block' in the `PHINode's
582   // incoming block list with `ReplaceBy'.
583   static void replacePHIBlock(PHINode *PN, BasicBlock *Block,
584                               BasicBlock *ReplaceBy);
585 
586   // Compute a safe set of limits for the main loop to run in -- effectively the
587   // intersection of `Range' and the iteration space of the original loop.
588   // Return None if unable to compute the set of subranges.
589   Optional<SubRanges> calculateSubRanges(bool IsSignedPredicate) const;
590 
591   // Clone `OriginalLoop' and return the result in CLResult.  The IR after
592   // running `cloneLoop' is well formed except for the PHI nodes in CLResult --
593   // the PHI nodes say that there is an incoming edge from `OriginalPreheader`
594   // but there is no such edge.
595   void cloneLoop(ClonedLoop &CLResult, const char *Tag) const;
596 
597   // Create the appropriate loop structure needed to describe a cloned copy of
598   // `Original`.  The clone is described by `VM`.
599   Loop *createClonedLoopStructure(Loop *Original, Loop *Parent,
600                                   ValueToValueMapTy &VM);
601 
602   // Rewrite the iteration space of the loop denoted by (LS, Preheader). The
603   // iteration space of the rewritten loop ends at ExitLoopAt.  The start of the
604   // iteration space is not changed.  `ExitLoopAt' is assumed to be slt
605   // `OriginalHeaderCount'.
606   //
607   // If there are iterations left to execute, control is made to jump to
608   // `ContinuationBlock', otherwise they take the normal loop exit.  The
609   // returned `RewrittenRangeInfo' object is populated as follows:
610   //
611   //  .PseudoExit is a basic block that unconditionally branches to
612   //      `ContinuationBlock'.
613   //
614   //  .ExitSelector is a basic block that decides, on exit from the loop,
615   //      whether to branch to the "true" exit or to `PseudoExit'.
616   //
617   //  .PHIValuesAtPseudoExit are PHINodes in `PseudoExit' that compute the value
618   //      for each PHINode in the loop header on taking the pseudo exit.
619   //
620   // After changeIterationSpaceEnd, `Preheader' is no longer a legitimate
621   // preheader because it is made to branch to the loop header only
622   // conditionally.
623   RewrittenRangeInfo
624   changeIterationSpaceEnd(const LoopStructure &LS, BasicBlock *Preheader,
625                           Value *ExitLoopAt,
626                           BasicBlock *ContinuationBlock) const;
627 
628   // The loop denoted by `LS' has `OldPreheader' as its preheader.  This
629   // function creates a new preheader for `LS' and returns it.
630   BasicBlock *createPreheader(const LoopStructure &LS, BasicBlock *OldPreheader,
631                               const char *Tag) const;
632 
633   // `ContinuationBlockAndPreheader' was the continuation block for some call to
634   // `changeIterationSpaceEnd' and is the preheader to the loop denoted by `LS'.
635   // This function rewrites the PHI nodes in `LS.Header' to start with the
636   // correct value.
637   void rewriteIncomingValuesForPHIs(
638       LoopStructure &LS, BasicBlock *ContinuationBlockAndPreheader,
639       const LoopConstrainer::RewrittenRangeInfo &RRI) const;
640 
641   // Even though we do not preserve any passes at this time, we at least need to
642   // keep the parent loop structure consistent.  The `LPPassManager' seems to
643   // verify this after running a loop pass.  This function adds the list of
644   // blocks denoted by BBs to this loops parent loop if required.
645   void addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs);
646 
647   // Some global state.
648   Function &F;
649   LLVMContext &Ctx;
650   ScalarEvolution &SE;
651   DominatorTree &DT;
652   LPPassManager &LPM;
653   LoopInfo &LI;
654 
655   // Information about the original loop we started out with.
656   Loop &OriginalLoop;
657 
658   const SCEV *LatchTakenCount = nullptr;
659   BasicBlock *OriginalPreheader = nullptr;
660 
661   // The preheader of the main loop.  This may or may not be different from
662   // `OriginalPreheader'.
663   BasicBlock *MainLoopPreheader = nullptr;
664 
665   // The range we need to run the main loop in.
666   InductiveRangeCheck::Range Range;
667 
668   // The structure of the main loop (see comment at the beginning of this class
669   // for a definition)
670   LoopStructure MainLoopStructure;
671 
672 public:
673   LoopConstrainer(Loop &L, LoopInfo &LI, LPPassManager &LPM,
674                   const LoopStructure &LS, ScalarEvolution &SE,
675                   DominatorTree &DT, InductiveRangeCheck::Range R)
676       : F(*L.getHeader()->getParent()), Ctx(L.getHeader()->getContext()),
677         SE(SE), DT(DT), LPM(LPM), LI(LI), OriginalLoop(L), Range(R),
678         MainLoopStructure(LS) {}
679 
680   // Entry point for the algorithm.  Returns true on success.
681   bool run();
682 };
683 
684 } // end anonymous namespace
685 
686 void LoopConstrainer::replacePHIBlock(PHINode *PN, BasicBlock *Block,
687                                       BasicBlock *ReplaceBy) {
688   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
689     if (PN->getIncomingBlock(i) == Block)
690       PN->setIncomingBlock(i, ReplaceBy);
691 }
692 
693 static bool CanBeMax(ScalarEvolution &SE, const SCEV *S, bool Signed) {
694   APInt Max = Signed ?
695       APInt::getSignedMaxValue(cast<IntegerType>(S->getType())->getBitWidth()) :
696       APInt::getMaxValue(cast<IntegerType>(S->getType())->getBitWidth());
697   return SE.getSignedRange(S).contains(Max) &&
698          SE.getUnsignedRange(S).contains(Max);
699 }
700 
701 static bool SumCanReachMax(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
702                            bool Signed) {
703   // S1 < INT_MAX - S2 ===> S1 + S2 < INT_MAX.
704   assert(SE.isKnownNonNegative(S2) &&
705          "We expected the 2nd arg to be non-negative!");
706   const SCEV *Max = SE.getConstant(
707       Signed ? APInt::getSignedMaxValue(
708                    cast<IntegerType>(S1->getType())->getBitWidth())
709              : APInt::getMaxValue(
710                    cast<IntegerType>(S1->getType())->getBitWidth()));
711   const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
712   return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
713                               S1, CapForS1);
714 }
715 
716 static bool CanBeMin(ScalarEvolution &SE, const SCEV *S, bool Signed) {
717   APInt Min = Signed ?
718       APInt::getSignedMinValue(cast<IntegerType>(S->getType())->getBitWidth()) :
719       APInt::getMinValue(cast<IntegerType>(S->getType())->getBitWidth());
720   return SE.getSignedRange(S).contains(Min) &&
721          SE.getUnsignedRange(S).contains(Min);
722 }
723 
724 static bool SumCanReachMin(ScalarEvolution &SE, const SCEV *S1, const SCEV *S2,
725                            bool Signed) {
726   // S1 > INT_MIN - S2 ===> S1 + S2 > INT_MIN.
727   assert(SE.isKnownNonPositive(S2) &&
728          "We expected the 2nd arg to be non-positive!");
729   const SCEV *Max = SE.getConstant(
730       Signed ? APInt::getSignedMinValue(
731                    cast<IntegerType>(S1->getType())->getBitWidth())
732              : APInt::getMinValue(
733                    cast<IntegerType>(S1->getType())->getBitWidth()));
734   const SCEV *CapForS1 = SE.getMinusSCEV(Max, S2);
735   return !SE.isKnownPredicate(Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT,
736                               S1, CapForS1);
737 }
738 
739 Optional<LoopStructure>
740 LoopStructure::parseLoopStructure(ScalarEvolution &SE,
741                                   BranchProbabilityInfo &BPI,
742                                   Loop &L, const char *&FailureReason) {
743   if (!L.isLoopSimplifyForm()) {
744     FailureReason = "loop not in LoopSimplify form";
745     return None;
746   }
747 
748   BasicBlock *Latch = L.getLoopLatch();
749   assert(Latch && "Simplified loops only have one latch!");
750 
751   if (Latch->getTerminator()->getMetadata(ClonedLoopTag)) {
752     FailureReason = "loop has already been cloned";
753     return None;
754   }
755 
756   if (!L.isLoopExiting(Latch)) {
757     FailureReason = "no loop latch";
758     return None;
759   }
760 
761   BasicBlock *Header = L.getHeader();
762   BasicBlock *Preheader = L.getLoopPreheader();
763   if (!Preheader) {
764     FailureReason = "no preheader";
765     return None;
766   }
767 
768   BranchInst *LatchBr = dyn_cast<BranchInst>(Latch->getTerminator());
769   if (!LatchBr || LatchBr->isUnconditional()) {
770     FailureReason = "latch terminator not conditional branch";
771     return None;
772   }
773 
774   unsigned LatchBrExitIdx = LatchBr->getSuccessor(0) == Header ? 1 : 0;
775 
776   BranchProbability ExitProbability =
777     BPI.getEdgeProbability(LatchBr->getParent(), LatchBrExitIdx);
778 
779   if (!SkipProfitabilityChecks &&
780       ExitProbability > BranchProbability(1, MaxExitProbReciprocal)) {
781     FailureReason = "short running loop, not profitable";
782     return None;
783   }
784 
785   ICmpInst *ICI = dyn_cast<ICmpInst>(LatchBr->getCondition());
786   if (!ICI || !isa<IntegerType>(ICI->getOperand(0)->getType())) {
787     FailureReason = "latch terminator branch not conditional on integral icmp";
788     return None;
789   }
790 
791   const SCEV *LatchCount = SE.getExitCount(&L, Latch);
792   if (isa<SCEVCouldNotCompute>(LatchCount)) {
793     FailureReason = "could not compute latch count";
794     return None;
795   }
796 
797   ICmpInst::Predicate Pred = ICI->getPredicate();
798   Value *LeftValue = ICI->getOperand(0);
799   const SCEV *LeftSCEV = SE.getSCEV(LeftValue);
800   IntegerType *IndVarTy = cast<IntegerType>(LeftValue->getType());
801 
802   Value *RightValue = ICI->getOperand(1);
803   const SCEV *RightSCEV = SE.getSCEV(RightValue);
804 
805   // We canonicalize `ICI` such that `LeftSCEV` is an add recurrence.
806   if (!isa<SCEVAddRecExpr>(LeftSCEV)) {
807     if (isa<SCEVAddRecExpr>(RightSCEV)) {
808       std::swap(LeftSCEV, RightSCEV);
809       std::swap(LeftValue, RightValue);
810       Pred = ICmpInst::getSwappedPredicate(Pred);
811     } else {
812       FailureReason = "no add recurrences in the icmp";
813       return None;
814     }
815   }
816 
817   auto HasNoSignedWrap = [&](const SCEVAddRecExpr *AR) {
818     if (AR->getNoWrapFlags(SCEV::FlagNSW))
819       return true;
820 
821     IntegerType *Ty = cast<IntegerType>(AR->getType());
822     IntegerType *WideTy =
823         IntegerType::get(Ty->getContext(), Ty->getBitWidth() * 2);
824 
825     const SCEVAddRecExpr *ExtendAfterOp =
826         dyn_cast<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
827     if (ExtendAfterOp) {
828       const SCEV *ExtendedStart = SE.getSignExtendExpr(AR->getStart(), WideTy);
829       const SCEV *ExtendedStep =
830           SE.getSignExtendExpr(AR->getStepRecurrence(SE), WideTy);
831 
832       bool NoSignedWrap = ExtendAfterOp->getStart() == ExtendedStart &&
833                           ExtendAfterOp->getStepRecurrence(SE) == ExtendedStep;
834 
835       if (NoSignedWrap)
836         return true;
837     }
838 
839     // We may have proved this when computing the sign extension above.
840     return AR->getNoWrapFlags(SCEV::FlagNSW) != SCEV::FlagAnyWrap;
841   };
842 
843   // Here we check whether the suggested AddRec is an induction variable that
844   // can be handled (i.e. with known constant step), and if yes, calculate its
845   // step and identify whether it is increasing or decreasing.
846   auto IsInductionVar = [&](const SCEVAddRecExpr *AR, bool &IsIncreasing,
847                             ConstantInt *&StepCI) {
848     if (!AR->isAffine())
849       return false;
850 
851     // Currently we only work with induction variables that have been proved to
852     // not wrap.  This restriction can potentially be lifted in the future.
853 
854     if (!HasNoSignedWrap(AR))
855       return false;
856 
857     if (const SCEVConstant *StepExpr =
858             dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE))) {
859       StepCI = StepExpr->getValue();
860       assert(!StepCI->isZero() && "Zero step?");
861       IsIncreasing = !StepCI->isNegative();
862       return true;
863     }
864 
865     return false;
866   };
867 
868   // `ICI` is interpreted as taking the backedge if the *next* value of the
869   // induction variable satisfies some constraint.
870 
871   const SCEVAddRecExpr *IndVarBase = cast<SCEVAddRecExpr>(LeftSCEV);
872   bool IsIncreasing = false;
873   bool IsSignedPredicate = true;
874   ConstantInt *StepCI;
875   if (!IsInductionVar(IndVarBase, IsIncreasing, StepCI)) {
876     FailureReason = "LHS in icmp not induction variable";
877     return None;
878   }
879 
880   const SCEV *StartNext = IndVarBase->getStart();
881   const SCEV *Addend = SE.getNegativeSCEV(IndVarBase->getStepRecurrence(SE));
882   const SCEV *IndVarStart = SE.getAddExpr(StartNext, Addend);
883   const SCEV *Step = SE.getSCEV(StepCI);
884 
885   ConstantInt *One = ConstantInt::get(IndVarTy, 1);
886   if (IsIncreasing) {
887     bool DecreasedRightValueByOne = false;
888     if (StepCI->isOne()) {
889       // Try to turn eq/ne predicates to those we can work with.
890       if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
891         // while (++i != len) {         while (++i < len) {
892         //   ...                 --->     ...
893         // }                            }
894         // If both parts are known non-negative, it is profitable to use
895         // unsigned comparison in increasing loop. This allows us to make the
896         // comparison check against "RightSCEV + 1" more optimistic.
897         if (SE.isKnownNonNegative(IndVarStart) &&
898             SE.isKnownNonNegative(RightSCEV))
899           Pred = ICmpInst::ICMP_ULT;
900         else
901           Pred = ICmpInst::ICMP_SLT;
902       else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
903                !CanBeMin(SE, RightSCEV, /* IsSignedPredicate */ true)) {
904         // while (true) {               while (true) {
905         //   if (++i == len)     --->     if (++i > len - 1)
906         //     break;                       break;
907         //   ...                          ...
908         // }                            }
909         // TODO: Insert ICMP_UGT if both are non-negative?
910         Pred = ICmpInst::ICMP_SGT;
911         RightSCEV = SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType()));
912         DecreasedRightValueByOne = true;
913       }
914     }
915 
916     bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
917     bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
918     bool FoundExpectedPred =
919         (LTPred && LatchBrExitIdx == 1) || (GTPred && LatchBrExitIdx == 0);
920 
921     if (!FoundExpectedPred) {
922       FailureReason = "expected icmp slt semantically, found something else";
923       return None;
924     }
925 
926     IsSignedPredicate =
927         Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
928 
929     if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
930       FailureReason = "unsigned latch conditions are explicitly prohibited";
931       return None;
932     }
933 
934     // The predicate that we need to check that the induction variable lies
935     // within bounds.
936     ICmpInst::Predicate BoundPred =
937         IsSignedPredicate ? CmpInst::ICMP_SLT : CmpInst::ICMP_ULT;
938 
939     if (LatchBrExitIdx == 0) {
940       const SCEV *StepMinusOne = SE.getMinusSCEV(Step,
941                                                  SE.getOne(Step->getType()));
942       if (SumCanReachMax(SE, RightSCEV, StepMinusOne, IsSignedPredicate)) {
943         // TODO: this restriction is easily removable -- we just have to
944         // remember that the icmp was an slt and not an sle.
945         FailureReason = "limit may overflow when coercing le to lt";
946         return None;
947       }
948 
949       if (!SE.isLoopEntryGuardedByCond(
950               &L, BoundPred, IndVarStart,
951               SE.getAddExpr(RightSCEV, Step))) {
952         FailureReason = "Induction variable start not bounded by upper limit";
953         return None;
954       }
955 
956       // We need to increase the right value unless we have already decreased
957       // it virtually when we replaced EQ with SGT.
958       if (!DecreasedRightValueByOne) {
959         IRBuilder<> B(Preheader->getTerminator());
960         RightValue = B.CreateAdd(RightValue, One);
961       }
962     } else {
963       if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
964         FailureReason = "Induction variable start not bounded by upper limit";
965         return None;
966       }
967       assert(!DecreasedRightValueByOne &&
968              "Right value can be decreased only for LatchBrExitIdx == 0!");
969     }
970   } else {
971     bool IncreasedRightValueByOne = false;
972     if (StepCI->isMinusOne()) {
973       // Try to turn eq/ne predicates to those we can work with.
974       if (Pred == ICmpInst::ICMP_NE && LatchBrExitIdx == 1)
975         // while (--i != len) {         while (--i > len) {
976         //   ...                 --->     ...
977         // }                            }
978         // We intentionally don't turn the predicate into UGT even if we know
979         // that both operands are non-negative, because it will only pessimize
980         // our check against "RightSCEV - 1".
981         Pred = ICmpInst::ICMP_SGT;
982       else if (Pred == ICmpInst::ICMP_EQ && LatchBrExitIdx == 0 &&
983                !CanBeMax(SE, RightSCEV, /* IsSignedPredicate */ true)) {
984         // while (true) {               while (true) {
985         //   if (--i == len)     --->     if (--i < len + 1)
986         //     break;                       break;
987         //   ...                          ...
988         // }                            }
989         // TODO: Insert ICMP_ULT if both are non-negative?
990         Pred = ICmpInst::ICMP_SLT;
991         RightSCEV = SE.getAddExpr(RightSCEV, SE.getOne(RightSCEV->getType()));
992         IncreasedRightValueByOne = true;
993       }
994     }
995 
996     bool LTPred = (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT);
997     bool GTPred = (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT);
998 
999     bool FoundExpectedPred =
1000         (GTPred && LatchBrExitIdx == 1) || (LTPred && LatchBrExitIdx == 0);
1001 
1002     if (!FoundExpectedPred) {
1003       FailureReason = "expected icmp sgt semantically, found something else";
1004       return None;
1005     }
1006 
1007     IsSignedPredicate =
1008         Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGT;
1009 
1010     if (!IsSignedPredicate && !AllowUnsignedLatchCondition) {
1011       FailureReason = "unsigned latch conditions are explicitly prohibited";
1012       return None;
1013     }
1014 
1015     // The predicate that we need to check that the induction variable lies
1016     // within bounds.
1017     ICmpInst::Predicate BoundPred =
1018         IsSignedPredicate ? CmpInst::ICMP_SGT : CmpInst::ICMP_UGT;
1019 
1020     if (LatchBrExitIdx == 0) {
1021       const SCEV *StepPlusOne = SE.getAddExpr(Step, SE.getOne(Step->getType()));
1022       if (SumCanReachMin(SE, RightSCEV, StepPlusOne, IsSignedPredicate)) {
1023         // TODO: this restriction is easily removable -- we just have to
1024         // remember that the icmp was an sgt and not an sge.
1025         FailureReason = "limit may overflow when coercing ge to gt";
1026         return None;
1027       }
1028 
1029       if (!SE.isLoopEntryGuardedByCond(
1030               &L, BoundPred, IndVarStart,
1031               SE.getMinusSCEV(RightSCEV, SE.getOne(RightSCEV->getType())))) {
1032         FailureReason = "Induction variable start not bounded by lower limit";
1033         return None;
1034       }
1035 
1036       // We need to decrease the right value unless we have already increased
1037       // it virtually when we replaced EQ with SLT.
1038       if (!IncreasedRightValueByOne) {
1039         IRBuilder<> B(Preheader->getTerminator());
1040         RightValue = B.CreateSub(RightValue, One);
1041       }
1042     } else {
1043       if (!SE.isLoopEntryGuardedByCond(&L, BoundPred, IndVarStart, RightSCEV)) {
1044         FailureReason = "Induction variable start not bounded by lower limit";
1045         return None;
1046       }
1047       assert(!IncreasedRightValueByOne &&
1048              "Right value can be increased only for LatchBrExitIdx == 0!");
1049     }
1050   }
1051   BasicBlock *LatchExit = LatchBr->getSuccessor(LatchBrExitIdx);
1052 
1053   assert(SE.getLoopDisposition(LatchCount, &L) ==
1054              ScalarEvolution::LoopInvariant &&
1055          "loop variant exit count doesn't make sense!");
1056 
1057   assert(!L.contains(LatchExit) && "expected an exit block!");
1058   const DataLayout &DL = Preheader->getModule()->getDataLayout();
1059   Value *IndVarStartV =
1060       SCEVExpander(SE, DL, "irce")
1061           .expandCodeFor(IndVarStart, IndVarTy, Preheader->getTerminator());
1062   IndVarStartV->setName("indvar.start");
1063 
1064   LoopStructure Result;
1065 
1066   Result.Tag = "main";
1067   Result.Header = Header;
1068   Result.Latch = Latch;
1069   Result.LatchBr = LatchBr;
1070   Result.LatchExit = LatchExit;
1071   Result.LatchBrExitIdx = LatchBrExitIdx;
1072   Result.IndVarStart = IndVarStartV;
1073   Result.IndVarStep = StepCI;
1074   Result.IndVarBase = LeftValue;
1075   Result.IndVarIncreasing = IsIncreasing;
1076   Result.LoopExitAt = RightValue;
1077   Result.IsSignedPredicate = IsSignedPredicate;
1078 
1079   FailureReason = nullptr;
1080 
1081   return Result;
1082 }
1083 
1084 Optional<LoopConstrainer::SubRanges>
1085 LoopConstrainer::calculateSubRanges(bool IsSignedPredicate) const {
1086   IntegerType *Ty = cast<IntegerType>(LatchTakenCount->getType());
1087 
1088   if (Range.getType() != Ty)
1089     return None;
1090 
1091   LoopConstrainer::SubRanges Result;
1092 
1093   // I think we can be more aggressive here and make this nuw / nsw if the
1094   // addition that feeds into the icmp for the latch's terminating branch is nuw
1095   // / nsw.  In any case, a wrapping 2's complement addition is safe.
1096   const SCEV *Start = SE.getSCEV(MainLoopStructure.IndVarStart);
1097   const SCEV *End = SE.getSCEV(MainLoopStructure.LoopExitAt);
1098 
1099   bool Increasing = MainLoopStructure.IndVarIncreasing;
1100 
1101   // We compute `Smallest` and `Greatest` such that [Smallest, Greatest), or
1102   // [Smallest, GreatestSeen] is the range of values the induction variable
1103   // takes.
1104 
1105   const SCEV *Smallest = nullptr, *Greatest = nullptr, *GreatestSeen = nullptr;
1106 
1107   const SCEV *One = SE.getOne(Ty);
1108   if (Increasing) {
1109     Smallest = Start;
1110     Greatest = End;
1111     // No overflow, because the range [Smallest, GreatestSeen] is not empty.
1112     GreatestSeen = SE.getMinusSCEV(End, One);
1113   } else {
1114     // These two computations may sign-overflow.  Here is why that is okay:
1115     //
1116     // We know that the induction variable does not sign-overflow on any
1117     // iteration except the last one, and it starts at `Start` and ends at
1118     // `End`, decrementing by one every time.
1119     //
1120     //  * if `Smallest` sign-overflows we know `End` is `INT_SMAX`. Since the
1121     //    induction variable is decreasing we know that that the smallest value
1122     //    the loop body is actually executed with is `INT_SMIN` == `Smallest`.
1123     //
1124     //  * if `Greatest` sign-overflows, we know it can only be `INT_SMIN`.  In
1125     //    that case, `Clamp` will always return `Smallest` and
1126     //    [`Result.LowLimit`, `Result.HighLimit`) = [`Smallest`, `Smallest`)
1127     //    will be an empty range.  Returning an empty range is always safe.
1128 
1129     Smallest = SE.getAddExpr(End, One);
1130     Greatest = SE.getAddExpr(Start, One);
1131     GreatestSeen = Start;
1132   }
1133 
1134   auto Clamp = [this, Smallest, Greatest, IsSignedPredicate](const SCEV *S) {
1135     bool MaybeNegativeValues = IsSignedPredicate || !SE.isKnownNonNegative(S);
1136     return MaybeNegativeValues
1137                ? SE.getSMaxExpr(Smallest, SE.getSMinExpr(Greatest, S))
1138                : SE.getUMaxExpr(Smallest, SE.getUMinExpr(Greatest, S));
1139   };
1140 
1141   // In some cases we can prove that we don't need a pre or post loop.
1142   ICmpInst::Predicate PredLE =
1143       IsSignedPredicate ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1144   ICmpInst::Predicate PredLT =
1145       IsSignedPredicate ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1146 
1147   bool ProvablyNoPreloop =
1148       SE.isKnownPredicate(PredLE, Range.getBegin(), Smallest);
1149   if (!ProvablyNoPreloop)
1150     Result.LowLimit = Clamp(Range.getBegin());
1151 
1152   bool ProvablyNoPostLoop =
1153       SE.isKnownPredicate(PredLT, GreatestSeen, Range.getEnd());
1154   if (!ProvablyNoPostLoop)
1155     Result.HighLimit = Clamp(Range.getEnd());
1156 
1157   return Result;
1158 }
1159 
1160 void LoopConstrainer::cloneLoop(LoopConstrainer::ClonedLoop &Result,
1161                                 const char *Tag) const {
1162   for (BasicBlock *BB : OriginalLoop.getBlocks()) {
1163     BasicBlock *Clone = CloneBasicBlock(BB, Result.Map, Twine(".") + Tag, &F);
1164     Result.Blocks.push_back(Clone);
1165     Result.Map[BB] = Clone;
1166   }
1167 
1168   auto GetClonedValue = [&Result](Value *V) {
1169     assert(V && "null values not in domain!");
1170     auto It = Result.Map.find(V);
1171     if (It == Result.Map.end())
1172       return V;
1173     return static_cast<Value *>(It->second);
1174   };
1175 
1176   auto *ClonedLatch =
1177       cast<BasicBlock>(GetClonedValue(OriginalLoop.getLoopLatch()));
1178   ClonedLatch->getTerminator()->setMetadata(ClonedLoopTag,
1179                                             MDNode::get(Ctx, {}));
1180 
1181   Result.Structure = MainLoopStructure.map(GetClonedValue);
1182   Result.Structure.Tag = Tag;
1183 
1184   for (unsigned i = 0, e = Result.Blocks.size(); i != e; ++i) {
1185     BasicBlock *ClonedBB = Result.Blocks[i];
1186     BasicBlock *OriginalBB = OriginalLoop.getBlocks()[i];
1187 
1188     assert(Result.Map[OriginalBB] == ClonedBB && "invariant!");
1189 
1190     for (Instruction &I : *ClonedBB)
1191       RemapInstruction(&I, Result.Map,
1192                        RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
1193 
1194     // Exit blocks will now have one more predecessor and their PHI nodes need
1195     // to be edited to reflect that.  No phi nodes need to be introduced because
1196     // the loop is in LCSSA.
1197 
1198     for (auto *SBB : successors(OriginalBB)) {
1199       if (OriginalLoop.contains(SBB))
1200         continue; // not an exit block
1201 
1202       for (Instruction &I : *SBB) {
1203         auto *PN = dyn_cast<PHINode>(&I);
1204         if (!PN)
1205           break;
1206 
1207         Value *OldIncoming = PN->getIncomingValueForBlock(OriginalBB);
1208         PN->addIncoming(GetClonedValue(OldIncoming), ClonedBB);
1209       }
1210     }
1211   }
1212 }
1213 
1214 LoopConstrainer::RewrittenRangeInfo LoopConstrainer::changeIterationSpaceEnd(
1215     const LoopStructure &LS, BasicBlock *Preheader, Value *ExitSubloopAt,
1216     BasicBlock *ContinuationBlock) const {
1217   // We start with a loop with a single latch:
1218   //
1219   //    +--------------------+
1220   //    |                    |
1221   //    |     preheader      |
1222   //    |                    |
1223   //    +--------+-----------+
1224   //             |      ----------------\
1225   //             |     /                |
1226   //    +--------v----v------+          |
1227   //    |                    |          |
1228   //    |      header        |          |
1229   //    |                    |          |
1230   //    +--------------------+          |
1231   //                                    |
1232   //            .....                   |
1233   //                                    |
1234   //    +--------------------+          |
1235   //    |                    |          |
1236   //    |       latch        >----------/
1237   //    |                    |
1238   //    +-------v------------+
1239   //            |
1240   //            |
1241   //            |   +--------------------+
1242   //            |   |                    |
1243   //            +--->   original exit    |
1244   //                |                    |
1245   //                +--------------------+
1246   //
1247   // We change the control flow to look like
1248   //
1249   //
1250   //    +--------------------+
1251   //    |                    |
1252   //    |     preheader      >-------------------------+
1253   //    |                    |                         |
1254   //    +--------v-----------+                         |
1255   //             |    /-------------+                  |
1256   //             |   /              |                  |
1257   //    +--------v--v--------+      |                  |
1258   //    |                    |      |                  |
1259   //    |      header        |      |   +--------+     |
1260   //    |                    |      |   |        |     |
1261   //    +--------------------+      |   |  +-----v-----v-----------+
1262   //                                |   |  |                       |
1263   //                                |   |  |     .pseudo.exit      |
1264   //                                |   |  |                       |
1265   //                                |   |  +-----------v-----------+
1266   //                                |   |              |
1267   //            .....               |   |              |
1268   //                                |   |     +--------v-------------+
1269   //    +--------------------+      |   |     |                      |
1270   //    |                    |      |   |     |   ContinuationBlock  |
1271   //    |       latch        >------+   |     |                      |
1272   //    |                    |          |     +----------------------+
1273   //    +---------v----------+          |
1274   //              |                     |
1275   //              |                     |
1276   //              |     +---------------^-----+
1277   //              |     |                     |
1278   //              +----->    .exit.selector   |
1279   //                    |                     |
1280   //                    +----------v----------+
1281   //                               |
1282   //     +--------------------+    |
1283   //     |                    |    |
1284   //     |   original exit    <----+
1285   //     |                    |
1286   //     +--------------------+
1287 
1288   RewrittenRangeInfo RRI;
1289 
1290   BasicBlock *BBInsertLocation = LS.Latch->getNextNode();
1291   RRI.ExitSelector = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".exit.selector",
1292                                         &F, BBInsertLocation);
1293   RRI.PseudoExit = BasicBlock::Create(Ctx, Twine(LS.Tag) + ".pseudo.exit", &F,
1294                                       BBInsertLocation);
1295 
1296   BranchInst *PreheaderJump = cast<BranchInst>(Preheader->getTerminator());
1297   bool Increasing = LS.IndVarIncreasing;
1298   bool IsSignedPredicate = LS.IsSignedPredicate;
1299 
1300   IRBuilder<> B(PreheaderJump);
1301 
1302   // EnterLoopCond - is it okay to start executing this `LS'?
1303   Value *EnterLoopCond = nullptr;
1304   if (Increasing)
1305     EnterLoopCond = IsSignedPredicate
1306                         ? B.CreateICmpSLT(LS.IndVarStart, ExitSubloopAt)
1307                         : B.CreateICmpULT(LS.IndVarStart, ExitSubloopAt);
1308   else
1309     EnterLoopCond = IsSignedPredicate
1310                         ? B.CreateICmpSGT(LS.IndVarStart, ExitSubloopAt)
1311                         : B.CreateICmpUGT(LS.IndVarStart, ExitSubloopAt);
1312 
1313   B.CreateCondBr(EnterLoopCond, LS.Header, RRI.PseudoExit);
1314   PreheaderJump->eraseFromParent();
1315 
1316   LS.LatchBr->setSuccessor(LS.LatchBrExitIdx, RRI.ExitSelector);
1317   B.SetInsertPoint(LS.LatchBr);
1318   Value *TakeBackedgeLoopCond = nullptr;
1319   if (Increasing)
1320     TakeBackedgeLoopCond = IsSignedPredicate
1321                         ? B.CreateICmpSLT(LS.IndVarBase, ExitSubloopAt)
1322                         : B.CreateICmpULT(LS.IndVarBase, ExitSubloopAt);
1323   else
1324     TakeBackedgeLoopCond = IsSignedPredicate
1325                         ? B.CreateICmpSGT(LS.IndVarBase, ExitSubloopAt)
1326                         : B.CreateICmpUGT(LS.IndVarBase, ExitSubloopAt);
1327   Value *CondForBranch = LS.LatchBrExitIdx == 1
1328                              ? TakeBackedgeLoopCond
1329                              : B.CreateNot(TakeBackedgeLoopCond);
1330 
1331   LS.LatchBr->setCondition(CondForBranch);
1332 
1333   B.SetInsertPoint(RRI.ExitSelector);
1334 
1335   // IterationsLeft - are there any more iterations left, given the original
1336   // upper bound on the induction variable?  If not, we branch to the "real"
1337   // exit.
1338   Value *IterationsLeft = nullptr;
1339   if (Increasing)
1340     IterationsLeft = IsSignedPredicate
1341                          ? B.CreateICmpSLT(LS.IndVarBase, LS.LoopExitAt)
1342                          : B.CreateICmpULT(LS.IndVarBase, LS.LoopExitAt);
1343   else
1344     IterationsLeft = IsSignedPredicate
1345                          ? B.CreateICmpSGT(LS.IndVarBase, LS.LoopExitAt)
1346                          : B.CreateICmpUGT(LS.IndVarBase, LS.LoopExitAt);
1347   B.CreateCondBr(IterationsLeft, RRI.PseudoExit, LS.LatchExit);
1348 
1349   BranchInst *BranchToContinuation =
1350       BranchInst::Create(ContinuationBlock, RRI.PseudoExit);
1351 
1352   // We emit PHI nodes into `RRI.PseudoExit' that compute the "latest" value of
1353   // each of the PHI nodes in the loop header.  This feeds into the initial
1354   // value of the same PHI nodes if/when we continue execution.
1355   for (Instruction &I : *LS.Header) {
1356     auto *PN = dyn_cast<PHINode>(&I);
1357     if (!PN)
1358       break;
1359 
1360     PHINode *NewPHI = PHINode::Create(PN->getType(), 2, PN->getName() + ".copy",
1361                                       BranchToContinuation);
1362 
1363     NewPHI->addIncoming(PN->getIncomingValueForBlock(Preheader), Preheader);
1364     NewPHI->addIncoming(PN->getIncomingValueForBlock(LS.Latch),
1365                         RRI.ExitSelector);
1366     RRI.PHIValuesAtPseudoExit.push_back(NewPHI);
1367   }
1368 
1369   RRI.IndVarEnd = PHINode::Create(LS.IndVarBase->getType(), 2, "indvar.end",
1370                                   BranchToContinuation);
1371   RRI.IndVarEnd->addIncoming(LS.IndVarStart, Preheader);
1372   RRI.IndVarEnd->addIncoming(LS.IndVarBase, RRI.ExitSelector);
1373 
1374   // The latch exit now has a branch from `RRI.ExitSelector' instead of
1375   // `LS.Latch'.  The PHI nodes need to be updated to reflect that.
1376   for (Instruction &I : *LS.LatchExit) {
1377     if (PHINode *PN = dyn_cast<PHINode>(&I))
1378       replacePHIBlock(PN, LS.Latch, RRI.ExitSelector);
1379     else
1380       break;
1381   }
1382 
1383   return RRI;
1384 }
1385 
1386 void LoopConstrainer::rewriteIncomingValuesForPHIs(
1387     LoopStructure &LS, BasicBlock *ContinuationBlock,
1388     const LoopConstrainer::RewrittenRangeInfo &RRI) const {
1389   unsigned PHIIndex = 0;
1390   for (Instruction &I : *LS.Header) {
1391     auto *PN = dyn_cast<PHINode>(&I);
1392     if (!PN)
1393       break;
1394 
1395     for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1396       if (PN->getIncomingBlock(i) == ContinuationBlock)
1397         PN->setIncomingValue(i, RRI.PHIValuesAtPseudoExit[PHIIndex++]);
1398   }
1399 
1400   LS.IndVarStart = RRI.IndVarEnd;
1401 }
1402 
1403 BasicBlock *LoopConstrainer::createPreheader(const LoopStructure &LS,
1404                                              BasicBlock *OldPreheader,
1405                                              const char *Tag) const {
1406   BasicBlock *Preheader = BasicBlock::Create(Ctx, Tag, &F, LS.Header);
1407   BranchInst::Create(LS.Header, Preheader);
1408 
1409   for (Instruction &I : *LS.Header) {
1410     auto *PN = dyn_cast<PHINode>(&I);
1411     if (!PN)
1412       break;
1413 
1414     for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i)
1415       replacePHIBlock(PN, OldPreheader, Preheader);
1416   }
1417 
1418   return Preheader;
1419 }
1420 
1421 void LoopConstrainer::addToParentLoopIfNeeded(ArrayRef<BasicBlock *> BBs) {
1422   Loop *ParentLoop = OriginalLoop.getParentLoop();
1423   if (!ParentLoop)
1424     return;
1425 
1426   for (BasicBlock *BB : BBs)
1427     ParentLoop->addBasicBlockToLoop(BB, LI);
1428 }
1429 
1430 Loop *LoopConstrainer::createClonedLoopStructure(Loop *Original, Loop *Parent,
1431                                                  ValueToValueMapTy &VM) {
1432   Loop &New = *LI.AllocateLoop();
1433   if (Parent)
1434     Parent->addChildLoop(&New);
1435   else
1436     LI.addTopLevelLoop(&New);
1437   LPM.addLoop(New);
1438 
1439   // Add all of the blocks in Original to the new loop.
1440   for (auto *BB : Original->blocks())
1441     if (LI.getLoopFor(BB) == Original)
1442       New.addBasicBlockToLoop(cast<BasicBlock>(VM[BB]), LI);
1443 
1444   // Add all of the subloops to the new loop.
1445   for (Loop *SubLoop : *Original)
1446     createClonedLoopStructure(SubLoop, &New, VM);
1447 
1448   return &New;
1449 }
1450 
1451 bool LoopConstrainer::run() {
1452   BasicBlock *Preheader = nullptr;
1453   LatchTakenCount = SE.getExitCount(&OriginalLoop, MainLoopStructure.Latch);
1454   Preheader = OriginalLoop.getLoopPreheader();
1455   assert(!isa<SCEVCouldNotCompute>(LatchTakenCount) && Preheader != nullptr &&
1456          "preconditions!");
1457 
1458   OriginalPreheader = Preheader;
1459   MainLoopPreheader = Preheader;
1460 
1461   bool IsSignedPredicate = MainLoopStructure.IsSignedPredicate;
1462   Optional<SubRanges> MaybeSR = calculateSubRanges(IsSignedPredicate);
1463   if (!MaybeSR.hasValue()) {
1464     DEBUG(dbgs() << "irce: could not compute subranges\n");
1465     return false;
1466   }
1467 
1468   SubRanges SR = MaybeSR.getValue();
1469   bool Increasing = MainLoopStructure.IndVarIncreasing;
1470   IntegerType *IVTy =
1471       cast<IntegerType>(MainLoopStructure.IndVarBase->getType());
1472 
1473   SCEVExpander Expander(SE, F.getParent()->getDataLayout(), "irce");
1474   Instruction *InsertPt = OriginalPreheader->getTerminator();
1475 
1476   // It would have been better to make `PreLoop' and `PostLoop'
1477   // `Optional<ClonedLoop>'s, but `ValueToValueMapTy' does not have a copy
1478   // constructor.
1479   ClonedLoop PreLoop, PostLoop;
1480   bool NeedsPreLoop =
1481       Increasing ? SR.LowLimit.hasValue() : SR.HighLimit.hasValue();
1482   bool NeedsPostLoop =
1483       Increasing ? SR.HighLimit.hasValue() : SR.LowLimit.hasValue();
1484 
1485   Value *ExitPreLoopAt = nullptr;
1486   Value *ExitMainLoopAt = nullptr;
1487   const SCEVConstant *MinusOneS =
1488       cast<SCEVConstant>(SE.getConstant(IVTy, -1, true /* isSigned */));
1489 
1490   if (NeedsPreLoop) {
1491     const SCEV *ExitPreLoopAtSCEV = nullptr;
1492 
1493     if (Increasing)
1494       ExitPreLoopAtSCEV = *SR.LowLimit;
1495     else {
1496       if (CanBeMin(SE, *SR.HighLimit, IsSignedPredicate)) {
1497         DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1498                      << "preloop exit limit.  HighLimit = " << *(*SR.HighLimit)
1499                      << "\n");
1500         return false;
1501       }
1502       ExitPreLoopAtSCEV = SE.getAddExpr(*SR.HighLimit, MinusOneS);
1503     }
1504 
1505     ExitPreLoopAt = Expander.expandCodeFor(ExitPreLoopAtSCEV, IVTy, InsertPt);
1506     ExitPreLoopAt->setName("exit.preloop.at");
1507   }
1508 
1509   if (NeedsPostLoop) {
1510     const SCEV *ExitMainLoopAtSCEV = nullptr;
1511 
1512     if (Increasing)
1513       ExitMainLoopAtSCEV = *SR.HighLimit;
1514     else {
1515       if (CanBeMin(SE, *SR.LowLimit, IsSignedPredicate)) {
1516         DEBUG(dbgs() << "irce: could not prove no-overflow when computing "
1517                      << "mainloop exit limit.  LowLimit = " << *(*SR.LowLimit)
1518                      << "\n");
1519         return false;
1520       }
1521       ExitMainLoopAtSCEV = SE.getAddExpr(*SR.LowLimit, MinusOneS);
1522     }
1523 
1524     ExitMainLoopAt = Expander.expandCodeFor(ExitMainLoopAtSCEV, IVTy, InsertPt);
1525     ExitMainLoopAt->setName("exit.mainloop.at");
1526   }
1527 
1528   // We clone these ahead of time so that we don't have to deal with changing
1529   // and temporarily invalid IR as we transform the loops.
1530   if (NeedsPreLoop)
1531     cloneLoop(PreLoop, "preloop");
1532   if (NeedsPostLoop)
1533     cloneLoop(PostLoop, "postloop");
1534 
1535   RewrittenRangeInfo PreLoopRRI;
1536 
1537   if (NeedsPreLoop) {
1538     Preheader->getTerminator()->replaceUsesOfWith(MainLoopStructure.Header,
1539                                                   PreLoop.Structure.Header);
1540 
1541     MainLoopPreheader =
1542         createPreheader(MainLoopStructure, Preheader, "mainloop");
1543     PreLoopRRI = changeIterationSpaceEnd(PreLoop.Structure, Preheader,
1544                                          ExitPreLoopAt, MainLoopPreheader);
1545     rewriteIncomingValuesForPHIs(MainLoopStructure, MainLoopPreheader,
1546                                  PreLoopRRI);
1547   }
1548 
1549   BasicBlock *PostLoopPreheader = nullptr;
1550   RewrittenRangeInfo PostLoopRRI;
1551 
1552   if (NeedsPostLoop) {
1553     PostLoopPreheader =
1554         createPreheader(PostLoop.Structure, Preheader, "postloop");
1555     PostLoopRRI = changeIterationSpaceEnd(MainLoopStructure, MainLoopPreheader,
1556                                           ExitMainLoopAt, PostLoopPreheader);
1557     rewriteIncomingValuesForPHIs(PostLoop.Structure, PostLoopPreheader,
1558                                  PostLoopRRI);
1559   }
1560 
1561   BasicBlock *NewMainLoopPreheader =
1562       MainLoopPreheader != Preheader ? MainLoopPreheader : nullptr;
1563   BasicBlock *NewBlocks[] = {PostLoopPreheader,        PreLoopRRI.PseudoExit,
1564                              PreLoopRRI.ExitSelector,  PostLoopRRI.PseudoExit,
1565                              PostLoopRRI.ExitSelector, NewMainLoopPreheader};
1566 
1567   // Some of the above may be nullptr, filter them out before passing to
1568   // addToParentLoopIfNeeded.
1569   auto NewBlocksEnd =
1570       std::remove(std::begin(NewBlocks), std::end(NewBlocks), nullptr);
1571 
1572   addToParentLoopIfNeeded(makeArrayRef(std::begin(NewBlocks), NewBlocksEnd));
1573 
1574   DT.recalculate(F);
1575 
1576   // We need to first add all the pre and post loop blocks into the loop
1577   // structures (as part of createClonedLoopStructure), and then update the
1578   // LCSSA form and LoopSimplifyForm. This is necessary for correctly updating
1579   // LI when LoopSimplifyForm is generated.
1580   Loop *PreL = nullptr, *PostL = nullptr;
1581   if (!PreLoop.Blocks.empty()) {
1582     PreL = createClonedLoopStructure(
1583         &OriginalLoop, OriginalLoop.getParentLoop(), PreLoop.Map);
1584   }
1585 
1586   if (!PostLoop.Blocks.empty()) {
1587     PostL = createClonedLoopStructure(
1588         &OriginalLoop, OriginalLoop.getParentLoop(), PostLoop.Map);
1589   }
1590 
1591   // This function canonicalizes the loop into Loop-Simplify and LCSSA forms.
1592   auto CanonicalizeLoop = [&] (Loop *L, bool IsOriginalLoop) {
1593     formLCSSARecursively(*L, DT, &LI, &SE);
1594     simplifyLoop(L, &DT, &LI, &SE, nullptr, true);
1595     // Pre/post loops are slow paths, we do not need to perform any loop
1596     // optimizations on them.
1597     if (!IsOriginalLoop)
1598       DisableAllLoopOptsOnLoop(*L);
1599   };
1600   if (PreL)
1601     CanonicalizeLoop(PreL, false);
1602   if (PostL)
1603     CanonicalizeLoop(PostL, false);
1604   CanonicalizeLoop(&OriginalLoop, true);
1605 
1606   return true;
1607 }
1608 
1609 /// Computes and returns a range of values for the induction variable (IndVar)
1610 /// in which the range check can be safely elided.  If it cannot compute such a
1611 /// range, returns None.
1612 Optional<InductiveRangeCheck::Range>
1613 InductiveRangeCheck::computeSafeIterationSpace(
1614     ScalarEvolution &SE, const SCEVAddRecExpr *IndVar) const {
1615   // IndVar is of the form "A + B * I" (where "I" is the canonical induction
1616   // variable, that may or may not exist as a real llvm::Value in the loop) and
1617   // this inductive range check is a range check on the "C + D * I" ("C" is
1618   // getOffset() and "D" is getScale()).  We rewrite the value being range
1619   // checked to "M + N * IndVar" where "N" = "D * B^(-1)" and "M" = "C - NA".
1620   //
1621   // The actual inequalities we solve are of the form
1622   //
1623   //   0 <= M + 1 * IndVar < L given L >= 0  (i.e. N == 1)
1624   //
1625   // The inequality is satisfied by -M <= IndVar < (L - M) [^1].  All additions
1626   // and subtractions are twos-complement wrapping and comparisons are signed.
1627   //
1628   // Proof:
1629   //
1630   //   If there exists IndVar such that -M <= IndVar < (L - M) then it follows
1631   //   that -M <= (-M + L) [== Eq. 1].  Since L >= 0, if (-M + L) sign-overflows
1632   //   then (-M + L) < (-M).  Hence by [Eq. 1], (-M + L) could not have
1633   //   overflown.
1634   //
1635   //   This means IndVar = t + (-M) for t in [0, L).  Hence (IndVar + M) = t.
1636   //   Hence 0 <= (IndVar + M) < L
1637 
1638   // [^1]: Note that the solution does _not_ apply if L < 0; consider values M =
1639   // 127, IndVar = 126 and L = -2 in an i8 world.
1640 
1641   if (!IndVar->isAffine())
1642     return None;
1643 
1644   const SCEV *A = IndVar->getStart();
1645   const SCEVConstant *B = dyn_cast<SCEVConstant>(IndVar->getStepRecurrence(SE));
1646   if (!B)
1647     return None;
1648   assert(!B->isZero() && "Recurrence with zero step?");
1649 
1650   const SCEV *C = getOffset();
1651   const SCEVConstant *D = dyn_cast<SCEVConstant>(getScale());
1652   if (D != B)
1653     return None;
1654 
1655   assert(!D->getValue()->isZero() && "Recurrence with zero step?");
1656 
1657   const SCEV *M = SE.getMinusSCEV(C, A);
1658   const SCEV *Begin = SE.getNegativeSCEV(M);
1659   const SCEV *UpperLimit = nullptr;
1660 
1661   // We strengthen "0 <= I" to "0 <= I < INT_SMAX" and "I < L" to "0 <= I < L".
1662   // We can potentially do much better here.
1663   if (Value *V = getLength()) {
1664     UpperLimit = SE.getSCEV(V);
1665   } else {
1666     assert(Kind == InductiveRangeCheck::RANGE_CHECK_LOWER && "invariant!");
1667     unsigned BitWidth = cast<IntegerType>(IndVar->getType())->getBitWidth();
1668     UpperLimit = SE.getConstant(APInt::getSignedMaxValue(BitWidth));
1669   }
1670 
1671   const SCEV *End = SE.getMinusSCEV(UpperLimit, M);
1672   return InductiveRangeCheck::Range(Begin, End);
1673 }
1674 
1675 static Optional<InductiveRangeCheck::Range>
1676 IntersectSignedRange(ScalarEvolution &SE,
1677                      const Optional<InductiveRangeCheck::Range> &R1,
1678                      const InductiveRangeCheck::Range &R2) {
1679   if (R2.isEmpty(SE, /* IsSigned */ true))
1680     return None;
1681   if (!R1.hasValue())
1682     return R2;
1683   auto &R1Value = R1.getValue();
1684   // We never return empty ranges from this function, and R1 is supposed to be
1685   // a result of intersection. Thus, R1 is never empty.
1686   assert(!R1Value.isEmpty(SE, /* IsSigned */ true) &&
1687          "We should never have empty R1!");
1688 
1689   // TODO: we could widen the smaller range and have this work; but for now we
1690   // bail out to keep things simple.
1691   if (R1Value.getType() != R2.getType())
1692     return None;
1693 
1694   const SCEV *NewBegin = SE.getSMaxExpr(R1Value.getBegin(), R2.getBegin());
1695   const SCEV *NewEnd = SE.getSMinExpr(R1Value.getEnd(), R2.getEnd());
1696 
1697   // If the resulting range is empty, just return None.
1698   auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1699   if (Ret.isEmpty(SE, /* IsSigned */ true))
1700     return None;
1701   return Ret;
1702 }
1703 
1704 static Optional<InductiveRangeCheck::Range>
1705 IntersectUnsignedRange(ScalarEvolution &SE,
1706                        const Optional<InductiveRangeCheck::Range> &R1,
1707                        const InductiveRangeCheck::Range &R2) {
1708   if (R2.isEmpty(SE, /* IsSigned */ false))
1709     return None;
1710   if (!R1.hasValue())
1711     return R2;
1712   auto &R1Value = R1.getValue();
1713   // We never return empty ranges from this function, and R1 is supposed to be
1714   // a result of intersection. Thus, R1 is never empty.
1715   assert(!R1Value.isEmpty(SE, /* IsSigned */ false) &&
1716          "We should never have empty R1!");
1717 
1718   // TODO: we could widen the smaller range and have this work; but for now we
1719   // bail out to keep things simple.
1720   if (R1Value.getType() != R2.getType())
1721     return None;
1722 
1723   const SCEV *NewBegin = SE.getUMaxExpr(R1Value.getBegin(), R2.getBegin());
1724   const SCEV *NewEnd = SE.getUMinExpr(R1Value.getEnd(), R2.getEnd());
1725 
1726   // If the resulting range is empty, just return None.
1727   auto Ret = InductiveRangeCheck::Range(NewBegin, NewEnd);
1728   if (Ret.isEmpty(SE, /* IsSigned */ false))
1729     return None;
1730   return Ret;
1731 }
1732 
1733 bool InductiveRangeCheckElimination::runOnLoop(Loop *L, LPPassManager &LPM) {
1734   if (skipLoop(L))
1735     return false;
1736 
1737   if (L->getBlocks().size() >= LoopSizeCutoff) {
1738     DEBUG(dbgs() << "irce: giving up constraining loop, too large\n";);
1739     return false;
1740   }
1741 
1742   BasicBlock *Preheader = L->getLoopPreheader();
1743   if (!Preheader) {
1744     DEBUG(dbgs() << "irce: loop has no preheader, leaving\n");
1745     return false;
1746   }
1747 
1748   LLVMContext &Context = Preheader->getContext();
1749   SmallVector<InductiveRangeCheck, 16> RangeChecks;
1750   ScalarEvolution &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
1751   BranchProbabilityInfo &BPI =
1752       getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
1753 
1754   for (auto BBI : L->getBlocks())
1755     if (BranchInst *TBI = dyn_cast<BranchInst>(BBI->getTerminator()))
1756       InductiveRangeCheck::extractRangeChecksFromBranch(TBI, L, SE, BPI,
1757                                                         RangeChecks);
1758 
1759   if (RangeChecks.empty())
1760     return false;
1761 
1762   auto PrintRecognizedRangeChecks = [&](raw_ostream &OS) {
1763     OS << "irce: looking at loop "; L->print(OS);
1764     OS << "irce: loop has " << RangeChecks.size()
1765        << " inductive range checks: \n";
1766     for (InductiveRangeCheck &IRC : RangeChecks)
1767       IRC.print(OS);
1768   };
1769 
1770   DEBUG(PrintRecognizedRangeChecks(dbgs()));
1771 
1772   if (PrintRangeChecks)
1773     PrintRecognizedRangeChecks(errs());
1774 
1775   const char *FailureReason = nullptr;
1776   Optional<LoopStructure> MaybeLoopStructure =
1777       LoopStructure::parseLoopStructure(SE, BPI, *L, FailureReason);
1778   if (!MaybeLoopStructure.hasValue()) {
1779     DEBUG(dbgs() << "irce: could not parse loop structure: " << FailureReason
1780                  << "\n";);
1781     return false;
1782   }
1783   LoopStructure LS = MaybeLoopStructure.getValue();
1784   const SCEVAddRecExpr *IndVar =
1785       cast<SCEVAddRecExpr>(SE.getMinusSCEV(SE.getSCEV(LS.IndVarBase), SE.getSCEV(LS.IndVarStep)));
1786 
1787   Optional<InductiveRangeCheck::Range> SafeIterRange;
1788   Instruction *ExprInsertPt = Preheader->getTerminator();
1789 
1790   SmallVector<InductiveRangeCheck, 4> RangeChecksToEliminate;
1791   auto RangeIsNonNegative = [&](InductiveRangeCheck::Range &R) {
1792     return SE.isKnownNonNegative(R.getBegin()) &&
1793            SE.isKnownNonNegative(R.getEnd());
1794   };
1795   // Basing on the type of latch predicate, we interpret the IV iteration range
1796   // as signed or unsigned range. We use different min/max functions (signed or
1797   // unsigned) when intersecting this range with safe iteration ranges implied
1798   // by range checks.
1799   auto IntersectRange =
1800       LS.IsSignedPredicate ? IntersectSignedRange : IntersectUnsignedRange;
1801 
1802   IRBuilder<> B(ExprInsertPt);
1803   for (InductiveRangeCheck &IRC : RangeChecks) {
1804     auto Result = IRC.computeSafeIterationSpace(SE, IndVar);
1805     if (Result.hasValue()) {
1806       // Intersecting a signed and an unsigned ranges may produce incorrect
1807       // results because we can use neither signed nor unsigned min/max for
1808       // reliably correct intersection if a range contains negative values
1809       // which are either actually negative or big positive. Intersection is
1810       // safe in two following cases:
1811       // 1. Both ranges are signed/unsigned, then we use signed/unsigned min/max
1812       //    respectively for their intersection;
1813       // 2. IRC safe iteration space only contains values from [0, SINT_MAX].
1814       //    The interpretation of these values is unambiguous.
1815       // We take the type of IV iteration range as a reference (we will
1816       // intersect it with the resulting range of all IRC's later in
1817       // calculateSubRanges). Only ranges of IRC of the same type are considered
1818       // for removal unless we prove that its range doesn't contain ambiguous
1819       // values.
1820       if (IRC.isSigned() != LS.IsSignedPredicate &&
1821           !RangeIsNonNegative(Result.getValue()))
1822         continue;
1823       auto MaybeSafeIterRange =
1824           IntersectRange(SE, SafeIterRange, Result.getValue());
1825       if (MaybeSafeIterRange.hasValue()) {
1826         assert(
1827             !MaybeSafeIterRange.getValue().isEmpty(SE, LS.IsSignedPredicate) &&
1828             "We should never return empty ranges!");
1829         RangeChecksToEliminate.push_back(IRC);
1830         SafeIterRange = MaybeSafeIterRange.getValue();
1831       }
1832     }
1833   }
1834 
1835   if (!SafeIterRange.hasValue())
1836     return false;
1837 
1838   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1839   LoopConstrainer LC(*L, getAnalysis<LoopInfoWrapperPass>().getLoopInfo(), LPM,
1840                      LS, SE, DT, SafeIterRange.getValue());
1841   bool Changed = LC.run();
1842 
1843   if (Changed) {
1844     auto PrintConstrainedLoopInfo = [L]() {
1845       dbgs() << "irce: in function ";
1846       dbgs() << L->getHeader()->getParent()->getName() << ": ";
1847       dbgs() << "constrained ";
1848       L->print(dbgs());
1849     };
1850 
1851     DEBUG(PrintConstrainedLoopInfo());
1852 
1853     if (PrintChangedLoops)
1854       PrintConstrainedLoopInfo();
1855 
1856     // Optimize away the now-redundant range checks.
1857 
1858     for (InductiveRangeCheck &IRC : RangeChecksToEliminate) {
1859       ConstantInt *FoldedRangeCheck = IRC.getPassingDirection()
1860                                           ? ConstantInt::getTrue(Context)
1861                                           : ConstantInt::getFalse(Context);
1862       IRC.getCheckUse()->set(FoldedRangeCheck);
1863     }
1864   }
1865 
1866   return Changed;
1867 }
1868 
1869 Pass *llvm::createInductiveRangeCheckEliminationPass() {
1870   return new InductiveRangeCheckElimination;
1871 }
1872