blob: 8487278d3d616c0612b8bf193054466099a682f2 [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"
Anna Thomas9b1176b2018-03-22 16:03:59 +0000181#include "llvm/Analysis/BranchProbabilityInfo.h"
Max Kazantsev28298e92018-12-26 08:22:25 +0000182#include "llvm/Analysis/GuardUtils.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000183#include "llvm/Analysis/LoopInfo.h"
184#include "llvm/Analysis/LoopPass.h"
185#include "llvm/Analysis/ScalarEvolution.h"
186#include "llvm/Analysis/ScalarEvolutionExpander.h"
187#include "llvm/Analysis/ScalarEvolutionExpressions.h"
188#include "llvm/IR/Function.h"
189#include "llvm/IR/GlobalValue.h"
190#include "llvm/IR/IntrinsicInst.h"
191#include "llvm/IR/Module.h"
192#include "llvm/IR/PatternMatch.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000193#include "llvm/Pass.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000194#include "llvm/Support/Debug.h"
195#include "llvm/Transforms/Scalar.h"
Philip Reamesd109e2a2019-04-01 16:05:15 +0000196#include "llvm/Transforms/Utils/Local.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000197#include "llvm/Transforms/Utils/LoopUtils.h"
198
199#define DEBUG_TYPE "loop-predication"
200
Fedor Sergeevc297e842018-10-17 09:02:54 +0000201STATISTIC(TotalConsidered, "Number of guards considered");
202STATISTIC(TotalWidened, "Number of checks widened");
203
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000204using namespace llvm;
205
Anna Thomas1d02b132017-11-02 21:21:02 +0000206static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
207 cl::Hidden, cl::init(true));
208
Anna Thomas7b360432017-12-04 15:11:48 +0000209static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
210 cl::Hidden, cl::init(true));
Anna Thomas9b1176b2018-03-22 16:03:59 +0000211
212static cl::opt<bool>
213 SkipProfitabilityChecks("loop-predication-skip-profitability-checks",
214 cl::Hidden, cl::init(false));
215
216// This is the scale factor for the latch probability. We use this during
217// profitability analysis to find other exiting blocks that have a much higher
218// probability of exiting the loop instead of loop exiting via latch.
219// This value should be greater than 1 for a sane profitability check.
220static cl::opt<float> LatchExitProbabilityScale(
221 "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0),
222 cl::desc("scale factor for the latch probability. Value should be greater "
223 "than 1. Lower values are ignored"));
224
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000225static cl::opt<bool> PredicateWidenableBranchGuards(
226 "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden,
227 cl::desc("Whether or not we should predicate guards "
228 "expressed as widenable branches to deoptimize blocks"),
229 cl::init(true));
230
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000231namespace {
232class LoopPredication {
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000233 /// Represents an induction variable check:
234 /// icmp Pred, <induction variable>, <loop invariant limit>
235 struct LoopICmp {
236 ICmpInst::Predicate Pred;
237 const SCEVAddRecExpr *IV;
238 const SCEV *Limit;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000239 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
240 const SCEV *Limit)
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000241 : Pred(Pred), IV(IV), Limit(Limit) {}
242 LoopICmp() {}
Anna Thomas68797212017-11-03 14:25:39 +0000243 void dump() {
244 dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
245 << ", Limit = " << *Limit << "\n";
246 }
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000247 };
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000248
249 ScalarEvolution *SE;
Anna Thomas9b1176b2018-03-22 16:03:59 +0000250 BranchProbabilityInfo *BPI;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000251
252 Loop *L;
253 const DataLayout *DL;
254 BasicBlock *Preheader;
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000255 LoopICmp LatchCheck;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000256
Anna Thomas68797212017-11-03 14:25:39 +0000257 bool isSupportedStep(const SCEV* Step);
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000258 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) {
259 return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0),
260 ICI->getOperand(1));
261 }
262 Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
263 Value *RHS);
264
265 Optional<LoopICmp> parseLoopLatchICmp();
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000266
Anna Thomas68797212017-11-03 14:25:39 +0000267 bool CanExpand(const SCEV* S);
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000268 Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder,
Philip Reames3d4e1082019-03-29 23:06:57 +0000269 ICmpInst::Predicate Pred, const SCEV *LHS,
270 const SCEV *RHS);
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000271
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000272 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
273 IRBuilder<> &Builder);
Anna Thomas68797212017-11-03 14:25:39 +0000274 Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
275 LoopICmp RangeCheck,
276 SCEVExpander &Expander,
277 IRBuilder<> &Builder);
Anna Thomas7b360432017-12-04 15:11:48 +0000278 Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
279 LoopICmp RangeCheck,
280 SCEVExpander &Expander,
281 IRBuilder<> &Builder);
Max Kazantsevca450872019-01-22 10:13:36 +0000282 unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition,
283 SCEVExpander &Expander, IRBuilder<> &Builder);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000284 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000285 bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander);
Anna Thomas9b1176b2018-03-22 16:03:59 +0000286 // If the loop always exits through another block in the loop, we should not
287 // predicate based on the latch check. For example, the latch check can be a
288 // very coarse grained check and there can be more fine grained exit checks
289 // within the loop. We identify such unprofitable loops through BPI.
290 bool isLoopProfitableToPredicate();
291
Anna Thomas1d02b132017-11-02 21:21:02 +0000292 // When the IV type is wider than the range operand type, we can still do loop
293 // predication, by generating SCEVs for the range and latch that are of the
294 // same type. We achieve this by generating a SCEV truncate expression for the
295 // latch IV. This is done iff truncation of the IV is a safe operation,
296 // without loss of information.
297 // Another way to achieve this is by generating a wider type SCEV for the
298 // range check operand, however, this needs a more involved check that
299 // operands do not overflow. This can lead to loss of information when the
300 // range operand is of the form: add i32 %offset, %iv. We need to prove that
301 // sext(x + y) is same as sext(x) + sext(y).
302 // This function returns true if we can safely represent the IV type in
303 // the RangeCheckType without loss of information.
304 bool isSafeToTruncateWideIVType(Type *RangeCheckType);
305 // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do
306 // so.
307 Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType);
Serguei Katkovebc90312018-02-07 06:53:37 +0000308
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000309public:
Anna Thomas9b1176b2018-03-22 16:03:59 +0000310 LoopPredication(ScalarEvolution *SE, BranchProbabilityInfo *BPI)
311 : SE(SE), BPI(BPI){};
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000312 bool runOnLoop(Loop *L);
313};
314
315class LoopPredicationLegacyPass : public LoopPass {
316public:
317 static char ID;
318 LoopPredicationLegacyPass() : LoopPass(ID) {
319 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
320 }
321
322 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anna Thomas9b1176b2018-03-22 16:03:59 +0000323 AU.addRequired<BranchProbabilityInfoWrapperPass>();
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000324 getLoopAnalysisUsage(AU);
325 }
326
327 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
328 if (skipLoop(L))
329 return false;
330 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
Anna Thomas9b1176b2018-03-22 16:03:59 +0000331 BranchProbabilityInfo &BPI =
332 getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
333 LoopPredication LP(SE, &BPI);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000334 return LP.runOnLoop(L);
335 }
336};
337
338char LoopPredicationLegacyPass::ID = 0;
339} // end namespace llvm
340
341INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
342 "Loop predication", false, false)
Anna Thomas9b1176b2018-03-22 16:03:59 +0000343INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000344INITIALIZE_PASS_DEPENDENCY(LoopPass)
345INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
346 "Loop predication", false, false)
347
348Pass *llvm::createLoopPredicationPass() {
349 return new LoopPredicationLegacyPass();
350}
351
352PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
353 LoopStandardAnalysisResults &AR,
354 LPMUpdater &U) {
Anna Thomas9b1176b2018-03-22 16:03:59 +0000355 const auto &FAM =
356 AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
357 Function *F = L.getHeader()->getParent();
358 auto *BPI = FAM.getCachedResult<BranchProbabilityAnalysis>(*F);
359 LoopPredication LP(&AR.SE, BPI);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000360 if (!LP.runOnLoop(&L))
361 return PreservedAnalyses::all();
362
363 return getLoopPassPreservedAnalyses();
364}
365
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000366Optional<LoopPredication::LoopICmp>
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000367LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
368 Value *RHS) {
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,
391 IRBuilder<> &Builder,
392 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
397 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
398 return Builder.getTrue();
Philip Reames05e3e552019-04-01 16:26:08 +0000399 if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred),
400 LHS, RHS))
401 return Builder.getFalse();
Artur Pilipenkoead69ee2017-10-12 21:21:17 +0000402
Philip Reames3d4e1082019-03-29 23:06:57 +0000403 Instruction *InsertAt = &*Builder.GetInsertPoint();
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000404 Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt);
405 Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt);
406 return Builder.CreateICmp(Pred, LHSV, RHSV);
407}
408
Anna Thomas1d02b132017-11-02 21:21:02 +0000409Optional<LoopPredication::LoopICmp>
410LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) {
411
412 auto *LatchType = LatchCheck.IV->getType();
413 if (RangeCheckType == LatchType)
414 return LatchCheck;
415 // For now, bail out if latch type is narrower than range type.
416 if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType))
417 return None;
418 if (!isSafeToTruncateWideIVType(RangeCheckType))
419 return None;
420 // We can now safely identify the truncated version of the IV and limit for
421 // RangeCheckType.
422 LoopICmp NewLatchCheck;
423 NewLatchCheck.Pred = LatchCheck.Pred;
424 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
425 SE->getTruncateExpr(LatchCheck.IV, RangeCheckType));
426 if (!NewLatchCheck.IV)
427 return None;
428 NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType);
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000429 LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType
430 << "can be represented as range check type:"
431 << *RangeCheckType << "\n");
432 LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
433 LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
Anna Thomas1d02b132017-11-02 21:21:02 +0000434 return NewLatchCheck;
435}
436
Anna Thomas68797212017-11-03 14:25:39 +0000437bool LoopPredication::isSupportedStep(const SCEV* Step) {
Anna Thomas7b360432017-12-04 15:11:48 +0000438 return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
Anna Thomas68797212017-11-03 14:25:39 +0000439}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000440
Anna Thomas68797212017-11-03 14:25:39 +0000441bool LoopPredication::CanExpand(const SCEV* S) {
442 return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
443}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000444
Anna Thomas68797212017-11-03 14:25:39 +0000445Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
446 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
447 SCEVExpander &Expander, IRBuilder<> &Builder) {
448 auto *Ty = RangeCheck.IV->getType();
449 // Generate the widened condition for the forward loop:
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000450 // guardStart u< guardLimit &&
451 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000452 // where <pred> depends on the latch condition predicate. See the file
453 // header comment for the reasoning.
Anna Thomas68797212017-11-03 14:25:39 +0000454 // guardLimit - guardStart + latchStart - 1
455 const SCEV *GuardStart = RangeCheck.IV->getStart();
456 const SCEV *GuardLimit = RangeCheck.Limit;
457 const SCEV *LatchStart = LatchCheck.IV->getStart();
458 const SCEV *LatchLimit = LatchCheck.Limit;
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000459
460 // guardLimit - guardStart + latchStart - 1
461 const SCEV *RHS =
462 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
463 SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
Anna Thomas68797212017-11-03 14:25:39 +0000464 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
465 !CanExpand(LatchLimit) || !CanExpand(RHS)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000466 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000467 return None;
468 }
Serguei Katkov3cb4c342018-02-09 07:59:07 +0000469 auto LimitCheckPred =
470 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
Artur Pilipenkoaab28662017-05-19 14:00:04 +0000471
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000472 LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
473 LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n");
474 LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
Philip Reames3d4e1082019-03-29 23:06:57 +0000475
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000476 auto *LimitCheck =
Philip Reames3d4e1082019-03-29 23:06:57 +0000477 expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS);
Anna Thomas68797212017-11-03 14:25:39 +0000478 auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck.Pred,
Philip Reames3d4e1082019-03-29 23:06:57 +0000479 GuardStart, GuardLimit);
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000480 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000481}
Anna Thomas7b360432017-12-04 15:11:48 +0000482
483Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
484 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
485 SCEVExpander &Expander, IRBuilder<> &Builder) {
486 auto *Ty = RangeCheck.IV->getType();
487 const SCEV *GuardStart = RangeCheck.IV->getStart();
488 const SCEV *GuardLimit = RangeCheck.Limit;
489 const SCEV *LatchLimit = LatchCheck.Limit;
490 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
491 !CanExpand(LatchLimit)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000492 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
Anna Thomas7b360432017-12-04 15:11:48 +0000493 return None;
494 }
495 // The decrement of the latch check IV should be the same as the
496 // rangeCheckIV.
497 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
498 if (RangeCheck.IV != PostDecLatchCheckIV) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000499 LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
500 << *PostDecLatchCheckIV
501 << " and RangeCheckIV: " << *RangeCheck.IV << "\n");
Anna Thomas7b360432017-12-04 15:11:48 +0000502 return None;
503 }
504
505 // Generate the widened condition for CountDownLoop:
506 // guardStart u< guardLimit &&
507 // latchLimit <pred> 1.
508 // See the header comment for reasoning of the checks.
Serguei Katkov3cb4c342018-02-09 07:59:07 +0000509 auto LimitCheckPred =
510 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
Anna Thomas7b360432017-12-04 15:11:48 +0000511 auto *FirstIterationCheck = expandCheck(Expander, Builder, ICmpInst::ICMP_ULT,
Philip Reames3d4e1082019-03-29 23:06:57 +0000512 GuardStart, GuardLimit);
Anna Thomas7b360432017-12-04 15:11:48 +0000513 auto *LimitCheck = expandCheck(Expander, Builder, LimitCheckPred, LatchLimit,
Philip Reames3d4e1082019-03-29 23:06:57 +0000514 SE->getOne(Ty));
Anna Thomas7b360432017-12-04 15:11:48 +0000515 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
516}
517
Anna Thomas68797212017-11-03 14:25:39 +0000518/// If ICI can be widened to a loop invariant condition emits the loop
519/// invariant condition in the loop preheader and return it, otherwise
520/// returns None.
521Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
522 SCEVExpander &Expander,
523 IRBuilder<> &Builder) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000524 LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
525 LLVM_DEBUG(ICI->dump());
Anna Thomas68797212017-11-03 14:25:39 +0000526
527 // parseLoopStructure guarantees that the latch condition is:
528 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
529 // We are looking for the range checks of the form:
530 // i u< guardLimit
531 auto RangeCheck = parseLoopICmp(ICI);
532 if (!RangeCheck) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000533 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000534 return None;
535 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000536 LLVM_DEBUG(dbgs() << "Guard check:\n");
537 LLVM_DEBUG(RangeCheck->dump());
Anna Thomas68797212017-11-03 14:25:39 +0000538 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000539 LLVM_DEBUG(dbgs() << "Unsupported range check predicate("
540 << RangeCheck->Pred << ")!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000541 return None;
542 }
543 auto *RangeCheckIV = RangeCheck->IV;
544 if (!RangeCheckIV->isAffine()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000545 LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000546 return None;
547 }
548 auto *Step = RangeCheckIV->getStepRecurrence(*SE);
549 // We cannot just compare with latch IV step because the latch and range IVs
550 // may have different types.
551 if (!isSupportedStep(Step)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000552 LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000553 return None;
554 }
555 auto *Ty = RangeCheckIV->getType();
556 auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty);
557 if (!CurrLatchCheckOpt) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000558 LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check "
559 "corresponding to range type: "
560 << *Ty << "\n");
Anna Thomas68797212017-11-03 14:25:39 +0000561 return None;
562 }
563
564 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
Anna Thomas7b360432017-12-04 15:11:48 +0000565 // At this point, the range and latch step should have the same type, but need
566 // not have the same value (we support both 1 and -1 steps).
567 assert(Step->getType() ==
568 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
569 "Range and latch steps should be of same type!");
570 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000571 LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n");
Anna Thomas7b360432017-12-04 15:11:48 +0000572 return None;
573 }
Anna Thomas68797212017-11-03 14:25:39 +0000574
Anna Thomas7b360432017-12-04 15:11:48 +0000575 if (Step->isOne())
576 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
577 Expander, Builder);
578 else {
579 assert(Step->isAllOnesValue() && "Step should be -1!");
580 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
581 Expander, Builder);
582 }
Anna Thomas68797212017-11-03 14:25:39 +0000583}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000584
Max Kazantsevca450872019-01-22 10:13:36 +0000585unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks,
586 Value *Condition,
587 SCEVExpander &Expander,
588 IRBuilder<> &Builder) {
589 unsigned NumWidened = 0;
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000590 // The guard condition is expected to be in form of:
591 // cond1 && cond2 && cond3 ...
Hiroshi Inoue0909ca12018-01-26 08:15:29 +0000592 // Iterate over subconditions looking for icmp conditions which can be
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000593 // widened across loop iterations. Widening these conditions remember the
594 // resulting list of subconditions in Checks vector.
Max Kazantsevca450872019-01-22 10:13:36 +0000595 SmallVector<Value *, 4> Worklist(1, Condition);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000596 SmallPtrSet<Value *, 4> Visited;
Philip Reamesadb3ece2019-04-02 02:42:57 +0000597 Value *WideableCond = nullptr;
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000598 do {
599 Value *Condition = Worklist.pop_back_val();
600 if (!Visited.insert(Condition).second)
601 continue;
602
603 Value *LHS, *RHS;
604 using namespace llvm::PatternMatch;
605 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
606 Worklist.push_back(LHS);
607 Worklist.push_back(RHS);
608 continue;
609 }
610
Philip Reamesadb3ece2019-04-02 02:42:57 +0000611 if (match(Condition,
612 m_Intrinsic<Intrinsic::experimental_widenable_condition>())) {
613 // Pick any, we don't care which
614 WideableCond = Condition;
615 continue;
616 }
617
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000618 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
Philip Reames3d4e1082019-03-29 23:06:57 +0000619 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander,
620 Builder)) {
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000621 Checks.push_back(NewRangeCheck.getValue());
622 NumWidened++;
623 continue;
624 }
625 }
626
627 // Save the condition as is if we can't widen it
628 Checks.push_back(Condition);
Max Kazantsevca450872019-01-22 10:13:36 +0000629 } while (!Worklist.empty());
Philip Reamesadb3ece2019-04-02 02:42:57 +0000630 // At the moment, our matching logic for wideable conditions implicitly
631 // assumes we preserve the form: (br (and Cond, WC())). FIXME
632 // Note that if there were multiple calls to wideable condition in the
633 // traversal, we only need to keep one, and which one is arbitrary.
634 if (WideableCond)
635 Checks.push_back(WideableCond);
Max Kazantsevca450872019-01-22 10:13:36 +0000636 return NumWidened;
637}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000638
Max Kazantsevca450872019-01-22 10:13:36 +0000639bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
640 SCEVExpander &Expander) {
641 LLVM_DEBUG(dbgs() << "Processing guard:\n");
642 LLVM_DEBUG(Guard->dump());
643
644 TotalConsidered++;
645 SmallVector<Value *, 4> Checks;
646 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
647 unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander,
648 Builder);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000649 if (NumWidened == 0)
650 return false;
651
Fedor Sergeevc297e842018-10-17 09:02:54 +0000652 TotalWidened += NumWidened;
653
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000654 // Emit the new guard condition
655 Builder.SetInsertPoint(Guard);
656 Value *LastCheck = nullptr;
657 for (auto *Check : Checks)
658 if (!LastCheck)
659 LastCheck = Check;
660 else
661 LastCheck = Builder.CreateAnd(LastCheck, Check);
Philip Reamesd109e2a2019-04-01 16:05:15 +0000662 auto *OldCond = Guard->getOperand(0);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000663 Guard->setOperand(0, LastCheck);
Philip Reamesd109e2a2019-04-01 16:05:15 +0000664 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000665
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000666 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000667 return true;
668}
669
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000670bool LoopPredication::widenWidenableBranchGuardConditions(
Philip Reamesf6086782019-04-01 22:39:54 +0000671 BranchInst *BI, SCEVExpander &Expander) {
672 assert(isGuardAsWidenableBranch(BI) && "Must be!");
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000673 LLVM_DEBUG(dbgs() << "Processing guard:\n");
Philip Reamesf6086782019-04-01 22:39:54 +0000674 LLVM_DEBUG(BI->dump());
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000675
676 TotalConsidered++;
677 SmallVector<Value *, 4> Checks;
678 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
Philip Reamesadb3ece2019-04-02 02:42:57 +0000679 unsigned NumWidened = collectChecks(Checks, BI->getCondition(),
680 Expander, Builder);
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000681 if (NumWidened == 0)
682 return false;
683
684 TotalWidened += NumWidened;
685
686 // Emit the new guard condition
Philip Reamesf6086782019-04-01 22:39:54 +0000687 Builder.SetInsertPoint(BI);
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000688 Value *LastCheck = nullptr;
689 for (auto *Check : Checks)
690 if (!LastCheck)
691 LastCheck = Check;
692 else
693 LastCheck = Builder.CreateAnd(LastCheck, Check);
Philip Reamesadb3ece2019-04-02 02:42:57 +0000694 auto *OldCond = BI->getCondition();
695 BI->setCondition(LastCheck);
Philip Reamesf6086782019-04-01 22:39:54 +0000696 assert(isGuardAsWidenableBranch(BI) &&
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000697 "Stopped being a guard after transform?");
Philip Reamesd109e2a2019-04-01 16:05:15 +0000698 RecursivelyDeleteTriviallyDeadInstructions(OldCond);
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000699
700 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
701 return true;
702}
703
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000704Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() {
705 using namespace PatternMatch;
706
707 BasicBlock *LoopLatch = L->getLoopLatch();
708 if (!LoopLatch) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000709 LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000710 return None;
711 }
712
713 ICmpInst::Predicate Pred;
714 Value *LHS, *RHS;
715 BasicBlock *TrueDest, *FalseDest;
716
717 if (!match(LoopLatch->getTerminator(),
718 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest,
719 FalseDest))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000720 LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000721 return None;
722 }
723 assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) &&
724 "One of the latch's destinations must be the header");
725 if (TrueDest != L->getHeader())
726 Pred = ICmpInst::getInversePredicate(Pred);
727
728 auto Result = parseLoopICmp(Pred, LHS, RHS);
729 if (!Result) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000730 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000731 return None;
732 }
733
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000734 // Check affine first, so if it's not we don't try to compute the step
735 // recurrence.
736 if (!Result->IV->isAffine()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000737 LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000738 return None;
739 }
740
741 auto *Step = Result->IV->getStepRecurrence(*SE);
Anna Thomas68797212017-11-03 14:25:39 +0000742 if (!isSupportedStep(Step)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000743 LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000744 return None;
745 }
746
Anna Thomas68797212017-11-03 14:25:39 +0000747 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
Anna Thomas7b360432017-12-04 15:11:48 +0000748 if (Step->isOne()) {
749 return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
750 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
751 } else {
752 assert(Step->isAllOnesValue() && "Step should be -1!");
Serguei Katkovc8016e72018-02-08 10:34:08 +0000753 return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT &&
754 Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE;
Anna Thomas7b360432017-12-04 15:11:48 +0000755 }
Anna Thomas68797212017-11-03 14:25:39 +0000756 };
757
758 if (IsUnsupportedPredicate(Step, Result->Pred)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000759 LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
760 << ")!\n");
Anna Thomas68797212017-11-03 14:25:39 +0000761 return None;
762 }
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000763 return Result;
764}
765
Anna Thomas1d02b132017-11-02 21:21:02 +0000766// Returns true if its safe to truncate the IV to RangeCheckType.
767bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) {
768 if (!EnableIVTruncation)
769 return false;
770 assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) >
771 DL->getTypeSizeInBits(RangeCheckType) &&
772 "Expected latch check IV type to be larger than range check operand "
773 "type!");
774 // The start and end values of the IV should be known. This is to guarantee
775 // that truncating the wide type will not lose information.
776 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
777 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
778 if (!Limit || !Start)
779 return false;
780 // This check makes sure that the IV does not change sign during loop
781 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
782 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
783 // IV wraps around, and the truncation of the IV would lose the range of
784 // iterations between 2^32 and 2^64.
785 bool Increasing;
786 if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing))
787 return false;
788 // The active bits should be less than the bits in the RangeCheckType. This
789 // guarantees that truncating the latch check to RangeCheckType is a safe
790 // operation.
791 auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType);
792 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
793 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
794}
795
Anna Thomas9b1176b2018-03-22 16:03:59 +0000796bool LoopPredication::isLoopProfitableToPredicate() {
797 if (SkipProfitabilityChecks || !BPI)
798 return true;
799
800 SmallVector<std::pair<const BasicBlock *, const BasicBlock *>, 8> ExitEdges;
801 L->getExitEdges(ExitEdges);
802 // If there is only one exiting edge in the loop, it is always profitable to
803 // predicate the loop.
804 if (ExitEdges.size() == 1)
805 return true;
806
807 // Calculate the exiting probabilities of all exiting edges from the loop,
808 // starting with the LatchExitProbability.
809 // Heuristic for profitability: If any of the exiting blocks' probability of
810 // exiting the loop is larger than exiting through the latch block, it's not
811 // profitable to predicate the loop.
812 auto *LatchBlock = L->getLoopLatch();
813 assert(LatchBlock && "Should have a single latch at this point!");
814 auto *LatchTerm = LatchBlock->getTerminator();
815 assert(LatchTerm->getNumSuccessors() == 2 &&
816 "expected to be an exiting block with 2 succs!");
817 unsigned LatchBrExitIdx =
818 LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0;
819 BranchProbability LatchExitProbability =
820 BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx);
821
822 // Protect against degenerate inputs provided by the user. Providing a value
823 // less than one, can invert the definition of profitable loop predication.
824 float ScaleFactor = LatchExitProbabilityScale;
825 if (ScaleFactor < 1) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000826 LLVM_DEBUG(
Anna Thomas9b1176b2018-03-22 16:03:59 +0000827 dbgs()
828 << "Ignored user setting for loop-predication-latch-probability-scale: "
829 << LatchExitProbabilityScale << "\n");
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000830 LLVM_DEBUG(dbgs() << "The value is set to 1.0\n");
Anna Thomas9b1176b2018-03-22 16:03:59 +0000831 ScaleFactor = 1.0;
832 }
833 const auto LatchProbabilityThreshold =
834 LatchExitProbability * ScaleFactor;
835
836 for (const auto &ExitEdge : ExitEdges) {
837 BranchProbability ExitingBlockProbability =
838 BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second);
839 // Some exiting edge has higher probability than the latch exiting edge.
840 // No longer profitable to predicate.
841 if (ExitingBlockProbability > LatchProbabilityThreshold)
842 return false;
843 }
844 // Using BPI, we have concluded that the most probable way to exit from the
845 // loop is through the latch (or there's no profile information and all
846 // exits are equally likely).
847 return true;
848}
849
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000850bool LoopPredication::runOnLoop(Loop *Loop) {
851 L = Loop;
852
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000853 LLVM_DEBUG(dbgs() << "Analyzing ");
854 LLVM_DEBUG(L->dump());
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000855
856 Module *M = L->getHeader()->getModule();
857
858 // There is nothing to do if the module doesn't use guards
859 auto *GuardDecl =
860 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000861 bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty();
862 auto *WCDecl = M->getFunction(
863 Intrinsic::getName(Intrinsic::experimental_widenable_condition));
864 bool HasWidenableConditions =
865 PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty();
866 if (!HasIntrinsicGuards && !HasWidenableConditions)
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000867 return false;
868
869 DL = &M->getDataLayout();
870
871 Preheader = L->getLoopPreheader();
872 if (!Preheader)
873 return false;
874
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000875 auto LatchCheckOpt = parseLoopLatchICmp();
876 if (!LatchCheckOpt)
877 return false;
878 LatchCheck = *LatchCheckOpt;
879
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000880 LLVM_DEBUG(dbgs() << "Latch check:\n");
881 LLVM_DEBUG(LatchCheck.dump());
Anna Thomas68797212017-11-03 14:25:39 +0000882
Anna Thomas9b1176b2018-03-22 16:03:59 +0000883 if (!isLoopProfitableToPredicate()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000884 LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n");
Anna Thomas9b1176b2018-03-22 16:03:59 +0000885 return false;
886 }
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000887 // Collect all the guards into a vector and process later, so as not
888 // to invalidate the instruction iterator.
889 SmallVector<IntrinsicInst *, 4> Guards;
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000890 SmallVector<BranchInst *, 4> GuardsAsWidenableBranches;
891 for (const auto BB : L->blocks()) {
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000892 for (auto &I : *BB)
Max Kazantsev28298e92018-12-26 08:22:25 +0000893 if (isGuard(&I))
894 Guards.push_back(cast<IntrinsicInst>(&I));
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000895 if (PredicateWidenableBranchGuards &&
896 isGuardAsWidenableBranch(BB->getTerminator()))
897 GuardsAsWidenableBranches.push_back(
898 cast<BranchInst>(BB->getTerminator()));
899 }
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000900
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000901 if (Guards.empty() && GuardsAsWidenableBranches.empty())
Artur Pilipenko46c4e0a2017-05-19 13:59:34 +0000902 return false;
903
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000904 SCEVExpander Expander(*SE, *DL, "loop-predication");
905
906 bool Changed = false;
907 for (auto *Guard : Guards)
908 Changed |= widenGuardConditions(Guard, Expander);
Max Kazantsevfeb475f2019-01-22 11:49:06 +0000909 for (auto *Guard : GuardsAsWidenableBranches)
910 Changed |= widenWidenableBranchGuardConditions(Guard, Expander);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000911
912 return Changed;
913}