blob: d1832f29e4f530259ebdb1c8d1a27bcee37d5b68 [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//
Anna Thomas7b360432017-12-04 15:11:48 +0000101// When S = 1 (i.e. forward iterating loop), the transformation is supported
102// when:
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000103// * The loop has a single latch with the condition of the form:
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000104// B(X) = latchStart + X <pred> latchLimit,
105// where <pred> is u<, u<=, s<, or s<=.
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//
Anna Thomas7b360432017-12-04 15:11:48 +0000109// For the ult latch comparison case M is:
110// forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
111// guardStart + X + 1 u< guardLimit
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000112//
Anna Thomas7b360432017-12-04 15:11:48 +0000113// The only way the antecedent can be true and the consequent can be false is
114// if
115// X == guardLimit - 1 - guardStart
116// (and guardLimit is non-zero, but we won't use this latter fact).
117// If X == guardLimit - 1 - guardStart then the second half of the antecedent is
118// latchStart + guardLimit - 1 - guardStart u< latchLimit
119// and its negation is
120// latchStart + guardLimit - 1 - guardStart u>= latchLimit
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000121//
Anna Thomas7b360432017-12-04 15:11:48 +0000122// In other words, if
123// latchLimit u<= latchStart + guardLimit - 1 - guardStart
124// then:
125// (the ranges below are written in ConstantRange notation, where [A, B) is the
126// set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000127//
Anna Thomas7b360432017-12-04 15:11:48 +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)
140// == true
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000141//
Anna Thomas7b360432017-12-04 15:11:48 +0000142// So the widened condition is:
143// 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//
Anna Thomas7b360432017-12-04 15:11:48 +0000155// When S = -1 (i.e. reverse iterating loop), the transformation is supported
156// when:
157// * The loop has a single latch with the condition of the form:
158// B(X) = X <pred> latchLimit, where <pred> is u> or s>.
159// * The guard condition is of the form
160// G(X) = X - 1 u< guardLimit
161//
162// For the ugt latch comparison case M is:
163// forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit
164//
165// The only way the antecedent can be true and the consequent can be false is if
166// X == 1.
167// If X == 1 then the second half of the antecedent is
168// 1 u> latchLimit, and its negation is latchLimit u>= 1.
169//
170// So the widened condition is:
171// guardStart u< guardLimit && latchLimit u>= 1.
172// Similarly for sgt condition the widened condition is:
173// guardStart u< guardLimit && latchLimit s>= 1.
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000174//===----------------------------------------------------------------------===//
175
176#include "llvm/Transforms/Scalar/LoopPredication.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000177#include "llvm/Analysis/LoopInfo.h"
178#include "llvm/Analysis/LoopPass.h"
179#include "llvm/Analysis/ScalarEvolution.h"
180#include "llvm/Analysis/ScalarEvolutionExpander.h"
181#include "llvm/Analysis/ScalarEvolutionExpressions.h"
182#include "llvm/IR/Function.h"
183#include "llvm/IR/GlobalValue.h"
184#include "llvm/IR/IntrinsicInst.h"
185#include "llvm/IR/Module.h"
186#include "llvm/IR/PatternMatch.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +0000187#include "llvm/Pass.h"
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000188#include "llvm/Support/Debug.h"
189#include "llvm/Transforms/Scalar.h"
190#include "llvm/Transforms/Utils/LoopUtils.h"
191
192#define DEBUG_TYPE "loop-predication"
193
194using namespace llvm;
195
Anna Thomas1d02b132017-11-02 21:21:02 +0000196static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
197 cl::Hidden, cl::init(true));
198
Anna Thomas7b360432017-12-04 15:11:48 +0000199static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
200 cl::Hidden, cl::init(true));
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000201namespace {
202class LoopPredication {
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000203 /// Represents an induction variable check:
204 /// icmp Pred, <induction variable>, <loop invariant limit>
205 struct LoopICmp {
206 ICmpInst::Predicate Pred;
207 const SCEVAddRecExpr *IV;
208 const SCEV *Limit;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000209 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
210 const SCEV *Limit)
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000211 : Pred(Pred), IV(IV), Limit(Limit) {}
212 LoopICmp() {}
Anna Thomas68797212017-11-03 14:25:39 +0000213 void dump() {
214 dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
215 << ", Limit = " << *Limit << "\n";
216 }
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000217 };
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000218
219 ScalarEvolution *SE;
220
221 Loop *L;
222 const DataLayout *DL;
223 BasicBlock *Preheader;
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000224 LoopICmp LatchCheck;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000225
Anna Thomas68797212017-11-03 14:25:39 +0000226 bool isSupportedStep(const SCEV* Step);
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000227 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) {
228 return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0),
229 ICI->getOperand(1));
230 }
231 Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
232 Value *RHS);
233
234 Optional<LoopICmp> parseLoopLatchICmp();
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000235
Anna Thomas68797212017-11-03 14:25:39 +0000236 bool CanExpand(const SCEV* S);
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000237 Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder,
238 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
239 Instruction *InsertAt);
240
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000241 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
242 IRBuilder<> &Builder);
Anna Thomas68797212017-11-03 14:25:39 +0000243 Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
244 LoopICmp RangeCheck,
245 SCEVExpander &Expander,
246 IRBuilder<> &Builder);
Anna Thomas7b360432017-12-04 15:11:48 +0000247 Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
248 LoopICmp RangeCheck,
249 SCEVExpander &Expander,
250 IRBuilder<> &Builder);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000251 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
252
Anna Thomas1d02b132017-11-02 21:21:02 +0000253 // When the IV type is wider than the range operand type, we can still do loop
254 // predication, by generating SCEVs for the range and latch that are of the
255 // same type. We achieve this by generating a SCEV truncate expression for the
256 // latch IV. This is done iff truncation of the IV is a safe operation,
257 // without loss of information.
258 // Another way to achieve this is by generating a wider type SCEV for the
259 // range check operand, however, this needs a more involved check that
260 // operands do not overflow. This can lead to loss of information when the
261 // range operand is of the form: add i32 %offset, %iv. We need to prove that
262 // sext(x + y) is same as sext(x) + sext(y).
263 // This function returns true if we can safely represent the IV type in
264 // the RangeCheckType without loss of information.
265 bool isSafeToTruncateWideIVType(Type *RangeCheckType);
266 // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do
267 // so.
268 Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType);
Serguei Katkovebc90312018-02-07 06:53:37 +0000269
270 // Returns the latch predicate for guard. SGT -> SGE, UGT -> UGE, SGE -> SGT,
271 // UGE -> UGT, etc.
272 ICmpInst::Predicate getLatchPredicateForGuard(ICmpInst::Predicate Pred);
273
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000274public:
275 LoopPredication(ScalarEvolution *SE) : SE(SE){};
276 bool runOnLoop(Loop *L);
277};
278
279class LoopPredicationLegacyPass : public LoopPass {
280public:
281 static char ID;
282 LoopPredicationLegacyPass() : LoopPass(ID) {
283 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
284 }
285
286 void getAnalysisUsage(AnalysisUsage &AU) const override {
287 getLoopAnalysisUsage(AU);
288 }
289
290 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
291 if (skipLoop(L))
292 return false;
293 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
294 LoopPredication LP(SE);
295 return LP.runOnLoop(L);
296 }
297};
298
299char LoopPredicationLegacyPass::ID = 0;
300} // end namespace llvm
301
302INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
303 "Loop predication", false, false)
304INITIALIZE_PASS_DEPENDENCY(LoopPass)
305INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
306 "Loop predication", false, false)
307
308Pass *llvm::createLoopPredicationPass() {
309 return new LoopPredicationLegacyPass();
310}
311
312PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
313 LoopStandardAnalysisResults &AR,
314 LPMUpdater &U) {
315 LoopPredication LP(&AR.SE);
316 if (!LP.runOnLoop(&L))
317 return PreservedAnalyses::all();
318
319 return getLoopPassPreservedAnalyses();
320}
321
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000322Optional<LoopPredication::LoopICmp>
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000323LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
324 Value *RHS) {
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000325 const SCEV *LHSS = SE->getSCEV(LHS);
326 if (isa<SCEVCouldNotCompute>(LHSS))
327 return None;
328 const SCEV *RHSS = SE->getSCEV(RHS);
329 if (isa<SCEVCouldNotCompute>(RHSS))
330 return None;
331
332 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
333 if (SE->isLoopInvariant(LHSS, L)) {
334 std::swap(LHS, RHS);
335 std::swap(LHSS, RHSS);
336 Pred = ICmpInst::getSwappedPredicate(Pred);
337 }
338
339 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
340 if (!AR || AR->getLoop() != L)
341 return None;
342
343 return LoopICmp(Pred, AR, RHSS);
344}
345
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000346Value *LoopPredication::expandCheck(SCEVExpander &Expander,
347 IRBuilder<> &Builder,
348 ICmpInst::Predicate Pred, const SCEV *LHS,
349 const SCEV *RHS, Instruction *InsertAt) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000350 // TODO: we can check isLoopEntryGuardedByCond before emitting the check
351
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000352 Type *Ty = LHS->getType();
353 assert(Ty == RHS->getType() && "expandCheck operands have different types?");
Artur Pilipenkoead69ee2017-10-12 21:21:17 +0000354
355 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
356 return Builder.getTrue();
357
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000358 Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt);
359 Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt);
360 return Builder.CreateICmp(Pred, LHSV, RHSV);
361}
362
Anna Thomas1d02b132017-11-02 21:21:02 +0000363Optional<LoopPredication::LoopICmp>
364LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) {
365
366 auto *LatchType = LatchCheck.IV->getType();
367 if (RangeCheckType == LatchType)
368 return LatchCheck;
369 // For now, bail out if latch type is narrower than range type.
370 if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType))
371 return None;
372 if (!isSafeToTruncateWideIVType(RangeCheckType))
373 return None;
374 // We can now safely identify the truncated version of the IV and limit for
375 // RangeCheckType.
376 LoopICmp NewLatchCheck;
377 NewLatchCheck.Pred = LatchCheck.Pred;
378 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
379 SE->getTruncateExpr(LatchCheck.IV, RangeCheckType));
380 if (!NewLatchCheck.IV)
381 return None;
382 NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType);
383 DEBUG(dbgs() << "IV of type: " << *LatchType
384 << "can be represented as range check type:" << *RangeCheckType
385 << "\n");
386 DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
387 DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
388 return NewLatchCheck;
389}
390
Anna Thomas68797212017-11-03 14:25:39 +0000391bool LoopPredication::isSupportedStep(const SCEV* Step) {
Anna Thomas7b360432017-12-04 15:11:48 +0000392 return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
Anna Thomas68797212017-11-03 14:25:39 +0000393}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000394
Anna Thomas68797212017-11-03 14:25:39 +0000395bool LoopPredication::CanExpand(const SCEV* S) {
396 return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
397}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000398
Serguei Katkovebc90312018-02-07 06:53:37 +0000399ICmpInst::Predicate
400LoopPredication::getLatchPredicateForGuard(ICmpInst::Predicate Pred) {
401 switch (LatchCheck.Pred) {
402 case ICmpInst::ICMP_ULT:
403 return ICmpInst::ICMP_ULE;
404 case ICmpInst::ICMP_ULE:
405 return ICmpInst::ICMP_ULT;
406 case ICmpInst::ICMP_SLT:
407 return ICmpInst::ICMP_SLE;
408 case ICmpInst::ICMP_SLE:
409 return ICmpInst::ICMP_SLT;
410 case ICmpInst::ICMP_UGT:
411 return ICmpInst::ICMP_UGE;
412 case ICmpInst::ICMP_UGE:
413 return ICmpInst::ICMP_UGT;
414 case ICmpInst::ICMP_SGT:
415 return ICmpInst::ICMP_SGE;
416 case ICmpInst::ICMP_SGE:
417 return ICmpInst::ICMP_SGT;
418 default:
419 llvm_unreachable("Unsupported loop latch!");
420 }
421}
422
Anna Thomas68797212017-11-03 14:25:39 +0000423Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
424 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
425 SCEVExpander &Expander, IRBuilder<> &Builder) {
426 auto *Ty = RangeCheck.IV->getType();
427 // Generate the widened condition for the forward loop:
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000428 // guardStart u< guardLimit &&
429 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000430 // where <pred> depends on the latch condition predicate. See the file
431 // header comment for the reasoning.
Anna Thomas68797212017-11-03 14:25:39 +0000432 // guardLimit - guardStart + latchStart - 1
433 const SCEV *GuardStart = RangeCheck.IV->getStart();
434 const SCEV *GuardLimit = RangeCheck.Limit;
435 const SCEV *LatchStart = LatchCheck.IV->getStart();
436 const SCEV *LatchLimit = LatchCheck.Limit;
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000437
438 // guardLimit - guardStart + latchStart - 1
439 const SCEV *RHS =
440 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
441 SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
Anna Thomas68797212017-11-03 14:25:39 +0000442 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
443 !CanExpand(LatchLimit) || !CanExpand(RHS)) {
444 DEBUG(dbgs() << "Can't expand limit check!\n");
445 return None;
446 }
Serguei Katkovebc90312018-02-07 06:53:37 +0000447 auto LimitCheckPred = getLatchPredicateForGuard(LatchCheck.Pred);
Artur Pilipenkoaab28662017-05-19 14:00:04 +0000448
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000449 DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
450 DEBUG(dbgs() << "RHS: " << *RHS << "\n");
451 DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
452
Artur Pilipenko0860bfc2017-02-27 15:44:49 +0000453 Instruction *InsertAt = Preheader->getTerminator();
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000454 auto *LimitCheck =
455 expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS, InsertAt);
Anna Thomas68797212017-11-03 14:25:39 +0000456 auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck.Pred,
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000457 GuardStart, GuardLimit, InsertAt);
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000458 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000459}
Anna Thomas7b360432017-12-04 15:11:48 +0000460
461Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
462 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
463 SCEVExpander &Expander, IRBuilder<> &Builder) {
464 auto *Ty = RangeCheck.IV->getType();
465 const SCEV *GuardStart = RangeCheck.IV->getStart();
466 const SCEV *GuardLimit = RangeCheck.Limit;
467 const SCEV *LatchLimit = LatchCheck.Limit;
468 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
469 !CanExpand(LatchLimit)) {
470 DEBUG(dbgs() << "Can't expand limit check!\n");
471 return None;
472 }
473 // The decrement of the latch check IV should be the same as the
474 // rangeCheckIV.
475 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
476 if (RangeCheck.IV != PostDecLatchCheckIV) {
477 DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
478 << *PostDecLatchCheckIV
479 << " and RangeCheckIV: " << *RangeCheck.IV << "\n");
480 return None;
481 }
482
483 // Generate the widened condition for CountDownLoop:
484 // guardStart u< guardLimit &&
485 // latchLimit <pred> 1.
486 // See the header comment for reasoning of the checks.
487 Instruction *InsertAt = Preheader->getTerminator();
488 auto LimitCheckPred = ICmpInst::isSigned(LatchCheck.Pred)
489 ? ICmpInst::ICMP_SGE
490 : ICmpInst::ICMP_UGE;
491 auto *FirstIterationCheck = expandCheck(Expander, Builder, ICmpInst::ICMP_ULT,
492 GuardStart, GuardLimit, InsertAt);
493 auto *LimitCheck = expandCheck(Expander, Builder, LimitCheckPred, LatchLimit,
494 SE->getOne(Ty), InsertAt);
495 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
496}
497
Anna Thomas68797212017-11-03 14:25:39 +0000498/// If ICI can be widened to a loop invariant condition emits the loop
499/// invariant condition in the loop preheader and return it, otherwise
500/// returns None.
501Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
502 SCEVExpander &Expander,
503 IRBuilder<> &Builder) {
504 DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
505 DEBUG(ICI->dump());
506
507 // parseLoopStructure guarantees that the latch condition is:
508 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
509 // We are looking for the range checks of the form:
510 // i u< guardLimit
511 auto RangeCheck = parseLoopICmp(ICI);
512 if (!RangeCheck) {
513 DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
514 return None;
515 }
516 DEBUG(dbgs() << "Guard check:\n");
517 DEBUG(RangeCheck->dump());
518 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
519 DEBUG(dbgs() << "Unsupported range check predicate(" << RangeCheck->Pred
520 << ")!\n");
521 return None;
522 }
523 auto *RangeCheckIV = RangeCheck->IV;
524 if (!RangeCheckIV->isAffine()) {
525 DEBUG(dbgs() << "Range check IV is not affine!\n");
526 return None;
527 }
528 auto *Step = RangeCheckIV->getStepRecurrence(*SE);
529 // We cannot just compare with latch IV step because the latch and range IVs
530 // may have different types.
531 if (!isSupportedStep(Step)) {
532 DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
533 return None;
534 }
535 auto *Ty = RangeCheckIV->getType();
536 auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty);
537 if (!CurrLatchCheckOpt) {
538 DEBUG(dbgs() << "Failed to generate a loop latch check "
539 "corresponding to range type: "
540 << *Ty << "\n");
541 return None;
542 }
543
544 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
Anna Thomas7b360432017-12-04 15:11:48 +0000545 // At this point, the range and latch step should have the same type, but need
546 // not have the same value (we support both 1 and -1 steps).
547 assert(Step->getType() ==
548 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
549 "Range and latch steps should be of same type!");
550 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
551 DEBUG(dbgs() << "Range and latch have different step values!\n");
552 return None;
553 }
Anna Thomas68797212017-11-03 14:25:39 +0000554
Anna Thomas7b360432017-12-04 15:11:48 +0000555 if (Step->isOne())
556 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
557 Expander, Builder);
558 else {
559 assert(Step->isAllOnesValue() && "Step should be -1!");
560 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
561 Expander, Builder);
562 }
Anna Thomas68797212017-11-03 14:25:39 +0000563}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000564
565bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
566 SCEVExpander &Expander) {
567 DEBUG(dbgs() << "Processing guard:\n");
568 DEBUG(Guard->dump());
569
570 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
571
572 // The guard condition is expected to be in form of:
573 // cond1 && cond2 && cond3 ...
Hiroshi Inoue0909ca12018-01-26 08:15:29 +0000574 // Iterate over subconditions looking for icmp conditions which can be
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000575 // widened across loop iterations. Widening these conditions remember the
576 // resulting list of subconditions in Checks vector.
577 SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0));
578 SmallPtrSet<Value *, 4> Visited;
579
580 SmallVector<Value *, 4> Checks;
581
582 unsigned NumWidened = 0;
583 do {
584 Value *Condition = Worklist.pop_back_val();
585 if (!Visited.insert(Condition).second)
586 continue;
587
588 Value *LHS, *RHS;
589 using namespace llvm::PatternMatch;
590 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
591 Worklist.push_back(LHS);
592 Worklist.push_back(RHS);
593 continue;
594 }
595
596 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
597 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
598 Checks.push_back(NewRangeCheck.getValue());
599 NumWidened++;
600 continue;
601 }
602 }
603
604 // Save the condition as is if we can't widen it
605 Checks.push_back(Condition);
606 } while (Worklist.size() != 0);
607
608 if (NumWidened == 0)
609 return false;
610
611 // Emit the new guard condition
612 Builder.SetInsertPoint(Guard);
613 Value *LastCheck = nullptr;
614 for (auto *Check : Checks)
615 if (!LastCheck)
616 LastCheck = Check;
617 else
618 LastCheck = Builder.CreateAnd(LastCheck, Check);
619 Guard->setOperand(0, LastCheck);
620
621 DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
622 return true;
623}
624
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000625Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() {
626 using namespace PatternMatch;
627
628 BasicBlock *LoopLatch = L->getLoopLatch();
629 if (!LoopLatch) {
630 DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
631 return None;
632 }
633
634 ICmpInst::Predicate Pred;
635 Value *LHS, *RHS;
636 BasicBlock *TrueDest, *FalseDest;
637
638 if (!match(LoopLatch->getTerminator(),
639 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest,
640 FalseDest))) {
641 DEBUG(dbgs() << "Failed to match the latch terminator!\n");
642 return None;
643 }
644 assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) &&
645 "One of the latch's destinations must be the header");
646 if (TrueDest != L->getHeader())
647 Pred = ICmpInst::getInversePredicate(Pred);
648
649 auto Result = parseLoopICmp(Pred, LHS, RHS);
650 if (!Result) {
651 DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
652 return None;
653 }
654
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000655 // Check affine first, so if it's not we don't try to compute the step
656 // recurrence.
657 if (!Result->IV->isAffine()) {
658 DEBUG(dbgs() << "The induction variable is not affine!\n");
659 return None;
660 }
661
662 auto *Step = Result->IV->getStepRecurrence(*SE);
Anna Thomas68797212017-11-03 14:25:39 +0000663 if (!isSupportedStep(Step)) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000664 DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
665 return None;
666 }
667
Anna Thomas68797212017-11-03 14:25:39 +0000668 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
Anna Thomas7b360432017-12-04 15:11:48 +0000669 if (Step->isOne()) {
670 return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
671 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
672 } else {
673 assert(Step->isAllOnesValue() && "Step should be -1!");
674 return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT;
675 }
Anna Thomas68797212017-11-03 14:25:39 +0000676 };
677
678 if (IsUnsupportedPredicate(Step, Result->Pred)) {
679 DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
680 << ")!\n");
681 return None;
682 }
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000683 return Result;
684}
685
Anna Thomas1d02b132017-11-02 21:21:02 +0000686// Returns true if its safe to truncate the IV to RangeCheckType.
687bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) {
688 if (!EnableIVTruncation)
689 return false;
690 assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) >
691 DL->getTypeSizeInBits(RangeCheckType) &&
692 "Expected latch check IV type to be larger than range check operand "
693 "type!");
694 // The start and end values of the IV should be known. This is to guarantee
695 // that truncating the wide type will not lose information.
696 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
697 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
698 if (!Limit || !Start)
699 return false;
700 // This check makes sure that the IV does not change sign during loop
701 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
702 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
703 // IV wraps around, and the truncation of the IV would lose the range of
704 // iterations between 2^32 and 2^64.
705 bool Increasing;
706 if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing))
707 return false;
708 // The active bits should be less than the bits in the RangeCheckType. This
709 // guarantees that truncating the latch check to RangeCheckType is a safe
710 // operation.
711 auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType);
712 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
713 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
714}
715
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000716bool LoopPredication::runOnLoop(Loop *Loop) {
717 L = Loop;
718
719 DEBUG(dbgs() << "Analyzing ");
720 DEBUG(L->dump());
721
722 Module *M = L->getHeader()->getModule();
723
724 // There is nothing to do if the module doesn't use guards
725 auto *GuardDecl =
726 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
727 if (!GuardDecl || GuardDecl->use_empty())
728 return false;
729
730 DL = &M->getDataLayout();
731
732 Preheader = L->getLoopPreheader();
733 if (!Preheader)
734 return false;
735
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000736 auto LatchCheckOpt = parseLoopLatchICmp();
737 if (!LatchCheckOpt)
738 return false;
739 LatchCheck = *LatchCheckOpt;
740
Anna Thomas68797212017-11-03 14:25:39 +0000741 DEBUG(dbgs() << "Latch check:\n");
742 DEBUG(LatchCheck.dump());
743
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000744 // Collect all the guards into a vector and process later, so as not
745 // to invalidate the instruction iterator.
746 SmallVector<IntrinsicInst *, 4> Guards;
747 for (const auto BB : L->blocks())
748 for (auto &I : *BB)
749 if (auto *II = dyn_cast<IntrinsicInst>(&I))
750 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
751 Guards.push_back(II);
752
Artur Pilipenko46c4e0a2017-05-19 13:59:34 +0000753 if (Guards.empty())
754 return false;
755
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000756 SCEVExpander Expander(*SE, *DL, "loop-predication");
757
758 bool Changed = false;
759 for (auto *Guard : Guards)
760 Changed |= widenGuardConditions(Guard, Expander);
761
762 return Changed;
763}