blob: 9a623be234fe877b6f602043a4ca9eeb2a62bfff [file] [log] [blame]
Artur Pilipenko8fb3d572017-01-25 16:00:44 +00001//===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// The LoopPredication pass tries to convert loop variant range checks to loop
11// invariant by widening checks across loop iterations. For example, it will
12// convert
13//
14// for (i = 0; i < n; i++) {
15// guard(i < len);
16// ...
17// }
18//
19// to
20//
21// for (i = 0; i < n; i++) {
22// guard(n - 1 < len);
23// ...
24// }
25//
26// After this transformation the condition of the guard is loop invariant, so
27// loop-unswitch can later unswitch the loop by this condition which basically
28// predicates the loop by the widened condition:
29//
30// if (n - 1 < len)
31// for (i = 0; i < n; i++) {
32// ...
33// }
34// else
35// deoptimize
36//
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000037// It's tempting to rely on SCEV here, but it has proven to be problematic.
38// Generally the facts SCEV provides about the increment step of add
39// recurrences are true if the backedge of the loop is taken, which implicitly
40// assumes that the guard doesn't fail. Using these facts to optimize the
41// guard results in a circular logic where the guard is optimized under the
42// assumption that it never fails.
43//
44// For example, in the loop below the induction variable will be marked as nuw
45// basing on the guard. Basing on nuw the guard predicate will be considered
46// monotonic. Given a monotonic condition it's tempting to replace the induction
47// variable in the condition with its value on the last iteration. But this
48// transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
49//
50// for (int i = b; i != e; i++)
51// guard(i u< len)
52//
53// One of the ways to reason about this problem is to use an inductive proof
54// approach. Given the loop:
55//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000056// if (B(0)) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000057// do {
Artur Pilipenko8aadc642017-10-27 14:46:17 +000058// I = PHI(0, I.INC)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000059// I.INC = I + Step
60// guard(G(I));
Artur Pilipenko8aadc642017-10-27 14:46:17 +000061// } while (B(I));
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000062// }
63//
64// where B(x) and G(x) are predicates that map integers to booleans, we want a
65// loop invariant expression M such the following program has the same semantics
66// as the above:
67//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000068// if (B(0)) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000069// do {
Artur Pilipenko8aadc642017-10-27 14:46:17 +000070// I = PHI(0, I.INC)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000071// I.INC = I + Step
Artur Pilipenko8aadc642017-10-27 14:46:17 +000072// guard(G(0) && M);
73// } while (B(I));
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000074// }
75//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000076// One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000077//
78// Informal proof that the transformation above is correct:
79//
80// By the definition of guards we can rewrite the guard condition to:
Artur Pilipenko8aadc642017-10-27 14:46:17 +000081// G(I) && G(0) && M
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000082//
83// Let's prove that for each iteration of the loop:
Artur Pilipenko8aadc642017-10-27 14:46:17 +000084// G(0) && M => G(I)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000085// And the condition above can be simplified to G(Start) && M.
86//
87// Induction base.
Artur Pilipenko8aadc642017-10-27 14:46:17 +000088// G(0) && M => G(0)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000089//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000090// Induction step. Assuming G(0) && M => G(I) on the subsequent
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000091// iteration:
92//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000093// B(I) is true because it's the backedge condition.
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000094// G(I) is true because the backedge is guarded by this condition.
95//
Artur Pilipenko8aadc642017-10-27 14:46:17 +000096// So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
Artur Pilipenko889dc1e2017-09-22 13:13:57 +000097//
98// Note that we can use anything stronger than M, i.e. any condition which
99// implies M.
100//
101// For now the transformation is limited to the following case:
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 Pilipenko889dc1e2017-09-22 13:13:57 +0000105// * The step of the IV used in the latch condition is 1.
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000106// * The guard condition is of the form
107// G(X) = guardStart + X u< guardLimit
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000108//
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000109// For the ult latch comparison case M is:
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000110// forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
111// guardStart + X + 1 u< guardLimit
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000112//
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000113// The only way the antecedent can be true and the consequent can be false is
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000114// if
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000115// X == guardLimit - 1 - guardStart
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000116// (and guardLimit is non-zero, but we won't use this latter fact).
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000117// If X == guardLimit - 1 - guardStart then the second half of the antecedent is
118// latchStart + guardLimit - 1 - guardStart u< latchLimit
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000119// and its negation is
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000120// latchStart + guardLimit - 1 - guardStart u>= latchLimit
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000121//
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000122// In other words, if
123// latchLimit u<= latchStart + guardLimit - 1 - guardStart
124// then:
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000125// (the ranges below are written in ConstantRange notation, where [A, B) is the
126// set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
127//
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000128// forall X . guardStart + X u< guardLimit &&
129// latchStart + X u< latchLimit =>
130// guardStart + X + 1 u< guardLimit
131// == forall X . guardStart + X u< guardLimit &&
132// latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
133// guardStart + X + 1 u< guardLimit
134// == forall X . (guardStart + X) in [0, guardLimit) &&
135// (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
136// (guardStart + X + 1) in [0, guardLimit)
137// == forall X . X in [-guardStart, guardLimit - guardStart) &&
138// X in [-latchStart, guardLimit - 1 - guardStart) =>
139// X in [-guardStart - 1, guardLimit - guardStart - 1)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000140// == true
141//
142// So the widened condition is:
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000143// guardStart u< guardLimit &&
144// latchStart + guardLimit - 1 - guardStart u>= latchLimit
145// Similarly for ule condition the widened condition is:
146// guardStart u< guardLimit &&
147// latchStart + guardLimit - 1 - guardStart u> latchLimit
148// For slt condition the widened condition is:
149// guardStart u< guardLimit &&
150// latchStart + guardLimit - 1 - guardStart s>= latchLimit
151// For sle condition the widened condition is:
152// guardStart u< guardLimit &&
153// latchStart + guardLimit - 1 - guardStart s> latchLimit
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000154//
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000155//===----------------------------------------------------------------------===//
156
157#include "llvm/Transforms/Scalar/LoopPredication.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000158#include "llvm/Analysis/LoopInfo.h"
159#include "llvm/Analysis/LoopPass.h"
160#include "llvm/Analysis/ScalarEvolution.h"
161#include "llvm/Analysis/ScalarEvolutionExpander.h"
162#include "llvm/Analysis/ScalarEvolutionExpressions.h"
163#include "llvm/IR/Function.h"
164#include "llvm/IR/GlobalValue.h"
165#include "llvm/IR/IntrinsicInst.h"
166#include "llvm/IR/Module.h"
167#include "llvm/IR/PatternMatch.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000168#include "llvm/Pass.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000169#include "llvm/Support/Debug.h"
170#include "llvm/Transforms/Scalar.h"
171#include "llvm/Transforms/Utils/LoopUtils.h"
172
173#define DEBUG_TYPE "loop-predication"
174
175using namespace llvm;
176
177namespace {
178class LoopPredication {
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000179 /// Represents an induction variable check:
180 /// icmp Pred, <induction variable>, <loop invariant limit>
181 struct LoopICmp {
182 ICmpInst::Predicate Pred;
183 const SCEVAddRecExpr *IV;
184 const SCEV *Limit;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000185 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
186 const SCEV *Limit)
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000187 : Pred(Pred), IV(IV), Limit(Limit) {}
188 LoopICmp() {}
189 };
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000190
191 ScalarEvolution *SE;
192
193 Loop *L;
194 const DataLayout *DL;
195 BasicBlock *Preheader;
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000196 LoopICmp LatchCheck;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000197
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000198 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) {
199 return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0),
200 ICI->getOperand(1));
201 }
202 Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
203 Value *RHS);
204
205 Optional<LoopICmp> parseLoopLatchICmp();
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000206
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000207 Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder,
208 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
209 Instruction *InsertAt);
210
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000211 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
212 IRBuilder<> &Builder);
213 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
214
215public:
216 LoopPredication(ScalarEvolution *SE) : SE(SE){};
217 bool runOnLoop(Loop *L);
218};
219
220class LoopPredicationLegacyPass : public LoopPass {
221public:
222 static char ID;
223 LoopPredicationLegacyPass() : LoopPass(ID) {
224 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
225 }
226
227 void getAnalysisUsage(AnalysisUsage &AU) const override {
228 getLoopAnalysisUsage(AU);
229 }
230
231 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
232 if (skipLoop(L))
233 return false;
234 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
235 LoopPredication LP(SE);
236 return LP.runOnLoop(L);
237 }
238};
239
240char LoopPredicationLegacyPass::ID = 0;
241} // end namespace llvm
242
243INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
244 "Loop predication", false, false)
245INITIALIZE_PASS_DEPENDENCY(LoopPass)
246INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
247 "Loop predication", false, false)
248
249Pass *llvm::createLoopPredicationPass() {
250 return new LoopPredicationLegacyPass();
251}
252
253PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
254 LoopStandardAnalysisResults &AR,
255 LPMUpdater &U) {
256 LoopPredication LP(&AR.SE);
257 if (!LP.runOnLoop(&L))
258 return PreservedAnalyses::all();
259
260 return getLoopPassPreservedAnalyses();
261}
262
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000263Optional<LoopPredication::LoopICmp>
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000264LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
265 Value *RHS) {
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000266 const SCEV *LHSS = SE->getSCEV(LHS);
267 if (isa<SCEVCouldNotCompute>(LHSS))
268 return None;
269 const SCEV *RHSS = SE->getSCEV(RHS);
270 if (isa<SCEVCouldNotCompute>(RHSS))
271 return None;
272
273 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
274 if (SE->isLoopInvariant(LHSS, L)) {
275 std::swap(LHS, RHS);
276 std::swap(LHSS, RHSS);
277 Pred = ICmpInst::getSwappedPredicate(Pred);
278 }
279
280 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
281 if (!AR || AR->getLoop() != L)
282 return None;
283
284 return LoopICmp(Pred, AR, RHSS);
285}
286
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000287Value *LoopPredication::expandCheck(SCEVExpander &Expander,
288 IRBuilder<> &Builder,
289 ICmpInst::Predicate Pred, const SCEV *LHS,
290 const SCEV *RHS, Instruction *InsertAt) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000291 // TODO: we can check isLoopEntryGuardedByCond before emitting the check
292
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000293 Type *Ty = LHS->getType();
294 assert(Ty == RHS->getType() && "expandCheck operands have different types?");
Artur Pilipenkoead69ee2017-10-12 21:21:17 +0000295
296 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
297 return Builder.getTrue();
298
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000299 Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt);
300 Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt);
301 return Builder.CreateICmp(Pred, LHSV, RHSV);
302}
303
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000304/// If ICI can be widened to a loop invariant condition emits the loop
305/// invariant condition in the loop preheader and return it, otherwise
306/// returns None.
307Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
308 SCEVExpander &Expander,
309 IRBuilder<> &Builder) {
310 DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
311 DEBUG(ICI->dump());
312
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000313 // parseLoopStructure guarantees that the latch condition is:
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000314 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000315 // We are looking for the range checks of the form:
316 // i u< guardLimit
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000317 auto RangeCheck = parseLoopICmp(ICI);
Artur Pilipenkoedee2512017-05-22 12:06:57 +0000318 if (!RangeCheck) {
319 DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000320 return None;
Artur Pilipenkoedee2512017-05-22 12:06:57 +0000321 }
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000322 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
323 DEBUG(dbgs() << "Unsupported range check predicate(" << RangeCheck->Pred
324 << ")!\n");
325 return None;
326 }
327 auto *RangeCheckIV = RangeCheck->IV;
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000328 auto *Ty = RangeCheckIV->getType();
329 if (Ty != LatchCheck.IV->getType()) {
330 DEBUG(dbgs() << "Type mismatch between range check and latch IVs!\n");
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000331 return None;
332 }
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000333 if (!RangeCheckIV->isAffine()) {
334 DEBUG(dbgs() << "Range check IV is not affine!\n");
335 return None;
336 }
337 auto *Step = RangeCheckIV->getStepRecurrence(*SE);
338 if (Step != LatchCheck.IV->getStepRecurrence(*SE)) {
339 DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
340 return None;
341 }
342 assert(Step->isOne() && "must be one");
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000343
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000344 // Generate the widened condition:
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000345 // guardStart u< guardLimit &&
346 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000347 // where <pred> depends on the latch condition predicate. See the file
348 // header comment for the reasoning.
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000349 const SCEV *GuardStart = RangeCheckIV->getStart();
350 const SCEV *GuardLimit = RangeCheck->Limit;
351 const SCEV *LatchStart = LatchCheck.IV->getStart();
352 const SCEV *LatchLimit = LatchCheck.Limit;
353
354 // guardLimit - guardStart + latchStart - 1
355 const SCEV *RHS =
356 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
357 SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
358
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000359 ICmpInst::Predicate LimitCheckPred;
360 switch (LatchCheck.Pred) {
361 case ICmpInst::ICMP_ULT:
362 LimitCheckPred = ICmpInst::ICMP_ULE;
363 break;
364 case ICmpInst::ICMP_ULE:
365 LimitCheckPred = ICmpInst::ICMP_ULT;
366 break;
367 case ICmpInst::ICMP_SLT:
368 LimitCheckPred = ICmpInst::ICMP_SLE;
369 break;
370 case ICmpInst::ICMP_SLE:
371 LimitCheckPred = ICmpInst::ICMP_SLT;
372 break;
373 default:
374 llvm_unreachable("Unsupported loop latch!");
375 }
Artur Pilipenkoaab28662017-05-19 14:00:04 +0000376
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000377 DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
378 DEBUG(dbgs() << "RHS: " << *RHS << "\n");
379 DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
380
Artur Pilipenkoaab28662017-05-19 14:00:04 +0000381 auto CanExpand = [this](const SCEV *S) {
382 return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
383 };
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000384 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
385 !CanExpand(LatchLimit) || !CanExpand(RHS)) {
386 DEBUG(dbgs() << "Can't expand limit check!\n");
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000387 return None;
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000388 }
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000389
Artur Pilipenko0860bfc2017-02-27 15:44:49 +0000390 Instruction *InsertAt = Preheader->getTerminator();
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000391 auto *LimitCheck =
392 expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS, InsertAt);
Artur Pilipenkoead69ee2017-10-12 21:21:17 +0000393 auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck->Pred,
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000394 GuardStart, GuardLimit, InsertAt);
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000395 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000396}
397
398bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
399 SCEVExpander &Expander) {
400 DEBUG(dbgs() << "Processing guard:\n");
401 DEBUG(Guard->dump());
402
403 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
404
405 // The guard condition is expected to be in form of:
406 // cond1 && cond2 && cond3 ...
407 // Iterate over subconditions looking for for icmp conditions which can be
408 // widened across loop iterations. Widening these conditions remember the
409 // resulting list of subconditions in Checks vector.
410 SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0));
411 SmallPtrSet<Value *, 4> Visited;
412
413 SmallVector<Value *, 4> Checks;
414
415 unsigned NumWidened = 0;
416 do {
417 Value *Condition = Worklist.pop_back_val();
418 if (!Visited.insert(Condition).second)
419 continue;
420
421 Value *LHS, *RHS;
422 using namespace llvm::PatternMatch;
423 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
424 Worklist.push_back(LHS);
425 Worklist.push_back(RHS);
426 continue;
427 }
428
429 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
430 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
431 Checks.push_back(NewRangeCheck.getValue());
432 NumWidened++;
433 continue;
434 }
435 }
436
437 // Save the condition as is if we can't widen it
438 Checks.push_back(Condition);
439 } while (Worklist.size() != 0);
440
441 if (NumWidened == 0)
442 return false;
443
444 // Emit the new guard condition
445 Builder.SetInsertPoint(Guard);
446 Value *LastCheck = nullptr;
447 for (auto *Check : Checks)
448 if (!LastCheck)
449 LastCheck = Check;
450 else
451 LastCheck = Builder.CreateAnd(LastCheck, Check);
452 Guard->setOperand(0, LastCheck);
453
454 DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
455 return true;
456}
457
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000458Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() {
459 using namespace PatternMatch;
460
461 BasicBlock *LoopLatch = L->getLoopLatch();
462 if (!LoopLatch) {
463 DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
464 return None;
465 }
466
467 ICmpInst::Predicate Pred;
468 Value *LHS, *RHS;
469 BasicBlock *TrueDest, *FalseDest;
470
471 if (!match(LoopLatch->getTerminator(),
472 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest,
473 FalseDest))) {
474 DEBUG(dbgs() << "Failed to match the latch terminator!\n");
475 return None;
476 }
477 assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) &&
478 "One of the latch's destinations must be the header");
479 if (TrueDest != L->getHeader())
480 Pred = ICmpInst::getInversePredicate(Pred);
481
482 auto Result = parseLoopICmp(Pred, LHS, RHS);
483 if (!Result) {
484 DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
485 return None;
486 }
487
488 if (Result->Pred != ICmpInst::ICMP_ULT &&
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000489 Result->Pred != ICmpInst::ICMP_SLT &&
490 Result->Pred != ICmpInst::ICMP_ULE &&
491 Result->Pred != ICmpInst::ICMP_SLE) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000492 DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
493 << ")!\n");
494 return None;
495 }
496
497 // Check affine first, so if it's not we don't try to compute the step
498 // recurrence.
499 if (!Result->IV->isAffine()) {
500 DEBUG(dbgs() << "The induction variable is not affine!\n");
501 return None;
502 }
503
504 auto *Step = Result->IV->getStepRecurrence(*SE);
505 if (!Step->isOne()) {
506 DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
507 return None;
508 }
509
510 return Result;
511}
512
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000513bool LoopPredication::runOnLoop(Loop *Loop) {
514 L = Loop;
515
516 DEBUG(dbgs() << "Analyzing ");
517 DEBUG(L->dump());
518
519 Module *M = L->getHeader()->getModule();
520
521 // There is nothing to do if the module doesn't use guards
522 auto *GuardDecl =
523 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
524 if (!GuardDecl || GuardDecl->use_empty())
525 return false;
526
527 DL = &M->getDataLayout();
528
529 Preheader = L->getLoopPreheader();
530 if (!Preheader)
531 return false;
532
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000533 auto LatchCheckOpt = parseLoopLatchICmp();
534 if (!LatchCheckOpt)
535 return false;
536 LatchCheck = *LatchCheckOpt;
537
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000538 // Collect all the guards into a vector and process later, so as not
539 // to invalidate the instruction iterator.
540 SmallVector<IntrinsicInst *, 4> Guards;
541 for (const auto BB : L->blocks())
542 for (auto &I : *BB)
543 if (auto *II = dyn_cast<IntrinsicInst>(&I))
544 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
545 Guards.push_back(II);
546
Artur Pilipenko46c4e0a2017-05-19 13:59:34 +0000547 if (Guards.empty())
548 return false;
549
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000550 SCEVExpander Expander(*SE, *DL, "loop-predication");
551
552 bool Changed = false;
553 for (auto *Guard : Guards)
554 Changed |= widenGuardConditions(Guard, Expander);
555
556 return Changed;
557}