1 //===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // The LoopPredication pass tries to convert loop variant range checks to loop
10 // invariant by widening checks across loop iterations. For example, it will
11 // convert
12 //
13 // for (i = 0; i < n; i++) {
14 // guard(i < len);
15 // ...
16 // }
17 //
18 // to
19 //
20 // for (i = 0; i < n; i++) {
21 // guard(n - 1 < len);
22 // ...
23 // }
24 //
25 // After this transformation the condition of the guard is loop invariant, so
26 // loop-unswitch can later unswitch the loop by this condition which basically
27 // predicates the loop by the widened condition:
28 //
29 // if (n - 1 < len)
30 // for (i = 0; i < n; i++) {
31 // ...
32 // }
33 // else
34 // deoptimize
35 //
36 // It's tempting to rely on SCEV here, but it has proven to be problematic.
37 // Generally the facts SCEV provides about the increment step of add
38 // recurrences are true if the backedge of the loop is taken, which implicitly
39 // assumes that the guard doesn't fail. Using these facts to optimize the
40 // guard results in a circular logic where the guard is optimized under the
41 // assumption that it never fails.
42 //
43 // For example, in the loop below the induction variable will be marked as nuw
44 // basing on the guard. Basing on nuw the guard predicate will be considered
45 // monotonic. Given a monotonic condition it's tempting to replace the induction
46 // variable in the condition with its value on the last iteration. But this
47 // transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
48 //
49 // for (int i = b; i != e; i++)
50 // guard(i u< len)
51 //
52 // One of the ways to reason about this problem is to use an inductive proof
53 // approach. Given the loop:
54 //
55 // if (B(0)) {
56 // do {
57 // I = PHI(0, I.INC)
58 // I.INC = I + Step
59 // guard(G(I));
60 // } while (B(I));
61 // }
62 //
63 // where B(x) and G(x) are predicates that map integers to booleans, we want a
64 // loop invariant expression M such the following program has the same semantics
65 // as the above:
66 //
67 // if (B(0)) {
68 // do {
69 // I = PHI(0, I.INC)
70 // I.INC = I + Step
71 // guard(G(0) && M);
72 // } while (B(I));
73 // }
74 //
75 // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
76 //
77 // Informal proof that the transformation above is correct:
78 //
79 // By the definition of guards we can rewrite the guard condition to:
80 // G(I) && G(0) && M
81 //
82 // Let's prove that for each iteration of the loop:
83 // G(0) && M => G(I)
84 // And the condition above can be simplified to G(Start) && M.
85 //
86 // Induction base.
87 // G(0) && M => G(0)
88 //
89 // Induction step. Assuming G(0) && M => G(I) on the subsequent
90 // iteration:
91 //
92 // B(I) is true because it's the backedge condition.
93 // G(I) is true because the backedge is guarded by this condition.
94 //
95 // So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
96 //
97 // Note that we can use anything stronger than M, i.e. any condition which
98 // implies M.
99 //
100 // When S = 1 (i.e. forward iterating loop), the transformation is supported
101 // when:
102 // * The loop has a single latch with the condition of the form:
103 // B(X) = latchStart + X <pred> latchLimit,
104 // where <pred> is u<, u<=, s<, or s<=.
105 // * The guard condition is of the form
106 // G(X) = guardStart + X u< guardLimit
107 //
108 // For the ult latch comparison case M is:
109 // forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
110 // guardStart + X + 1 u< guardLimit
111 //
112 // The only way the antecedent can be true and the consequent can be false is
113 // if
114 // X == guardLimit - 1 - guardStart
115 // (and guardLimit is non-zero, but we won't use this latter fact).
116 // If X == guardLimit - 1 - guardStart then the second half of the antecedent is
117 // latchStart + guardLimit - 1 - guardStart u< latchLimit
118 // and its negation is
119 // latchStart + guardLimit - 1 - guardStart u>= latchLimit
120 //
121 // In other words, if
122 // latchLimit u<= latchStart + guardLimit - 1 - guardStart
123 // then:
124 // (the ranges below are written in ConstantRange notation, where [A, B) is the
125 // set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
126 //
127 // forall X . guardStart + X u< guardLimit &&
128 // latchStart + X u< latchLimit =>
129 // guardStart + X + 1 u< guardLimit
130 // == forall X . guardStart + X u< guardLimit &&
131 // latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
132 // guardStart + X + 1 u< guardLimit
133 // == forall X . (guardStart + X) in [0, guardLimit) &&
134 // (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
135 // (guardStart + X + 1) in [0, guardLimit)
136 // == forall X . X in [-guardStart, guardLimit - guardStart) &&
137 // X in [-latchStart, guardLimit - 1 - guardStart) =>
138 // X in [-guardStart - 1, guardLimit - guardStart - 1)
139 // == true
140 //
141 // So the widened condition is:
142 // guardStart u< guardLimit &&
143 // latchStart + guardLimit - 1 - guardStart u>= latchLimit
144 // Similarly for ule condition the widened condition is:
145 // guardStart u< guardLimit &&
146 // latchStart + guardLimit - 1 - guardStart u> latchLimit
147 // For slt condition the widened condition is:
148 // guardStart u< guardLimit &&
149 // latchStart + guardLimit - 1 - guardStart s>= latchLimit
150 // For sle condition the widened condition is:
151 // guardStart u< guardLimit &&
152 // latchStart + guardLimit - 1 - guardStart s> latchLimit
153 //
154 // When S = -1 (i.e. reverse iterating loop), the transformation is supported
155 // when:
156 // * The loop has a single latch with the condition of the form:
157 // B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=.
158 // * The guard condition is of the form
159 // G(X) = X - 1 u< guardLimit
160 //
161 // For the ugt latch comparison case M is:
162 // forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit
163 //
164 // The only way the antecedent can be true and the consequent can be false is if
165 // X == 1.
166 // If X == 1 then the second half of the antecedent is
167 // 1 u> latchLimit, and its negation is latchLimit u>= 1.
168 //
169 // So the widened condition is:
170 // guardStart u< guardLimit && latchLimit u>= 1.
171 // Similarly for sgt condition the widened condition is:
172 // guardStart u< guardLimit && latchLimit s>= 1.
173 // For uge condition the widened condition is:
174 // guardStart u< guardLimit && latchLimit u> 1.
175 // For sge condition the widened condition is:
176 // guardStart u< guardLimit && latchLimit s> 1.
177 //===----------------------------------------------------------------------===//
178
179 #include "llvm/Transforms/Scalar/LoopPredication.h"
180 #include "llvm/ADT/Statistic.h"
181 #include "llvm/Analysis/AliasAnalysis.h"
182 #include "llvm/Analysis/BranchProbabilityInfo.h"
183 #include "llvm/Analysis/GuardUtils.h"
184 #include "llvm/Analysis/LoopInfo.h"
185 #include "llvm/Analysis/LoopPass.h"
186 #include "llvm/Analysis/MemorySSA.h"
187 #include "llvm/Analysis/MemorySSAUpdater.h"
188 #include "llvm/Analysis/ScalarEvolution.h"
189 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
190 #include "llvm/IR/Function.h"
191 #include "llvm/IR/IntrinsicInst.h"
192 #include "llvm/IR/Module.h"
193 #include "llvm/IR/PatternMatch.h"
194 #include "llvm/InitializePasses.h"
195 #include "llvm/Pass.h"
196 #include "llvm/Support/CommandLine.h"
197 #include "llvm/Support/Debug.h"
198 #include "llvm/Transforms/Scalar.h"
199 #include "llvm/Transforms/Utils/GuardUtils.h"
200 #include "llvm/Transforms/Utils/Local.h"
201 #include "llvm/Transforms/Utils/LoopUtils.h"
202 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
203
204 #define DEBUG_TYPE "loop-predication"
205
206 STATISTIC(TotalConsidered, "Number of guards considered");
207 STATISTIC(TotalWidened, "Number of checks widened");
208
209 using namespace llvm;
210
211 static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
212 cl::Hidden, cl::init(true));
213
214 static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
215 cl::Hidden, cl::init(true));
216
217 static cl::opt<bool>
218 SkipProfitabilityChecks("loop-predication-skip-profitability-checks",
219 cl::Hidden, cl::init(false));
220
221 // This is the scale factor for the latch probability. We use this during
222 // profitability analysis to find other exiting blocks that have a much higher
223 // probability of exiting the loop instead of loop exiting via latch.
224 // This value should be greater than 1 for a sane profitability check.
225 static cl::opt<float> LatchExitProbabilityScale(
226 "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0),
227 cl::desc("scale factor for the latch probability. Value should be greater "
228 "than 1. Lower values are ignored"));
229
230 static cl::opt<bool> PredicateWidenableBranchGuards(
231 "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden,
232 cl::desc("Whether or not we should predicate guards "
233 "expressed as widenable branches to deoptimize blocks"),
234 cl::init(true));
235
236 namespace {
237 /// Represents an induction variable check:
238 /// icmp Pred, <induction variable>, <loop invariant limit>
239 struct LoopICmp {
240 ICmpInst::Predicate Pred;
241 const SCEVAddRecExpr *IV;
242 const SCEV *Limit;
LoopICmp__anon082da8af0111::LoopICmp243 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
244 const SCEV *Limit)
245 : Pred(Pred), IV(IV), Limit(Limit) {}
246 LoopICmp() = default;
dump__anon082da8af0111::LoopICmp247 void dump() {
248 dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
249 << ", Limit = " << *Limit << "\n";
250 }
251 };
252
253 class LoopPredication {
254 AliasAnalysis *AA;
255 DominatorTree *DT;
256 ScalarEvolution *SE;
257 LoopInfo *LI;
258 MemorySSAUpdater *MSSAU;
259
260 Loop *L;
261 const DataLayout *DL;
262 BasicBlock *Preheader;
263 LoopICmp LatchCheck;
264
265 bool isSupportedStep(const SCEV* Step);
266 Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI);
267 Optional<LoopICmp> parseLoopLatchICmp();
268
269 /// Return an insertion point suitable for inserting a safe to speculate
270 /// instruction whose only user will be 'User' which has operands 'Ops'. A
271 /// trivial result would be the at the User itself, but we try to return a
272 /// loop invariant location if possible.
273 Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops);
274 /// Same as above, *except* that this uses the SCEV definition of invariant
275 /// which is that an expression *can be made* invariant via SCEVExpander.
276 /// Thus, this version is only suitable for finding an insert point to be be
277 /// passed to SCEVExpander!
278 Instruction *findInsertPt(const SCEVExpander &Expander, Instruction *User,
279 ArrayRef<const SCEV *> Ops);
280
281 /// Return true if the value is known to produce a single fixed value across
282 /// all iterations on which it executes. Note that this does not imply
283 /// speculation safety. That must be established separately.
284 bool isLoopInvariantValue(const SCEV* S);
285
286 Value *expandCheck(SCEVExpander &Expander, Instruction *Guard,
287 ICmpInst::Predicate Pred, const SCEV *LHS,
288 const SCEV *RHS);
289
290 Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
291 Instruction *Guard);
292 Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
293 LoopICmp RangeCheck,
294 SCEVExpander &Expander,
295 Instruction *Guard);
296 Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
297 LoopICmp RangeCheck,
298 SCEVExpander &Expander,
299 Instruction *Guard);
300 unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition,
301 SCEVExpander &Expander, Instruction *Guard);
302 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
303 bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander);
304 // If the loop always exits through another block in the loop, we should not
305 // predicate based on the latch check. For example, the latch check can be a
306 // very coarse grained check and there can be more fine grained exit checks
307 // within the loop.
308 bool isLoopProfitableToPredicate();
309
310 bool predicateLoopExits(Loop *L, SCEVExpander &Rewriter);
311
312 public:
LoopPredication(AliasAnalysis * AA,DominatorTree * DT,ScalarEvolution * SE,LoopInfo * LI,MemorySSAUpdater * MSSAU)313 LoopPredication(AliasAnalysis *AA, DominatorTree *DT, ScalarEvolution *SE,
314 LoopInfo *LI, MemorySSAUpdater *MSSAU)
315 : AA(AA), DT(DT), SE(SE), LI(LI), MSSAU(MSSAU){};
316 bool runOnLoop(Loop *L);
317 };
318
319 class LoopPredicationLegacyPass : public LoopPass {
320 public:
321 static char ID;
LoopPredicationLegacyPass()322 LoopPredicationLegacyPass() : LoopPass(ID) {
323 initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
324 }
325
getAnalysisUsage(AnalysisUsage & AU) const326 void getAnalysisUsage(AnalysisUsage &AU) const override {
327 AU.addRequired<BranchProbabilityInfoWrapperPass>();
328 getLoopAnalysisUsage(AU);
329 AU.addPreserved<MemorySSAWrapperPass>();
330 }
331
runOnLoop(Loop * L,LPPassManager & LPM)332 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
333 if (skipLoop(L))
334 return false;
335 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
336 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
337 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
338 auto *MSSAWP = getAnalysisIfAvailable<MemorySSAWrapperPass>();
339 std::unique_ptr<MemorySSAUpdater> MSSAU;
340 if (MSSAWP)
341 MSSAU = std::make_unique<MemorySSAUpdater>(&MSSAWP->getMSSA());
342 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
343 LoopPredication LP(AA, DT, SE, LI, MSSAU ? MSSAU.get() : nullptr);
344 return LP.runOnLoop(L);
345 }
346 };
347
348 char LoopPredicationLegacyPass::ID = 0;
349 } // end namespace
350
351 INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
352 "Loop predication", false, false)
INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)353 INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
354 INITIALIZE_PASS_DEPENDENCY(LoopPass)
355 INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
356 "Loop predication", false, false)
357
358 Pass *llvm::createLoopPredicationPass() {
359 return new LoopPredicationLegacyPass();
360 }
361
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater & U)362 PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
363 LoopStandardAnalysisResults &AR,
364 LPMUpdater &U) {
365 std::unique_ptr<MemorySSAUpdater> MSSAU;
366 if (AR.MSSA)
367 MSSAU = std::make_unique<MemorySSAUpdater>(AR.MSSA);
368 LoopPredication LP(&AR.AA, &AR.DT, &AR.SE, &AR.LI,
369 MSSAU ? MSSAU.get() : nullptr);
370 if (!LP.runOnLoop(&L))
371 return PreservedAnalyses::all();
372
373 auto PA = getLoopPassPreservedAnalyses();
374 if (AR.MSSA)
375 PA.preserve<MemorySSAAnalysis>();
376 return PA;
377 }
378
379 Optional<LoopICmp>
parseLoopICmp(ICmpInst * ICI)380 LoopPredication::parseLoopICmp(ICmpInst *ICI) {
381 auto Pred = ICI->getPredicate();
382 auto *LHS = ICI->getOperand(0);
383 auto *RHS = ICI->getOperand(1);
384
385 const SCEV *LHSS = SE->getSCEV(LHS);
386 if (isa<SCEVCouldNotCompute>(LHSS))
387 return None;
388 const SCEV *RHSS = SE->getSCEV(RHS);
389 if (isa<SCEVCouldNotCompute>(RHSS))
390 return None;
391
392 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
393 if (SE->isLoopInvariant(LHSS, L)) {
394 std::swap(LHS, RHS);
395 std::swap(LHSS, RHSS);
396 Pred = ICmpInst::getSwappedPredicate(Pred);
397 }
398
399 const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
400 if (!AR || AR->getLoop() != L)
401 return None;
402
403 return LoopICmp(Pred, AR, RHSS);
404 }
405
expandCheck(SCEVExpander & Expander,Instruction * Guard,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)406 Value *LoopPredication::expandCheck(SCEVExpander &Expander,
407 Instruction *Guard,
408 ICmpInst::Predicate Pred, const SCEV *LHS,
409 const SCEV *RHS) {
410 Type *Ty = LHS->getType();
411 assert(Ty == RHS->getType() && "expandCheck operands have different types?");
412
413 if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) {
414 IRBuilder<> Builder(Guard);
415 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
416 return Builder.getTrue();
417 if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred),
418 LHS, RHS))
419 return Builder.getFalse();
420 }
421
422 Value *LHSV =
423 Expander.expandCodeFor(LHS, Ty, findInsertPt(Expander, Guard, {LHS}));
424 Value *RHSV =
425 Expander.expandCodeFor(RHS, Ty, findInsertPt(Expander, Guard, {RHS}));
426 IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV}));
427 return Builder.CreateICmp(Pred, LHSV, RHSV);
428 }
429
430 // Returns true if its safe to truncate the IV to RangeCheckType.
431 // When the IV type is wider than the range operand type, we can still do loop
432 // predication, by generating SCEVs for the range and latch that are of the
433 // same type. We achieve this by generating a SCEV truncate expression for the
434 // latch IV. This is done iff truncation of the IV is a safe operation,
435 // without loss of information.
436 // Another way to achieve this is by generating a wider type SCEV for the
437 // range check operand, however, this needs a more involved check that
438 // operands do not overflow. This can lead to loss of information when the
439 // range operand is of the form: add i32 %offset, %iv. We need to prove that
440 // sext(x + y) is same as sext(x) + sext(y).
441 // This function returns true if we can safely represent the IV type in
442 // the RangeCheckType without loss of information.
isSafeToTruncateWideIVType(const DataLayout & DL,ScalarEvolution & SE,const LoopICmp LatchCheck,Type * RangeCheckType)443 static bool isSafeToTruncateWideIVType(const DataLayout &DL,
444 ScalarEvolution &SE,
445 const LoopICmp LatchCheck,
446 Type *RangeCheckType) {
447 if (!EnableIVTruncation)
448 return false;
449 assert(DL.getTypeSizeInBits(LatchCheck.IV->getType()).getFixedSize() >
450 DL.getTypeSizeInBits(RangeCheckType).getFixedSize() &&
451 "Expected latch check IV type to be larger than range check operand "
452 "type!");
453 // The start and end values of the IV should be known. This is to guarantee
454 // that truncating the wide type will not lose information.
455 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
456 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
457 if (!Limit || !Start)
458 return false;
459 // This check makes sure that the IV does not change sign during loop
460 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
461 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
462 // IV wraps around, and the truncation of the IV would lose the range of
463 // iterations between 2^32 and 2^64.
464 if (!SE.getMonotonicPredicateType(LatchCheck.IV, LatchCheck.Pred))
465 return false;
466 // The active bits should be less than the bits in the RangeCheckType. This
467 // guarantees that truncating the latch check to RangeCheckType is a safe
468 // operation.
469 auto RangeCheckTypeBitSize =
470 DL.getTypeSizeInBits(RangeCheckType).getFixedSize();
471 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
472 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
473 }
474
475
476 // Return an LoopICmp describing a latch check equivlent to LatchCheck but with
477 // the requested type if safe to do so. May involve the use of a new IV.
generateLoopLatchCheck(const DataLayout & DL,ScalarEvolution & SE,const LoopICmp LatchCheck,Type * RangeCheckType)478 static Optional<LoopICmp> generateLoopLatchCheck(const DataLayout &DL,
479 ScalarEvolution &SE,
480 const LoopICmp LatchCheck,
481 Type *RangeCheckType) {
482
483 auto *LatchType = LatchCheck.IV->getType();
484 if (RangeCheckType == LatchType)
485 return LatchCheck;
486 // For now, bail out if latch type is narrower than range type.
487 if (DL.getTypeSizeInBits(LatchType).getFixedSize() <
488 DL.getTypeSizeInBits(RangeCheckType).getFixedSize())
489 return None;
490 if (!isSafeToTruncateWideIVType(DL, SE, LatchCheck, RangeCheckType))
491 return None;
492 // We can now safely identify the truncated version of the IV and limit for
493 // RangeCheckType.
494 LoopICmp NewLatchCheck;
495 NewLatchCheck.Pred = LatchCheck.Pred;
496 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
497 SE.getTruncateExpr(LatchCheck.IV, RangeCheckType));
498 if (!NewLatchCheck.IV)
499 return None;
500 NewLatchCheck.Limit = SE.getTruncateExpr(LatchCheck.Limit, RangeCheckType);
501 LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType
502 << "can be represented as range check type:"
503 << *RangeCheckType << "\n");
504 LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
505 LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
506 return NewLatchCheck;
507 }
508
isSupportedStep(const SCEV * Step)509 bool LoopPredication::isSupportedStep(const SCEV* Step) {
510 return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
511 }
512
findInsertPt(Instruction * Use,ArrayRef<Value * > Ops)513 Instruction *LoopPredication::findInsertPt(Instruction *Use,
514 ArrayRef<Value*> Ops) {
515 for (Value *Op : Ops)
516 if (!L->isLoopInvariant(Op))
517 return Use;
518 return Preheader->getTerminator();
519 }
520
findInsertPt(const SCEVExpander & Expander,Instruction * Use,ArrayRef<const SCEV * > Ops)521 Instruction *LoopPredication::findInsertPt(const SCEVExpander &Expander,
522 Instruction *Use,
523 ArrayRef<const SCEV *> Ops) {
524 // Subtlety: SCEV considers things to be invariant if the value produced is
525 // the same across iterations. This is not the same as being able to
526 // evaluate outside the loop, which is what we actually need here.
527 for (const SCEV *Op : Ops)
528 if (!SE->isLoopInvariant(Op, L) ||
529 !Expander.isSafeToExpandAt(Op, Preheader->getTerminator()))
530 return Use;
531 return Preheader->getTerminator();
532 }
533
isLoopInvariantValue(const SCEV * S)534 bool LoopPredication::isLoopInvariantValue(const SCEV* S) {
535 // Handling expressions which produce invariant results, but *haven't* yet
536 // been removed from the loop serves two important purposes.
537 // 1) Most importantly, it resolves a pass ordering cycle which would
538 // otherwise need us to iteration licm, loop-predication, and either
539 // loop-unswitch or loop-peeling to make progress on examples with lots of
540 // predicable range checks in a row. (Since, in the general case, we can't
541 // hoist the length checks until the dominating checks have been discharged
542 // as we can't prove doing so is safe.)
543 // 2) As a nice side effect, this exposes the value of peeling or unswitching
544 // much more obviously in the IR. Otherwise, the cost modeling for other
545 // transforms would end up needing to duplicate all of this logic to model a
546 // check which becomes predictable based on a modeled peel or unswitch.
547 //
548 // The cost of doing so in the worst case is an extra fill from the stack in
549 // the loop to materialize the loop invariant test value instead of checking
550 // against the original IV which is presumable in a register inside the loop.
551 // Such cases are presumably rare, and hint at missing oppurtunities for
552 // other passes.
553
554 if (SE->isLoopInvariant(S, L))
555 // Note: This the SCEV variant, so the original Value* may be within the
556 // loop even though SCEV has proven it is loop invariant.
557 return true;
558
559 // Handle a particular important case which SCEV doesn't yet know about which
560 // shows up in range checks on arrays with immutable lengths.
561 // TODO: This should be sunk inside SCEV.
562 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
563 if (const auto *LI = dyn_cast<LoadInst>(U->getValue()))
564 if (LI->isUnordered() && L->hasLoopInvariantOperands(LI))
565 if (AA->pointsToConstantMemory(LI->getOperand(0)) ||
566 LI->hasMetadata(LLVMContext::MD_invariant_load))
567 return true;
568 return false;
569 }
570
widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,LoopICmp RangeCheck,SCEVExpander & Expander,Instruction * Guard)571 Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
572 LoopICmp LatchCheck, LoopICmp RangeCheck,
573 SCEVExpander &Expander, Instruction *Guard) {
574 auto *Ty = RangeCheck.IV->getType();
575 // Generate the widened condition for the forward loop:
576 // guardStart u< guardLimit &&
577 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart
578 // where <pred> depends on the latch condition predicate. See the file
579 // header comment for the reasoning.
580 // guardLimit - guardStart + latchStart - 1
581 const SCEV *GuardStart = RangeCheck.IV->getStart();
582 const SCEV *GuardLimit = RangeCheck.Limit;
583 const SCEV *LatchStart = LatchCheck.IV->getStart();
584 const SCEV *LatchLimit = LatchCheck.Limit;
585 // Subtlety: We need all the values to be *invariant* across all iterations,
586 // but we only need to check expansion safety for those which *aren't*
587 // already guaranteed to dominate the guard.
588 if (!isLoopInvariantValue(GuardStart) ||
589 !isLoopInvariantValue(GuardLimit) ||
590 !isLoopInvariantValue(LatchStart) ||
591 !isLoopInvariantValue(LatchLimit)) {
592 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
593 return None;
594 }
595 if (!Expander.isSafeToExpandAt(LatchStart, Guard) ||
596 !Expander.isSafeToExpandAt(LatchLimit, Guard)) {
597 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
598 return None;
599 }
600
601 // guardLimit - guardStart + latchStart - 1
602 const SCEV *RHS =
603 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
604 SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
605 auto LimitCheckPred =
606 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
607
608 LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
609 LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n");
610 LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
611
612 auto *LimitCheck =
613 expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS);
614 auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred,
615 GuardStart, GuardLimit);
616 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
617 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
618 }
619
widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,LoopICmp RangeCheck,SCEVExpander & Expander,Instruction * Guard)620 Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
621 LoopICmp LatchCheck, LoopICmp RangeCheck,
622 SCEVExpander &Expander, Instruction *Guard) {
623 auto *Ty = RangeCheck.IV->getType();
624 const SCEV *GuardStart = RangeCheck.IV->getStart();
625 const SCEV *GuardLimit = RangeCheck.Limit;
626 const SCEV *LatchStart = LatchCheck.IV->getStart();
627 const SCEV *LatchLimit = LatchCheck.Limit;
628 // Subtlety: We need all the values to be *invariant* across all iterations,
629 // but we only need to check expansion safety for those which *aren't*
630 // already guaranteed to dominate the guard.
631 if (!isLoopInvariantValue(GuardStart) ||
632 !isLoopInvariantValue(GuardLimit) ||
633 !isLoopInvariantValue(LatchStart) ||
634 !isLoopInvariantValue(LatchLimit)) {
635 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
636 return None;
637 }
638 if (!Expander.isSafeToExpandAt(LatchStart, Guard) ||
639 !Expander.isSafeToExpandAt(LatchLimit, Guard)) {
640 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
641 return None;
642 }
643 // The decrement of the latch check IV should be the same as the
644 // rangeCheckIV.
645 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
646 if (RangeCheck.IV != PostDecLatchCheckIV) {
647 LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
648 << *PostDecLatchCheckIV
649 << " and RangeCheckIV: " << *RangeCheck.IV << "\n");
650 return None;
651 }
652
653 // Generate the widened condition for CountDownLoop:
654 // guardStart u< guardLimit &&
655 // latchLimit <pred> 1.
656 // See the header comment for reasoning of the checks.
657 auto LimitCheckPred =
658 ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
659 auto *FirstIterationCheck = expandCheck(Expander, Guard,
660 ICmpInst::ICMP_ULT,
661 GuardStart, GuardLimit);
662 auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit,
663 SE->getOne(Ty));
664 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
665 return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
666 }
667
normalizePredicate(ScalarEvolution * SE,Loop * L,LoopICmp & RC)668 static void normalizePredicate(ScalarEvolution *SE, Loop *L,
669 LoopICmp& RC) {
670 // LFTR canonicalizes checks to the ICMP_NE/EQ form; normalize back to the
671 // ULT/UGE form for ease of handling by our caller.
672 if (ICmpInst::isEquality(RC.Pred) &&
673 RC.IV->getStepRecurrence(*SE)->isOne() &&
674 SE->isKnownPredicate(ICmpInst::ICMP_ULE, RC.IV->getStart(), RC.Limit))
675 RC.Pred = RC.Pred == ICmpInst::ICMP_NE ?
676 ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
677 }
678
679
680 /// If ICI can be widened to a loop invariant condition emits the loop
681 /// invariant condition in the loop preheader and return it, otherwise
682 /// returns None.
widenICmpRangeCheck(ICmpInst * ICI,SCEVExpander & Expander,Instruction * Guard)683 Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
684 SCEVExpander &Expander,
685 Instruction *Guard) {
686 LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
687 LLVM_DEBUG(ICI->dump());
688
689 // parseLoopStructure guarantees that the latch condition is:
690 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
691 // We are looking for the range checks of the form:
692 // i u< guardLimit
693 auto RangeCheck = parseLoopICmp(ICI);
694 if (!RangeCheck) {
695 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
696 return None;
697 }
698 LLVM_DEBUG(dbgs() << "Guard check:\n");
699 LLVM_DEBUG(RangeCheck->dump());
700 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
701 LLVM_DEBUG(dbgs() << "Unsupported range check predicate("
702 << RangeCheck->Pred << ")!\n");
703 return None;
704 }
705 auto *RangeCheckIV = RangeCheck->IV;
706 if (!RangeCheckIV->isAffine()) {
707 LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n");
708 return None;
709 }
710 auto *Step = RangeCheckIV->getStepRecurrence(*SE);
711 // We cannot just compare with latch IV step because the latch and range IVs
712 // may have different types.
713 if (!isSupportedStep(Step)) {
714 LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
715 return None;
716 }
717 auto *Ty = RangeCheckIV->getType();
718 auto CurrLatchCheckOpt = generateLoopLatchCheck(*DL, *SE, LatchCheck, Ty);
719 if (!CurrLatchCheckOpt) {
720 LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check "
721 "corresponding to range type: "
722 << *Ty << "\n");
723 return None;
724 }
725
726 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
727 // At this point, the range and latch step should have the same type, but need
728 // not have the same value (we support both 1 and -1 steps).
729 assert(Step->getType() ==
730 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
731 "Range and latch steps should be of same type!");
732 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
733 LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n");
734 return None;
735 }
736
737 if (Step->isOne())
738 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
739 Expander, Guard);
740 else {
741 assert(Step->isAllOnesValue() && "Step should be -1!");
742 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
743 Expander, Guard);
744 }
745 }
746
collectChecks(SmallVectorImpl<Value * > & Checks,Value * Condition,SCEVExpander & Expander,Instruction * Guard)747 unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks,
748 Value *Condition,
749 SCEVExpander &Expander,
750 Instruction *Guard) {
751 unsigned NumWidened = 0;
752 // The guard condition is expected to be in form of:
753 // cond1 && cond2 && cond3 ...
754 // Iterate over subconditions looking for icmp conditions which can be
755 // widened across loop iterations. Widening these conditions remember the
756 // resulting list of subconditions in Checks vector.
757 SmallVector<Value *, 4> Worklist(1, Condition);
758 SmallPtrSet<Value *, 4> Visited;
759 Value *WideableCond = nullptr;
760 do {
761 Value *Condition = Worklist.pop_back_val();
762 if (!Visited.insert(Condition).second)
763 continue;
764
765 Value *LHS, *RHS;
766 using namespace llvm::PatternMatch;
767 if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
768 Worklist.push_back(LHS);
769 Worklist.push_back(RHS);
770 continue;
771 }
772
773 if (match(Condition,
774 m_Intrinsic<Intrinsic::experimental_widenable_condition>())) {
775 // Pick any, we don't care which
776 WideableCond = Condition;
777 continue;
778 }
779
780 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
781 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander,
782 Guard)) {
783 Checks.push_back(*NewRangeCheck);
784 NumWidened++;
785 continue;
786 }
787 }
788
789 // Save the condition as is if we can't widen it
790 Checks.push_back(Condition);
791 } while (!Worklist.empty());
792 // At the moment, our matching logic for wideable conditions implicitly
793 // assumes we preserve the form: (br (and Cond, WC())). FIXME
794 // Note that if there were multiple calls to wideable condition in the
795 // traversal, we only need to keep one, and which one is arbitrary.
796 if (WideableCond)
797 Checks.push_back(WideableCond);
798 return NumWidened;
799 }
800
widenGuardConditions(IntrinsicInst * Guard,SCEVExpander & Expander)801 bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
802 SCEVExpander &Expander) {
803 LLVM_DEBUG(dbgs() << "Processing guard:\n");
804 LLVM_DEBUG(Guard->dump());
805
806 TotalConsidered++;
807 SmallVector<Value *, 4> Checks;
808 unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander,
809 Guard);
810 if (NumWidened == 0)
811 return false;
812
813 TotalWidened += NumWidened;
814
815 // Emit the new guard condition
816 IRBuilder<> Builder(findInsertPt(Guard, Checks));
817 Value *AllChecks = Builder.CreateAnd(Checks);
818 auto *OldCond = Guard->getOperand(0);
819 Guard->setOperand(0, AllChecks);
820 RecursivelyDeleteTriviallyDeadInstructions(OldCond, nullptr /* TLI */, MSSAU);
821
822 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
823 return true;
824 }
825
widenWidenableBranchGuardConditions(BranchInst * BI,SCEVExpander & Expander)826 bool LoopPredication::widenWidenableBranchGuardConditions(
827 BranchInst *BI, SCEVExpander &Expander) {
828 assert(isGuardAsWidenableBranch(BI) && "Must be!");
829 LLVM_DEBUG(dbgs() << "Processing guard:\n");
830 LLVM_DEBUG(BI->dump());
831
832 TotalConsidered++;
833 SmallVector<Value *, 4> Checks;
834 unsigned NumWidened = collectChecks(Checks, BI->getCondition(),
835 Expander, BI);
836 if (NumWidened == 0)
837 return false;
838
839 TotalWidened += NumWidened;
840
841 // Emit the new guard condition
842 IRBuilder<> Builder(findInsertPt(BI, Checks));
843 Value *AllChecks = Builder.CreateAnd(Checks);
844 auto *OldCond = BI->getCondition();
845 BI->setCondition(AllChecks);
846 RecursivelyDeleteTriviallyDeadInstructions(OldCond, nullptr /* TLI */, MSSAU);
847 assert(isGuardAsWidenableBranch(BI) &&
848 "Stopped being a guard after transform?");
849
850 LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
851 return true;
852 }
853
parseLoopLatchICmp()854 Optional<LoopICmp> LoopPredication::parseLoopLatchICmp() {
855 using namespace PatternMatch;
856
857 BasicBlock *LoopLatch = L->getLoopLatch();
858 if (!LoopLatch) {
859 LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
860 return None;
861 }
862
863 auto *BI = dyn_cast<BranchInst>(LoopLatch->getTerminator());
864 if (!BI || !BI->isConditional()) {
865 LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n");
866 return None;
867 }
868 BasicBlock *TrueDest = BI->getSuccessor(0);
869 assert(
870 (TrueDest == L->getHeader() || BI->getSuccessor(1) == L->getHeader()) &&
871 "One of the latch's destinations must be the header");
872
873 auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
874 if (!ICI) {
875 LLVM_DEBUG(dbgs() << "Failed to match the latch condition!\n");
876 return None;
877 }
878 auto Result = parseLoopICmp(ICI);
879 if (!Result) {
880 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
881 return None;
882 }
883
884 if (TrueDest != L->getHeader())
885 Result->Pred = ICmpInst::getInversePredicate(Result->Pred);
886
887 // Check affine first, so if it's not we don't try to compute the step
888 // recurrence.
889 if (!Result->IV->isAffine()) {
890 LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n");
891 return None;
892 }
893
894 auto *Step = Result->IV->getStepRecurrence(*SE);
895 if (!isSupportedStep(Step)) {
896 LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
897 return None;
898 }
899
900 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
901 if (Step->isOne()) {
902 return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
903 Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
904 } else {
905 assert(Step->isAllOnesValue() && "Step should be -1!");
906 return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT &&
907 Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE;
908 }
909 };
910
911 normalizePredicate(SE, L, *Result);
912 if (IsUnsupportedPredicate(Step, Result->Pred)) {
913 LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
914 << ")!\n");
915 return None;
916 }
917
918 return Result;
919 }
920
921
isLoopProfitableToPredicate()922 bool LoopPredication::isLoopProfitableToPredicate() {
923 if (SkipProfitabilityChecks)
924 return true;
925
926 SmallVector<std::pair<BasicBlock *, BasicBlock *>, 8> ExitEdges;
927 L->getExitEdges(ExitEdges);
928 // If there is only one exiting edge in the loop, it is always profitable to
929 // predicate the loop.
930 if (ExitEdges.size() == 1)
931 return true;
932
933 // Calculate the exiting probabilities of all exiting edges from the loop,
934 // starting with the LatchExitProbability.
935 // Heuristic for profitability: If any of the exiting blocks' probability of
936 // exiting the loop is larger than exiting through the latch block, it's not
937 // profitable to predicate the loop.
938 auto *LatchBlock = L->getLoopLatch();
939 assert(LatchBlock && "Should have a single latch at this point!");
940 auto *LatchTerm = LatchBlock->getTerminator();
941 assert(LatchTerm->getNumSuccessors() == 2 &&
942 "expected to be an exiting block with 2 succs!");
943 unsigned LatchBrExitIdx =
944 LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0;
945 // We compute branch probabilities without BPI. We do not rely on BPI since
946 // Loop predication is usually run in an LPM and BPI is only preserved
947 // lossily within loop pass managers, while BPI has an inherent notion of
948 // being complete for an entire function.
949
950 // If the latch exits into a deoptimize or an unreachable block, do not
951 // predicate on that latch check.
952 auto *LatchExitBlock = LatchTerm->getSuccessor(LatchBrExitIdx);
953 if (isa<UnreachableInst>(LatchTerm) ||
954 LatchExitBlock->getTerminatingDeoptimizeCall())
955 return false;
956
957 auto IsValidProfileData = [](MDNode *ProfileData, const Instruction *Term) {
958 if (!ProfileData || !ProfileData->getOperand(0))
959 return false;
960 if (MDString *MDS = dyn_cast<MDString>(ProfileData->getOperand(0)))
961 if (!MDS->getString().equals("branch_weights"))
962 return false;
963 if (ProfileData->getNumOperands() != 1 + Term->getNumSuccessors())
964 return false;
965 return true;
966 };
967 MDNode *LatchProfileData = LatchTerm->getMetadata(LLVMContext::MD_prof);
968 // Latch terminator has no valid profile data, so nothing to check
969 // profitability on.
970 if (!IsValidProfileData(LatchProfileData, LatchTerm))
971 return true;
972
973 auto ComputeBranchProbability =
974 [&](const BasicBlock *ExitingBlock,
975 const BasicBlock *ExitBlock) -> BranchProbability {
976 auto *Term = ExitingBlock->getTerminator();
977 MDNode *ProfileData = Term->getMetadata(LLVMContext::MD_prof);
978 unsigned NumSucc = Term->getNumSuccessors();
979 if (IsValidProfileData(ProfileData, Term)) {
980 uint64_t Numerator = 0, Denominator = 0, ProfVal = 0;
981 for (unsigned i = 0; i < NumSucc; i++) {
982 ConstantInt *CI =
983 mdconst::extract<ConstantInt>(ProfileData->getOperand(i + 1));
984 ProfVal = CI->getValue().getZExtValue();
985 if (Term->getSuccessor(i) == ExitBlock)
986 Numerator += ProfVal;
987 Denominator += ProfVal;
988 }
989 return BranchProbability::getBranchProbability(Numerator, Denominator);
990 } else {
991 assert(LatchBlock != ExitingBlock &&
992 "Latch term should always have profile data!");
993 // No profile data, so we choose the weight as 1/num_of_succ(Src)
994 return BranchProbability::getBranchProbability(1, NumSucc);
995 }
996 };
997
998 BranchProbability LatchExitProbability =
999 ComputeBranchProbability(LatchBlock, LatchExitBlock);
1000
1001 // Protect against degenerate inputs provided by the user. Providing a value
1002 // less than one, can invert the definition of profitable loop predication.
1003 float ScaleFactor = LatchExitProbabilityScale;
1004 if (ScaleFactor < 1) {
1005 LLVM_DEBUG(
1006 dbgs()
1007 << "Ignored user setting for loop-predication-latch-probability-scale: "
1008 << LatchExitProbabilityScale << "\n");
1009 LLVM_DEBUG(dbgs() << "The value is set to 1.0\n");
1010 ScaleFactor = 1.0;
1011 }
1012 const auto LatchProbabilityThreshold = LatchExitProbability * ScaleFactor;
1013
1014 for (const auto &ExitEdge : ExitEdges) {
1015 BranchProbability ExitingBlockProbability =
1016 ComputeBranchProbability(ExitEdge.first, ExitEdge.second);
1017 // Some exiting edge has higher probability than the latch exiting edge.
1018 // No longer profitable to predicate.
1019 if (ExitingBlockProbability > LatchProbabilityThreshold)
1020 return false;
1021 }
1022
1023 // We have concluded that the most probable way to exit from the
1024 // loop is through the latch (or there's no profile information and all
1025 // exits are equally likely).
1026 return true;
1027 }
1028
1029 /// If we can (cheaply) find a widenable branch which controls entry into the
1030 /// loop, return it.
FindWidenableTerminatorAboveLoop(Loop * L,LoopInfo & LI)1031 static BranchInst *FindWidenableTerminatorAboveLoop(Loop *L, LoopInfo &LI) {
1032 // Walk back through any unconditional executed blocks and see if we can find
1033 // a widenable condition which seems to control execution of this loop. Note
1034 // that we predict that maythrow calls are likely untaken and thus that it's
1035 // profitable to widen a branch before a maythrow call with a condition
1036 // afterwards even though that may cause the slow path to run in a case where
1037 // it wouldn't have otherwise.
1038 BasicBlock *BB = L->getLoopPreheader();
1039 if (!BB)
1040 return nullptr;
1041 do {
1042 if (BasicBlock *Pred = BB->getSinglePredecessor())
1043 if (BB == Pred->getSingleSuccessor()) {
1044 BB = Pred;
1045 continue;
1046 }
1047 break;
1048 } while (true);
1049
1050 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
1051 auto *Term = Pred->getTerminator();
1052
1053 Value *Cond, *WC;
1054 BasicBlock *IfTrueBB, *IfFalseBB;
1055 if (parseWidenableBranch(Term, Cond, WC, IfTrueBB, IfFalseBB) &&
1056 IfTrueBB == BB)
1057 return cast<BranchInst>(Term);
1058 }
1059 return nullptr;
1060 }
1061
1062 /// Return the minimum of all analyzeable exit counts. This is an upper bound
1063 /// on the actual exit count. If there are not at least two analyzeable exits,
1064 /// returns SCEVCouldNotCompute.
getMinAnalyzeableBackedgeTakenCount(ScalarEvolution & SE,DominatorTree & DT,Loop * L)1065 static const SCEV *getMinAnalyzeableBackedgeTakenCount(ScalarEvolution &SE,
1066 DominatorTree &DT,
1067 Loop *L) {
1068 SmallVector<BasicBlock *, 16> ExitingBlocks;
1069 L->getExitingBlocks(ExitingBlocks);
1070
1071 SmallVector<const SCEV *, 4> ExitCounts;
1072 for (BasicBlock *ExitingBB : ExitingBlocks) {
1073 const SCEV *ExitCount = SE.getExitCount(L, ExitingBB);
1074 if (isa<SCEVCouldNotCompute>(ExitCount))
1075 continue;
1076 assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
1077 "We should only have known counts for exiting blocks that "
1078 "dominate latch!");
1079 ExitCounts.push_back(ExitCount);
1080 }
1081 if (ExitCounts.size() < 2)
1082 return SE.getCouldNotCompute();
1083 return SE.getUMinFromMismatchedTypes(ExitCounts);
1084 }
1085
1086 /// This implements an analogous, but entirely distinct transform from the main
1087 /// loop predication transform. This one is phrased in terms of using a
1088 /// widenable branch *outside* the loop to allow us to simplify loop exits in a
1089 /// following loop. This is close in spirit to the IndVarSimplify transform
1090 /// of the same name, but is materially different widening loosens legality
1091 /// sharply.
predicateLoopExits(Loop * L,SCEVExpander & Rewriter)1092 bool LoopPredication::predicateLoopExits(Loop *L, SCEVExpander &Rewriter) {
1093 // The transformation performed here aims to widen a widenable condition
1094 // above the loop such that all analyzeable exit leading to deopt are dead.
1095 // It assumes that the latch is the dominant exit for profitability and that
1096 // exits branching to deoptimizing blocks are rarely taken. It relies on the
1097 // semantics of widenable expressions for legality. (i.e. being able to fall
1098 // down the widenable path spuriously allows us to ignore exit order,
1099 // unanalyzeable exits, side effects, exceptional exits, and other challenges
1100 // which restrict the applicability of the non-WC based version of this
1101 // transform in IndVarSimplify.)
1102 //
1103 // NOTE ON POISON/UNDEF - We're hoisting an expression above guards which may
1104 // imply flags on the expression being hoisted and inserting new uses (flags
1105 // are only correct for current uses). The result is that we may be
1106 // inserting a branch on the value which can be either poison or undef. In
1107 // this case, the branch can legally go either way; we just need to avoid
1108 // introducing UB. This is achieved through the use of the freeze
1109 // instruction.
1110
1111 SmallVector<BasicBlock *, 16> ExitingBlocks;
1112 L->getExitingBlocks(ExitingBlocks);
1113
1114 if (ExitingBlocks.empty())
1115 return false; // Nothing to do.
1116
1117 auto *Latch = L->getLoopLatch();
1118 if (!Latch)
1119 return false;
1120
1121 auto *WidenableBR = FindWidenableTerminatorAboveLoop(L, *LI);
1122 if (!WidenableBR)
1123 return false;
1124
1125 const SCEV *LatchEC = SE->getExitCount(L, Latch);
1126 if (isa<SCEVCouldNotCompute>(LatchEC))
1127 return false; // profitability - want hot exit in analyzeable set
1128
1129 // At this point, we have found an analyzeable latch, and a widenable
1130 // condition above the loop. If we have a widenable exit within the loop
1131 // (for which we can't compute exit counts), drop the ability to further
1132 // widen so that we gain ability to analyze it's exit count and perform this
1133 // transform. TODO: It'd be nice to know for sure the exit became
1134 // analyzeable after dropping widenability.
1135 bool ChangedLoop = false;
1136
1137 for (auto *ExitingBB : ExitingBlocks) {
1138 if (LI->getLoopFor(ExitingBB) != L)
1139 continue;
1140
1141 auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
1142 if (!BI)
1143 continue;
1144
1145 Use *Cond, *WC;
1146 BasicBlock *IfTrueBB, *IfFalseBB;
1147 if (parseWidenableBranch(BI, Cond, WC, IfTrueBB, IfFalseBB) &&
1148 L->contains(IfTrueBB)) {
1149 WC->set(ConstantInt::getTrue(IfTrueBB->getContext()));
1150 ChangedLoop = true;
1151 }
1152 }
1153 if (ChangedLoop)
1154 SE->forgetLoop(L);
1155
1156 // The use of umin(all analyzeable exits) instead of latch is subtle, but
1157 // important for profitability. We may have a loop which hasn't been fully
1158 // canonicalized just yet. If the exit we chose to widen is provably never
1159 // taken, we want the widened form to *also* be provably never taken. We
1160 // can't guarantee this as a current unanalyzeable exit may later become
1161 // analyzeable, but we can at least avoid the obvious cases.
1162 const SCEV *MinEC = getMinAnalyzeableBackedgeTakenCount(*SE, *DT, L);
1163 if (isa<SCEVCouldNotCompute>(MinEC) || MinEC->getType()->isPointerTy() ||
1164 !SE->isLoopInvariant(MinEC, L) ||
1165 !Rewriter.isSafeToExpandAt(MinEC, WidenableBR))
1166 return ChangedLoop;
1167
1168 // Subtlety: We need to avoid inserting additional uses of the WC. We know
1169 // that it can only have one transitive use at the moment, and thus moving
1170 // that use to just before the branch and inserting code before it and then
1171 // modifying the operand is legal.
1172 auto *IP = cast<Instruction>(WidenableBR->getCondition());
1173 // Here we unconditionally modify the IR, so after this point we should return
1174 // only `true`!
1175 IP->moveBefore(WidenableBR);
1176 if (MSSAU)
1177 if (auto *MUD = MSSAU->getMemorySSA()->getMemoryAccess(IP))
1178 MSSAU->moveToPlace(MUD, WidenableBR->getParent(),
1179 MemorySSA::BeforeTerminator);
1180 Rewriter.setInsertPoint(IP);
1181 IRBuilder<> B(IP);
1182
1183 bool InvalidateLoop = false;
1184 Value *MinECV = nullptr; // lazily generated if needed
1185 for (BasicBlock *ExitingBB : ExitingBlocks) {
1186 // If our exiting block exits multiple loops, we can only rewrite the
1187 // innermost one. Otherwise, we're changing how many times the innermost
1188 // loop runs before it exits.
1189 if (LI->getLoopFor(ExitingBB) != L)
1190 continue;
1191
1192 // Can't rewrite non-branch yet.
1193 auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
1194 if (!BI)
1195 continue;
1196
1197 // If already constant, nothing to do.
1198 if (isa<Constant>(BI->getCondition()))
1199 continue;
1200
1201 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
1202 if (isa<SCEVCouldNotCompute>(ExitCount) ||
1203 ExitCount->getType()->isPointerTy() ||
1204 !Rewriter.isSafeToExpandAt(ExitCount, WidenableBR))
1205 continue;
1206
1207 const bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));
1208 BasicBlock *ExitBB = BI->getSuccessor(ExitIfTrue ? 0 : 1);
1209 if (!ExitBB->getPostdominatingDeoptimizeCall())
1210 continue;
1211
1212 /// Here we can be fairly sure that executing this exit will most likely
1213 /// lead to executing llvm.experimental.deoptimize.
1214 /// This is a profitability heuristic, not a legality constraint.
1215
1216 // If we found a widenable exit condition, do two things:
1217 // 1) fold the widened exit test into the widenable condition
1218 // 2) fold the branch to untaken - avoids infinite looping
1219
1220 Value *ECV = Rewriter.expandCodeFor(ExitCount);
1221 if (!MinECV)
1222 MinECV = Rewriter.expandCodeFor(MinEC);
1223 Value *RHS = MinECV;
1224 if (ECV->getType() != RHS->getType()) {
1225 Type *WiderTy = SE->getWiderType(ECV->getType(), RHS->getType());
1226 ECV = B.CreateZExt(ECV, WiderTy);
1227 RHS = B.CreateZExt(RHS, WiderTy);
1228 }
1229 assert(!Latch || DT->dominates(ExitingBB, Latch));
1230 Value *NewCond = B.CreateICmp(ICmpInst::ICMP_UGT, ECV, RHS);
1231 // Freeze poison or undef to an arbitrary bit pattern to ensure we can
1232 // branch without introducing UB. See NOTE ON POISON/UNDEF above for
1233 // context.
1234 NewCond = B.CreateFreeze(NewCond);
1235
1236 widenWidenableBranch(WidenableBR, NewCond);
1237
1238 Value *OldCond = BI->getCondition();
1239 BI->setCondition(ConstantInt::get(OldCond->getType(), !ExitIfTrue));
1240 InvalidateLoop = true;
1241 }
1242
1243 if (InvalidateLoop)
1244 // We just mutated a bunch of loop exits changing there exit counts
1245 // widely. We need to force recomputation of the exit counts given these
1246 // changes. Note that all of the inserted exits are never taken, and
1247 // should be removed next time the CFG is modified.
1248 SE->forgetLoop(L);
1249
1250 // Always return `true` since we have moved the WidenableBR's condition.
1251 return true;
1252 }
1253
runOnLoop(Loop * Loop)1254 bool LoopPredication::runOnLoop(Loop *Loop) {
1255 L = Loop;
1256
1257 LLVM_DEBUG(dbgs() << "Analyzing ");
1258 LLVM_DEBUG(L->dump());
1259
1260 Module *M = L->getHeader()->getModule();
1261
1262 // There is nothing to do if the module doesn't use guards
1263 auto *GuardDecl =
1264 M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
1265 bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty();
1266 auto *WCDecl = M->getFunction(
1267 Intrinsic::getName(Intrinsic::experimental_widenable_condition));
1268 bool HasWidenableConditions =
1269 PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty();
1270 if (!HasIntrinsicGuards && !HasWidenableConditions)
1271 return false;
1272
1273 DL = &M->getDataLayout();
1274
1275 Preheader = L->getLoopPreheader();
1276 if (!Preheader)
1277 return false;
1278
1279 auto LatchCheckOpt = parseLoopLatchICmp();
1280 if (!LatchCheckOpt)
1281 return false;
1282 LatchCheck = *LatchCheckOpt;
1283
1284 LLVM_DEBUG(dbgs() << "Latch check:\n");
1285 LLVM_DEBUG(LatchCheck.dump());
1286
1287 if (!isLoopProfitableToPredicate()) {
1288 LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n");
1289 return false;
1290 }
1291 // Collect all the guards into a vector and process later, so as not
1292 // to invalidate the instruction iterator.
1293 SmallVector<IntrinsicInst *, 4> Guards;
1294 SmallVector<BranchInst *, 4> GuardsAsWidenableBranches;
1295 for (const auto BB : L->blocks()) {
1296 for (auto &I : *BB)
1297 if (isGuard(&I))
1298 Guards.push_back(cast<IntrinsicInst>(&I));
1299 if (PredicateWidenableBranchGuards &&
1300 isGuardAsWidenableBranch(BB->getTerminator()))
1301 GuardsAsWidenableBranches.push_back(
1302 cast<BranchInst>(BB->getTerminator()));
1303 }
1304
1305 SCEVExpander Expander(*SE, *DL, "loop-predication");
1306 bool Changed = false;
1307 for (auto *Guard : Guards)
1308 Changed |= widenGuardConditions(Guard, Expander);
1309 for (auto *Guard : GuardsAsWidenableBranches)
1310 Changed |= widenWidenableBranchGuardConditions(Guard, Expander);
1311 Changed |= predicateLoopExits(L, Expander);
1312
1313 if (MSSAU && VerifyMemorySSA)
1314 MSSAU->getMemorySSA()->verifyMemorySSA();
1315 return Changed;
1316 }
1317