xref: /llvm-project/llvm/lib/Transforms/Scalar/LoopPredication.cpp (revision 452714f8f8037ff37f9358317651d1652e231db2)
1 //===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
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 LoopPredication pass tries to convert loop variant range checks to loop
10 // invariant by widening checks across loop iterations. For example, it will
11 // convert
12 //
13 //   for (i = 0; i < n; i++) {
14 //     guard(i < len);
15 //     ...
16 //   }
17 //
18 // to
19 //
20 //   for (i = 0; i < n; i++) {
21 //     guard(n - 1 < len);
22 //     ...
23 //   }
24 //
25 // After this transformation the condition of the guard is loop invariant, so
26 // loop-unswitch can later unswitch the loop by this condition which basically
27 // predicates the loop by the widened condition:
28 //
29 //   if (n - 1 < len)
30 //     for (i = 0; i < n; i++) {
31 //       ...
32 //     }
33 //   else
34 //     deoptimize
35 //
36 // It's tempting to rely on SCEV here, but it has proven to be problematic.
37 // Generally the facts SCEV provides about the increment step of add
38 // recurrences are true if the backedge of the loop is taken, which implicitly
39 // assumes that the guard doesn't fail. Using these facts to optimize the
40 // guard results in a circular logic where the guard is optimized under the
41 // assumption that it never fails.
42 //
43 // For example, in the loop below the induction variable will be marked as nuw
44 // basing on the guard. Basing on nuw the guard predicate will be considered
45 // monotonic. Given a monotonic condition it's tempting to replace the induction
46 // variable in the condition with its value on the last iteration. But this
47 // transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
48 //
49 //   for (int i = b; i != e; i++)
50 //     guard(i u< len)
51 //
52 // One of the ways to reason about this problem is to use an inductive proof
53 // approach. Given the loop:
54 //
55 //   if (B(0)) {
56 //     do {
57 //       I = PHI(0, I.INC)
58 //       I.INC = I + Step
59 //       guard(G(I));
60 //     } while (B(I));
61 //   }
62 //
63 // where B(x) and G(x) are predicates that map integers to booleans, we want a
64 // loop invariant expression M such the following program has the same semantics
65 // as the above:
66 //
67 //   if (B(0)) {
68 //     do {
69 //       I = PHI(0, I.INC)
70 //       I.INC = I + Step
71 //       guard(G(0) && M);
72 //     } while (B(I));
73 //   }
74 //
75 // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
76 //
77 // Informal proof that the transformation above is correct:
78 //
79 //   By the definition of guards we can rewrite the guard condition to:
80 //     G(I) && G(0) && M
81 //
82 //   Let's prove that for each iteration of the loop:
83 //     G(0) && M => G(I)
84 //   And the condition above can be simplified to G(Start) && M.
85 //
86 //   Induction base.
87 //     G(0) && M => G(0)
88 //
89 //   Induction step. Assuming G(0) && M => G(I) on the subsequent
90 //   iteration:
91 //
92 //     B(I) is true because it's the backedge condition.
93 //     G(I) is true because the backedge is guarded by this condition.
94 //
95 //   So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
96 //
97 // Note that we can use anything stronger than M, i.e. any condition which
98 // implies M.
99 //
100 // When S = 1 (i.e. forward iterating loop), the transformation is supported
101 // when:
102 //   * The loop has a single latch with the condition of the form:
103 //     B(X) = latchStart + X <pred> latchLimit,
104 //     where <pred> is u<, u<=, s<, or s<=.
105 //   * The guard condition is of the form
106 //     G(X) = guardStart + X u< guardLimit
107 //
108 //   For the ult latch comparison case M is:
109 //     forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
110 //        guardStart + X + 1 u< guardLimit
111 //
112 //   The only way the antecedent can be true and the consequent can be false is
113 //   if
114 //     X == guardLimit - 1 - guardStart
115 //   (and guardLimit is non-zero, but we won't use this latter fact).
116 //   If X == guardLimit - 1 - guardStart then the second half of the antecedent is
117 //     latchStart + guardLimit - 1 - guardStart u< latchLimit
118 //   and its negation is
119 //     latchStart + guardLimit - 1 - guardStart u>= latchLimit
120 //
121 //   In other words, if
122 //     latchLimit u<= latchStart + guardLimit - 1 - guardStart
123 //   then:
124 //   (the ranges below are written in ConstantRange notation, where [A, B) is the
125 //   set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
126 //
127 //      forall X . guardStart + X u< guardLimit &&
128 //                 latchStart + X u< latchLimit =>
129 //        guardStart + X + 1 u< guardLimit
130 //   == forall X . guardStart + X u< guardLimit &&
131 //                 latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
132 //        guardStart + X + 1 u< guardLimit
133 //   == forall X . (guardStart + X) in [0, guardLimit) &&
134 //                 (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
135 //        (guardStart + X + 1) in [0, guardLimit)
136 //   == forall X . X in [-guardStart, guardLimit - guardStart) &&
137 //                 X in [-latchStart, guardLimit - 1 - guardStart) =>
138 //         X in [-guardStart - 1, guardLimit - guardStart - 1)
139 //   == true
140 //
141 //   So the widened condition is:
142 //     guardStart u< guardLimit &&
143 //     latchStart + guardLimit - 1 - guardStart u>= latchLimit
144 //   Similarly for ule condition the widened condition is:
145 //     guardStart u< guardLimit &&
146 //     latchStart + guardLimit - 1 - guardStart u> latchLimit
147 //   For slt condition the widened condition is:
148 //     guardStart u< guardLimit &&
149 //     latchStart + guardLimit - 1 - guardStart s>= latchLimit
150 //   For sle condition the widened condition is:
151 //     guardStart u< guardLimit &&
152 //     latchStart + guardLimit - 1 - guardStart s> latchLimit
153 //
154 // When S = -1 (i.e. reverse iterating loop), the transformation is supported
155 // when:
156 //   * The loop has a single latch with the condition of the form:
157 //     B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=.
158 //   * The guard condition is of the form
159 //     G(X) = X - 1 u< guardLimit
160 //
161 //   For the ugt latch comparison case M is:
162 //     forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit
163 //
164 //   The only way the antecedent can be true and the consequent can be false is if
165 //     X == 1.
166 //   If X == 1 then the second half of the antecedent is
167 //     1 u> latchLimit, and its negation is latchLimit u>= 1.
168 //
169 //   So the widened condition is:
170 //     guardStart u< guardLimit && latchLimit u>= 1.
171 //   Similarly for sgt condition the widened condition is:
172 //     guardStart u< guardLimit && latchLimit s>= 1.
173 //   For uge condition the widened condition is:
174 //     guardStart u< guardLimit && latchLimit u> 1.
175 //   For sge condition the widened condition is:
176 //     guardStart u< guardLimit && latchLimit s> 1.
177 //===----------------------------------------------------------------------===//
178 
179 #include "llvm/Transforms/Scalar/LoopPredication.h"
180 #include "llvm/ADT/Statistic.h"
181 #include "llvm/Analysis/AliasAnalysis.h"
182 #include "llvm/Analysis/BranchProbabilityInfo.h"
183 #include "llvm/Analysis/GuardUtils.h"
184 #include "llvm/Analysis/LoopInfo.h"
185 #include "llvm/Analysis/LoopPass.h"
186 #include "llvm/Analysis/MemorySSA.h"
187 #include "llvm/Analysis/MemorySSAUpdater.h"
188 #include "llvm/Analysis/ScalarEvolution.h"
189 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
190 #include "llvm/IR/Function.h"
191 #include "llvm/IR/GlobalValue.h"
192 #include "llvm/IR/IntrinsicInst.h"
193 #include "llvm/IR/Module.h"
194 #include "llvm/IR/PatternMatch.h"
195 #include "llvm/InitializePasses.h"
196 #include "llvm/Pass.h"
197 #include "llvm/Support/CommandLine.h"
198 #include "llvm/Support/Debug.h"
199 #include "llvm/Transforms/Scalar.h"
200 #include "llvm/Transforms/Utils/GuardUtils.h"
201 #include "llvm/Transforms/Utils/Local.h"
202 #include "llvm/Transforms/Utils/LoopUtils.h"
203 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
204 
205 #define DEBUG_TYPE "loop-predication"
206 
207 STATISTIC(TotalConsidered, "Number of guards considered");
208 STATISTIC(TotalWidened, "Number of checks widened");
209 
210 using namespace llvm;
211 
212 static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
213                                         cl::Hidden, cl::init(true));
214 
215 static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
216                                         cl::Hidden, cl::init(true));
217 
218 static cl::opt<bool>
219     SkipProfitabilityChecks("loop-predication-skip-profitability-checks",
220                             cl::Hidden, cl::init(false));
221 
222 // This is the scale factor for the latch probability. We use this during
223 // profitability analysis to find other exiting blocks that have a much higher
224 // probability of exiting the loop instead of loop exiting via latch.
225 // This value should be greater than 1 for a sane profitability check.
226 static cl::opt<float> LatchExitProbabilityScale(
227     "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0),
228     cl::desc("scale factor for the latch probability. Value should be greater "
229              "than 1. Lower values are ignored"));
230 
231 static cl::opt<bool> PredicateWidenableBranchGuards(
232     "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden,
233     cl::desc("Whether or not we should predicate guards "
234              "expressed as widenable branches to deoptimize blocks"),
235     cl::init(true));
236 
237 namespace {
238 /// Represents an induction variable check:
239 ///   icmp Pred, <induction variable>, <loop invariant limit>
240 struct LoopICmp {
241   ICmpInst::Predicate Pred;
242   const SCEVAddRecExpr *IV;
243   const SCEV *Limit;
244   LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
245            const SCEV *Limit)
246     : Pred(Pred), IV(IV), Limit(Limit) {}
247   LoopICmp() {}
248   void dump() {
249     dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
250            << ", Limit = " << *Limit << "\n";
251   }
252 };
253 
254 class LoopPredication {
255   AliasAnalysis *AA;
256   DominatorTree *DT;
257   ScalarEvolution *SE;
258   LoopInfo *LI;
259   BranchProbabilityInfo *BPI;
260   MemorySSAUpdater *MSSAU;
261 
262   Loop *L;
263   const DataLayout *DL;
264   BasicBlock *Preheader;
265   LoopICmp LatchCheck;
266 
267   bool isSupportedStep(const SCEV* Step);
268   Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI);
269   Optional<LoopICmp> parseLoopLatchICmp();
270 
271   /// Return an insertion point suitable for inserting a safe to speculate
272   /// instruction whose only user will be 'User' which has operands 'Ops'.  A
273   /// trivial result would be the at the User itself, but we try to return a
274   /// loop invariant location if possible.
275   Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops);
276   /// Same as above, *except* that this uses the SCEV definition of invariant
277   /// which is that an expression *can be made* invariant via SCEVExpander.
278   /// Thus, this version is only suitable for finding an insert point to be be
279   /// passed to SCEVExpander!
280   Instruction *findInsertPt(Instruction *User, ArrayRef<const SCEV*> Ops);
281 
282   /// Return true if the value is known to produce a single fixed value across
283   /// all iterations on which it executes.  Note that this does not imply
284   /// speculation safety.  That must be established separately.
285   bool isLoopInvariantValue(const SCEV* S);
286 
287   Value *expandCheck(SCEVExpander &Expander, Instruction *Guard,
288                      ICmpInst::Predicate Pred, const SCEV *LHS,
289                      const SCEV *RHS);
290 
291   Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
292                                         Instruction *Guard);
293   Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
294                                                         LoopICmp RangeCheck,
295                                                         SCEVExpander &Expander,
296                                                         Instruction *Guard);
297   Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
298                                                         LoopICmp RangeCheck,
299                                                         SCEVExpander &Expander,
300                                                         Instruction *Guard);
301   unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition,
302                          SCEVExpander &Expander, Instruction *Guard);
303   bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
304   bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander);
305   // If the loop always exits through another block in the loop, we should not
306   // predicate based on the latch check. For example, the latch check can be a
307   // very coarse grained check and there can be more fine grained exit checks
308   // within the loop. We identify such unprofitable loops through BPI.
309   bool isLoopProfitableToPredicate();
310 
311   bool predicateLoopExits(Loop *L, SCEVExpander &Rewriter);
312 
313 public:
314   LoopPredication(AliasAnalysis *AA, DominatorTree *DT, ScalarEvolution *SE,
315                   LoopInfo *LI, BranchProbabilityInfo *BPI,
316                   MemorySSAUpdater *MSSAU)
317       : AA(AA), DT(DT), SE(SE), LI(LI), BPI(BPI), MSSAU(MSSAU){};
318   bool runOnLoop(Loop *L);
319 };
320 
321 class LoopPredicationLegacyPass : public LoopPass {
322 public:
323   static char ID;
324   LoopPredicationLegacyPass() : LoopPass(ID) {
325     initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
326   }
327 
328   void getAnalysisUsage(AnalysisUsage &AU) const override {
329     AU.addRequired<BranchProbabilityInfoWrapperPass>();
330     getLoopAnalysisUsage(AU);
331     AU.addPreserved<MemorySSAWrapperPass>();
332   }
333 
334   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
335     if (skipLoop(L))
336       return false;
337     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
338     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
339     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
340     auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>();
341     std::unique_ptr<MemorySSAUpdater> MSSAU;
342     if (MSSAWP)
343       MSSAU = std::make_unique<MemorySSAUpdater>(&MSSAWP->getMSSA());
344     BranchProbabilityInfo &BPI =
345         getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
346     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
347     LoopPredication LP(AA, DT, SE, LI, &BPI, MSSAU ? MSSAU.get() : nullptr);
348     return LP.runOnLoop(L);
349   }
350 };
351 
352 char LoopPredicationLegacyPass::ID = 0;
353 } // end namespace
354 
355 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
356                       "Loop predication", false, false)
357 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
358 INITIALIZE_PASS_DEPENDENCY(LoopPass)
359 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
360                     "Loop predication", false, false)
361 
362 Pass *llvm::createLoopPredicationPass() {
363   return new LoopPredicationLegacyPass();
364 }
365 
366 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
367                                            LoopStandardAnalysisResults &AR,
368                                            LPMUpdater &U) {
369   Function *F = L.getHeader()->getParent();
370   std::unique_ptr<MemorySSAUpdater> MSSAU;
371   if (AR.MSSA)
372     MSSAU = std::make_unique<MemorySSAUpdater>(AR.MSSA);
373   LoopPredication LP(&AR.AA, &AR.DT, &AR.SE, &AR.LI, AR.BPI,
374                      MSSAU ? MSSAU.get() : nullptr);
375   if (!LP.runOnLoop(&L))
376     return PreservedAnalyses::all();
377 
378   auto PA = getLoopPassPreservedAnalyses();
379   if (AR.MSSA)
380     PA.preserve<MemorySSAAnalysis>();
381   return PA;
382 }
383 
384 Optional<LoopICmp>
385 LoopPredication::parseLoopICmp(ICmpInst *ICI) {
386   auto Pred = ICI->getPredicate();
387   auto *LHS = ICI->getOperand(0);
388   auto *RHS = ICI->getOperand(1);
389 
390   const SCEV *LHSS = SE->getSCEV(LHS);
391   if (isa<SCEVCouldNotCompute>(LHSS))
392     return None;
393   const SCEV *RHSS = SE->getSCEV(RHS);
394   if (isa<SCEVCouldNotCompute>(RHSS))
395     return None;
396 
397   // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
398   if (SE->isLoopInvariant(LHSS, L)) {
399     std::swap(LHS, RHS);
400     std::swap(LHSS, RHSS);
401     Pred = ICmpInst::getSwappedPredicate(Pred);
402   }
403 
404   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
405   if (!AR || AR->getLoop() != L)
406     return None;
407 
408   return LoopICmp(Pred, AR, RHSS);
409 }
410 
411 Value *LoopPredication::expandCheck(SCEVExpander &Expander,
412                                     Instruction *Guard,
413                                     ICmpInst::Predicate Pred, const SCEV *LHS,
414                                     const SCEV *RHS) {
415   Type *Ty = LHS->getType();
416   assert(Ty == RHS->getType() && "expandCheck operands have different types?");
417 
418   if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) {
419     IRBuilder<> Builder(Guard);
420     if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
421       return Builder.getTrue();
422     if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred),
423                                      LHS, RHS))
424       return Builder.getFalse();
425   }
426 
427   Value *LHSV = Expander.expandCodeFor(LHS, Ty, findInsertPt(Guard, {LHS}));
428   Value *RHSV = Expander.expandCodeFor(RHS, Ty, findInsertPt(Guard, {RHS}));
429   IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV}));
430   return Builder.CreateICmp(Pred, LHSV, RHSV);
431 }
432 
433 
434 // Returns true if its safe to truncate the IV to RangeCheckType.
435 // When the IV type is wider than the range operand type, we can still do loop
436 // predication, by generating SCEVs for the range and latch that are of the
437 // same type. We achieve this by generating a SCEV truncate expression for the
438 // latch IV. This is done iff truncation of the IV is a safe operation,
439 // without loss of information.
440 // Another way to achieve this is by generating a wider type SCEV for the
441 // range check operand, however, this needs a more involved check that
442 // operands do not overflow. This can lead to loss of information when the
443 // range operand is of the form: add i32 %offset, %iv. We need to prove that
444 // sext(x + y) is same as sext(x) + sext(y).
445 // This function returns true if we can safely represent the IV type in
446 // the RangeCheckType without loss of information.
447 static bool isSafeToTruncateWideIVType(const DataLayout &DL,
448                                        ScalarEvolution &SE,
449                                        const LoopICmp LatchCheck,
450                                        Type *RangeCheckType) {
451   if (!EnableIVTruncation)
452     return false;
453   assert(DL.getTypeSizeInBits(LatchCheck.IV->getType()).getFixedSize() >
454              DL.getTypeSizeInBits(RangeCheckType).getFixedSize() &&
455          "Expected latch check IV type to be larger than range check operand "
456          "type!");
457   // The start and end values of the IV should be known. This is to guarantee
458   // that truncating the wide type will not lose information.
459   auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
460   auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
461   if (!Limit || !Start)
462     return false;
463   // This check makes sure that the IV does not change sign during loop
464   // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
465   // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
466   // IV wraps around, and the truncation of the IV would lose the range of
467   // iterations between 2^32 and 2^64.
468   if (!SE.getMonotonicPredicateType(LatchCheck.IV, LatchCheck.Pred))
469     return false;
470   // The active bits should be less than the bits in the RangeCheckType. This
471   // guarantees that truncating the latch check to RangeCheckType is a safe
472   // operation.
473   auto RangeCheckTypeBitSize =
474       DL.getTypeSizeInBits(RangeCheckType).getFixedSize();
475   return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
476          Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
477 }
478 
479 
480 // Return an LoopICmp describing a latch check equivlent to LatchCheck but with
481 // the requested type if safe to do so.  May involve the use of a new IV.
482 static Optional<LoopICmp> generateLoopLatchCheck(const DataLayout &DL,
483                                                  ScalarEvolution &SE,
484                                                  const LoopICmp LatchCheck,
485                                                  Type *RangeCheckType) {
486 
487   auto *LatchType = LatchCheck.IV->getType();
488   if (RangeCheckType == LatchType)
489     return LatchCheck;
490   // For now, bail out if latch type is narrower than range type.
491   if (DL.getTypeSizeInBits(LatchType).getFixedSize() <
492       DL.getTypeSizeInBits(RangeCheckType).getFixedSize())
493     return None;
494   if (!isSafeToTruncateWideIVType(DL, SE, LatchCheck, RangeCheckType))
495     return None;
496   // We can now safely identify the truncated version of the IV and limit for
497   // RangeCheckType.
498   LoopICmp NewLatchCheck;
499   NewLatchCheck.Pred = LatchCheck.Pred;
500   NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
501       SE.getTruncateExpr(LatchCheck.IV, RangeCheckType));
502   if (!NewLatchCheck.IV)
503     return None;
504   NewLatchCheck.Limit = SE.getTruncateExpr(LatchCheck.Limit, RangeCheckType);
505   LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType
506                     << "can be represented as range check type:"
507                     << *RangeCheckType << "\n");
508   LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
509   LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
510   return NewLatchCheck;
511 }
512 
513 bool LoopPredication::isSupportedStep(const SCEV* Step) {
514   return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
515 }
516 
517 Instruction *LoopPredication::findInsertPt(Instruction *Use,
518                                            ArrayRef<Value*> Ops) {
519   for (Value *Op : Ops)
520     if (!L->isLoopInvariant(Op))
521       return Use;
522   return Preheader->getTerminator();
523 }
524 
525 Instruction *LoopPredication::findInsertPt(Instruction *Use,
526                                            ArrayRef<const SCEV*> Ops) {
527   // Subtlety: SCEV considers things to be invariant if the value produced is
528   // the same across iterations.  This is not the same as being able to
529   // evaluate outside the loop, which is what we actually need here.
530   for (const SCEV *Op : Ops)
531     if (!SE->isLoopInvariant(Op, L) ||
532         !isSafeToExpandAt(Op, Preheader->getTerminator(), *SE))
533       return Use;
534   return Preheader->getTerminator();
535 }
536 
537 bool LoopPredication::isLoopInvariantValue(const SCEV* S) {
538   // Handling expressions which produce invariant results, but *haven't* yet
539   // been removed from the loop serves two important purposes.
540   // 1) Most importantly, it resolves a pass ordering cycle which would
541   // otherwise need us to iteration licm, loop-predication, and either
542   // loop-unswitch or loop-peeling to make progress on examples with lots of
543   // predicable range checks in a row.  (Since, in the general case,  we can't
544   // hoist the length checks until the dominating checks have been discharged
545   // as we can't prove doing so is safe.)
546   // 2) As a nice side effect, this exposes the value of peeling or unswitching
547   // much more obviously in the IR.  Otherwise, the cost modeling for other
548   // transforms would end up needing to duplicate all of this logic to model a
549   // check which becomes predictable based on a modeled peel or unswitch.
550   //
551   // The cost of doing so in the worst case is an extra fill from the stack  in
552   // the loop to materialize the loop invariant test value instead of checking
553   // against the original IV which is presumable in a register inside the loop.
554   // Such cases are presumably rare, and hint at missing oppurtunities for
555   // other passes.
556 
557   if (SE->isLoopInvariant(S, L))
558     // Note: This the SCEV variant, so the original Value* may be within the
559     // loop even though SCEV has proven it is loop invariant.
560     return true;
561 
562   // Handle a particular important case which SCEV doesn't yet know about which
563   // shows up in range checks on arrays with immutable lengths.
564   // TODO: This should be sunk inside SCEV.
565   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
566     if (const auto *LI = dyn_cast<LoadInst>(U->getValue()))
567       if (LI->isUnordered() && L->hasLoopInvariantOperands(LI))
568         if (AA->pointsToConstantMemory(LI->getOperand(0)) ||
569             LI->hasMetadata(LLVMContext::MD_invariant_load))
570           return true;
571   return false;
572 }
573 
574 Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
575     LoopICmp LatchCheck, LoopICmp RangeCheck,
576     SCEVExpander &Expander, Instruction *Guard) {
577   auto *Ty = RangeCheck.IV->getType();
578   // Generate the widened condition for the forward loop:
579   //   guardStart u< guardLimit &&
580   //   latchLimit <pred> guardLimit - 1 - guardStart + latchStart
581   // where <pred> depends on the latch condition predicate. See the file
582   // header comment for the reasoning.
583   // guardLimit - guardStart + latchStart - 1
584   const SCEV *GuardStart = RangeCheck.IV->getStart();
585   const SCEV *GuardLimit = RangeCheck.Limit;
586   const SCEV *LatchStart = LatchCheck.IV->getStart();
587   const SCEV *LatchLimit = LatchCheck.Limit;
588   // Subtlety: We need all the values to be *invariant* across all iterations,
589   // but we only need to check expansion safety for those which *aren't*
590   // already guaranteed to dominate the guard.
591   if (!isLoopInvariantValue(GuardStart) ||
592       !isLoopInvariantValue(GuardLimit) ||
593       !isLoopInvariantValue(LatchStart) ||
594       !isLoopInvariantValue(LatchLimit)) {
595     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
596     return None;
597   }
598   if (!isSafeToExpandAt(LatchStart, Guard, *SE) ||
599       !isSafeToExpandAt(LatchLimit, Guard, *SE)) {
600     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
601     return None;
602   }
603 
604   // guardLimit - guardStart + latchStart - 1
605   const SCEV *RHS =
606       SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
607                      SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
608   auto LimitCheckPred =
609       ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
610 
611   LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
612   LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n");
613   LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
614 
615   auto *LimitCheck =
616       expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS);
617   auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred,
618                                           GuardStart, GuardLimit);
619   IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
620   return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
621 }
622 
623 Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
624     LoopICmp LatchCheck, LoopICmp RangeCheck,
625     SCEVExpander &Expander, Instruction *Guard) {
626   auto *Ty = RangeCheck.IV->getType();
627   const SCEV *GuardStart = RangeCheck.IV->getStart();
628   const SCEV *GuardLimit = RangeCheck.Limit;
629   const SCEV *LatchStart = LatchCheck.IV->getStart();
630   const SCEV *LatchLimit = LatchCheck.Limit;
631   // Subtlety: We need all the values to be *invariant* across all iterations,
632   // but we only need to check expansion safety for those which *aren't*
633   // already guaranteed to dominate the guard.
634   if (!isLoopInvariantValue(GuardStart) ||
635       !isLoopInvariantValue(GuardLimit) ||
636       !isLoopInvariantValue(LatchStart) ||
637       !isLoopInvariantValue(LatchLimit)) {
638     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
639     return None;
640   }
641   if (!isSafeToExpandAt(LatchStart, Guard, *SE) ||
642       !isSafeToExpandAt(LatchLimit, Guard, *SE)) {
643     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
644     return None;
645   }
646   // The decrement of the latch check IV should be the same as the
647   // rangeCheckIV.
648   auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
649   if (RangeCheck.IV != PostDecLatchCheckIV) {
650     LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
651                       << *PostDecLatchCheckIV
652                       << "  and RangeCheckIV: " << *RangeCheck.IV << "\n");
653     return None;
654   }
655 
656   // Generate the widened condition for CountDownLoop:
657   // guardStart u< guardLimit &&
658   // latchLimit <pred> 1.
659   // See the header comment for reasoning of the checks.
660   auto LimitCheckPred =
661       ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
662   auto *FirstIterationCheck = expandCheck(Expander, Guard,
663                                           ICmpInst::ICMP_ULT,
664                                           GuardStart, GuardLimit);
665   auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit,
666                                  SE->getOne(Ty));
667   IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
668   return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
669 }
670 
671 static void normalizePredicate(ScalarEvolution *SE, Loop *L,
672                                LoopICmp& RC) {
673   // LFTR canonicalizes checks to the ICMP_NE/EQ form; normalize back to the
674   // ULT/UGE form for ease of handling by our caller.
675   if (ICmpInst::isEquality(RC.Pred) &&
676       RC.IV->getStepRecurrence(*SE)->isOne() &&
677       SE->isKnownPredicate(ICmpInst::ICMP_ULE, RC.IV->getStart(), RC.Limit))
678     RC.Pred = RC.Pred == ICmpInst::ICMP_NE ?
679       ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
680 }
681 
682 
683 /// If ICI can be widened to a loop invariant condition emits the loop
684 /// invariant condition in the loop preheader and return it, otherwise
685 /// returns None.
686 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
687                                                        SCEVExpander &Expander,
688                                                        Instruction *Guard) {
689   LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
690   LLVM_DEBUG(ICI->dump());
691 
692   // parseLoopStructure guarantees that the latch condition is:
693   //   ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
694   // We are looking for the range checks of the form:
695   //   i u< guardLimit
696   auto RangeCheck = parseLoopICmp(ICI);
697   if (!RangeCheck) {
698     LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
699     return None;
700   }
701   LLVM_DEBUG(dbgs() << "Guard check:\n");
702   LLVM_DEBUG(RangeCheck->dump());
703   if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
704     LLVM_DEBUG(dbgs() << "Unsupported range check predicate("
705                       << RangeCheck->Pred << ")!\n");
706     return None;
707   }
708   auto *RangeCheckIV = RangeCheck->IV;
709   if (!RangeCheckIV->isAffine()) {
710     LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n");
711     return None;
712   }
713   auto *Step = RangeCheckIV->getStepRecurrence(*SE);
714   // We cannot just compare with latch IV step because the latch and range IVs
715   // may have different types.
716   if (!isSupportedStep(Step)) {
717     LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
718     return None;
719   }
720   auto *Ty = RangeCheckIV->getType();
721   auto CurrLatchCheckOpt = generateLoopLatchCheck(*DL, *SE, LatchCheck, Ty);
722   if (!CurrLatchCheckOpt) {
723     LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check "
724                          "corresponding to range type: "
725                       << *Ty << "\n");
726     return None;
727   }
728 
729   LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
730   // At this point, the range and latch step should have the same type, but need
731   // not have the same value (we support both 1 and -1 steps).
732   assert(Step->getType() ==
733              CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
734          "Range and latch steps should be of same type!");
735   if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
736     LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n");
737     return None;
738   }
739 
740   if (Step->isOne())
741     return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
742                                                Expander, Guard);
743   else {
744     assert(Step->isAllOnesValue() && "Step should be -1!");
745     return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
746                                                Expander, Guard);
747   }
748 }
749 
750 unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks,
751                                         Value *Condition,
752                                         SCEVExpander &Expander,
753                                         Instruction *Guard) {
754   unsigned NumWidened = 0;
755   // The guard condition is expected to be in form of:
756   //   cond1 && cond2 && cond3 ...
757   // Iterate over subconditions looking for icmp conditions which can be
758   // widened across loop iterations. Widening these conditions remember the
759   // resulting list of subconditions in Checks vector.
760   SmallVector<Value *, 4> Worklist(1, Condition);
761   SmallPtrSet<Value *, 4> Visited;
762   Value *WideableCond = nullptr;
763   do {
764     Value *Condition = Worklist.pop_back_val();
765     if (!Visited.insert(Condition).second)
766       continue;
767 
768     Value *LHS, *RHS;
769     using namespace llvm::PatternMatch;
770     if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
771       Worklist.push_back(LHS);
772       Worklist.push_back(RHS);
773       continue;
774     }
775 
776     if (match(Condition,
777               m_Intrinsic<Intrinsic::experimental_widenable_condition>())) {
778       // Pick any, we don't care which
779       WideableCond = Condition;
780       continue;
781     }
782 
783     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
784       if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander,
785                                                    Guard)) {
786         Checks.push_back(NewRangeCheck.getValue());
787         NumWidened++;
788         continue;
789       }
790     }
791 
792     // Save the condition as is if we can't widen it
793     Checks.push_back(Condition);
794   } while (!Worklist.empty());
795   // At the moment, our matching logic for wideable conditions implicitly
796   // assumes we preserve the form: (br (and Cond, WC())).  FIXME
797   // Note that if there were multiple calls to wideable condition in the
798   // traversal, we only need to keep one, and which one is arbitrary.
799   if (WideableCond)
800     Checks.push_back(WideableCond);
801   return NumWidened;
802 }
803 
804 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
805                                            SCEVExpander &Expander) {
806   LLVM_DEBUG(dbgs() << "Processing guard:\n");
807   LLVM_DEBUG(Guard->dump());
808 
809   TotalConsidered++;
810   SmallVector<Value *, 4> Checks;
811   unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander,
812                                       Guard);
813   if (NumWidened == 0)
814     return false;
815 
816   TotalWidened += NumWidened;
817 
818   // Emit the new guard condition
819   IRBuilder<> Builder(findInsertPt(Guard, Checks));
820   Value *AllChecks = Builder.CreateAnd(Checks);
821   auto *OldCond = Guard->getOperand(0);
822   Guard->setOperand(0, AllChecks);
823   RecursivelyDeleteTriviallyDeadInstructions(OldCond, nullptr /* TLI */, MSSAU);
824 
825   LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
826   return true;
827 }
828 
829 bool LoopPredication::widenWidenableBranchGuardConditions(
830     BranchInst *BI, SCEVExpander &Expander) {
831   assert(isGuardAsWidenableBranch(BI) && "Must be!");
832   LLVM_DEBUG(dbgs() << "Processing guard:\n");
833   LLVM_DEBUG(BI->dump());
834 
835   TotalConsidered++;
836   SmallVector<Value *, 4> Checks;
837   unsigned NumWidened = collectChecks(Checks, BI->getCondition(),
838                                       Expander, BI);
839   if (NumWidened == 0)
840     return false;
841 
842   TotalWidened += NumWidened;
843 
844   // Emit the new guard condition
845   IRBuilder<> Builder(findInsertPt(BI, Checks));
846   Value *AllChecks = Builder.CreateAnd(Checks);
847   auto *OldCond = BI->getCondition();
848   BI->setCondition(AllChecks);
849   RecursivelyDeleteTriviallyDeadInstructions(OldCond, nullptr /* TLI */, MSSAU);
850   assert(isGuardAsWidenableBranch(BI) &&
851          "Stopped being a guard after transform?");
852 
853   LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
854   return true;
855 }
856 
857 Optional<LoopICmp> LoopPredication::parseLoopLatchICmp() {
858   using namespace PatternMatch;
859 
860   BasicBlock *LoopLatch = L->getLoopLatch();
861   if (!LoopLatch) {
862     LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
863     return None;
864   }
865 
866   auto *BI = dyn_cast<BranchInst>(LoopLatch->getTerminator());
867   if (!BI || !BI->isConditional()) {
868     LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n");
869     return None;
870   }
871   BasicBlock *TrueDest = BI->getSuccessor(0);
872   assert(
873       (TrueDest == L->getHeader() || BI->getSuccessor(1) == L->getHeader()) &&
874       "One of the latch's destinations must be the header");
875 
876   auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
877   if (!ICI) {
878     LLVM_DEBUG(dbgs() << "Failed to match the latch condition!\n");
879     return None;
880   }
881   auto Result = parseLoopICmp(ICI);
882   if (!Result) {
883     LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
884     return None;
885   }
886 
887   if (TrueDest != L->getHeader())
888     Result->Pred = ICmpInst::getInversePredicate(Result->Pred);
889 
890   // Check affine first, so if it's not we don't try to compute the step
891   // recurrence.
892   if (!Result->IV->isAffine()) {
893     LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n");
894     return None;
895   }
896 
897   auto *Step = Result->IV->getStepRecurrence(*SE);
898   if (!isSupportedStep(Step)) {
899     LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
900     return None;
901   }
902 
903   auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
904     if (Step->isOne()) {
905       return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
906              Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
907     } else {
908       assert(Step->isAllOnesValue() && "Step should be -1!");
909       return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT &&
910              Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE;
911     }
912   };
913 
914   normalizePredicate(SE, L, *Result);
915   if (IsUnsupportedPredicate(Step, Result->Pred)) {
916     LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
917                       << ")!\n");
918     return None;
919   }
920 
921   return Result;
922 }
923 
924 
925 bool LoopPredication::isLoopProfitableToPredicate() {
926   if (SkipProfitabilityChecks || !BPI)
927     return true;
928 
929   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 8> ExitEdges;
930   L->getExitEdges(ExitEdges);
931   // If there is only one exiting edge in the loop, it is always profitable to
932   // predicate the loop.
933   if (ExitEdges.size() == 1)
934     return true;
935 
936   // Calculate the exiting probabilities of all exiting edges from the loop,
937   // starting with the LatchExitProbability.
938   // Heuristic for profitability: If any of the exiting blocks' probability of
939   // exiting the loop is larger than exiting through the latch block, it's not
940   // profitable to predicate the loop.
941   auto *LatchBlock = L->getLoopLatch();
942   assert(LatchBlock && "Should have a single latch at this point!");
943   auto *LatchTerm = LatchBlock->getTerminator();
944   assert(LatchTerm->getNumSuccessors() == 2 &&
945          "expected to be an exiting block with 2 succs!");
946   unsigned LatchBrExitIdx =
947       LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0;
948   BranchProbability LatchExitProbability =
949       BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx);
950 
951   // Protect against degenerate inputs provided by the user. Providing a value
952   // less than one, can invert the definition of profitable loop predication.
953   float ScaleFactor = LatchExitProbabilityScale;
954   if (ScaleFactor < 1) {
955     LLVM_DEBUG(
956         dbgs()
957         << "Ignored user setting for loop-predication-latch-probability-scale: "
958         << LatchExitProbabilityScale << "\n");
959     LLVM_DEBUG(dbgs() << "The value is set to 1.0\n");
960     ScaleFactor = 1.0;
961   }
962   const auto LatchProbabilityThreshold =
963       LatchExitProbability * ScaleFactor;
964 
965   for (const auto &ExitEdge : ExitEdges) {
966     BranchProbability ExitingBlockProbability =
967         BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second);
968     // Some exiting edge has higher probability than the latch exiting edge.
969     // No longer profitable to predicate.
970     if (ExitingBlockProbability > LatchProbabilityThreshold)
971       return false;
972   }
973   // Using BPI, we have concluded that the most probable way to exit from the
974   // loop is through the latch (or there's no profile information and all
975   // exits are equally likely).
976   return true;
977 }
978 
979 /// If we can (cheaply) find a widenable branch which controls entry into the
980 /// loop, return it.
981 static BranchInst *FindWidenableTerminatorAboveLoop(Loop *L, LoopInfo &LI) {
982   // Walk back through any unconditional executed blocks and see if we can find
983   // a widenable condition which seems to control execution of this loop.  Note
984   // that we predict that maythrow calls are likely untaken and thus that it's
985   // profitable to widen a branch before a maythrow call with a condition
986   // afterwards even though that may cause the slow path to run in a case where
987   // it wouldn't have otherwise.
988   BasicBlock *BB = L->getLoopPreheader();
989   if (!BB)
990     return nullptr;
991   do {
992     if (BasicBlock *Pred = BB->getSinglePredecessor())
993       if (BB == Pred->getSingleSuccessor()) {
994         BB = Pred;
995         continue;
996       }
997     break;
998   } while (true);
999 
1000   if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1001     auto *Term = Pred->getTerminator();
1002 
1003     Value *Cond, *WC;
1004     BasicBlock *IfTrueBB, *IfFalseBB;
1005     if (parseWidenableBranch(Term, Cond, WC, IfTrueBB, IfFalseBB) &&
1006         IfTrueBB == BB)
1007       return cast<BranchInst>(Term);
1008   }
1009   return nullptr;
1010 }
1011 
1012 /// Return the minimum of all analyzeable exit counts.  This is an upper bound
1013 /// on the actual exit count.  If there are not at least two analyzeable exits,
1014 /// returns SCEVCouldNotCompute.
1015 static const SCEV *getMinAnalyzeableBackedgeTakenCount(ScalarEvolution &SE,
1016                                                        DominatorTree &DT,
1017                                                        Loop *L) {
1018   SmallVector<BasicBlock *, 16> ExitingBlocks;
1019   L->getExitingBlocks(ExitingBlocks);
1020 
1021   SmallVector<const SCEV *, 4> ExitCounts;
1022   for (BasicBlock *ExitingBB : ExitingBlocks) {
1023     const SCEV *ExitCount = SE.getExitCount(L, ExitingBB);
1024     if (isa<SCEVCouldNotCompute>(ExitCount))
1025       continue;
1026     assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
1027            "We should only have known counts for exiting blocks that "
1028            "dominate latch!");
1029     ExitCounts.push_back(ExitCount);
1030   }
1031   if (ExitCounts.size() < 2)
1032     return SE.getCouldNotCompute();
1033   return SE.getUMinFromMismatchedTypes(ExitCounts);
1034 }
1035 
1036 /// This implements an analogous, but entirely distinct transform from the main
1037 /// loop predication transform.  This one is phrased in terms of using a
1038 /// widenable branch *outside* the loop to allow us to simplify loop exits in a
1039 /// following loop.  This is close in spirit to the IndVarSimplify transform
1040 /// of the same name, but is materially different widening loosens legality
1041 /// sharply.
1042 bool LoopPredication::predicateLoopExits(Loop *L, SCEVExpander &Rewriter) {
1043   // The transformation performed here aims to widen a widenable condition
1044   // above the loop such that all analyzeable exit leading to deopt are dead.
1045   // It assumes that the latch is the dominant exit for profitability and that
1046   // exits branching to deoptimizing blocks are rarely taken. It relies on the
1047   // semantics of widenable expressions for legality. (i.e. being able to fall
1048   // down the widenable path spuriously allows us to ignore exit order,
1049   // unanalyzeable exits, side effects, exceptional exits, and other challenges
1050   // which restrict the applicability of the non-WC based version of this
1051   // transform in IndVarSimplify.)
1052   //
1053   // NOTE ON POISON/UNDEF - We're hoisting an expression above guards which may
1054   // imply flags on the expression being hoisted and inserting new uses (flags
1055   // are only correct for current uses).  The result is that we may be
1056   // inserting a branch on the value which can be either poison or undef.  In
1057   // this case, the branch can legally go either way; we just need to avoid
1058   // introducing UB.  This is achieved through the use of the freeze
1059   // instruction.
1060 
1061   SmallVector<BasicBlock *, 16> ExitingBlocks;
1062   L->getExitingBlocks(ExitingBlocks);
1063 
1064   if (ExitingBlocks.empty())
1065     return false; // Nothing to do.
1066 
1067   auto *Latch = L->getLoopLatch();
1068   if (!Latch)
1069     return false;
1070 
1071   auto *WidenableBR = FindWidenableTerminatorAboveLoop(L, *LI);
1072   if (!WidenableBR)
1073     return false;
1074 
1075   const SCEV *LatchEC = SE->getExitCount(L, Latch);
1076   if (isa<SCEVCouldNotCompute>(LatchEC))
1077     return false; // profitability - want hot exit in analyzeable set
1078 
1079   // At this point, we have found an analyzeable latch, and a widenable
1080   // condition above the loop.  If we have a widenable exit within the loop
1081   // (for which we can't compute exit counts), drop the ability to further
1082   // widen so that we gain ability to analyze it's exit count and perform this
1083   // transform.  TODO: It'd be nice to know for sure the exit became
1084   // analyzeable after dropping widenability.
1085   bool ChangedLoop = false;
1086 
1087   for (auto *ExitingBB : ExitingBlocks) {
1088     if (LI->getLoopFor(ExitingBB) != L)
1089       continue;
1090 
1091     auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
1092     if (!BI)
1093       continue;
1094 
1095     Use *Cond, *WC;
1096     BasicBlock *IfTrueBB, *IfFalseBB;
1097     if (parseWidenableBranch(BI, Cond, WC, IfTrueBB, IfFalseBB) &&
1098         L->contains(IfTrueBB)) {
1099       WC->set(ConstantInt::getTrue(IfTrueBB->getContext()));
1100       ChangedLoop = true;
1101     }
1102   }
1103   if (ChangedLoop)
1104     SE->forgetLoop(L);
1105 
1106   // The use of umin(all analyzeable exits) instead of latch is subtle, but
1107   // important for profitability.  We may have a loop which hasn't been fully
1108   // canonicalized just yet.  If the exit we chose to widen is provably never
1109   // taken, we want the widened form to *also* be provably never taken.  We
1110   // can't guarantee this as a current unanalyzeable exit may later become
1111   // analyzeable, but we can at least avoid the obvious cases.
1112   const SCEV *MinEC = getMinAnalyzeableBackedgeTakenCount(*SE, *DT, L);
1113   if (isa<SCEVCouldNotCompute>(MinEC) || MinEC->getType()->isPointerTy() ||
1114       !SE->isLoopInvariant(MinEC, L) ||
1115       !isSafeToExpandAt(MinEC, WidenableBR, *SE))
1116     return ChangedLoop;
1117 
1118   // Subtlety: We need to avoid inserting additional uses of the WC.  We know
1119   // that it can only have one transitive use at the moment, and thus moving
1120   // that use to just before the branch and inserting code before it and then
1121   // modifying the operand is legal.
1122   auto *IP = cast<Instruction>(WidenableBR->getCondition());
1123   // Here we unconditionally modify the IR, so after this point we should return
1124   // only `true`!
1125   IP->moveBefore(WidenableBR);
1126   if (MSSAU)
1127     if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(IP))
1128        MSSAU->moveToPlace(MUD, WidenableBR->getParent(),
1129                           MemorySSA::BeforeTerminator);
1130   Rewriter.setInsertPoint(IP);
1131   IRBuilder<> B(IP);
1132 
1133   bool InvalidateLoop = false;
1134   Value *MinECV = nullptr; // lazily generated if needed
1135   for (BasicBlock *ExitingBB : ExitingBlocks) {
1136     // If our exiting block exits multiple loops, we can only rewrite the
1137     // innermost one.  Otherwise, we're changing how many times the innermost
1138     // loop runs before it exits.
1139     if (LI->getLoopFor(ExitingBB) != L)
1140       continue;
1141 
1142     // Can't rewrite non-branch yet.
1143     auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
1144     if (!BI)
1145       continue;
1146 
1147     // If already constant, nothing to do.
1148     if (isa<Constant>(BI->getCondition()))
1149       continue;
1150 
1151     const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
1152     if (isa<SCEVCouldNotCompute>(ExitCount) ||
1153         ExitCount->getType()->isPointerTy() ||
1154         !isSafeToExpandAt(ExitCount, WidenableBR, *SE))
1155       continue;
1156 
1157     const bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));
1158     BasicBlock *ExitBB = BI->getSuccessor(ExitIfTrue ? 0 : 1);
1159     if (!ExitBB->getPostdominatingDeoptimizeCall())
1160       continue;
1161 
1162     /// Here we can be fairly sure that executing this exit will most likely
1163     /// lead to executing llvm.experimental.deoptimize.
1164     /// This is a profitability heuristic, not a legality constraint.
1165 
1166     // If we found a widenable exit condition, do two things:
1167     // 1) fold the widened exit test into the widenable condition
1168     // 2) fold the branch to untaken - avoids infinite looping
1169 
1170     Value *ECV = Rewriter.expandCodeFor(ExitCount);
1171     if (!MinECV)
1172       MinECV = Rewriter.expandCodeFor(MinEC);
1173     Value *RHS = MinECV;
1174     if (ECV->getType() != RHS->getType()) {
1175       Type *WiderTy = SE->getWiderType(ECV->getType(), RHS->getType());
1176       ECV = B.CreateZExt(ECV, WiderTy);
1177       RHS = B.CreateZExt(RHS, WiderTy);
1178     }
1179     assert(!Latch || DT->dominates(ExitingBB, Latch));
1180     Value *NewCond = B.CreateICmp(ICmpInst::ICMP_UGT, ECV, RHS);
1181     // Freeze poison or undef to an arbitrary bit pattern to ensure we can
1182     // branch without introducing UB.  See NOTE ON POISON/UNDEF above for
1183     // context.
1184     NewCond = B.CreateFreeze(NewCond);
1185 
1186     widenWidenableBranch(WidenableBR, NewCond);
1187 
1188     Value *OldCond = BI->getCondition();
1189     BI->setCondition(ConstantInt::get(OldCond->getType(), !ExitIfTrue));
1190     InvalidateLoop = true;
1191   }
1192 
1193   if (InvalidateLoop)
1194     // We just mutated a bunch of loop exits changing there exit counts
1195     // widely.  We need to force recomputation of the exit counts given these
1196     // changes.  Note that all of the inserted exits are never taken, and
1197     // should be removed next time the CFG is modified.
1198     SE->forgetLoop(L);
1199 
1200   // Always return `true` since we have moved the WidenableBR's condition.
1201   return true;
1202 }
1203 
1204 bool LoopPredication::runOnLoop(Loop *Loop) {
1205   L = Loop;
1206 
1207   LLVM_DEBUG(dbgs() << "Analyzing ");
1208   LLVM_DEBUG(L->dump());
1209 
1210   Module *M = L->getHeader()->getModule();
1211 
1212   // There is nothing to do if the module doesn't use guards
1213   auto *GuardDecl =
1214       M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
1215   bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty();
1216   auto *WCDecl = M->getFunction(
1217       Intrinsic::getName(Intrinsic::experimental_widenable_condition));
1218   bool HasWidenableConditions =
1219       PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty();
1220   if (!HasIntrinsicGuards && !HasWidenableConditions)
1221     return false;
1222 
1223   DL = &M->getDataLayout();
1224 
1225   Preheader = L->getLoopPreheader();
1226   if (!Preheader)
1227     return false;
1228 
1229   auto LatchCheckOpt = parseLoopLatchICmp();
1230   if (!LatchCheckOpt)
1231     return false;
1232   LatchCheck = *LatchCheckOpt;
1233 
1234   LLVM_DEBUG(dbgs() << "Latch check:\n");
1235   LLVM_DEBUG(LatchCheck.dump());
1236 
1237   if (!isLoopProfitableToPredicate()) {
1238     LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n");
1239     return false;
1240   }
1241   // Collect all the guards into a vector and process later, so as not
1242   // to invalidate the instruction iterator.
1243   SmallVector<IntrinsicInst *, 4> Guards;
1244   SmallVector<BranchInst *, 4> GuardsAsWidenableBranches;
1245   for (const auto BB : L->blocks()) {
1246     for (auto &I : *BB)
1247       if (isGuard(&I))
1248         Guards.push_back(cast<IntrinsicInst>(&I));
1249     if (PredicateWidenableBranchGuards &&
1250         isGuardAsWidenableBranch(BB->getTerminator()))
1251       GuardsAsWidenableBranches.push_back(
1252           cast<BranchInst>(BB->getTerminator()));
1253   }
1254 
1255   SCEVExpander Expander(*SE, *DL, "loop-predication");
1256   bool Changed = false;
1257   for (auto *Guard : Guards)
1258     Changed |= widenGuardConditions(Guard, Expander);
1259   for (auto *Guard : GuardsAsWidenableBranches)
1260     Changed |= widenWidenableBranchGuardConditions(Guard, Expander);
1261   Changed |= predicateLoopExits(L, Expander);
1262 
1263   if (MSSAU && VerifyMemorySSA)
1264     MSSAU->getMemorySSA()->verifyMemorySSA();
1265   return Changed;
1266 }
1267