blob: 52dea3254e79e5f98f36caa68630970553ad9a42 [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
Anna Thomas1d02b132017-11-02 21:21:02 +0000177static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
178 cl::Hidden, cl::init(true));
179
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000180namespace {
181class LoopPredication {
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000182 /// Represents an induction variable check:
183 /// icmp Pred, <induction variable>, <loop invariant limit>
184 struct LoopICmp {
185 ICmpInst::Predicate Pred;
186 const SCEVAddRecExpr *IV;
187 const SCEV *Limit;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000188 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
189 const SCEV *Limit)
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000190 : Pred(Pred), IV(IV), Limit(Limit) {}
191 LoopICmp() {}
Anna Thomas68797212017-11-03 14:25:39 +0000192 void dump() {
193 dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
194 << ", Limit = " << *Limit << "\n";
195 }
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000196 };
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000197
198 ScalarEvolution *SE;
199
200 Loop *L;
201 const DataLayout *DL;
202 BasicBlock *Preheader;
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000203 LoopICmp LatchCheck;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000204
Anna Thomas68797212017-11-03 14:25:39 +0000205 bool isSupportedStep(const SCEV* Step);
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000206 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) {
207 return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0),
208 ICI->getOperand(1));
209 }
210 Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
211 Value *RHS);
212
213 Optional<LoopICmp> parseLoopLatchICmp();
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000214
Anna Thomas68797212017-11-03 14:25:39 +0000215 bool CanExpand(const SCEV* S);
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000216 Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder,
217 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
218 Instruction *InsertAt);
219
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000220 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
221 IRBuilder<> &Builder);
Anna Thomas68797212017-11-03 14:25:39 +0000222 Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
223 LoopICmp RangeCheck,
224 SCEVExpander &Expander,
225 IRBuilder<> &Builder);
226
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000227 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
228
Anna Thomas1d02b132017-11-02 21:21:02 +0000229 // When the IV type is wider than the range operand type, we can still do loop
230 // predication, by generating SCEVs for the range and latch that are of the
231 // same type. We achieve this by generating a SCEV truncate expression for the
232 // latch IV. This is done iff truncation of the IV is a safe operation,
233 // without loss of information.
234 // Another way to achieve this is by generating a wider type SCEV for the
235 // range check operand, however, this needs a more involved check that
236 // operands do not overflow. This can lead to loss of information when the
237 // range operand is of the form: add i32 %offset, %iv. We need to prove that
238 // sext(x + y) is same as sext(x) + sext(y).
239 // This function returns true if we can safely represent the IV type in
240 // the RangeCheckType without loss of information.
241 bool isSafeToTruncateWideIVType(Type *RangeCheckType);
242 // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do
243 // so.
244 Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000245public:
246 LoopPredication(ScalarEvolution *SE) : SE(SE){};
247 bool runOnLoop(Loop *L);
248};
249
250class LoopPredicationLegacyPass : public LoopPass {
251public:
252 static char ID;
253 LoopPredicationLegacyPass() : LoopPass(ID) {
254 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
255 }
256
257 void getAnalysisUsage(AnalysisUsage &AU) const override {
258 getLoopAnalysisUsage(AU);
259 }
260
261 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
262 if (skipLoop(L))
263 return false;
264 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
265 LoopPredication LP(SE);
266 return LP.runOnLoop(L);
267 }
268};
269
270char LoopPredicationLegacyPass::ID = 0;
271} // end namespace llvm
272
273INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
274 "Loop predication", false, false)
275INITIALIZE_PASS_DEPENDENCY(LoopPass)
276INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
277 "Loop predication", false, false)
278
279Pass *llvm::createLoopPredicationPass() {
280 return new LoopPredicationLegacyPass();
281}
282
283PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
284 LoopStandardAnalysisResults &AR,
285 LPMUpdater &U) {
286 LoopPredication LP(&AR.SE);
287 if (!LP.runOnLoop(&L))
288 return PreservedAnalyses::all();
289
290 return getLoopPassPreservedAnalyses();
291}
292
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000293Optional<LoopPredication::LoopICmp>
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000294LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
295 Value *RHS) {
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000296 const SCEV *LHSS = SE->getSCEV(LHS);
297 if (isa<SCEVCouldNotCompute>(LHSS))
298 return None;
299 const SCEV *RHSS = SE->getSCEV(RHS);
300 if (isa<SCEVCouldNotCompute>(RHSS))
301 return None;
302
303 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
304 if (SE->isLoopInvariant(LHSS, L)) {
305 std::swap(LHS, RHS);
306 std::swap(LHSS, RHSS);
307 Pred = ICmpInst::getSwappedPredicate(Pred);
308 }
309
310 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
311 if (!AR || AR->getLoop() != L)
312 return None;
313
314 return LoopICmp(Pred, AR, RHSS);
315}
316
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000317Value *LoopPredication::expandCheck(SCEVExpander &Expander,
318 IRBuilder<> &Builder,
319 ICmpInst::Predicate Pred, const SCEV *LHS,
320 const SCEV *RHS, Instruction *InsertAt) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000321 // TODO: we can check isLoopEntryGuardedByCond before emitting the check
322
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000323 Type *Ty = LHS->getType();
324 assert(Ty == RHS->getType() && "expandCheck operands have different types?");
Artur Pilipenkoead69ee2017-10-12 21:21:17 +0000325
326 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
327 return Builder.getTrue();
328
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000329 Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt);
330 Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt);
331 return Builder.CreateICmp(Pred, LHSV, RHSV);
332}
333
Anna Thomas1d02b132017-11-02 21:21:02 +0000334Optional<LoopPredication::LoopICmp>
335LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) {
336
337 auto *LatchType = LatchCheck.IV->getType();
338 if (RangeCheckType == LatchType)
339 return LatchCheck;
340 // For now, bail out if latch type is narrower than range type.
341 if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType))
342 return None;
343 if (!isSafeToTruncateWideIVType(RangeCheckType))
344 return None;
345 // We can now safely identify the truncated version of the IV and limit for
346 // RangeCheckType.
347 LoopICmp NewLatchCheck;
348 NewLatchCheck.Pred = LatchCheck.Pred;
349 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
350 SE->getTruncateExpr(LatchCheck.IV, RangeCheckType));
351 if (!NewLatchCheck.IV)
352 return None;
353 NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType);
354 DEBUG(dbgs() << "IV of type: " << *LatchType
355 << "can be represented as range check type:" << *RangeCheckType
356 << "\n");
357 DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
358 DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
359 return NewLatchCheck;
360}
361
Anna Thomas68797212017-11-03 14:25:39 +0000362bool LoopPredication::isSupportedStep(const SCEV* Step) {
363 return Step->isOne();
364}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000365
Anna Thomas68797212017-11-03 14:25:39 +0000366bool LoopPredication::CanExpand(const SCEV* S) {
367 return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
368}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000369
Anna Thomas68797212017-11-03 14:25:39 +0000370Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
371 LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
372 SCEVExpander &Expander, IRBuilder<> &Builder) {
373 auto *Ty = RangeCheck.IV->getType();
374 // Generate the widened condition for the forward loop:
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000375 // guardStart u< guardLimit &&
376 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000377 // where <pred> depends on the latch condition predicate. See the file
378 // header comment for the reasoning.
Anna Thomas68797212017-11-03 14:25:39 +0000379 // guardLimit - guardStart + latchStart - 1
380 const SCEV *GuardStart = RangeCheck.IV->getStart();
381 const SCEV *GuardLimit = RangeCheck.Limit;
382 const SCEV *LatchStart = LatchCheck.IV->getStart();
383 const SCEV *LatchLimit = LatchCheck.Limit;
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000384
385 // guardLimit - guardStart + latchStart - 1
386 const SCEV *RHS =
387 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
388 SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
Anna Thomas68797212017-11-03 14:25:39 +0000389 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
390 !CanExpand(LatchLimit) || !CanExpand(RHS)) {
391 DEBUG(dbgs() << "Can't expand limit check!\n");
392 return None;
393 }
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000394 ICmpInst::Predicate LimitCheckPred;
Anna Thomas68797212017-11-03 14:25:39 +0000395 switch (LatchCheck.Pred) {
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000396 case ICmpInst::ICMP_ULT:
397 LimitCheckPred = ICmpInst::ICMP_ULE;
398 break;
399 case ICmpInst::ICMP_ULE:
400 LimitCheckPred = ICmpInst::ICMP_ULT;
401 break;
402 case ICmpInst::ICMP_SLT:
403 LimitCheckPred = ICmpInst::ICMP_SLE;
404 break;
405 case ICmpInst::ICMP_SLE:
406 LimitCheckPred = ICmpInst::ICMP_SLT;
407 break;
408 default:
409 llvm_unreachable("Unsupported loop latch!");
410 }
Artur Pilipenkoaab28662017-05-19 14:00:04 +0000411
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000412 DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
413 DEBUG(dbgs() << "RHS: " << *RHS << "\n");
414 DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
415
Artur Pilipenko0860bfc2017-02-27 15:44:49 +0000416 Instruction *InsertAt = Preheader->getTerminator();
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000417 auto *LimitCheck =
418 expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS, InsertAt);
Anna Thomas68797212017-11-03 14:25:39 +0000419 auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck.Pred,
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000420 GuardStart, GuardLimit, InsertAt);
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000421 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000422}
Anna Thomas68797212017-11-03 14:25:39 +0000423/// If ICI can be widened to a loop invariant condition emits the loop
424/// invariant condition in the loop preheader and return it, otherwise
425/// returns None.
426Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
427 SCEVExpander &Expander,
428 IRBuilder<> &Builder) {
429 DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
430 DEBUG(ICI->dump());
431
432 // parseLoopStructure guarantees that the latch condition is:
433 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
434 // We are looking for the range checks of the form:
435 // i u< guardLimit
436 auto RangeCheck = parseLoopICmp(ICI);
437 if (!RangeCheck) {
438 DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
439 return None;
440 }
441 DEBUG(dbgs() << "Guard check:\n");
442 DEBUG(RangeCheck->dump());
443 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
444 DEBUG(dbgs() << "Unsupported range check predicate(" << RangeCheck->Pred
445 << ")!\n");
446 return None;
447 }
448 auto *RangeCheckIV = RangeCheck->IV;
449 if (!RangeCheckIV->isAffine()) {
450 DEBUG(dbgs() << "Range check IV is not affine!\n");
451 return None;
452 }
453 auto *Step = RangeCheckIV->getStepRecurrence(*SE);
454 // We cannot just compare with latch IV step because the latch and range IVs
455 // may have different types.
456 if (!isSupportedStep(Step)) {
457 DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
458 return None;
459 }
460 auto *Ty = RangeCheckIV->getType();
461 auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty);
462 if (!CurrLatchCheckOpt) {
463 DEBUG(dbgs() << "Failed to generate a loop latch check "
464 "corresponding to range type: "
465 << *Ty << "\n");
466 return None;
467 }
468
469 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
470 // At this point the range check step and latch step should have the same
471 // value and type.
472 assert(Step == CurrLatchCheck.IV->getStepRecurrence(*SE) &&
473 "Range and latch should have same step recurrence!");
474
475 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
476 Expander, Builder);
477}
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000478
479bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
480 SCEVExpander &Expander) {
481 DEBUG(dbgs() << "Processing guard:\n");
482 DEBUG(Guard->dump());
483
484 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
485
486 // The guard condition is expected to be in form of:
487 // cond1 && cond2 && cond3 ...
488 // Iterate over subconditions looking for for icmp conditions which can be
489 // widened across loop iterations. Widening these conditions remember the
490 // resulting list of subconditions in Checks vector.
491 SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0));
492 SmallPtrSet<Value *, 4> Visited;
493
494 SmallVector<Value *, 4> Checks;
495
496 unsigned NumWidened = 0;
497 do {
498 Value *Condition = Worklist.pop_back_val();
499 if (!Visited.insert(Condition).second)
500 continue;
501
502 Value *LHS, *RHS;
503 using namespace llvm::PatternMatch;
504 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
505 Worklist.push_back(LHS);
506 Worklist.push_back(RHS);
507 continue;
508 }
509
510 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
511 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
512 Checks.push_back(NewRangeCheck.getValue());
513 NumWidened++;
514 continue;
515 }
516 }
517
518 // Save the condition as is if we can't widen it
519 Checks.push_back(Condition);
520 } while (Worklist.size() != 0);
521
522 if (NumWidened == 0)
523 return false;
524
525 // Emit the new guard condition
526 Builder.SetInsertPoint(Guard);
527 Value *LastCheck = nullptr;
528 for (auto *Check : Checks)
529 if (!LastCheck)
530 LastCheck = Check;
531 else
532 LastCheck = Builder.CreateAnd(LastCheck, Check);
533 Guard->setOperand(0, LastCheck);
534
535 DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
536 return true;
537}
538
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000539Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() {
540 using namespace PatternMatch;
541
542 BasicBlock *LoopLatch = L->getLoopLatch();
543 if (!LoopLatch) {
544 DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
545 return None;
546 }
547
548 ICmpInst::Predicate Pred;
549 Value *LHS, *RHS;
550 BasicBlock *TrueDest, *FalseDest;
551
552 if (!match(LoopLatch->getTerminator(),
553 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest,
554 FalseDest))) {
555 DEBUG(dbgs() << "Failed to match the latch terminator!\n");
556 return None;
557 }
558 assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) &&
559 "One of the latch's destinations must be the header");
560 if (TrueDest != L->getHeader())
561 Pred = ICmpInst::getInversePredicate(Pred);
562
563 auto Result = parseLoopICmp(Pred, LHS, RHS);
564 if (!Result) {
565 DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
566 return None;
567 }
568
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000569 // Check affine first, so if it's not we don't try to compute the step
570 // recurrence.
571 if (!Result->IV->isAffine()) {
572 DEBUG(dbgs() << "The induction variable is not affine!\n");
573 return None;
574 }
575
576 auto *Step = Result->IV->getStepRecurrence(*SE);
Anna Thomas68797212017-11-03 14:25:39 +0000577 if (!isSupportedStep(Step)) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000578 DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
579 return None;
580 }
581
Anna Thomas68797212017-11-03 14:25:39 +0000582 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
583 assert(Step->isOne() && "expected Step to be one!");
584 return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
585 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
586 };
587
588 if (IsUnsupportedPredicate(Step, Result->Pred)) {
589 DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
590 << ")!\n");
591 return None;
592 }
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000593 return Result;
594}
595
Anna Thomas1d02b132017-11-02 21:21:02 +0000596// Returns true if its safe to truncate the IV to RangeCheckType.
597bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) {
598 if (!EnableIVTruncation)
599 return false;
600 assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) >
601 DL->getTypeSizeInBits(RangeCheckType) &&
602 "Expected latch check IV type to be larger than range check operand "
603 "type!");
604 // The start and end values of the IV should be known. This is to guarantee
605 // that truncating the wide type will not lose information.
606 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
607 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
608 if (!Limit || !Start)
609 return false;
610 // This check makes sure that the IV does not change sign during loop
611 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
612 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
613 // IV wraps around, and the truncation of the IV would lose the range of
614 // iterations between 2^32 and 2^64.
615 bool Increasing;
616 if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing))
617 return false;
618 // The active bits should be less than the bits in the RangeCheckType. This
619 // guarantees that truncating the latch check to RangeCheckType is a safe
620 // operation.
621 auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType);
622 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
623 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
624}
625
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000626bool LoopPredication::runOnLoop(Loop *Loop) {
627 L = Loop;
628
629 DEBUG(dbgs() << "Analyzing ");
630 DEBUG(L->dump());
631
632 Module *M = L->getHeader()->getModule();
633
634 // There is nothing to do if the module doesn't use guards
635 auto *GuardDecl =
636 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
637 if (!GuardDecl || GuardDecl->use_empty())
638 return false;
639
640 DL = &M->getDataLayout();
641
642 Preheader = L->getLoopPreheader();
643 if (!Preheader)
644 return false;
645
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000646 auto LatchCheckOpt = parseLoopLatchICmp();
647 if (!LatchCheckOpt)
648 return false;
649 LatchCheck = *LatchCheckOpt;
650
Anna Thomas68797212017-11-03 14:25:39 +0000651 DEBUG(dbgs() << "Latch check:\n");
652 DEBUG(LatchCheck.dump());
653
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000654 // Collect all the guards into a vector and process later, so as not
655 // to invalidate the instruction iterator.
656 SmallVector<IntrinsicInst *, 4> Guards;
657 for (const auto BB : L->blocks())
658 for (auto &I : *BB)
659 if (auto *II = dyn_cast<IntrinsicInst>(&I))
660 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
661 Guards.push_back(II);
662
Artur Pilipenko46c4e0a2017-05-19 13:59:34 +0000663 if (Guards.empty())
664 return false;
665
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000666 SCEVExpander Expander(*SE, *DL, "loop-predication");
667
668 bool Changed = false;
669 for (auto *Guard : Guards)
670 Changed |= widenGuardConditions(Guard, Expander);
671
672 return Changed;
673}