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