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