18fb3d57eSArtur Pilipenko //===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
28fb3d57eSArtur Pilipenko //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
68fb3d57eSArtur Pilipenko //
78fb3d57eSArtur Pilipenko //===----------------------------------------------------------------------===//
88fb3d57eSArtur Pilipenko //
98fb3d57eSArtur Pilipenko // The LoopPredication pass tries to convert loop variant range checks to loop
108fb3d57eSArtur Pilipenko // invariant by widening checks across loop iterations. For example, it will
118fb3d57eSArtur Pilipenko // convert
128fb3d57eSArtur Pilipenko //
138fb3d57eSArtur Pilipenko //   for (i = 0; i < n; i++) {
148fb3d57eSArtur Pilipenko //     guard(i < len);
158fb3d57eSArtur Pilipenko //     ...
168fb3d57eSArtur Pilipenko //   }
178fb3d57eSArtur Pilipenko //
188fb3d57eSArtur Pilipenko // to
198fb3d57eSArtur Pilipenko //
208fb3d57eSArtur Pilipenko //   for (i = 0; i < n; i++) {
218fb3d57eSArtur Pilipenko //     guard(n - 1 < len);
228fb3d57eSArtur Pilipenko //     ...
238fb3d57eSArtur Pilipenko //   }
248fb3d57eSArtur Pilipenko //
258fb3d57eSArtur Pilipenko // After this transformation the condition of the guard is loop invariant, so
268fb3d57eSArtur Pilipenko // loop-unswitch can later unswitch the loop by this condition which basically
278fb3d57eSArtur Pilipenko // predicates the loop by the widened condition:
288fb3d57eSArtur Pilipenko //
298fb3d57eSArtur Pilipenko //   if (n - 1 < len)
308fb3d57eSArtur Pilipenko //     for (i = 0; i < n; i++) {
318fb3d57eSArtur Pilipenko //       ...
328fb3d57eSArtur Pilipenko //     }
338fb3d57eSArtur Pilipenko //   else
348fb3d57eSArtur Pilipenko //     deoptimize
358fb3d57eSArtur Pilipenko //
36889dc1e3SArtur Pilipenko // It's tempting to rely on SCEV here, but it has proven to be problematic.
37889dc1e3SArtur Pilipenko // Generally the facts SCEV provides about the increment step of add
38889dc1e3SArtur Pilipenko // recurrences are true if the backedge of the loop is taken, which implicitly
39889dc1e3SArtur Pilipenko // assumes that the guard doesn't fail. Using these facts to optimize the
40889dc1e3SArtur Pilipenko // guard results in a circular logic where the guard is optimized under the
41889dc1e3SArtur Pilipenko // assumption that it never fails.
42889dc1e3SArtur Pilipenko //
43889dc1e3SArtur Pilipenko // For example, in the loop below the induction variable will be marked as nuw
44889dc1e3SArtur Pilipenko // basing on the guard. Basing on nuw the guard predicate will be considered
45889dc1e3SArtur Pilipenko // monotonic. Given a monotonic condition it's tempting to replace the induction
46889dc1e3SArtur Pilipenko // variable in the condition with its value on the last iteration. But this
47889dc1e3SArtur Pilipenko // transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
48889dc1e3SArtur Pilipenko //
49889dc1e3SArtur Pilipenko //   for (int i = b; i != e; i++)
50889dc1e3SArtur Pilipenko //     guard(i u< len)
51889dc1e3SArtur Pilipenko //
52889dc1e3SArtur Pilipenko // One of the ways to reason about this problem is to use an inductive proof
53889dc1e3SArtur Pilipenko // approach. Given the loop:
54889dc1e3SArtur Pilipenko //
558aadc643SArtur Pilipenko //   if (B(0)) {
56889dc1e3SArtur Pilipenko //     do {
578aadc643SArtur Pilipenko //       I = PHI(0, I.INC)
58889dc1e3SArtur Pilipenko //       I.INC = I + Step
59889dc1e3SArtur Pilipenko //       guard(G(I));
608aadc643SArtur Pilipenko //     } while (B(I));
61889dc1e3SArtur Pilipenko //   }
62889dc1e3SArtur Pilipenko //
63889dc1e3SArtur Pilipenko // where B(x) and G(x) are predicates that map integers to booleans, we want a
64889dc1e3SArtur Pilipenko // loop invariant expression M such the following program has the same semantics
65889dc1e3SArtur Pilipenko // as the above:
66889dc1e3SArtur Pilipenko //
678aadc643SArtur Pilipenko //   if (B(0)) {
68889dc1e3SArtur Pilipenko //     do {
698aadc643SArtur Pilipenko //       I = PHI(0, I.INC)
70889dc1e3SArtur Pilipenko //       I.INC = I + Step
718aadc643SArtur Pilipenko //       guard(G(0) && M);
728aadc643SArtur Pilipenko //     } while (B(I));
73889dc1e3SArtur Pilipenko //   }
74889dc1e3SArtur Pilipenko //
758aadc643SArtur Pilipenko // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
76889dc1e3SArtur Pilipenko //
77889dc1e3SArtur Pilipenko // Informal proof that the transformation above is correct:
78889dc1e3SArtur Pilipenko //
79889dc1e3SArtur Pilipenko //   By the definition of guards we can rewrite the guard condition to:
808aadc643SArtur Pilipenko //     G(I) && G(0) && M
81889dc1e3SArtur Pilipenko //
82889dc1e3SArtur Pilipenko //   Let's prove that for each iteration of the loop:
838aadc643SArtur Pilipenko //     G(0) && M => G(I)
84889dc1e3SArtur Pilipenko //   And the condition above can be simplified to G(Start) && M.
85889dc1e3SArtur Pilipenko //
86889dc1e3SArtur Pilipenko //   Induction base.
878aadc643SArtur Pilipenko //     G(0) && M => G(0)
88889dc1e3SArtur Pilipenko //
898aadc643SArtur Pilipenko //   Induction step. Assuming G(0) && M => G(I) on the subsequent
90889dc1e3SArtur Pilipenko //   iteration:
91889dc1e3SArtur Pilipenko //
928aadc643SArtur Pilipenko //     B(I) is true because it's the backedge condition.
93889dc1e3SArtur Pilipenko //     G(I) is true because the backedge is guarded by this condition.
94889dc1e3SArtur Pilipenko //
958aadc643SArtur Pilipenko //   So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
96889dc1e3SArtur Pilipenko //
97889dc1e3SArtur Pilipenko // Note that we can use anything stronger than M, i.e. any condition which
98889dc1e3SArtur Pilipenko // implies M.
99889dc1e3SArtur Pilipenko //
1007b360434SAnna Thomas // When S = 1 (i.e. forward iterating loop), the transformation is supported
1017b360434SAnna Thomas // when:
102b4527e1cSArtur Pilipenko //   * The loop has a single latch with the condition of the form:
1038aadc643SArtur Pilipenko //     B(X) = latchStart + X <pred> latchLimit,
1048aadc643SArtur Pilipenko //     where <pred> is u<, u<=, s<, or s<=.
1058aadc643SArtur Pilipenko //   * The guard condition is of the form
1068aadc643SArtur Pilipenko //     G(X) = guardStart + X u< guardLimit
107889dc1e3SArtur Pilipenko //
108b4527e1cSArtur Pilipenko //   For the ult latch comparison case M is:
1098aadc643SArtur Pilipenko //     forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
1108aadc643SArtur Pilipenko //        guardStart + X + 1 u< guardLimit
111889dc1e3SArtur Pilipenko //
112889dc1e3SArtur Pilipenko //   The only way the antecedent can be true and the consequent can be false is
113889dc1e3SArtur Pilipenko //   if
1148aadc643SArtur Pilipenko //     X == guardLimit - 1 - guardStart
115889dc1e3SArtur Pilipenko //   (and guardLimit is non-zero, but we won't use this latter fact).
1168aadc643SArtur Pilipenko //   If X == guardLimit - 1 - guardStart then the second half of the antecedent is
1178aadc643SArtur Pilipenko //     latchStart + guardLimit - 1 - guardStart u< latchLimit
118889dc1e3SArtur Pilipenko //   and its negation is
1198aadc643SArtur Pilipenko //     latchStart + guardLimit - 1 - guardStart u>= latchLimit
120889dc1e3SArtur Pilipenko //
1218aadc643SArtur Pilipenko //   In other words, if
1228aadc643SArtur Pilipenko //     latchLimit u<= latchStart + guardLimit - 1 - guardStart
1238aadc643SArtur Pilipenko //   then:
124889dc1e3SArtur Pilipenko //   (the ranges below are written in ConstantRange notation, where [A, B) is the
125889dc1e3SArtur Pilipenko //   set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
126889dc1e3SArtur Pilipenko //
1278aadc643SArtur Pilipenko //      forall X . guardStart + X u< guardLimit &&
1288aadc643SArtur Pilipenko //                 latchStart + X u< latchLimit =>
1298aadc643SArtur Pilipenko //        guardStart + X + 1 u< guardLimit
1308aadc643SArtur Pilipenko //   == forall X . guardStart + X u< guardLimit &&
1318aadc643SArtur Pilipenko //                 latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
1328aadc643SArtur Pilipenko //        guardStart + X + 1 u< guardLimit
1338aadc643SArtur Pilipenko //   == forall X . (guardStart + X) in [0, guardLimit) &&
1348aadc643SArtur Pilipenko //                 (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
1358aadc643SArtur Pilipenko //        (guardStart + X + 1) in [0, guardLimit)
1368aadc643SArtur Pilipenko //   == forall X . X in [-guardStart, guardLimit - guardStart) &&
1378aadc643SArtur Pilipenko //                 X in [-latchStart, guardLimit - 1 - guardStart) =>
1388aadc643SArtur Pilipenko //         X in [-guardStart - 1, guardLimit - guardStart - 1)
139889dc1e3SArtur Pilipenko //   == true
140889dc1e3SArtur Pilipenko //
141889dc1e3SArtur Pilipenko //   So the widened condition is:
1428aadc643SArtur Pilipenko //     guardStart u< guardLimit &&
1438aadc643SArtur Pilipenko //     latchStart + guardLimit - 1 - guardStart u>= latchLimit
1448aadc643SArtur Pilipenko //   Similarly for ule condition the widened condition is:
1458aadc643SArtur Pilipenko //     guardStart u< guardLimit &&
1468aadc643SArtur Pilipenko //     latchStart + guardLimit - 1 - guardStart u> latchLimit
1478aadc643SArtur Pilipenko //   For slt condition the widened condition is:
1488aadc643SArtur Pilipenko //     guardStart u< guardLimit &&
1498aadc643SArtur Pilipenko //     latchStart + guardLimit - 1 - guardStart s>= latchLimit
1508aadc643SArtur Pilipenko //   For sle condition the widened condition is:
1518aadc643SArtur Pilipenko //     guardStart u< guardLimit &&
1528aadc643SArtur Pilipenko //     latchStart + guardLimit - 1 - guardStart s> latchLimit
153889dc1e3SArtur Pilipenko //
1547b360434SAnna Thomas // When S = -1 (i.e. reverse iterating loop), the transformation is supported
1557b360434SAnna Thomas // when:
1567b360434SAnna Thomas //   * The loop has a single latch with the condition of the form:
157c8016e7aSSerguei Katkov //     B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=.
1587b360434SAnna Thomas //   * The guard condition is of the form
1597b360434SAnna Thomas //     G(X) = X - 1 u< guardLimit
1607b360434SAnna Thomas //
1617b360434SAnna Thomas //   For the ugt latch comparison case M is:
1627b360434SAnna Thomas //     forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit
1637b360434SAnna Thomas //
1647b360434SAnna Thomas //   The only way the antecedent can be true and the consequent can be false is if
1657b360434SAnna Thomas //     X == 1.
1667b360434SAnna Thomas //   If X == 1 then the second half of the antecedent is
1677b360434SAnna Thomas //     1 u> latchLimit, and its negation is latchLimit u>= 1.
1687b360434SAnna Thomas //
1697b360434SAnna Thomas //   So the widened condition is:
1707b360434SAnna Thomas //     guardStart u< guardLimit && latchLimit u>= 1.
1717b360434SAnna Thomas //   Similarly for sgt condition the widened condition is:
1727b360434SAnna Thomas //     guardStart u< guardLimit && latchLimit s>= 1.
173c8016e7aSSerguei Katkov //   For uge condition the widened condition is:
174c8016e7aSSerguei Katkov //     guardStart u< guardLimit && latchLimit u> 1.
175c8016e7aSSerguei Katkov //   For sge condition the widened condition is:
176c8016e7aSSerguei Katkov //     guardStart u< guardLimit && latchLimit s> 1.
1778fb3d57eSArtur Pilipenko //===----------------------------------------------------------------------===//
1788fb3d57eSArtur Pilipenko 
1798fb3d57eSArtur Pilipenko #include "llvm/Transforms/Scalar/LoopPredication.h"
180c297e84bSFedor Sergeev #include "llvm/ADT/Statistic.h"
18192a7177eSPhilip Reames #include "llvm/Analysis/AliasAnalysis.h"
1829b1176b0SAnna Thomas #include "llvm/Analysis/BranchProbabilityInfo.h"
18328298e96SMax Kazantsev #include "llvm/Analysis/GuardUtils.h"
1848fb3d57eSArtur Pilipenko #include "llvm/Analysis/LoopInfo.h"
1858fb3d57eSArtur Pilipenko #include "llvm/Analysis/LoopPass.h"
1868fb3d57eSArtur Pilipenko #include "llvm/Analysis/ScalarEvolution.h"
1878fb3d57eSArtur Pilipenko #include "llvm/Analysis/ScalarEvolutionExpander.h"
1888fb3d57eSArtur Pilipenko #include "llvm/Analysis/ScalarEvolutionExpressions.h"
1898fb3d57eSArtur Pilipenko #include "llvm/IR/Function.h"
1908fb3d57eSArtur Pilipenko #include "llvm/IR/GlobalValue.h"
1918fb3d57eSArtur Pilipenko #include "llvm/IR/IntrinsicInst.h"
1928fb3d57eSArtur Pilipenko #include "llvm/IR/Module.h"
1938fb3d57eSArtur Pilipenko #include "llvm/IR/PatternMatch.h"
194*05da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
1956bda14b3SChandler Carruth #include "llvm/Pass.h"
1968fb3d57eSArtur Pilipenko #include "llvm/Support/Debug.h"
1978fb3d57eSArtur Pilipenko #include "llvm/Transforms/Scalar.h"
198d109e2a7SPhilip Reames #include "llvm/Transforms/Utils/Local.h"
1998fb3d57eSArtur Pilipenko #include "llvm/Transforms/Utils/LoopUtils.h"
2008fb3d57eSArtur Pilipenko 
2018fb3d57eSArtur Pilipenko #define DEBUG_TYPE "loop-predication"
2028fb3d57eSArtur Pilipenko 
203c297e84bSFedor Sergeev STATISTIC(TotalConsidered, "Number of guards considered");
204c297e84bSFedor Sergeev STATISTIC(TotalWidened, "Number of checks widened");
205c297e84bSFedor Sergeev 
2068fb3d57eSArtur Pilipenko using namespace llvm;
2078fb3d57eSArtur Pilipenko 
2081d02b13eSAnna Thomas static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
2091d02b13eSAnna Thomas                                         cl::Hidden, cl::init(true));
2101d02b13eSAnna Thomas 
2117b360434SAnna Thomas static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
2127b360434SAnna Thomas                                         cl::Hidden, cl::init(true));
2139b1176b0SAnna Thomas 
2149b1176b0SAnna Thomas static cl::opt<bool>
2159b1176b0SAnna Thomas     SkipProfitabilityChecks("loop-predication-skip-profitability-checks",
2169b1176b0SAnna Thomas                             cl::Hidden, cl::init(false));
2179b1176b0SAnna Thomas 
2189b1176b0SAnna Thomas // This is the scale factor for the latch probability. We use this during
2199b1176b0SAnna Thomas // profitability analysis to find other exiting blocks that have a much higher
2209b1176b0SAnna Thomas // probability of exiting the loop instead of loop exiting via latch.
2219b1176b0SAnna Thomas // This value should be greater than 1 for a sane profitability check.
2229b1176b0SAnna Thomas static cl::opt<float> LatchExitProbabilityScale(
2239b1176b0SAnna Thomas     "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0),
2249b1176b0SAnna Thomas     cl::desc("scale factor for the latch probability. Value should be greater "
2259b1176b0SAnna Thomas              "than 1. Lower values are ignored"));
2269b1176b0SAnna Thomas 
227feb475f4SMax Kazantsev static cl::opt<bool> PredicateWidenableBranchGuards(
228feb475f4SMax Kazantsev     "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden,
229feb475f4SMax Kazantsev     cl::desc("Whether or not we should predicate guards "
230feb475f4SMax Kazantsev              "expressed as widenable branches to deoptimize blocks"),
231feb475f4SMax Kazantsev     cl::init(true));
232feb475f4SMax Kazantsev 
2338fb3d57eSArtur Pilipenko namespace {
234a6c27804SArtur Pilipenko /// Represents an induction variable check:
235a6c27804SArtur Pilipenko ///   icmp Pred, <induction variable>, <loop invariant limit>
236a6c27804SArtur Pilipenko struct LoopICmp {
237a6c27804SArtur Pilipenko   ICmpInst::Predicate Pred;
238a6c27804SArtur Pilipenko   const SCEVAddRecExpr *IV;
239a6c27804SArtur Pilipenko   const SCEV *Limit;
240c488dfabSArtur Pilipenko   LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
241c488dfabSArtur Pilipenko            const SCEV *Limit)
242a6c27804SArtur Pilipenko     : Pred(Pred), IV(IV), Limit(Limit) {}
243a6c27804SArtur Pilipenko   LoopICmp() {}
24468797214SAnna Thomas   void dump() {
24568797214SAnna Thomas     dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
24668797214SAnna Thomas            << ", Limit = " << *Limit << "\n";
24768797214SAnna Thomas   }
248a6c27804SArtur Pilipenko };
249c488dfabSArtur Pilipenko 
250099eca83SPhilip Reames class LoopPredication {
25192a7177eSPhilip Reames   AliasAnalysis *AA;
252c488dfabSArtur Pilipenko   ScalarEvolution *SE;
2539b1176b0SAnna Thomas   BranchProbabilityInfo *BPI;
254c488dfabSArtur Pilipenko 
255c488dfabSArtur Pilipenko   Loop *L;
256c488dfabSArtur Pilipenko   const DataLayout *DL;
257c488dfabSArtur Pilipenko   BasicBlock *Preheader;
258889dc1e3SArtur Pilipenko   LoopICmp LatchCheck;
259c488dfabSArtur Pilipenko 
26068797214SAnna Thomas   bool isSupportedStep(const SCEV* Step);
26119afdf74SPhilip Reames   Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI);
262889dc1e3SArtur Pilipenko   Optional<LoopICmp> parseLoopLatchICmp();
263a6c27804SArtur Pilipenko 
264fbe64a2cSPhilip Reames   /// Return an insertion point suitable for inserting a safe to speculate
265fbe64a2cSPhilip Reames   /// instruction whose only user will be 'User' which has operands 'Ops'.  A
266fbe64a2cSPhilip Reames   /// trivial result would be the at the User itself, but we try to return a
267fbe64a2cSPhilip Reames   /// loop invariant location if possible.
268fbe64a2cSPhilip Reames   Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops);
269e46d77d1SPhilip Reames   /// Same as above, *except* that this uses the SCEV definition of invariant
270e46d77d1SPhilip Reames   /// which is that an expression *can be made* invariant via SCEVExpander.
271e46d77d1SPhilip Reames   /// Thus, this version is only suitable for finding an insert point to be be
272e46d77d1SPhilip Reames   /// passed to SCEVExpander!
273e46d77d1SPhilip Reames   Instruction *findInsertPt(Instruction *User, ArrayRef<const SCEV*> Ops);
274fbe64a2cSPhilip Reames 
27592a7177eSPhilip Reames   /// Return true if the value is known to produce a single fixed value across
27692a7177eSPhilip Reames   /// all iterations on which it executes.  Note that this does not imply
27792a7177eSPhilip Reames   /// speculation safety.  That must be established seperately.
27892a7177eSPhilip Reames   bool isLoopInvariantValue(const SCEV* S);
27992a7177eSPhilip Reames 
280e46d77d1SPhilip Reames   Value *expandCheck(SCEVExpander &Expander, Instruction *Guard,
2813d4e1082SPhilip Reames                      ICmpInst::Predicate Pred, const SCEV *LHS,
2823d4e1082SPhilip Reames                      const SCEV *RHS);
2836780ba65SArtur Pilipenko 
2848fb3d57eSArtur Pilipenko   Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
285e46d77d1SPhilip Reames                                         Instruction *Guard);
28668797214SAnna Thomas   Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
28768797214SAnna Thomas                                                         LoopICmp RangeCheck,
28868797214SAnna Thomas                                                         SCEVExpander &Expander,
289e46d77d1SPhilip Reames                                                         Instruction *Guard);
2907b360434SAnna Thomas   Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
2917b360434SAnna Thomas                                                         LoopICmp RangeCheck,
2927b360434SAnna Thomas                                                         SCEVExpander &Expander,
293e46d77d1SPhilip Reames                                                         Instruction *Guard);
294ca450878SMax Kazantsev   unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition,
295e46d77d1SPhilip Reames                          SCEVExpander &Expander, Instruction *Guard);
2968fb3d57eSArtur Pilipenko   bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
297feb475f4SMax Kazantsev   bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander);
2989b1176b0SAnna Thomas   // If the loop always exits through another block in the loop, we should not
2999b1176b0SAnna Thomas   // predicate based on the latch check. For example, the latch check can be a
3009b1176b0SAnna Thomas   // very coarse grained check and there can be more fine grained exit checks
3019b1176b0SAnna Thomas   // within the loop. We identify such unprofitable loops through BPI.
3029b1176b0SAnna Thomas   bool isLoopProfitableToPredicate();
3039b1176b0SAnna Thomas 
3048fb3d57eSArtur Pilipenko public:
30592a7177eSPhilip Reames   LoopPredication(AliasAnalysis *AA, ScalarEvolution *SE,
30692a7177eSPhilip Reames                   BranchProbabilityInfo *BPI)
30792a7177eSPhilip Reames     : AA(AA), SE(SE), BPI(BPI){};
3088fb3d57eSArtur Pilipenko   bool runOnLoop(Loop *L);
3098fb3d57eSArtur Pilipenko };
3108fb3d57eSArtur Pilipenko 
3118fb3d57eSArtur Pilipenko class LoopPredicationLegacyPass : public LoopPass {
3128fb3d57eSArtur Pilipenko public:
3138fb3d57eSArtur Pilipenko   static char ID;
3148fb3d57eSArtur Pilipenko   LoopPredicationLegacyPass() : LoopPass(ID) {
3158fb3d57eSArtur Pilipenko     initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
3168fb3d57eSArtur Pilipenko   }
3178fb3d57eSArtur Pilipenko 
3188fb3d57eSArtur Pilipenko   void getAnalysisUsage(AnalysisUsage &AU) const override {
3199b1176b0SAnna Thomas     AU.addRequired<BranchProbabilityInfoWrapperPass>();
3208fb3d57eSArtur Pilipenko     getLoopAnalysisUsage(AU);
3218fb3d57eSArtur Pilipenko   }
3228fb3d57eSArtur Pilipenko 
3238fb3d57eSArtur Pilipenko   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
3248fb3d57eSArtur Pilipenko     if (skipLoop(L))
3258fb3d57eSArtur Pilipenko       return false;
3268fb3d57eSArtur Pilipenko     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3279b1176b0SAnna Thomas     BranchProbabilityInfo &BPI =
3289b1176b0SAnna Thomas         getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
32992a7177eSPhilip Reames     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
33092a7177eSPhilip Reames     LoopPredication LP(AA, SE, &BPI);
3318fb3d57eSArtur Pilipenko     return LP.runOnLoop(L);
3328fb3d57eSArtur Pilipenko   }
3338fb3d57eSArtur Pilipenko };
3348fb3d57eSArtur Pilipenko 
3358fb3d57eSArtur Pilipenko char LoopPredicationLegacyPass::ID = 0;
3368fb3d57eSArtur Pilipenko } // end namespace llvm
3378fb3d57eSArtur Pilipenko 
3388fb3d57eSArtur Pilipenko INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
3398fb3d57eSArtur Pilipenko                       "Loop predication", false, false)
3409b1176b0SAnna Thomas INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
3418fb3d57eSArtur Pilipenko INITIALIZE_PASS_DEPENDENCY(LoopPass)
3428fb3d57eSArtur Pilipenko INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
3438fb3d57eSArtur Pilipenko                     "Loop predication", false, false)
3448fb3d57eSArtur Pilipenko 
3458fb3d57eSArtur Pilipenko Pass *llvm::createLoopPredicationPass() {
3468fb3d57eSArtur Pilipenko   return new LoopPredicationLegacyPass();
3478fb3d57eSArtur Pilipenko }
3488fb3d57eSArtur Pilipenko 
3498fb3d57eSArtur Pilipenko PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
3508fb3d57eSArtur Pilipenko                                            LoopStandardAnalysisResults &AR,
3518fb3d57eSArtur Pilipenko                                            LPMUpdater &U) {
3529b1176b0SAnna Thomas   const auto &FAM =
3539b1176b0SAnna Thomas       AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
3549b1176b0SAnna Thomas   Function *F = L.getHeader()->getParent();
3559b1176b0SAnna Thomas   auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F);
35692a7177eSPhilip Reames   LoopPredication LP(&AR.AA, &AR.SE, BPI);
3578fb3d57eSArtur Pilipenko   if (!LP.runOnLoop(&L))
3588fb3d57eSArtur Pilipenko     return PreservedAnalyses::all();
3598fb3d57eSArtur Pilipenko 
3608fb3d57eSArtur Pilipenko   return getLoopPassPreservedAnalyses();
3618fb3d57eSArtur Pilipenko }
3628fb3d57eSArtur Pilipenko 
363099eca83SPhilip Reames Optional<LoopICmp>
36419afdf74SPhilip Reames LoopPredication::parseLoopICmp(ICmpInst *ICI) {
36519afdf74SPhilip Reames   auto Pred = ICI->getPredicate();
36619afdf74SPhilip Reames   auto *LHS = ICI->getOperand(0);
36719afdf74SPhilip Reames   auto *RHS = ICI->getOperand(1);
36819afdf74SPhilip Reames 
369a6c27804SArtur Pilipenko   const SCEV *LHSS = SE->getSCEV(LHS);
370a6c27804SArtur Pilipenko   if (isa<SCEVCouldNotCompute>(LHSS))
371a6c27804SArtur Pilipenko     return None;
372a6c27804SArtur Pilipenko   const SCEV *RHSS = SE->getSCEV(RHS);
373a6c27804SArtur Pilipenko   if (isa<SCEVCouldNotCompute>(RHSS))
374a6c27804SArtur Pilipenko     return None;
375a6c27804SArtur Pilipenko 
376a6c27804SArtur Pilipenko   // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
377a6c27804SArtur Pilipenko   if (SE->isLoopInvariant(LHSS, L)) {
378a6c27804SArtur Pilipenko     std::swap(LHS, RHS);
379a6c27804SArtur Pilipenko     std::swap(LHSS, RHSS);
380a6c27804SArtur Pilipenko     Pred = ICmpInst::getSwappedPredicate(Pred);
381a6c27804SArtur Pilipenko   }
382a6c27804SArtur Pilipenko 
383a6c27804SArtur Pilipenko   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
384a6c27804SArtur Pilipenko   if (!AR || AR->getLoop() != L)
385a6c27804SArtur Pilipenko     return None;
386a6c27804SArtur Pilipenko 
387a6c27804SArtur Pilipenko   return LoopICmp(Pred, AR, RHSS);
388a6c27804SArtur Pilipenko }
389a6c27804SArtur Pilipenko 
3906780ba65SArtur Pilipenko Value *LoopPredication::expandCheck(SCEVExpander &Expander,
391e46d77d1SPhilip Reames                                     Instruction *Guard,
3926780ba65SArtur Pilipenko                                     ICmpInst::Predicate Pred, const SCEV *LHS,
3933d4e1082SPhilip Reames                                     const SCEV *RHS) {
3946780ba65SArtur Pilipenko   Type *Ty = LHS->getType();
3956780ba65SArtur Pilipenko   assert(Ty == RHS->getType() && "expandCheck operands have different types?");
396ead69ee4SArtur Pilipenko 
397e46d77d1SPhilip Reames   if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) {
398e46d77d1SPhilip Reames     IRBuilder<> Builder(Guard);
399ead69ee4SArtur Pilipenko     if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
400ead69ee4SArtur Pilipenko       return Builder.getTrue();
40105e3e554SPhilip Reames     if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred),
40205e3e554SPhilip Reames                                      LHS, RHS))
40305e3e554SPhilip Reames       return Builder.getFalse();
404e46d77d1SPhilip Reames   }
405ead69ee4SArtur Pilipenko 
406e46d77d1SPhilip Reames   Value *LHSV = Expander.expandCodeFor(LHS, Ty, findInsertPt(Guard, {LHS}));
407e46d77d1SPhilip Reames   Value *RHSV = Expander.expandCodeFor(RHS, Ty, findInsertPt(Guard, {RHS}));
408e46d77d1SPhilip Reames   IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV}));
4096780ba65SArtur Pilipenko   return Builder.CreateICmp(Pred, LHSV, RHSV);
4106780ba65SArtur Pilipenko }
4116780ba65SArtur Pilipenko 
4120912b06fSPhilip Reames 
4130912b06fSPhilip Reames // Returns true if its safe to truncate the IV to RangeCheckType.
4140912b06fSPhilip Reames // When the IV type is wider than the range operand type, we can still do loop
4150912b06fSPhilip Reames // predication, by generating SCEVs for the range and latch that are of the
4160912b06fSPhilip Reames // same type. We achieve this by generating a SCEV truncate expression for the
4170912b06fSPhilip Reames // latch IV. This is done iff truncation of the IV is a safe operation,
4180912b06fSPhilip Reames // without loss of information.
4190912b06fSPhilip Reames // Another way to achieve this is by generating a wider type SCEV for the
4200912b06fSPhilip Reames // range check operand, however, this needs a more involved check that
4210912b06fSPhilip Reames // operands do not overflow. This can lead to loss of information when the
4220912b06fSPhilip Reames // range operand is of the form: add i32 %offset, %iv. We need to prove that
4230912b06fSPhilip Reames // sext(x + y) is same as sext(x) + sext(y).
4240912b06fSPhilip Reames // This function returns true if we can safely represent the IV type in
4250912b06fSPhilip Reames // the RangeCheckType without loss of information.
4269ed16737SPhilip Reames static bool isSafeToTruncateWideIVType(const DataLayout &DL,
4279ed16737SPhilip Reames                                        ScalarEvolution &SE,
4280912b06fSPhilip Reames                                        const LoopICmp LatchCheck,
4290912b06fSPhilip Reames                                        Type *RangeCheckType) {
4300912b06fSPhilip Reames   if (!EnableIVTruncation)
4310912b06fSPhilip Reames     return false;
4320912b06fSPhilip Reames   assert(DL.getTypeSizeInBits(LatchCheck.IV->getType()) >
4330912b06fSPhilip Reames              DL.getTypeSizeInBits(RangeCheckType) &&
4340912b06fSPhilip Reames          "Expected latch check IV type to be larger than range check operand "
4350912b06fSPhilip Reames          "type!");
4360912b06fSPhilip Reames   // The start and end values of the IV should be known. This is to guarantee
4370912b06fSPhilip Reames   // that truncating the wide type will not lose information.
4380912b06fSPhilip Reames   auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
4390912b06fSPhilip Reames   auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
4400912b06fSPhilip Reames   if (!Limit || !Start)
4410912b06fSPhilip Reames     return false;
4420912b06fSPhilip Reames   // This check makes sure that the IV does not change sign during loop
4430912b06fSPhilip Reames   // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
4440912b06fSPhilip Reames   // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
4450912b06fSPhilip Reames   // IV wraps around, and the truncation of the IV would lose the range of
4460912b06fSPhilip Reames   // iterations between 2^32 and 2^64.
4470912b06fSPhilip Reames   bool Increasing;
4480912b06fSPhilip Reames   if (!SE.isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing))
4490912b06fSPhilip Reames     return false;
4500912b06fSPhilip Reames   // The active bits should be less than the bits in the RangeCheckType. This
4510912b06fSPhilip Reames   // guarantees that truncating the latch check to RangeCheckType is a safe
4520912b06fSPhilip Reames   // operation.
4530912b06fSPhilip Reames   auto RangeCheckTypeBitSize = DL.getTypeSizeInBits(RangeCheckType);
4540912b06fSPhilip Reames   return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
4550912b06fSPhilip Reames          Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
4560912b06fSPhilip Reames }
4570912b06fSPhilip Reames 
4580912b06fSPhilip Reames 
4599ed16737SPhilip Reames // Return an LoopICmp describing a latch check equivlent to LatchCheck but with
4609ed16737SPhilip Reames // the requested type if safe to do so.  May involve the use of a new IV.
4619ed16737SPhilip Reames static Optional<LoopICmp> generateLoopLatchCheck(const DataLayout &DL,
4629ed16737SPhilip Reames                                                  ScalarEvolution &SE,
4639ed16737SPhilip Reames                                                  const LoopICmp LatchCheck,
4649ed16737SPhilip Reames                                                  Type *RangeCheckType) {
4651d02b13eSAnna Thomas 
4661d02b13eSAnna Thomas   auto *LatchType = LatchCheck.IV->getType();
4671d02b13eSAnna Thomas   if (RangeCheckType == LatchType)
4681d02b13eSAnna Thomas     return LatchCheck;
4691d02b13eSAnna Thomas   // For now, bail out if latch type is narrower than range type.
4709ed16737SPhilip Reames   if (DL.getTypeSizeInBits(LatchType) < DL.getTypeSizeInBits(RangeCheckType))
4711d02b13eSAnna Thomas     return None;
4729ed16737SPhilip Reames   if (!isSafeToTruncateWideIVType(DL, SE, LatchCheck, RangeCheckType))
4731d02b13eSAnna Thomas     return None;
4741d02b13eSAnna Thomas   // We can now safely identify the truncated version of the IV and limit for
4751d02b13eSAnna Thomas   // RangeCheckType.
4761d02b13eSAnna Thomas   LoopICmp NewLatchCheck;
4771d02b13eSAnna Thomas   NewLatchCheck.Pred = LatchCheck.Pred;
4781d02b13eSAnna Thomas   NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
4799ed16737SPhilip Reames       SE.getTruncateExpr(LatchCheck.IV, RangeCheckType));
4801d02b13eSAnna Thomas   if (!NewLatchCheck.IV)
4811d02b13eSAnna Thomas     return None;
4829ed16737SPhilip Reames   NewLatchCheck.Limit = SE.getTruncateExpr(LatchCheck.Limit, RangeCheckType);
483d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType
484d34e60caSNicola Zaghen                     << "can be represented as range check type:"
485d34e60caSNicola Zaghen                     << *RangeCheckType << "\n");
486d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
487d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
4881d02b13eSAnna Thomas   return NewLatchCheck;
4891d02b13eSAnna Thomas }
4901d02b13eSAnna Thomas 
49168797214SAnna Thomas bool LoopPredication::isSupportedStep(const SCEV* Step) {
4927b360434SAnna Thomas   return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
4931d02b13eSAnna Thomas }
4948fb3d57eSArtur Pilipenko 
495fbe64a2cSPhilip Reames Instruction *LoopPredication::findInsertPt(Instruction *Use,
496fbe64a2cSPhilip Reames                                            ArrayRef<Value*> Ops) {
497fbe64a2cSPhilip Reames   for (Value *Op : Ops)
498fbe64a2cSPhilip Reames     if (!L->isLoopInvariant(Op))
499fbe64a2cSPhilip Reames       return Use;
500fbe64a2cSPhilip Reames   return Preheader->getTerminator();
501fbe64a2cSPhilip Reames }
502fbe64a2cSPhilip Reames 
503e46d77d1SPhilip Reames Instruction *LoopPredication::findInsertPt(Instruction *Use,
504e46d77d1SPhilip Reames                                            ArrayRef<const SCEV*> Ops) {
50592a7177eSPhilip Reames   // Subtlety: SCEV considers things to be invariant if the value produced is
50692a7177eSPhilip Reames   // the same across iterations.  This is not the same as being able to
50792a7177eSPhilip Reames   // evaluate outside the loop, which is what we actually need here.
508e46d77d1SPhilip Reames   for (const SCEV *Op : Ops)
50992a7177eSPhilip Reames     if (!SE->isLoopInvariant(Op, L) ||
51092a7177eSPhilip Reames         !isSafeToExpandAt(Op, Preheader->getTerminator(), *SE))
511e46d77d1SPhilip Reames       return Use;
512e46d77d1SPhilip Reames   return Preheader->getTerminator();
513e46d77d1SPhilip Reames }
514e46d77d1SPhilip Reames 
51592a7177eSPhilip Reames bool LoopPredication::isLoopInvariantValue(const SCEV* S) {
51692a7177eSPhilip Reames   // Handling expressions which produce invariant results, but *haven't* yet
51792a7177eSPhilip Reames   // been removed from the loop serves two important purposes.
51892a7177eSPhilip Reames   // 1) Most importantly, it resolves a pass ordering cycle which would
51992a7177eSPhilip Reames   // otherwise need us to iteration licm, loop-predication, and either
52092a7177eSPhilip Reames   // loop-unswitch or loop-peeling to make progress on examples with lots of
52192a7177eSPhilip Reames   // predicable range checks in a row.  (Since, in the general case,  we can't
52292a7177eSPhilip Reames   // hoist the length checks until the dominating checks have been discharged
52392a7177eSPhilip Reames   // as we can't prove doing so is safe.)
52492a7177eSPhilip Reames   // 2) As a nice side effect, this exposes the value of peeling or unswitching
52592a7177eSPhilip Reames   // much more obviously in the IR.  Otherwise, the cost modeling for other
52692a7177eSPhilip Reames   // transforms would end up needing to duplicate all of this logic to model a
52792a7177eSPhilip Reames   // check which becomes predictable based on a modeled peel or unswitch.
52892a7177eSPhilip Reames   //
52992a7177eSPhilip Reames   // The cost of doing so in the worst case is an extra fill from the stack  in
53092a7177eSPhilip Reames   // the loop to materialize the loop invariant test value instead of checking
53192a7177eSPhilip Reames   // against the original IV which is presumable in a register inside the loop.
53292a7177eSPhilip Reames   // Such cases are presumably rare, and hint at missing oppurtunities for
53392a7177eSPhilip Reames   // other passes.
534e46d77d1SPhilip Reames 
53592a7177eSPhilip Reames   if (SE->isLoopInvariant(S, L))
53692a7177eSPhilip Reames     // Note: This the SCEV variant, so the original Value* may be within the
53792a7177eSPhilip Reames     // loop even though SCEV has proven it is loop invariant.
53892a7177eSPhilip Reames     return true;
53992a7177eSPhilip Reames 
54092a7177eSPhilip Reames   // Handle a particular important case which SCEV doesn't yet know about which
54192a7177eSPhilip Reames   // shows up in range checks on arrays with immutable lengths.
54292a7177eSPhilip Reames   // TODO: This should be sunk inside SCEV.
54392a7177eSPhilip Reames   if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
54492a7177eSPhilip Reames     if (const auto *LI = dyn_cast<LoadInst>(U->getValue()))
545adf288c5SPhilip Reames       if (LI->isUnordered() && L->hasLoopInvariantOperands(LI))
54692a7177eSPhilip Reames         if (AA->pointsToConstantMemory(LI->getOperand(0)) ||
54727820f99SPhilip Reames             LI->hasMetadata(LLVMContext::MD_invariant_load))
54892a7177eSPhilip Reames           return true;
54992a7177eSPhilip Reames   return false;
55068797214SAnna Thomas }
55168797214SAnna Thomas 
55268797214SAnna Thomas Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
553099eca83SPhilip Reames     LoopICmp LatchCheck, LoopICmp RangeCheck,
554e46d77d1SPhilip Reames     SCEVExpander &Expander, Instruction *Guard) {
55568797214SAnna Thomas   auto *Ty = RangeCheck.IV->getType();
55668797214SAnna Thomas   // Generate the widened condition for the forward loop:
5578aadc643SArtur Pilipenko   //   guardStart u< guardLimit &&
5588aadc643SArtur Pilipenko   //   latchLimit <pred> guardLimit - 1 - guardStart + latchStart
559b4527e1cSArtur Pilipenko   // where <pred> depends on the latch condition predicate. See the file
560b4527e1cSArtur Pilipenko   // header comment for the reasoning.
56168797214SAnna Thomas   // guardLimit - guardStart + latchStart - 1
56268797214SAnna Thomas   const SCEV *GuardStart = RangeCheck.IV->getStart();
56368797214SAnna Thomas   const SCEV *GuardLimit = RangeCheck.Limit;
56468797214SAnna Thomas   const SCEV *LatchStart = LatchCheck.IV->getStart();
56568797214SAnna Thomas   const SCEV *LatchLimit = LatchCheck.Limit;
56692a7177eSPhilip Reames   // Subtlety: We need all the values to be *invariant* across all iterations,
56792a7177eSPhilip Reames   // but we only need to check expansion safety for those which *aren't*
56892a7177eSPhilip Reames   // already guaranteed to dominate the guard.
56992a7177eSPhilip Reames   if (!isLoopInvariantValue(GuardStart) ||
57092a7177eSPhilip Reames       !isLoopInvariantValue(GuardLimit) ||
57192a7177eSPhilip Reames       !isLoopInvariantValue(LatchStart) ||
57292a7177eSPhilip Reames       !isLoopInvariantValue(LatchLimit)) {
57392a7177eSPhilip Reames     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
57492a7177eSPhilip Reames     return None;
57592a7177eSPhilip Reames   }
57692a7177eSPhilip Reames   if (!isSafeToExpandAt(LatchStart, Guard, *SE) ||
57792a7177eSPhilip Reames       !isSafeToExpandAt(LatchLimit, Guard, *SE)) {
57892a7177eSPhilip Reames     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
57992a7177eSPhilip Reames     return None;
58092a7177eSPhilip Reames   }
5818aadc643SArtur Pilipenko 
5828aadc643SArtur Pilipenko   // guardLimit - guardStart + latchStart - 1
5838aadc643SArtur Pilipenko   const SCEV *RHS =
5848aadc643SArtur Pilipenko       SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
5858aadc643SArtur Pilipenko                      SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
5863cb4c34aSSerguei Katkov   auto LimitCheckPred =
5873cb4c34aSSerguei Katkov       ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
588aab28666SArtur Pilipenko 
589d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
590d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n");
591d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
5928aadc643SArtur Pilipenko 
5938aadc643SArtur Pilipenko   auto *LimitCheck =
594e46d77d1SPhilip Reames       expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS);
595e46d77d1SPhilip Reames   auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred,
5963d4e1082SPhilip Reames                                           GuardStart, GuardLimit);
597e46d77d1SPhilip Reames   IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
598889dc1e3SArtur Pilipenko   return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
5998fb3d57eSArtur Pilipenko }
6007b360434SAnna Thomas 
6017b360434SAnna Thomas Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
602099eca83SPhilip Reames     LoopICmp LatchCheck, LoopICmp RangeCheck,
603e46d77d1SPhilip Reames     SCEVExpander &Expander, Instruction *Guard) {
6047b360434SAnna Thomas   auto *Ty = RangeCheck.IV->getType();
6057b360434SAnna Thomas   const SCEV *GuardStart = RangeCheck.IV->getStart();
6067b360434SAnna Thomas   const SCEV *GuardLimit = RangeCheck.Limit;
60792a7177eSPhilip Reames   const SCEV *LatchStart = LatchCheck.IV->getStart();
6087b360434SAnna Thomas   const SCEV *LatchLimit = LatchCheck.Limit;
60992a7177eSPhilip Reames   // Subtlety: We need all the values to be *invariant* across all iterations,
61092a7177eSPhilip Reames   // but we only need to check expansion safety for those which *aren't*
61192a7177eSPhilip Reames   // already guaranteed to dominate the guard.
61292a7177eSPhilip Reames   if (!isLoopInvariantValue(GuardStart) ||
61392a7177eSPhilip Reames       !isLoopInvariantValue(GuardLimit) ||
61492a7177eSPhilip Reames       !isLoopInvariantValue(LatchStart) ||
61592a7177eSPhilip Reames       !isLoopInvariantValue(LatchLimit)) {
61692a7177eSPhilip Reames     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
61792a7177eSPhilip Reames     return None;
61892a7177eSPhilip Reames   }
61992a7177eSPhilip Reames   if (!isSafeToExpandAt(LatchStart, Guard, *SE) ||
62092a7177eSPhilip Reames       !isSafeToExpandAt(LatchLimit, Guard, *SE)) {
621d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
6227b360434SAnna Thomas     return None;
6237b360434SAnna Thomas   }
6247b360434SAnna Thomas   // The decrement of the latch check IV should be the same as the
6257b360434SAnna Thomas   // rangeCheckIV.
6267b360434SAnna Thomas   auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
6277b360434SAnna Thomas   if (RangeCheck.IV != PostDecLatchCheckIV) {
628d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
6297b360434SAnna Thomas                       << *PostDecLatchCheckIV
6307b360434SAnna Thomas                       << "  and RangeCheckIV: " << *RangeCheck.IV << "\n");
6317b360434SAnna Thomas     return None;
6327b360434SAnna Thomas   }
6337b360434SAnna Thomas 
6347b360434SAnna Thomas   // Generate the widened condition for CountDownLoop:
6357b360434SAnna Thomas   // guardStart u< guardLimit &&
6367b360434SAnna Thomas   // latchLimit <pred> 1.
6377b360434SAnna Thomas   // See the header comment for reasoning of the checks.
6383cb4c34aSSerguei Katkov   auto LimitCheckPred =
6393cb4c34aSSerguei Katkov       ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
640e46d77d1SPhilip Reames   auto *FirstIterationCheck = expandCheck(Expander, Guard,
641e46d77d1SPhilip Reames                                           ICmpInst::ICMP_ULT,
6423d4e1082SPhilip Reames                                           GuardStart, GuardLimit);
643e46d77d1SPhilip Reames   auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit,
6443d4e1082SPhilip Reames                                  SE->getOne(Ty));
645e46d77d1SPhilip Reames   IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
6467b360434SAnna Thomas   return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
6477b360434SAnna Thomas }
6487b360434SAnna Thomas 
649099eca83SPhilip Reames static void normalizePredicate(ScalarEvolution *SE, Loop *L,
650099eca83SPhilip Reames                                LoopICmp& RC) {
6510e344e9dSPhilip Reames   // LFTR canonicalizes checks to the ICMP_NE/EQ form; normalize back to the
6520e344e9dSPhilip Reames   // ULT/UGE form for ease of handling by our caller.
6530e344e9dSPhilip Reames   if (ICmpInst::isEquality(RC.Pred) &&
654099eca83SPhilip Reames       RC.IV->getStepRecurrence(*SE)->isOne() &&
655099eca83SPhilip Reames       SE->isKnownPredicate(ICmpInst::ICMP_ULE, RC.IV->getStart(), RC.Limit))
6560e344e9dSPhilip Reames     RC.Pred = RC.Pred == ICmpInst::ICMP_NE ?
6570e344e9dSPhilip Reames       ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
658099eca83SPhilip Reames }
659099eca83SPhilip Reames 
660099eca83SPhilip Reames 
66168797214SAnna Thomas /// If ICI can be widened to a loop invariant condition emits the loop
66268797214SAnna Thomas /// invariant condition in the loop preheader and return it, otherwise
66368797214SAnna Thomas /// returns None.
66468797214SAnna Thomas Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
66568797214SAnna Thomas                                                        SCEVExpander &Expander,
666e46d77d1SPhilip Reames                                                        Instruction *Guard) {
667d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
668d34e60caSNicola Zaghen   LLVM_DEBUG(ICI->dump());
66968797214SAnna Thomas 
67068797214SAnna Thomas   // parseLoopStructure guarantees that the latch condition is:
67168797214SAnna Thomas   //   ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
67268797214SAnna Thomas   // We are looking for the range checks of the form:
67368797214SAnna Thomas   //   i u< guardLimit
67468797214SAnna Thomas   auto RangeCheck = parseLoopICmp(ICI);
67568797214SAnna Thomas   if (!RangeCheck) {
676d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
67768797214SAnna Thomas     return None;
67868797214SAnna Thomas   }
679d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Guard check:\n");
680d34e60caSNicola Zaghen   LLVM_DEBUG(RangeCheck->dump());
68168797214SAnna Thomas   if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
682d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Unsupported range check predicate("
683d34e60caSNicola Zaghen                       << RangeCheck->Pred << ")!\n");
68468797214SAnna Thomas     return None;
68568797214SAnna Thomas   }
68668797214SAnna Thomas   auto *RangeCheckIV = RangeCheck->IV;
68768797214SAnna Thomas   if (!RangeCheckIV->isAffine()) {
688d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n");
68968797214SAnna Thomas     return None;
69068797214SAnna Thomas   }
69168797214SAnna Thomas   auto *Step = RangeCheckIV->getStepRecurrence(*SE);
69268797214SAnna Thomas   // We cannot just compare with latch IV step because the latch and range IVs
69368797214SAnna Thomas   // may have different types.
69468797214SAnna Thomas   if (!isSupportedStep(Step)) {
695d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
69668797214SAnna Thomas     return None;
69768797214SAnna Thomas   }
69868797214SAnna Thomas   auto *Ty = RangeCheckIV->getType();
6999ed16737SPhilip Reames   auto CurrLatchCheckOpt = generateLoopLatchCheck(*DL, *SE, LatchCheck, Ty);
70068797214SAnna Thomas   if (!CurrLatchCheckOpt) {
701d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check "
70268797214SAnna Thomas                          "corresponding to range type: "
70368797214SAnna Thomas                       << *Ty << "\n");
70468797214SAnna Thomas     return None;
70568797214SAnna Thomas   }
70668797214SAnna Thomas 
70768797214SAnna Thomas   LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
7087b360434SAnna Thomas   // At this point, the range and latch step should have the same type, but need
7097b360434SAnna Thomas   // not have the same value (we support both 1 and -1 steps).
7107b360434SAnna Thomas   assert(Step->getType() ==
7117b360434SAnna Thomas              CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
7127b360434SAnna Thomas          "Range and latch steps should be of same type!");
7137b360434SAnna Thomas   if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
714d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n");
7157b360434SAnna Thomas     return None;
7167b360434SAnna Thomas   }
71768797214SAnna Thomas 
7187b360434SAnna Thomas   if (Step->isOne())
71968797214SAnna Thomas     return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
720e46d77d1SPhilip Reames                                                Expander, Guard);
7217b360434SAnna Thomas   else {
7227b360434SAnna Thomas     assert(Step->isAllOnesValue() && "Step should be -1!");
7237b360434SAnna Thomas     return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
724e46d77d1SPhilip Reames                                                Expander, Guard);
7257b360434SAnna Thomas   }
72668797214SAnna Thomas }
7278fb3d57eSArtur Pilipenko 
728ca450878SMax Kazantsev unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks,
729ca450878SMax Kazantsev                                         Value *Condition,
730ca450878SMax Kazantsev                                         SCEVExpander &Expander,
731e46d77d1SPhilip Reames                                         Instruction *Guard) {
732ca450878SMax Kazantsev   unsigned NumWidened = 0;
7338fb3d57eSArtur Pilipenko   // The guard condition is expected to be in form of:
7348fb3d57eSArtur Pilipenko   //   cond1 && cond2 && cond3 ...
7350909ca13SHiroshi Inoue   // Iterate over subconditions looking for icmp conditions which can be
7368fb3d57eSArtur Pilipenko   // widened across loop iterations. Widening these conditions remember the
7378fb3d57eSArtur Pilipenko   // resulting list of subconditions in Checks vector.
738ca450878SMax Kazantsev   SmallVector<Value *, 4> Worklist(1, Condition);
7398fb3d57eSArtur Pilipenko   SmallPtrSet<Value *, 4> Visited;
740adb3ece2SPhilip Reames   Value *WideableCond = nullptr;
7418fb3d57eSArtur Pilipenko   do {
7428fb3d57eSArtur Pilipenko     Value *Condition = Worklist.pop_back_val();
7438fb3d57eSArtur Pilipenko     if (!Visited.insert(Condition).second)
7448fb3d57eSArtur Pilipenko       continue;
7458fb3d57eSArtur Pilipenko 
7468fb3d57eSArtur Pilipenko     Value *LHS, *RHS;
7478fb3d57eSArtur Pilipenko     using namespace llvm::PatternMatch;
7488fb3d57eSArtur Pilipenko     if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
7498fb3d57eSArtur Pilipenko       Worklist.push_back(LHS);
7508fb3d57eSArtur Pilipenko       Worklist.push_back(RHS);
7518fb3d57eSArtur Pilipenko       continue;
7528fb3d57eSArtur Pilipenko     }
7538fb3d57eSArtur Pilipenko 
754adb3ece2SPhilip Reames     if (match(Condition,
755adb3ece2SPhilip Reames               m_Intrinsic<Intrinsic::experimental_widenable_condition>())) {
756adb3ece2SPhilip Reames       // Pick any, we don't care which
757adb3ece2SPhilip Reames       WideableCond = Condition;
758adb3ece2SPhilip Reames       continue;
759adb3ece2SPhilip Reames     }
760adb3ece2SPhilip Reames 
7618fb3d57eSArtur Pilipenko     if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
7623d4e1082SPhilip Reames       if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander,
763e46d77d1SPhilip Reames                                                    Guard)) {
7648fb3d57eSArtur Pilipenko         Checks.push_back(NewRangeCheck.getValue());
7658fb3d57eSArtur Pilipenko         NumWidened++;
7668fb3d57eSArtur Pilipenko         continue;
7678fb3d57eSArtur Pilipenko       }
7688fb3d57eSArtur Pilipenko     }
7698fb3d57eSArtur Pilipenko 
7708fb3d57eSArtur Pilipenko     // Save the condition as is if we can't widen it
7718fb3d57eSArtur Pilipenko     Checks.push_back(Condition);
772ca450878SMax Kazantsev   } while (!Worklist.empty());
773adb3ece2SPhilip Reames   // At the moment, our matching logic for wideable conditions implicitly
774adb3ece2SPhilip Reames   // assumes we preserve the form: (br (and Cond, WC())).  FIXME
775adb3ece2SPhilip Reames   // Note that if there were multiple calls to wideable condition in the
776adb3ece2SPhilip Reames   // traversal, we only need to keep one, and which one is arbitrary.
777adb3ece2SPhilip Reames   if (WideableCond)
778adb3ece2SPhilip Reames     Checks.push_back(WideableCond);
779ca450878SMax Kazantsev   return NumWidened;
780ca450878SMax Kazantsev }
7818fb3d57eSArtur Pilipenko 
782ca450878SMax Kazantsev bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
783ca450878SMax Kazantsev                                            SCEVExpander &Expander) {
784ca450878SMax Kazantsev   LLVM_DEBUG(dbgs() << "Processing guard:\n");
785ca450878SMax Kazantsev   LLVM_DEBUG(Guard->dump());
786ca450878SMax Kazantsev 
787ca450878SMax Kazantsev   TotalConsidered++;
788ca450878SMax Kazantsev   SmallVector<Value *, 4> Checks;
789ca450878SMax Kazantsev   unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander,
790e46d77d1SPhilip Reames                                       Guard);
7918fb3d57eSArtur Pilipenko   if (NumWidened == 0)
7928fb3d57eSArtur Pilipenko     return false;
7938fb3d57eSArtur Pilipenko 
794c297e84bSFedor Sergeev   TotalWidened += NumWidened;
795c297e84bSFedor Sergeev 
7968fb3d57eSArtur Pilipenko   // Emit the new guard condition
797e46d77d1SPhilip Reames   IRBuilder<> Builder(findInsertPt(Guard, Checks));
7989e62c864SPhilip Reames   Value *AllChecks = Builder.CreateAnd(Checks);
799d109e2a7SPhilip Reames   auto *OldCond = Guard->getOperand(0);
8009e62c864SPhilip Reames   Guard->setOperand(0, AllChecks);
801d109e2a7SPhilip Reames   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
8028fb3d57eSArtur Pilipenko 
803d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
8048fb3d57eSArtur Pilipenko   return true;
8058fb3d57eSArtur Pilipenko }
8068fb3d57eSArtur Pilipenko 
807feb475f4SMax Kazantsev bool LoopPredication::widenWidenableBranchGuardConditions(
808f608678fSPhilip Reames     BranchInst *BI, SCEVExpander &Expander) {
809f608678fSPhilip Reames   assert(isGuardAsWidenableBranch(BI) && "Must be!");
810feb475f4SMax Kazantsev   LLVM_DEBUG(dbgs() << "Processing guard:\n");
811f608678fSPhilip Reames   LLVM_DEBUG(BI->dump());
812feb475f4SMax Kazantsev 
813feb475f4SMax Kazantsev   TotalConsidered++;
814feb475f4SMax Kazantsev   SmallVector<Value *, 4> Checks;
815adb3ece2SPhilip Reames   unsigned NumWidened = collectChecks(Checks, BI->getCondition(),
816e46d77d1SPhilip Reames                                       Expander, BI);
817feb475f4SMax Kazantsev   if (NumWidened == 0)
818feb475f4SMax Kazantsev     return false;
819feb475f4SMax Kazantsev 
820feb475f4SMax Kazantsev   TotalWidened += NumWidened;
821feb475f4SMax Kazantsev 
822feb475f4SMax Kazantsev   // Emit the new guard condition
823e46d77d1SPhilip Reames   IRBuilder<> Builder(findInsertPt(BI, Checks));
8249e62c864SPhilip Reames   Value *AllChecks = Builder.CreateAnd(Checks);
825adb3ece2SPhilip Reames   auto *OldCond = BI->getCondition();
8269e62c864SPhilip Reames   BI->setCondition(AllChecks);
827686f449eSPhilip Reames   RecursivelyDeleteTriviallyDeadInstructions(OldCond);
828f608678fSPhilip Reames   assert(isGuardAsWidenableBranch(BI) &&
829feb475f4SMax Kazantsev          "Stopped being a guard after transform?");
830feb475f4SMax Kazantsev 
831feb475f4SMax Kazantsev   LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
832feb475f4SMax Kazantsev   return true;
833feb475f4SMax Kazantsev }
834feb475f4SMax Kazantsev 
835099eca83SPhilip Reames Optional<LoopICmp> LoopPredication::parseLoopLatchICmp() {
836889dc1e3SArtur Pilipenko   using namespace PatternMatch;
837889dc1e3SArtur Pilipenko 
838889dc1e3SArtur Pilipenko   BasicBlock *LoopLatch = L->getLoopLatch();
839889dc1e3SArtur Pilipenko   if (!LoopLatch) {
840d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
841889dc1e3SArtur Pilipenko     return None;
842889dc1e3SArtur Pilipenko   }
843889dc1e3SArtur Pilipenko 
84419afdf74SPhilip Reames   auto *BI = dyn_cast<BranchInst>(LoopLatch->getTerminator());
845101915cfSPhilip Reames   if (!BI || !BI->isConditional()) {
846d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n");
847889dc1e3SArtur Pilipenko     return None;
848889dc1e3SArtur Pilipenko   }
84919afdf74SPhilip Reames   BasicBlock *TrueDest = BI->getSuccessor(0);
8504e875464SRichard Trieu   assert(
8514e875464SRichard Trieu       (TrueDest == L->getHeader() || BI->getSuccessor(1) == L->getHeader()) &&
852889dc1e3SArtur Pilipenko       "One of the latch's destinations must be the header");
853889dc1e3SArtur Pilipenko 
85419afdf74SPhilip Reames   auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
855101915cfSPhilip Reames   if (!ICI) {
85619afdf74SPhilip Reames     LLVM_DEBUG(dbgs() << "Failed to match the latch condition!\n");
85719afdf74SPhilip Reames     return None;
85819afdf74SPhilip Reames   }
85919afdf74SPhilip Reames   auto Result = parseLoopICmp(ICI);
860889dc1e3SArtur Pilipenko   if (!Result) {
861d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
862889dc1e3SArtur Pilipenko     return None;
863889dc1e3SArtur Pilipenko   }
864889dc1e3SArtur Pilipenko 
86519afdf74SPhilip Reames   if (TrueDest != L->getHeader())
86619afdf74SPhilip Reames     Result->Pred = ICmpInst::getInversePredicate(Result->Pred);
86719afdf74SPhilip Reames 
868889dc1e3SArtur Pilipenko   // Check affine first, so if it's not we don't try to compute the step
869889dc1e3SArtur Pilipenko   // recurrence.
870889dc1e3SArtur Pilipenko   if (!Result->IV->isAffine()) {
871d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n");
872889dc1e3SArtur Pilipenko     return None;
873889dc1e3SArtur Pilipenko   }
874889dc1e3SArtur Pilipenko 
875889dc1e3SArtur Pilipenko   auto *Step = Result->IV->getStepRecurrence(*SE);
87668797214SAnna Thomas   if (!isSupportedStep(Step)) {
877d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
878889dc1e3SArtur Pilipenko     return None;
879889dc1e3SArtur Pilipenko   }
880889dc1e3SArtur Pilipenko 
88168797214SAnna Thomas   auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
8827b360434SAnna Thomas     if (Step->isOne()) {
88368797214SAnna Thomas       return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
88468797214SAnna Thomas              Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
8857b360434SAnna Thomas     } else {
8867b360434SAnna Thomas       assert(Step->isAllOnesValue() && "Step should be -1!");
887c8016e7aSSerguei Katkov       return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT &&
888c8016e7aSSerguei Katkov              Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE;
8897b360434SAnna Thomas     }
89068797214SAnna Thomas   };
89168797214SAnna Thomas 
892099eca83SPhilip Reames   normalizePredicate(SE, L, *Result);
89368797214SAnna Thomas   if (IsUnsupportedPredicate(Step, Result->Pred)) {
894d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
89568797214SAnna Thomas                       << ")!\n");
89668797214SAnna Thomas     return None;
89768797214SAnna Thomas   }
89819afdf74SPhilip Reames 
899889dc1e3SArtur Pilipenko   return Result;
900889dc1e3SArtur Pilipenko }
901889dc1e3SArtur Pilipenko 
9021d02b13eSAnna Thomas 
9039b1176b0SAnna Thomas bool LoopPredication::isLoopProfitableToPredicate() {
9049b1176b0SAnna Thomas   if (SkipProfitabilityChecks || !BPI)
9059b1176b0SAnna Thomas     return true;
9069b1176b0SAnna Thomas 
907c6caddb7SSerguei Katkov   SmallVector<std::pair<BasicBlock *, BasicBlock *>, 8> ExitEdges;
9089b1176b0SAnna Thomas   L->getExitEdges(ExitEdges);
9099b1176b0SAnna Thomas   // If there is only one exiting edge in the loop, it is always profitable to
9109b1176b0SAnna Thomas   // predicate the loop.
9119b1176b0SAnna Thomas   if (ExitEdges.size() == 1)
9129b1176b0SAnna Thomas     return true;
9139b1176b0SAnna Thomas 
9149b1176b0SAnna Thomas   // Calculate the exiting probabilities of all exiting edges from the loop,
9159b1176b0SAnna Thomas   // starting with the LatchExitProbability.
9169b1176b0SAnna Thomas   // Heuristic for profitability: If any of the exiting blocks' probability of
9179b1176b0SAnna Thomas   // exiting the loop is larger than exiting through the latch block, it's not
9189b1176b0SAnna Thomas   // profitable to predicate the loop.
9199b1176b0SAnna Thomas   auto *LatchBlock = L->getLoopLatch();
9209b1176b0SAnna Thomas   assert(LatchBlock && "Should have a single latch at this point!");
9219b1176b0SAnna Thomas   auto *LatchTerm = LatchBlock->getTerminator();
9229b1176b0SAnna Thomas   assert(LatchTerm->getNumSuccessors() == 2 &&
9239b1176b0SAnna Thomas          "expected to be an exiting block with 2 succs!");
9249b1176b0SAnna Thomas   unsigned LatchBrExitIdx =
9259b1176b0SAnna Thomas       LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0;
9269b1176b0SAnna Thomas   BranchProbability LatchExitProbability =
9279b1176b0SAnna Thomas       BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx);
9289b1176b0SAnna Thomas 
9299b1176b0SAnna Thomas   // Protect against degenerate inputs provided by the user. Providing a value
9309b1176b0SAnna Thomas   // less than one, can invert the definition of profitable loop predication.
9319b1176b0SAnna Thomas   float ScaleFactor = LatchExitProbabilityScale;
9329b1176b0SAnna Thomas   if (ScaleFactor < 1) {
933d34e60caSNicola Zaghen     LLVM_DEBUG(
9349b1176b0SAnna Thomas         dbgs()
9359b1176b0SAnna Thomas         << "Ignored user setting for loop-predication-latch-probability-scale: "
9369b1176b0SAnna Thomas         << LatchExitProbabilityScale << "\n");
937d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "The value is set to 1.0\n");
9389b1176b0SAnna Thomas     ScaleFactor = 1.0;
9399b1176b0SAnna Thomas   }
9409b1176b0SAnna Thomas   const auto LatchProbabilityThreshold =
9419b1176b0SAnna Thomas       LatchExitProbability * ScaleFactor;
9429b1176b0SAnna Thomas 
9439b1176b0SAnna Thomas   for (const auto &ExitEdge : ExitEdges) {
9449b1176b0SAnna Thomas     BranchProbability ExitingBlockProbability =
9459b1176b0SAnna Thomas         BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second);
9469b1176b0SAnna Thomas     // Some exiting edge has higher probability than the latch exiting edge.
9479b1176b0SAnna Thomas     // No longer profitable to predicate.
9489b1176b0SAnna Thomas     if (ExitingBlockProbability > LatchProbabilityThreshold)
9499b1176b0SAnna Thomas       return false;
9509b1176b0SAnna Thomas   }
9519b1176b0SAnna Thomas   // Using BPI, we have concluded that the most probable way to exit from the
9529b1176b0SAnna Thomas   // loop is through the latch (or there's no profile information and all
9539b1176b0SAnna Thomas   // exits are equally likely).
9549b1176b0SAnna Thomas   return true;
9559b1176b0SAnna Thomas }
9569b1176b0SAnna Thomas 
9578fb3d57eSArtur Pilipenko bool LoopPredication::runOnLoop(Loop *Loop) {
9588fb3d57eSArtur Pilipenko   L = Loop;
9598fb3d57eSArtur Pilipenko 
960d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Analyzing ");
961d34e60caSNicola Zaghen   LLVM_DEBUG(L->dump());
9628fb3d57eSArtur Pilipenko 
9638fb3d57eSArtur Pilipenko   Module *M = L->getHeader()->getModule();
9648fb3d57eSArtur Pilipenko 
9658fb3d57eSArtur Pilipenko   // There is nothing to do if the module doesn't use guards
9668fb3d57eSArtur Pilipenko   auto *GuardDecl =
9678fb3d57eSArtur Pilipenko       M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
968feb475f4SMax Kazantsev   bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty();
969feb475f4SMax Kazantsev   auto *WCDecl = M->getFunction(
970feb475f4SMax Kazantsev       Intrinsic::getName(Intrinsic::experimental_widenable_condition));
971feb475f4SMax Kazantsev   bool HasWidenableConditions =
972feb475f4SMax Kazantsev       PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty();
973feb475f4SMax Kazantsev   if (!HasIntrinsicGuards && !HasWidenableConditions)
9748fb3d57eSArtur Pilipenko     return false;
9758fb3d57eSArtur Pilipenko 
9768fb3d57eSArtur Pilipenko   DL = &M->getDataLayout();
9778fb3d57eSArtur Pilipenko 
9788fb3d57eSArtur Pilipenko   Preheader = L->getLoopPreheader();
9798fb3d57eSArtur Pilipenko   if (!Preheader)
9808fb3d57eSArtur Pilipenko     return false;
9818fb3d57eSArtur Pilipenko 
982889dc1e3SArtur Pilipenko   auto LatchCheckOpt = parseLoopLatchICmp();
983889dc1e3SArtur Pilipenko   if (!LatchCheckOpt)
984889dc1e3SArtur Pilipenko     return false;
985889dc1e3SArtur Pilipenko   LatchCheck = *LatchCheckOpt;
986889dc1e3SArtur Pilipenko 
987d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Latch check:\n");
988d34e60caSNicola Zaghen   LLVM_DEBUG(LatchCheck.dump());
98968797214SAnna Thomas 
9909b1176b0SAnna Thomas   if (!isLoopProfitableToPredicate()) {
991d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n");
9929b1176b0SAnna Thomas     return false;
9939b1176b0SAnna Thomas   }
9948fb3d57eSArtur Pilipenko   // Collect all the guards into a vector and process later, so as not
9958fb3d57eSArtur Pilipenko   // to invalidate the instruction iterator.
9968fb3d57eSArtur Pilipenko   SmallVector<IntrinsicInst *, 4> Guards;
997feb475f4SMax Kazantsev   SmallVector<BranchInst *, 4> GuardsAsWidenableBranches;
998feb475f4SMax Kazantsev   for (const auto BB : L->blocks()) {
9998fb3d57eSArtur Pilipenko     for (auto &I : *BB)
100028298e96SMax Kazantsev       if (isGuard(&I))
100128298e96SMax Kazantsev         Guards.push_back(cast<IntrinsicInst>(&I));
1002feb475f4SMax Kazantsev     if (PredicateWidenableBranchGuards &&
1003feb475f4SMax Kazantsev         isGuardAsWidenableBranch(BB->getTerminator()))
1004feb475f4SMax Kazantsev       GuardsAsWidenableBranches.push_back(
1005feb475f4SMax Kazantsev           cast<BranchInst>(BB->getTerminator()));
1006feb475f4SMax Kazantsev   }
10078fb3d57eSArtur Pilipenko 
1008feb475f4SMax Kazantsev   if (Guards.empty() && GuardsAsWidenableBranches.empty())
100946c4e0a4SArtur Pilipenko     return false;
101046c4e0a4SArtur Pilipenko 
10118fb3d57eSArtur Pilipenko   SCEVExpander Expander(*SE, *DL, "loop-predication");
10128fb3d57eSArtur Pilipenko 
10138fb3d57eSArtur Pilipenko   bool Changed = false;
10148fb3d57eSArtur Pilipenko   for (auto *Guard : Guards)
10158fb3d57eSArtur Pilipenko     Changed |= widenGuardConditions(Guard, Expander);
1016feb475f4SMax Kazantsev   for (auto *Guard : GuardsAsWidenableBranches)
1017feb475f4SMax Kazantsev     Changed |= widenWidenableBranchGuardConditions(Guard, Expander);
10188fb3d57eSArtur Pilipenko 
10198fb3d57eSArtur Pilipenko   return Changed;
10208fb3d57eSArtur Pilipenko }
1021