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