blob: f02fdd90974368b75ffeea8c3cf3d5a55d417d1a [file] [log] [blame]
Artur Pilipenko8fb3d572017-01-25 16:00:44 +00001//===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Artur Pilipenko8fb3d572017-01-25 16:00:44 +00006//
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//
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000036// 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//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000055// if (B(0)) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000056// do {
Artur Pilipenko8aadc642017-10-27 14:46:17 +000057// I = PHI(0, I.INC)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000058// I.INC = I + Step
59// guard(G(I));
Artur Pilipenko8aadc642017-10-27 14:46:17 +000060// } while (B(I));
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000061// }
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//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000067// if (B(0)) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000068// do {
Artur Pilipenko8aadc642017-10-27 14:46:17 +000069// I = PHI(0, I.INC)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000070// I.INC = I + Step
Artur Pilipenko8aadc642017-10-27 14:46:17 +000071// guard(G(0) && M);
72// } while (B(I));
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000073// }
74//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000075// One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
Fangrui Songf78650a2018-07-30 19:41:25 +000076//
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000077// Informal proof that the transformation above is correct:
78//
79// By the definition of guards we can rewrite the guard condition to:
Artur Pilipenko8aadc642017-10-27 14:46:17 +000080// G(I) && G(0) && M
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000081//
82// Let's prove that for each iteration of the loop:
Artur Pilipenko8aadc642017-10-27 14:46:17 +000083// G(0) && M => G(I)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000084// And the condition above can be simplified to G(Start) && M.
Fangrui Songf78650a2018-07-30 19:41:25 +000085//
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000086// Induction base.
Artur Pilipenko8aadc642017-10-27 14:46:17 +000087// G(0) && M => G(0)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000088//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000089// Induction step. Assuming G(0) && M => G(I) on the subsequent
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000090// iteration:
91//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000092// B(I) is true because it's the backedge condition.
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000093// G(I) is true because the backedge is guarded by this condition.
94//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000095// So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000096//
97// Note that we can use anything stronger than M, i.e. any condition which
98// implies M.
99//
Anna Thomas7b360432017-12-04 15:11:48 +0000100// When S = 1 (i.e. forward iterating loop), the transformation is supported
101// when:
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000102// * The loop has a single latch with the condition of the form:
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000103// B(X) = latchStart + X <pred> latchLimit,
104// where <pred> is u<, u<=, s<, or s<=.
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000105// * The guard condition is of the form
106// G(X) = guardStart + X u< guardLimit
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000107//
Anna Thomas7b360432017-12-04 15:11:48 +0000108// 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
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000111//
Anna Thomas7b360432017-12-04 15:11:48 +0000112// 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
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000120//
Anna Thomas7b360432017-12-04 15:11:48 +0000121// 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);)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000126//
Anna Thomas7b360432017-12-04 15:11:48 +0000127// 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
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000140//
Anna Thomas7b360432017-12-04 15:11:48 +0000141// 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
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000153//
Anna Thomas7b360432017-12-04 15:11:48 +0000154// 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:
Serguei Katkovc8016e72018-02-08 10:34:08 +0000157// B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=.
Anna Thomas7b360432017-12-04 15:11:48 +0000158// * 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.
Serguei Katkovc8016e72018-02-08 10:34:08 +0000173// 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.
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000177//===----------------------------------------------------------------------===//
178
179#include "llvm/Transforms/Scalar/LoopPredication.h"
Fedor Sergeevc297e842018-10-17 09:02:54 +0000180#include "llvm/ADT/Statistic.h"
Philip Reames92a71772019-04-18 16:33:17 +0000181#include "llvm/Analysis/AliasAnalysis.h"
Anna Thomas9b1176b2018-03-22 16:03:59 +0000182#include "llvm/Analysis/BranchProbabilityInfo.h"
Max Kazantsev28298e92018-12-26 08:22:25 +0000183#include "llvm/Analysis/GuardUtils.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000184#include "llvm/Analysis/LoopInfo.h"
185#include "llvm/Analysis/LoopPass.h"
186#include "llvm/Analysis/ScalarEvolution.h"
187#include "llvm/Analysis/ScalarEvolutionExpander.h"
188#include "llvm/Analysis/ScalarEvolutionExpressions.h"
189#include "llvm/IR/Function.h"
190#include "llvm/IR/GlobalValue.h"
191#include "llvm/IR/IntrinsicInst.h"
192#include "llvm/IR/Module.h"
193#include "llvm/IR/PatternMatch.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -0800194#include "llvm/InitializePasses.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000195#include "llvm/Pass.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000196#include "llvm/Support/Debug.h"
197#include "llvm/Transforms/Scalar.h"
Philip Reamesd109e2a2019-04-01 16:05:15 +0000198#include "llvm/Transforms/Utils/Local.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000199#include "llvm/Transforms/Utils/LoopUtils.h"
200
201#define DEBUG_TYPE "loop-predication"
202
Fedor Sergeevc297e842018-10-17 09:02:54 +0000203STATISTIC(TotalConsidered, "Number of guards considered");
204STATISTIC(TotalWidened, "Number of checks widened");
205
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000206using namespace llvm;
207
Anna Thomas1d02b132017-11-02 21:21:02 +0000208static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
209 cl::Hidden, cl::init(true));
210
Anna Thomas7b360432017-12-04 15:11:48 +0000211static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
212 cl::Hidden, cl::init(true));
Anna Thomas9b1176b2018-03-22 16:03:59 +0000213
214static cl::opt<bool>
215 SkipProfitabilityChecks("loop-predication-skip-profitability-checks",
216 cl::Hidden, cl::init(false));
217
218// This is the scale factor for the latch probability. We use this during
219// profitability analysis to find other exiting blocks that have a much higher
220// probability of exiting the loop instead of loop exiting via latch.
221// This value should be greater than 1 for a sane profitability check.
222static cl::opt<float> LatchExitProbabilityScale(
223 "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0),
224 cl::desc("scale factor for the latch probability. Value should be greater "
225 "than 1. Lower values are ignored"));
226
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000227static cl::opt<bool> PredicateWidenableBranchGuards(
228 "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden,
229 cl::desc("Whether or not we should predicate guards "
230 "expressed as widenable branches to deoptimize blocks"),
231 cl::init(true));
232
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000233namespace {
Philip Reames099eca82019-06-01 00:31:58 +0000234/// Represents an induction variable check:
235/// icmp Pred, <induction variable>, <loop invariant limit>
236struct LoopICmp {
237 ICmpInst::Predicate Pred;
238 const SCEVAddRecExpr *IV;
239 const SCEV *Limit;
240 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
241 const SCEV *Limit)
242 : Pred(Pred), IV(IV), Limit(Limit) {}
243 LoopICmp() {}
244 void dump() {
245 dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
246 << ", Limit = " << *Limit << "\n";
247 }
248};
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000249
Philip Reames099eca82019-06-01 00:31:58 +0000250class LoopPredication {
Philip Reames92a71772019-04-18 16:33:17 +0000251 AliasAnalysis *AA;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000252 ScalarEvolution *SE;
Anna Thomas9b1176b2018-03-22 16:03:59 +0000253 BranchProbabilityInfo *BPI;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000254
255 Loop *L;
256 const DataLayout *DL;
257 BasicBlock *Preheader;
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000258 LoopICmp LatchCheck;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000259
Anna Thomas68797212017-11-03 14:25:39 +0000260 bool isSupportedStep(const SCEV* Step);
Philip Reames19afdf72019-06-01 03:09:28 +0000261 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI);
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000262 Optional<LoopICmp> parseLoopLatchICmp();
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000263
Philip Reamesfbe64a22019-04-15 15:53:25 +0000264 /// Return an insertion point suitable for inserting a safe to speculate
265 /// instruction whose only user will be 'User' which has operands 'Ops'. A
266 /// trivial result would be the at the User itself, but we try to return a
267 /// loop invariant location if possible.
268 Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops);
Philip Reamese46d77d2019-04-15 18:15:08 +0000269 /// Same as above, *except* that this uses the SCEV definition of invariant
270 /// which is that an expression *can be made* invariant via SCEVExpander.
271 /// Thus, this version is only suitable for finding an insert point to be be
272 /// passed to SCEVExpander!
273 Instruction *findInsertPt(Instruction *User, ArrayRef<const SCEV*> Ops);
Philip Reamesfbe64a22019-04-15 15:53:25 +0000274
Philip Reames92a71772019-04-18 16:33:17 +0000275 /// Return true if the value is known to produce a single fixed value across
276 /// all iterations on which it executes. Note that this does not imply
277 /// speculation safety. That must be established seperately.
278 bool isLoopInvariantValue(const SCEV* S);
279
Philip Reamese46d77d2019-04-15 18:15:08 +0000280 Value *expandCheck(SCEVExpander &Expander, Instruction *Guard,
Philip Reames3d4e1082019-03-29 23:06:57 +0000281 ICmpInst::Predicate Pred, const SCEV *LHS,
282 const SCEV *RHS);
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000283
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000284 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
Philip Reamese46d77d2019-04-15 18:15:08 +0000285 Instruction *Guard);
Anna Thomas68797212017-11-03 14:25:39 +0000286 Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
287 LoopICmp RangeCheck,
288 SCEVExpander &Expander,
Philip Reamese46d77d2019-04-15 18:15:08 +0000289 Instruction *Guard);
Anna Thomas7b360432017-12-04 15:11:48 +0000290 Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
291 LoopICmp RangeCheck,
292 SCEVExpander &Expander,
Philip Reamese46d77d2019-04-15 18:15:08 +0000293 Instruction *Guard);
Max Kazantsevca450872019-01-22 10:13:36 +0000294 unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition,
Philip Reamese46d77d2019-04-15 18:15:08 +0000295 SCEVExpander &Expander, Instruction *Guard);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000296 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000297 bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander);
Anna Thomas9b1176b2018-03-22 16:03:59 +0000298 // If the loop always exits through another block in the loop, we should not
299 // predicate based on the latch check. For example, the latch check can be a
300 // very coarse grained check and there can be more fine grained exit checks
301 // within the loop. We identify such unprofitable loops through BPI.
302 bool isLoopProfitableToPredicate();
303
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000304public:
Philip Reames92a71772019-04-18 16:33:17 +0000305 LoopPredication(AliasAnalysis *AA, ScalarEvolution *SE,
306 BranchProbabilityInfo *BPI)
307 : AA(AA), SE(SE), BPI(BPI){};
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000308 bool runOnLoop(Loop *L);
309};
310
311class LoopPredicationLegacyPass : public LoopPass {
312public:
313 static char ID;
314 LoopPredicationLegacyPass() : LoopPass(ID) {
315 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
316 }
317
318 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anna Thomas9b1176b2018-03-22 16:03:59 +0000319 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000320 getLoopAnalysisUsage(AU);
321 }
322
323 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
324 if (skipLoop(L))
325 return false;
326 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Anna Thomas9b1176b2018-03-22 16:03:59 +0000327 BranchProbabilityInfo &BPI =
328 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
Philip Reames92a71772019-04-18 16:33:17 +0000329 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
330 LoopPredication LP(AA, SE, &BPI);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000331 return LP.runOnLoop(L);
332 }
333};
334
335char LoopPredicationLegacyPass::ID = 0;
336} // end namespace llvm
337
338INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
339 "Loop predication", false, false)
Anna Thomas9b1176b2018-03-22 16:03:59 +0000340INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000341INITIALIZE_PASS_DEPENDENCY(LoopPass)
342INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
343 "Loop predication", false, false)
344
345Pass *llvm::createLoopPredicationPass() {
346 return new LoopPredicationLegacyPass();
347}
348
349PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
350 LoopStandardAnalysisResults &AR,
351 LPMUpdater &U) {
Anna Thomas9b1176b2018-03-22 16:03:59 +0000352 const auto &FAM =
353 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
354 Function *F = L.getHeader()->getParent();
355 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F);
Philip Reames92a71772019-04-18 16:33:17 +0000356 LoopPredication LP(&AR.AA, &AR.SE, BPI);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000357 if (!LP.runOnLoop(&L))
358 return PreservedAnalyses::all();
359
360 return getLoopPassPreservedAnalyses();
361}
362
Philip Reames099eca82019-06-01 00:31:58 +0000363Optional<LoopICmp>
Philip Reames19afdf72019-06-01 03:09:28 +0000364LoopPredication::parseLoopICmp(ICmpInst *ICI) {
365 auto Pred = ICI->getPredicate();
366 auto *LHS = ICI->getOperand(0);
367 auto *RHS = ICI->getOperand(1);
368
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000369 const SCEV *LHSS = SE->getSCEV(LHS);
370 if (isa<SCEVCouldNotCompute>(LHSS))
371 return None;
372 const SCEV *RHSS = SE->getSCEV(RHS);
373 if (isa<SCEVCouldNotCompute>(RHSS))
374 return None;
375
376 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
377 if (SE->isLoopInvariant(LHSS, L)) {
378 std::swap(LHS, RHS);
379 std::swap(LHSS, RHSS);
380 Pred = ICmpInst::getSwappedPredicate(Pred);
381 }
382
383 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
384 if (!AR || AR->getLoop() != L)
385 return None;
386
387 return LoopICmp(Pred, AR, RHSS);
388}
389
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000390Value *LoopPredication::expandCheck(SCEVExpander &Expander,
Philip Reamese46d77d2019-04-15 18:15:08 +0000391 Instruction *Guard,
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000392 ICmpInst::Predicate Pred, const SCEV *LHS,
Philip Reames3d4e1082019-03-29 23:06:57 +0000393 const SCEV *RHS) {
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000394 Type *Ty = LHS->getType();
395 assert(Ty == RHS->getType() && "expandCheck operands have different types?");
Artur Pilipenkoead69ee2017-10-12 21:21:17 +0000396
Philip Reamese46d77d2019-04-15 18:15:08 +0000397 if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) {
398 IRBuilder<> Builder(Guard);
399 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
400 return Builder.getTrue();
401 if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred),
402 LHS, RHS))
403 return Builder.getFalse();
404 }
Artur Pilipenkoead69ee2017-10-12 21:21:17 +0000405
Philip Reamese46d77d2019-04-15 18:15:08 +0000406 Value *LHSV = Expander.expandCodeFor(LHS, Ty, findInsertPt(Guard, {LHS}));
407 Value *RHSV = Expander.expandCodeFor(RHS, Ty, findInsertPt(Guard, {RHS}));
408 IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV}));
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000409 return Builder.CreateICmp(Pred, LHSV, RHSV);
410}
411
Philip Reames0912b062019-06-03 16:17:14 +0000412
413// Returns true if its safe to truncate the IV to RangeCheckType.
414// When the IV type is wider than the range operand type, we can still do loop
415// predication, by generating SCEVs for the range and latch that are of the
416// same type. We achieve this by generating a SCEV truncate expression for the
417// latch IV. This is done iff truncation of the IV is a safe operation,
418// without loss of information.
419// Another way to achieve this is by generating a wider type SCEV for the
420// range check operand, however, this needs a more involved check that
421// operands do not overflow. This can lead to loss of information when the
422// range operand is of the form: add i32 %offset, %iv. We need to prove that
423// sext(x + y) is same as sext(x) + sext(y).
424// This function returns true if we can safely represent the IV type in
425// the RangeCheckType without loss of information.
Philip Reames9ed16732019-06-03 16:23:20 +0000426static bool isSafeToTruncateWideIVType(const DataLayout &DL,
427 ScalarEvolution &SE,
428 const LoopICmp LatchCheck,
429 Type *RangeCheckType) {
Philip Reames0912b062019-06-03 16:17:14 +0000430 if (!EnableIVTruncation)
431 return false;
432 assert(DL.getTypeSizeInBits(LatchCheck.IV->getType()) >
433 DL.getTypeSizeInBits(RangeCheckType) &&
434 "Expected latch check IV type to be larger than range check operand "
435 "type!");
436 // The start and end values of the IV should be known. This is to guarantee
437 // that truncating the wide type will not lose information.
438 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
439 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
440 if (!Limit || !Start)
441 return false;
442 // This check makes sure that the IV does not change sign during loop
443 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
444 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
445 // IV wraps around, and the truncation of the IV would lose the range of
446 // iterations between 2^32 and 2^64.
447 bool Increasing;
448 if (!SE.isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing))
449 return false;
450 // The active bits should be less than the bits in the RangeCheckType. This
451 // guarantees that truncating the latch check to RangeCheckType is a safe
452 // operation.
453 auto RangeCheckTypeBitSize = DL.getTypeSizeInBits(RangeCheckType);
454 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
455 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
456}
457
458
Philip Reames9ed16732019-06-03 16:23:20 +0000459// Return an LoopICmp describing a latch check equivlent to LatchCheck but with
460// the requested type if safe to do so. May involve the use of a new IV.
461static Optional<LoopICmp> generateLoopLatchCheck(const DataLayout &DL,
462 ScalarEvolution &SE,
463 const LoopICmp LatchCheck,
464 Type *RangeCheckType) {
Anna Thomas1d02b132017-11-02 21:21:02 +0000465
466 auto *LatchType = LatchCheck.IV->getType();
467 if (RangeCheckType == LatchType)
468 return LatchCheck;
469 // For now, bail out if latch type is narrower than range type.
Philip Reames9ed16732019-06-03 16:23:20 +0000470 if (DL.getTypeSizeInBits(LatchType) < DL.getTypeSizeInBits(RangeCheckType))
Anna Thomas1d02b132017-11-02 21:21:02 +0000471 return None;
Philip Reames9ed16732019-06-03 16:23:20 +0000472 if (!isSafeToTruncateWideIVType(DL, SE, LatchCheck, RangeCheckType))
Anna Thomas1d02b132017-11-02 21:21:02 +0000473 return None;
474 // We can now safely identify the truncated version of the IV and limit for
475 // RangeCheckType.
476 LoopICmp NewLatchCheck;
477 NewLatchCheck.Pred = LatchCheck.Pred;
478 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
Philip Reames9ed16732019-06-03 16:23:20 +0000479 SE.getTruncateExpr(LatchCheck.IV, RangeCheckType));
Anna Thomas1d02b132017-11-02 21:21:02 +0000480 if (!NewLatchCheck.IV)
481 return None;
Philip Reames9ed16732019-06-03 16:23:20 +0000482 NewLatchCheck.Limit = SE.getTruncateExpr(LatchCheck.Limit, RangeCheckType);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000483 LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType
484 << "can be represented as range check type:"
485 << *RangeCheckType << "\n");
486 LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
487 LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
Anna Thomas1d02b132017-11-02 21:21:02 +0000488 return NewLatchCheck;
489}
490
Anna Thomas68797212017-11-03 14:25:39 +0000491bool LoopPredication::isSupportedStep(const SCEV* Step) {
Anna Thomas7b360432017-12-04 15:11:48 +0000492 return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
Anna Thomas68797212017-11-03 14:25:39 +0000493}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000494
Philip Reamesfbe64a22019-04-15 15:53:25 +0000495Instruction *LoopPredication::findInsertPt(Instruction *Use,
496 ArrayRef<Value*> Ops) {
497 for (Value *Op : Ops)
498 if (!L->isLoopInvariant(Op))
499 return Use;
500 return Preheader->getTerminator();
501}
502
Philip Reamese46d77d2019-04-15 18:15:08 +0000503Instruction *LoopPredication::findInsertPt(Instruction *Use,
504 ArrayRef<const SCEV*> Ops) {
Philip Reames92a71772019-04-18 16:33:17 +0000505 // Subtlety: SCEV considers things to be invariant if the value produced is
506 // the same across iterations. This is not the same as being able to
507 // evaluate outside the loop, which is what we actually need here.
Philip Reamese46d77d2019-04-15 18:15:08 +0000508 for (const SCEV *Op : Ops)
Philip Reames92a71772019-04-18 16:33:17 +0000509 if (!SE->isLoopInvariant(Op, L) ||
510 !isSafeToExpandAt(Op, Preheader->getTerminator(), *SE))
Philip Reamese46d77d2019-04-15 18:15:08 +0000511 return Use;
512 return Preheader->getTerminator();
513}
514
Philip Reames92a71772019-04-18 16:33:17 +0000515bool LoopPredication::isLoopInvariantValue(const SCEV* S) {
516 // Handling expressions which produce invariant results, but *haven't* yet
517 // been removed from the loop serves two important purposes.
518 // 1) Most importantly, it resolves a pass ordering cycle which would
519 // otherwise need us to iteration licm, loop-predication, and either
520 // loop-unswitch or loop-peeling to make progress on examples with lots of
521 // predicable range checks in a row. (Since, in the general case, we can't
522 // hoist the length checks until the dominating checks have been discharged
523 // as we can't prove doing so is safe.)
524 // 2) As a nice side effect, this exposes the value of peeling or unswitching
525 // much more obviously in the IR. Otherwise, the cost modeling for other
526 // transforms would end up needing to duplicate all of this logic to model a
527 // check which becomes predictable based on a modeled peel or unswitch.
528 //
529 // The cost of doing so in the worst case is an extra fill from the stack in
530 // the loop to materialize the loop invariant test value instead of checking
531 // against the original IV which is presumable in a register inside the loop.
532 // Such cases are presumably rare, and hint at missing oppurtunities for
533 // other passes.
Philip Reamese46d77d2019-04-15 18:15:08 +0000534
Philip Reames92a71772019-04-18 16:33:17 +0000535 if (SE->isLoopInvariant(S, L))
536 // Note: This the SCEV variant, so the original Value* may be within the
537 // loop even though SCEV has proven it is loop invariant.
538 return true;
539
540 // Handle a particular important case which SCEV doesn't yet know about which
541 // shows up in range checks on arrays with immutable lengths.
542 // TODO: This should be sunk inside SCEV.
543 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
544 if (const auto *LI = dyn_cast<LoadInst>(U->getValue()))
Philip Reamesadf288c2019-04-18 17:01:19 +0000545 if (LI->isUnordered() && L->hasLoopInvariantOperands(LI))
Philip Reames92a71772019-04-18 16:33:17 +0000546 if (AA->pointsToConstantMemory(LI->getOperand(0)) ||
Philip Reames27820f92019-09-04 17:28:48 +0000547 LI->hasMetadata(LLVMContext::MD_invariant_load))
Philip Reames92a71772019-04-18 16:33:17 +0000548 return true;
549 return false;
Anna Thomas68797212017-11-03 14:25:39 +0000550}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000551
Anna Thomas68797212017-11-03 14:25:39 +0000552Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
Philip Reames099eca82019-06-01 00:31:58 +0000553 LoopICmp LatchCheck, LoopICmp RangeCheck,
Philip Reamese46d77d2019-04-15 18:15:08 +0000554 SCEVExpander &Expander, Instruction *Guard) {
Anna Thomas68797212017-11-03 14:25:39 +0000555 auto *Ty = RangeCheck.IV->getType();
556 // Generate the widened condition for the forward loop:
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000557 // guardStart u< guardLimit &&
558 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000559 // where <pred> depends on the latch condition predicate. See the file
560 // header comment for the reasoning.
Anna Thomas68797212017-11-03 14:25:39 +0000561 // guardLimit - guardStart + latchStart - 1
562 const SCEV *GuardStart = RangeCheck.IV->getStart();
563 const SCEV *GuardLimit = RangeCheck.Limit;
564 const SCEV *LatchStart = LatchCheck.IV->getStart();
565 const SCEV *LatchLimit = LatchCheck.Limit;
Philip Reames92a71772019-04-18 16:33:17 +0000566 // Subtlety: We need all the values to be *invariant* across all iterations,
567 // but we only need to check expansion safety for those which *aren't*
568 // already guaranteed to dominate the guard.
569 if (!isLoopInvariantValue(GuardStart) ||
570 !isLoopInvariantValue(GuardLimit) ||
571 !isLoopInvariantValue(LatchStart) ||
572 !isLoopInvariantValue(LatchLimit)) {
573 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
574 return None;
575 }
576 if (!isSafeToExpandAt(LatchStart, Guard, *SE) ||
577 !isSafeToExpandAt(LatchLimit, Guard, *SE)) {
578 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
579 return None;
580 }
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000581
582 // guardLimit - guardStart + latchStart - 1
583 const SCEV *RHS =
584 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
585 SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
Serguei Katkov3cb4c342018-02-09 07:59:07 +0000586 auto LimitCheckPred =
587 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
Artur Pilipenkoaab28662017-05-19 14:00:04 +0000588
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000589 LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
590 LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n");
591 LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
Philip Reames3d4e1082019-03-29 23:06:57 +0000592
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000593 auto *LimitCheck =
Philip Reamese46d77d2019-04-15 18:15:08 +0000594 expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS);
595 auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred,
Philip Reames3d4e1082019-03-29 23:06:57 +0000596 GuardStart, GuardLimit);
Philip Reamese46d77d2019-04-15 18:15:08 +0000597 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000598 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000599}
Anna Thomas7b360432017-12-04 15:11:48 +0000600
601Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
Philip Reames099eca82019-06-01 00:31:58 +0000602 LoopICmp LatchCheck, LoopICmp RangeCheck,
Philip Reamese46d77d2019-04-15 18:15:08 +0000603 SCEVExpander &Expander, Instruction *Guard) {
Anna Thomas7b360432017-12-04 15:11:48 +0000604 auto *Ty = RangeCheck.IV->getType();
605 const SCEV *GuardStart = RangeCheck.IV->getStart();
606 const SCEV *GuardLimit = RangeCheck.Limit;
Philip Reames92a71772019-04-18 16:33:17 +0000607 const SCEV *LatchStart = LatchCheck.IV->getStart();
Anna Thomas7b360432017-12-04 15:11:48 +0000608 const SCEV *LatchLimit = LatchCheck.Limit;
Philip Reames92a71772019-04-18 16:33:17 +0000609 // Subtlety: We need all the values to be *invariant* across all iterations,
610 // but we only need to check expansion safety for those which *aren't*
611 // already guaranteed to dominate the guard.
612 if (!isLoopInvariantValue(GuardStart) ||
613 !isLoopInvariantValue(GuardLimit) ||
614 !isLoopInvariantValue(LatchStart) ||
615 !isLoopInvariantValue(LatchLimit)) {
616 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
617 return None;
618 }
619 if (!isSafeToExpandAt(LatchStart, Guard, *SE) ||
620 !isSafeToExpandAt(LatchLimit, Guard, *SE)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000621 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
Anna Thomas7b360432017-12-04 15:11:48 +0000622 return None;
623 }
624 // The decrement of the latch check IV should be the same as the
625 // rangeCheckIV.
626 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
627 if (RangeCheck.IV != PostDecLatchCheckIV) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000628 LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
629 << *PostDecLatchCheckIV
630 << " and RangeCheckIV: " << *RangeCheck.IV << "\n");
Anna Thomas7b360432017-12-04 15:11:48 +0000631 return None;
632 }
633
634 // Generate the widened condition for CountDownLoop:
635 // guardStart u< guardLimit &&
636 // latchLimit <pred> 1.
637 // See the header comment for reasoning of the checks.
Serguei Katkov3cb4c342018-02-09 07:59:07 +0000638 auto LimitCheckPred =
639 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
Philip Reamese46d77d2019-04-15 18:15:08 +0000640 auto *FirstIterationCheck = expandCheck(Expander, Guard,
641 ICmpInst::ICMP_ULT,
Philip Reames3d4e1082019-03-29 23:06:57 +0000642 GuardStart, GuardLimit);
Philip Reamese46d77d2019-04-15 18:15:08 +0000643 auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit,
Philip Reames3d4e1082019-03-29 23:06:57 +0000644 SE->getOne(Ty));
Philip Reamese46d77d2019-04-15 18:15:08 +0000645 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
Anna Thomas7b360432017-12-04 15:11:48 +0000646 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
647}
648
Philip Reames099eca82019-06-01 00:31:58 +0000649static void normalizePredicate(ScalarEvolution *SE, Loop *L,
650 LoopICmp& RC) {
Philip Reames0e344e92019-07-09 02:03:31 +0000651 // LFTR canonicalizes checks to the ICMP_NE/EQ form; normalize back to the
652 // ULT/UGE form for ease of handling by our caller.
653 if (ICmpInst::isEquality(RC.Pred) &&
Philip Reames099eca82019-06-01 00:31:58 +0000654 RC.IV->getStepRecurrence(*SE)->isOne() &&
655 SE->isKnownPredicate(ICmpInst::ICMP_ULE, RC.IV->getStart(), RC.Limit))
Philip Reames0e344e92019-07-09 02:03:31 +0000656 RC.Pred = RC.Pred == ICmpInst::ICMP_NE ?
657 ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
Philip Reames099eca82019-06-01 00:31:58 +0000658}
659
660
Anna Thomas68797212017-11-03 14:25:39 +0000661/// If ICI can be widened to a loop invariant condition emits the loop
662/// invariant condition in the loop preheader and return it, otherwise
663/// returns None.
664Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
665 SCEVExpander &Expander,
Philip Reamese46d77d2019-04-15 18:15:08 +0000666 Instruction *Guard) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000667 LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
668 LLVM_DEBUG(ICI->dump());
Anna Thomas68797212017-11-03 14:25:39 +0000669
670 // parseLoopStructure guarantees that the latch condition is:
671 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
672 // We are looking for the range checks of the form:
673 // i u< guardLimit
674 auto RangeCheck = parseLoopICmp(ICI);
675 if (!RangeCheck) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000676 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000677 return None;
678 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000679 LLVM_DEBUG(dbgs() << "Guard check:\n");
680 LLVM_DEBUG(RangeCheck->dump());
Anna Thomas68797212017-11-03 14:25:39 +0000681 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000682 LLVM_DEBUG(dbgs() << "Unsupported range check predicate("
683 << RangeCheck->Pred << ")!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000684 return None;
685 }
686 auto *RangeCheckIV = RangeCheck->IV;
687 if (!RangeCheckIV->isAffine()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000688 LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000689 return None;
690 }
691 auto *Step = RangeCheckIV->getStepRecurrence(*SE);
692 // We cannot just compare with latch IV step because the latch and range IVs
693 // may have different types.
694 if (!isSupportedStep(Step)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000695 LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000696 return None;
697 }
698 auto *Ty = RangeCheckIV->getType();
Philip Reames9ed16732019-06-03 16:23:20 +0000699 auto CurrLatchCheckOpt = generateLoopLatchCheck(*DL, *SE, LatchCheck, Ty);
Anna Thomas68797212017-11-03 14:25:39 +0000700 if (!CurrLatchCheckOpt) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000701 LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check "
702 "corresponding to range type: "
703 << *Ty << "\n");
Anna Thomas68797212017-11-03 14:25:39 +0000704 return None;
705 }
706
707 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
Anna Thomas7b360432017-12-04 15:11:48 +0000708 // At this point, the range and latch step should have the same type, but need
709 // not have the same value (we support both 1 and -1 steps).
710 assert(Step->getType() ==
711 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
712 "Range and latch steps should be of same type!");
713 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000714 LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n");
Anna Thomas7b360432017-12-04 15:11:48 +0000715 return None;
716 }
Anna Thomas68797212017-11-03 14:25:39 +0000717
Anna Thomas7b360432017-12-04 15:11:48 +0000718 if (Step->isOne())
719 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
Philip Reamese46d77d2019-04-15 18:15:08 +0000720 Expander, Guard);
Anna Thomas7b360432017-12-04 15:11:48 +0000721 else {
722 assert(Step->isAllOnesValue() && "Step should be -1!");
723 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
Philip Reamese46d77d2019-04-15 18:15:08 +0000724 Expander, Guard);
Anna Thomas7b360432017-12-04 15:11:48 +0000725 }
Anna Thomas68797212017-11-03 14:25:39 +0000726}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000727
Max Kazantsevca450872019-01-22 10:13:36 +0000728unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks,
729 Value *Condition,
730 SCEVExpander &Expander,
Philip Reamese46d77d2019-04-15 18:15:08 +0000731 Instruction *Guard) {
Max Kazantsevca450872019-01-22 10:13:36 +0000732 unsigned NumWidened = 0;
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000733 // The guard condition is expected to be in form of:
734 // cond1 && cond2 && cond3 ...
Hiroshi Inoue0909ca12018-01-26 08:15:29 +0000735 // Iterate over subconditions looking for icmp conditions which can be
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000736 // widened across loop iterations. Widening these conditions remember the
737 // resulting list of subconditions in Checks vector.
Max Kazantsevca450872019-01-22 10:13:36 +0000738 SmallVector<Value *, 4> Worklist(1, Condition);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000739 SmallPtrSet<Value *, 4> Visited;
Philip Reamesadb3ece2019-04-02 02:42:57 +0000740 Value *WideableCond = nullptr;
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000741 do {
742 Value *Condition = Worklist.pop_back_val();
743 if (!Visited.insert(Condition).second)
744 continue;
745
746 Value *LHS, *RHS;
747 using namespace llvm::PatternMatch;
748 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
749 Worklist.push_back(LHS);
750 Worklist.push_back(RHS);
751 continue;
752 }
753
Philip Reamesadb3ece2019-04-02 02:42:57 +0000754 if (match(Condition,
755 m_Intrinsic<Intrinsic::experimental_widenable_condition>())) {
756 // Pick any, we don't care which
757 WideableCond = Condition;
758 continue;
759 }
760
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000761 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
Philip Reames3d4e1082019-03-29 23:06:57 +0000762 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander,
Philip Reamese46d77d2019-04-15 18:15:08 +0000763 Guard)) {
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000764 Checks.push_back(NewRangeCheck.getValue());
765 NumWidened++;
766 continue;
767 }
768 }
769
770 // Save the condition as is if we can't widen it
771 Checks.push_back(Condition);
Max Kazantsevca450872019-01-22 10:13:36 +0000772 } while (!Worklist.empty());
Philip Reamesadb3ece2019-04-02 02:42:57 +0000773 // At the moment, our matching logic for wideable conditions implicitly
774 // assumes we preserve the form: (br (and Cond, WC())). FIXME
775 // Note that if there were multiple calls to wideable condition in the
776 // traversal, we only need to keep one, and which one is arbitrary.
777 if (WideableCond)
778 Checks.push_back(WideableCond);
Max Kazantsevca450872019-01-22 10:13:36 +0000779 return NumWidened;
780}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000781
Max Kazantsevca450872019-01-22 10:13:36 +0000782bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
783 SCEVExpander &Expander) {
784 LLVM_DEBUG(dbgs() << "Processing guard:\n");
785 LLVM_DEBUG(Guard->dump());
786
787 TotalConsidered++;
788 SmallVector<Value *, 4> Checks;
Max Kazantsevca450872019-01-22 10:13:36 +0000789 unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander,
Philip Reamese46d77d2019-04-15 18:15:08 +0000790 Guard);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000791 if (NumWidened == 0)
792 return false;
793
Fedor Sergeevc297e842018-10-17 09:02:54 +0000794 TotalWidened += NumWidened;
795
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000796 // Emit the new guard condition
Philip Reamese46d77d2019-04-15 18:15:08 +0000797 IRBuilder<> Builder(findInsertPt(Guard, Checks));
Philip Reames9e62c862019-07-06 03:46:18 +0000798 Value *AllChecks = Builder.CreateAnd(Checks);
Philip Reamesd109e2a2019-04-01 16:05:15 +0000799 auto *OldCond = Guard->getOperand(0);
Philip Reames9e62c862019-07-06 03:46:18 +0000800 Guard->setOperand(0, AllChecks);
Philip Reamesd109e2a2019-04-01 16:05:15 +0000801 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000802
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000803 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000804 return true;
805}
806
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000807bool LoopPredication::widenWidenableBranchGuardConditions(
Philip Reamesf6086782019-04-01 22:39:54 +0000808 BranchInst *BI, SCEVExpander &Expander) {
809 assert(isGuardAsWidenableBranch(BI) && "Must be!");
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000810 LLVM_DEBUG(dbgs() << "Processing guard:\n");
Philip Reamesf6086782019-04-01 22:39:54 +0000811 LLVM_DEBUG(BI->dump());
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000812
813 TotalConsidered++;
814 SmallVector<Value *, 4> Checks;
Philip Reamesadb3ece2019-04-02 02:42:57 +0000815 unsigned NumWidened = collectChecks(Checks, BI->getCondition(),
Philip Reamese46d77d2019-04-15 18:15:08 +0000816 Expander, BI);
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000817 if (NumWidened == 0)
818 return false;
819
820 TotalWidened += NumWidened;
821
822 // Emit the new guard condition
Philip Reamese46d77d2019-04-15 18:15:08 +0000823 IRBuilder<> Builder(findInsertPt(BI, Checks));
Philip Reames9e62c862019-07-06 03:46:18 +0000824 Value *AllChecks = Builder.CreateAnd(Checks);
Philip Reamesadb3ece2019-04-02 02:42:57 +0000825 auto *OldCond = BI->getCondition();
Philip Reames9e62c862019-07-06 03:46:18 +0000826 BI->setCondition(AllChecks);
Philip Reames686f4492019-11-06 14:05:59 -0800827 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Philip Reamesf6086782019-04-01 22:39:54 +0000828 assert(isGuardAsWidenableBranch(BI) &&
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000829 "Stopped being a guard after transform?");
830
831 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
832 return true;
833}
834
Philip Reames099eca82019-06-01 00:31:58 +0000835Optional<LoopICmp> LoopPredication::parseLoopLatchICmp() {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000836 using namespace PatternMatch;
837
838 BasicBlock *LoopLatch = L->getLoopLatch();
839 if (!LoopLatch) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000840 LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000841 return None;
842 }
843
Philip Reames19afdf72019-06-01 03:09:28 +0000844 auto *BI = dyn_cast<BranchInst>(LoopLatch->getTerminator());
Philip Reames101915c2019-06-06 18:02:36 +0000845 if (!BI || !BI->isConditional()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000846 LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000847 return None;
848 }
Philip Reames19afdf72019-06-01 03:09:28 +0000849 BasicBlock *TrueDest = BI->getSuccessor(0);
Richard Trieu4e875462019-06-01 03:32:20 +0000850 assert(
851 (TrueDest == L->getHeader() || BI->getSuccessor(1) == L->getHeader()) &&
852 "One of the latch's destinations must be the header");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000853
Philip Reames19afdf72019-06-01 03:09:28 +0000854 auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
Philip Reames101915c2019-06-06 18:02:36 +0000855 if (!ICI) {
Philip Reames19afdf72019-06-01 03:09:28 +0000856 LLVM_DEBUG(dbgs() << "Failed to match the latch condition!\n");
857 return None;
858 }
859 auto Result = parseLoopICmp(ICI);
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000860 if (!Result) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000861 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000862 return None;
863 }
864
Philip Reames19afdf72019-06-01 03:09:28 +0000865 if (TrueDest != L->getHeader())
866 Result->Pred = ICmpInst::getInversePredicate(Result->Pred);
867
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000868 // Check affine first, so if it's not we don't try to compute the step
869 // recurrence.
870 if (!Result->IV->isAffine()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000871 LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000872 return None;
873 }
874
875 auto *Step = Result->IV->getStepRecurrence(*SE);
Anna Thomas68797212017-11-03 14:25:39 +0000876 if (!isSupportedStep(Step)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000877 LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000878 return None;
879 }
880
Anna Thomas68797212017-11-03 14:25:39 +0000881 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
Anna Thomas7b360432017-12-04 15:11:48 +0000882 if (Step->isOne()) {
883 return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
884 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
885 } else {
886 assert(Step->isAllOnesValue() && "Step should be -1!");
Serguei Katkovc8016e72018-02-08 10:34:08 +0000887 return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT &&
888 Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE;
Anna Thomas7b360432017-12-04 15:11:48 +0000889 }
Anna Thomas68797212017-11-03 14:25:39 +0000890 };
891
Philip Reames099eca82019-06-01 00:31:58 +0000892 normalizePredicate(SE, L, *Result);
Anna Thomas68797212017-11-03 14:25:39 +0000893 if (IsUnsupportedPredicate(Step, Result->Pred)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000894 LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
895 << ")!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000896 return None;
897 }
Philip Reames19afdf72019-06-01 03:09:28 +0000898
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000899 return Result;
900}
901
Anna Thomas1d02b132017-11-02 21:21:02 +0000902
Anna Thomas9b1176b2018-03-22 16:03:59 +0000903bool LoopPredication::isLoopProfitableToPredicate() {
904 if (SkipProfitabilityChecks || !BPI)
905 return true;
906
Serguei Katkovc6caddb2019-07-09 04:20:43 +0000907 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 8> ExitEdges;
Anna Thomas9b1176b2018-03-22 16:03:59 +0000908 L->getExitEdges(ExitEdges);
909 // If there is only one exiting edge in the loop, it is always profitable to
910 // predicate the loop.
911 if (ExitEdges.size() == 1)
912 return true;
913
914 // Calculate the exiting probabilities of all exiting edges from the loop,
915 // starting with the LatchExitProbability.
916 // Heuristic for profitability: If any of the exiting blocks' probability of
917 // exiting the loop is larger than exiting through the latch block, it's not
918 // profitable to predicate the loop.
919 auto *LatchBlock = L->getLoopLatch();
920 assert(LatchBlock && "Should have a single latch at this point!");
921 auto *LatchTerm = LatchBlock->getTerminator();
922 assert(LatchTerm->getNumSuccessors() == 2 &&
923 "expected to be an exiting block with 2 succs!");
924 unsigned LatchBrExitIdx =
925 LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0;
926 BranchProbability LatchExitProbability =
927 BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx);
928
929 // Protect against degenerate inputs provided by the user. Providing a value
930 // less than one, can invert the definition of profitable loop predication.
931 float ScaleFactor = LatchExitProbabilityScale;
932 if (ScaleFactor < 1) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000933 LLVM_DEBUG(
Anna Thomas9b1176b2018-03-22 16:03:59 +0000934 dbgs()
935 << "Ignored user setting for loop-predication-latch-probability-scale: "
936 << LatchExitProbabilityScale << "\n");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000937 LLVM_DEBUG(dbgs() << "The value is set to 1.0\n");
Anna Thomas9b1176b2018-03-22 16:03:59 +0000938 ScaleFactor = 1.0;
939 }
940 const auto LatchProbabilityThreshold =
941 LatchExitProbability * ScaleFactor;
942
943 for (const auto &ExitEdge : ExitEdges) {
944 BranchProbability ExitingBlockProbability =
945 BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second);
946 // Some exiting edge has higher probability than the latch exiting edge.
947 // No longer profitable to predicate.
948 if (ExitingBlockProbability > LatchProbabilityThreshold)
949 return false;
950 }
951 // Using BPI, we have concluded that the most probable way to exit from the
952 // loop is through the latch (or there's no profile information and all
953 // exits are equally likely).
954 return true;
955}
956
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000957bool LoopPredication::runOnLoop(Loop *Loop) {
958 L = Loop;
959
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000960 LLVM_DEBUG(dbgs() << "Analyzing ");
961 LLVM_DEBUG(L->dump());
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000962
963 Module *M = L->getHeader()->getModule();
964
965 // There is nothing to do if the module doesn't use guards
966 auto *GuardDecl =
967 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000968 bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty();
969 auto *WCDecl = M->getFunction(
970 Intrinsic::getName(Intrinsic::experimental_widenable_condition));
971 bool HasWidenableConditions =
972 PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty();
973 if (!HasIntrinsicGuards && !HasWidenableConditions)
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000974 return false;
975
976 DL = &M->getDataLayout();
977
978 Preheader = L->getLoopPreheader();
979 if (!Preheader)
980 return false;
981
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000982 auto LatchCheckOpt = parseLoopLatchICmp();
983 if (!LatchCheckOpt)
984 return false;
985 LatchCheck = *LatchCheckOpt;
986
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000987 LLVM_DEBUG(dbgs() << "Latch check:\n");
988 LLVM_DEBUG(LatchCheck.dump());
Anna Thomas68797212017-11-03 14:25:39 +0000989
Anna Thomas9b1176b2018-03-22 16:03:59 +0000990 if (!isLoopProfitableToPredicate()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000991 LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n");
Anna Thomas9b1176b2018-03-22 16:03:59 +0000992 return false;
993 }
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000994 // Collect all the guards into a vector and process later, so as not
995 // to invalidate the instruction iterator.
996 SmallVector<IntrinsicInst *, 4> Guards;
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000997 SmallVector<BranchInst *, 4> GuardsAsWidenableBranches;
998 for (const auto BB : L->blocks()) {
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000999 for (auto &I : *BB)
Max Kazantsev28298e92018-12-26 08:22:25 +00001000 if (isGuard(&I))
1001 Guards.push_back(cast<IntrinsicInst>(&I));
Max Kazantsevfeb475f2019-01-22 11:49:06 +00001002 if (PredicateWidenableBranchGuards &&
1003 isGuardAsWidenableBranch(BB->getTerminator()))
1004 GuardsAsWidenableBranches.push_back(
1005 cast<BranchInst>(BB->getTerminator()));
1006 }
Artur Pilipenko8fb3d572017-01-25 16:00:44 +00001007
Max Kazantsevfeb475f2019-01-22 11:49:06 +00001008 if (Guards.empty() && GuardsAsWidenableBranches.empty())
Artur Pilipenko46c4e0a2017-05-19 13:59:34 +00001009 return false;
1010
Artur Pilipenko8fb3d572017-01-25 16:00:44 +00001011 SCEVExpander Expander(*SE, *DL, "loop-predication");
1012
1013 bool Changed = false;
1014 for (auto *Guard : Guards)
1015 Changed |= widenGuardConditions(Guard, Expander);
Max Kazantsevfeb475f2019-01-22 11:49:06 +00001016 for (auto *Guard : GuardsAsWidenableBranches)
1017 Changed |= widenWidenableBranchGuardConditions(Guard, Expander);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +00001018
1019 return Changed;
1020}