blob: e680fbed1138fc84dab084e912688d7910b3ee6d [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() {}
192 };
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000193
194 ScalarEvolution *SE;
195
196 Loop *L;
197 const DataLayout *DL;
198 BasicBlock *Preheader;
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000199 LoopICmp LatchCheck;
Artur Pilipenkoc488dfa2017-05-22 12:01:32 +0000200
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000201 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) {
202 return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0),
203 ICI->getOperand(1));
204 }
205 Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
206 Value *RHS);
207
208 Optional<LoopICmp> parseLoopLatchICmp();
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000209
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000210 Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder,
211 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
212 Instruction *InsertAt);
213
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000214 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
215 IRBuilder<> &Builder);
216 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
217
Anna Thomas1d02b132017-11-02 21:21:02 +0000218 // When the IV type is wider than the range operand type, we can still do loop
219 // predication, by generating SCEVs for the range and latch that are of the
220 // same type. We achieve this by generating a SCEV truncate expression for the
221 // latch IV. This is done iff truncation of the IV is a safe operation,
222 // without loss of information.
223 // Another way to achieve this is by generating a wider type SCEV for the
224 // range check operand, however, this needs a more involved check that
225 // operands do not overflow. This can lead to loss of information when the
226 // range operand is of the form: add i32 %offset, %iv. We need to prove that
227 // sext(x + y) is same as sext(x) + sext(y).
228 // This function returns true if we can safely represent the IV type in
229 // the RangeCheckType without loss of information.
230 bool isSafeToTruncateWideIVType(Type *RangeCheckType);
231 // Return the loopLatchCheck corresponding to the RangeCheckType if safe to do
232 // so.
233 Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000234public:
235 LoopPredication(ScalarEvolution *SE) : SE(SE){};
236 bool runOnLoop(Loop *L);
237};
238
239class LoopPredicationLegacyPass : public LoopPass {
240public:
241 static char ID;
242 LoopPredicationLegacyPass() : LoopPass(ID) {
243 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
244 }
245
246 void getAnalysisUsage(AnalysisUsage &AU) const override {
247 getLoopAnalysisUsage(AU);
248 }
249
250 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
251 if (skipLoop(L))
252 return false;
253 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
254 LoopPredication LP(SE);
255 return LP.runOnLoop(L);
256 }
257};
258
259char LoopPredicationLegacyPass::ID = 0;
260} // end namespace llvm
261
262INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
263 "Loop predication", false, false)
264INITIALIZE_PASS_DEPENDENCY(LoopPass)
265INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
266 "Loop predication", false, false)
267
268Pass *llvm::createLoopPredicationPass() {
269 return new LoopPredicationLegacyPass();
270}
271
272PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
273 LoopStandardAnalysisResults &AR,
274 LPMUpdater &U) {
275 LoopPredication LP(&AR.SE);
276 if (!LP.runOnLoop(&L))
277 return PreservedAnalyses::all();
278
279 return getLoopPassPreservedAnalyses();
280}
281
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000282Optional<LoopPredication::LoopICmp>
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000283LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
284 Value *RHS) {
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000285 const SCEV *LHSS = SE->getSCEV(LHS);
286 if (isa<SCEVCouldNotCompute>(LHSS))
287 return None;
288 const SCEV *RHSS = SE->getSCEV(RHS);
289 if (isa<SCEVCouldNotCompute>(RHSS))
290 return None;
291
292 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
293 if (SE->isLoopInvariant(LHSS, L)) {
294 std::swap(LHS, RHS);
295 std::swap(LHSS, RHSS);
296 Pred = ICmpInst::getSwappedPredicate(Pred);
297 }
298
299 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
300 if (!AR || AR->getLoop() != L)
301 return None;
302
303 return LoopICmp(Pred, AR, RHSS);
304}
305
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000306Value *LoopPredication::expandCheck(SCEVExpander &Expander,
307 IRBuilder<> &Builder,
308 ICmpInst::Predicate Pred, const SCEV *LHS,
309 const SCEV *RHS, Instruction *InsertAt) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000310 // TODO: we can check isLoopEntryGuardedByCond before emitting the check
311
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000312 Type *Ty = LHS->getType();
313 assert(Ty == RHS->getType() && "expandCheck operands have different types?");
Artur Pilipenkoead69ee2017-10-12 21:21:17 +0000314
315 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
316 return Builder.getTrue();
317
Artur Pilipenko6780ba62017-05-19 14:00:58 +0000318 Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt);
319 Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt);
320 return Builder.CreateICmp(Pred, LHSV, RHSV);
321}
322
Anna Thomas1d02b132017-11-02 21:21:02 +0000323Optional<LoopPredication::LoopICmp>
324LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) {
325
326 auto *LatchType = LatchCheck.IV->getType();
327 if (RangeCheckType == LatchType)
328 return LatchCheck;
329 // For now, bail out if latch type is narrower than range type.
330 if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType))
331 return None;
332 if (!isSafeToTruncateWideIVType(RangeCheckType))
333 return None;
334 // We can now safely identify the truncated version of the IV and limit for
335 // RangeCheckType.
336 LoopICmp NewLatchCheck;
337 NewLatchCheck.Pred = LatchCheck.Pred;
338 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
339 SE->getTruncateExpr(LatchCheck.IV, RangeCheckType));
340 if (!NewLatchCheck.IV)
341 return None;
342 NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType);
343 DEBUG(dbgs() << "IV of type: " << *LatchType
344 << "can be represented as range check type:" << *RangeCheckType
345 << "\n");
346 DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
347 DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
348 return NewLatchCheck;
349}
350
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000351/// If ICI can be widened to a loop invariant condition emits the loop
352/// invariant condition in the loop preheader and return it, otherwise
353/// returns None.
354Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
355 SCEVExpander &Expander,
356 IRBuilder<> &Builder) {
357 DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
358 DEBUG(ICI->dump());
359
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000360 // parseLoopStructure guarantees that the latch condition is:
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000361 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000362 // We are looking for the range checks of the form:
363 // i u< guardLimit
Artur Pilipenkoa6c278042017-05-19 14:02:46 +0000364 auto RangeCheck = parseLoopICmp(ICI);
Artur Pilipenkoedee2512017-05-22 12:06:57 +0000365 if (!RangeCheck) {
366 DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000367 return None;
Artur Pilipenkoedee2512017-05-22 12:06:57 +0000368 }
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000369 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
370 DEBUG(dbgs() << "Unsupported range check predicate(" << RangeCheck->Pred
371 << ")!\n");
372 return None;
373 }
374 auto *RangeCheckIV = RangeCheck->IV;
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000375 if (!RangeCheckIV->isAffine()) {
376 DEBUG(dbgs() << "Range check IV is not affine!\n");
377 return None;
378 }
379 auto *Step = RangeCheckIV->getStepRecurrence(*SE);
Anna Thomas1d02b132017-11-02 21:21:02 +0000380 // We cannot just compare with latch IV step because the latch and range IVs
381 // may have different types.
382 if (!Step->isOne()) {
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000383 DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
384 return None;
385 }
Anna Thomas1d02b132017-11-02 21:21:02 +0000386 auto *Ty = RangeCheckIV->getType();
387 auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty);
388 if (!CurrLatchCheckOpt) {
389 DEBUG(dbgs() << "Failed to generate a loop latch check "
390 "corresponding to range type: "
391 << *Ty << "\n");
392 return None;
393 }
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000394
Anna Thomas1d02b132017-11-02 21:21:02 +0000395 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
396 // At this point the range check step and latch step should have the same
397 // value and type.
398 assert(Step == CurrLatchCheck.IV->getStepRecurrence(*SE) &&
399 "Range and latch should have same step recurrence!");
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000400 // Generate the widened condition:
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000401 // guardStart u< guardLimit &&
402 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000403 // where <pred> depends on the latch condition predicate. See the file
404 // header comment for the reasoning.
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000405 const SCEV *GuardStart = RangeCheckIV->getStart();
406 const SCEV *GuardLimit = RangeCheck->Limit;
Anna Thomas1d02b132017-11-02 21:21:02 +0000407 const SCEV *LatchStart = CurrLatchCheck.IV->getStart();
408 const SCEV *LatchLimit = CurrLatchCheck.Limit;
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000409
410 // guardLimit - guardStart + latchStart - 1
411 const SCEV *RHS =
412 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
413 SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
414
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000415 ICmpInst::Predicate LimitCheckPred;
Anna Thomas1d02b132017-11-02 21:21:02 +0000416 switch (CurrLatchCheck.Pred) {
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000417 case ICmpInst::ICMP_ULT:
418 LimitCheckPred = ICmpInst::ICMP_ULE;
419 break;
420 case ICmpInst::ICMP_ULE:
421 LimitCheckPred = ICmpInst::ICMP_ULT;
422 break;
423 case ICmpInst::ICMP_SLT:
424 LimitCheckPred = ICmpInst::ICMP_SLE;
425 break;
426 case ICmpInst::ICMP_SLE:
427 LimitCheckPred = ICmpInst::ICMP_SLT;
428 break;
429 default:
430 llvm_unreachable("Unsupported loop latch!");
431 }
Artur Pilipenkoaab28662017-05-19 14:00:04 +0000432
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000433 DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
434 DEBUG(dbgs() << "RHS: " << *RHS << "\n");
435 DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
436
Artur Pilipenkoaab28662017-05-19 14:00:04 +0000437 auto CanExpand = [this](const SCEV *S) {
438 return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
439 };
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000440 if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
441 !CanExpand(LatchLimit) || !CanExpand(RHS)) {
442 DEBUG(dbgs() << "Can't expand limit check!\n");
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000443 return None;
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000444 }
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000445
Artur Pilipenko0860bfc2017-02-27 15:44:49 +0000446 Instruction *InsertAt = Preheader->getTerminator();
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000447 auto *LimitCheck =
448 expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS, InsertAt);
Artur Pilipenkoead69ee2017-10-12 21:21:17 +0000449 auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck->Pred,
Artur Pilipenko8aadc642017-10-27 14:46:17 +0000450 GuardStart, GuardLimit, InsertAt);
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000451 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000452}
453
454bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
455 SCEVExpander &Expander) {
456 DEBUG(dbgs() << "Processing guard:\n");
457 DEBUG(Guard->dump());
458
459 IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
460
461 // The guard condition is expected to be in form of:
462 // cond1 && cond2 && cond3 ...
463 // Iterate over subconditions looking for for icmp conditions which can be
464 // widened across loop iterations. Widening these conditions remember the
465 // resulting list of subconditions in Checks vector.
466 SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0));
467 SmallPtrSet<Value *, 4> Visited;
468
469 SmallVector<Value *, 4> Checks;
470
471 unsigned NumWidened = 0;
472 do {
473 Value *Condition = Worklist.pop_back_val();
474 if (!Visited.insert(Condition).second)
475 continue;
476
477 Value *LHS, *RHS;
478 using namespace llvm::PatternMatch;
479 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
480 Worklist.push_back(LHS);
481 Worklist.push_back(RHS);
482 continue;
483 }
484
485 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
486 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
487 Checks.push_back(NewRangeCheck.getValue());
488 NumWidened++;
489 continue;
490 }
491 }
492
493 // Save the condition as is if we can't widen it
494 Checks.push_back(Condition);
495 } while (Worklist.size() != 0);
496
497 if (NumWidened == 0)
498 return false;
499
500 // Emit the new guard condition
501 Builder.SetInsertPoint(Guard);
502 Value *LastCheck = nullptr;
503 for (auto *Check : Checks)
504 if (!LastCheck)
505 LastCheck = Check;
506 else
507 LastCheck = Builder.CreateAnd(LastCheck, Check);
508 Guard->setOperand(0, LastCheck);
509
510 DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
511 return true;
512}
513
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000514Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() {
515 using namespace PatternMatch;
516
517 BasicBlock *LoopLatch = L->getLoopLatch();
518 if (!LoopLatch) {
519 DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
520 return None;
521 }
522
523 ICmpInst::Predicate Pred;
524 Value *LHS, *RHS;
525 BasicBlock *TrueDest, *FalseDest;
526
527 if (!match(LoopLatch->getTerminator(),
528 m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest,
529 FalseDest))) {
530 DEBUG(dbgs() << "Failed to match the latch terminator!\n");
531 return None;
532 }
533 assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) &&
534 "One of the latch's destinations must be the header");
535 if (TrueDest != L->getHeader())
536 Pred = ICmpInst::getInversePredicate(Pred);
537
538 auto Result = parseLoopICmp(Pred, LHS, RHS);
539 if (!Result) {
540 DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
541 return None;
542 }
543
544 if (Result->Pred != ICmpInst::ICMP_ULT &&
Artur Pilipenkob4527e12017-10-12 20:40:27 +0000545 Result->Pred != ICmpInst::ICMP_SLT &&
546 Result->Pred != ICmpInst::ICMP_ULE &&
547 Result->Pred != ICmpInst::ICMP_SLE) {
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000548 DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
549 << ")!\n");
550 return None;
551 }
552
553 // Check affine first, so if it's not we don't try to compute the step
554 // recurrence.
555 if (!Result->IV->isAffine()) {
556 DEBUG(dbgs() << "The induction variable is not affine!\n");
557 return None;
558 }
559
560 auto *Step = Result->IV->getStepRecurrence(*SE);
561 if (!Step->isOne()) {
562 DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
563 return None;
564 }
565
566 return Result;
567}
568
Anna Thomas1d02b132017-11-02 21:21:02 +0000569// Returns true if its safe to truncate the IV to RangeCheckType.
570bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) {
571 if (!EnableIVTruncation)
572 return false;
573 assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) >
574 DL->getTypeSizeInBits(RangeCheckType) &&
575 "Expected latch check IV type to be larger than range check operand "
576 "type!");
577 // The start and end values of the IV should be known. This is to guarantee
578 // that truncating the wide type will not lose information.
579 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
580 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
581 if (!Limit || !Start)
582 return false;
583 // This check makes sure that the IV does not change sign during loop
584 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
585 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
586 // IV wraps around, and the truncation of the IV would lose the range of
587 // iterations between 2^32 and 2^64.
588 bool Increasing;
589 if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing))
590 return false;
591 // The active bits should be less than the bits in the RangeCheckType. This
592 // guarantees that truncating the latch check to RangeCheckType is a safe
593 // operation.
594 auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType);
595 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
596 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
597}
598
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000599bool LoopPredication::runOnLoop(Loop *Loop) {
600 L = Loop;
601
602 DEBUG(dbgs() << "Analyzing ");
603 DEBUG(L->dump());
604
605 Module *M = L->getHeader()->getModule();
606
607 // There is nothing to do if the module doesn't use guards
608 auto *GuardDecl =
609 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
610 if (!GuardDecl || GuardDecl->use_empty())
611 return false;
612
613 DL = &M->getDataLayout();
614
615 Preheader = L->getLoopPreheader();
616 if (!Preheader)
617 return false;
618
Artur Pilipenko889dc1e2017-09-22 13:13:57 +0000619 auto LatchCheckOpt = parseLoopLatchICmp();
620 if (!LatchCheckOpt)
621 return false;
622 LatchCheck = *LatchCheckOpt;
623
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000624 // Collect all the guards into a vector and process later, so as not
625 // to invalidate the instruction iterator.
626 SmallVector<IntrinsicInst *, 4> Guards;
627 for (const auto BB : L->blocks())
628 for (auto &I : *BB)
629 if (auto *II = dyn_cast<IntrinsicInst>(&I))
630 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
631 Guards.push_back(II);
632
Artur Pilipenko46c4e0a2017-05-19 13:59:34 +0000633 if (Guards.empty())
634 return false;
635
Artur Pilipenko8fb3d572017-01-25 16:00:44 +0000636 SCEVExpander Expander(*SE, *DL, "loop-predication");
637
638 bool Changed = false;
639 for (auto *Guard : Guards)
640 Changed |= widenGuardConditions(Guard, Expander);
641
642 return Changed;
643}