LLVM 24.0.0git
LoopPredication.cpp
Go to the documentation of this file.
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
180#include "ScalarOptions.h"
181#include "llvm/ADT/Statistic.h"
192#include "llvm/IR/Function.h"
194#include "llvm/IR/Module.h"
195#include "llvm/IR/PatternMatch.h"
197#include "llvm/Pass.h"
198#include "llvm/Support/Debug.h"
204#include <optional>
205
206#define DEBUG_TYPE "loop-predication"
207
208STATISTIC(TotalConsidered, "Number of guards considered");
209STATISTIC(TotalWidened, "Number of checks widened");
210
211using namespace llvm;
212
213namespace {
214/// Represents an induction variable check:
215/// icmp Pred, <induction variable>, <loop invariant limit>
216struct LoopICmp {
218 const SCEVAddRecExpr *IV;
219 const SCEV *Limit;
220 LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
221 const SCEV *Limit)
222 : Pred(Pred), IV(IV), Limit(Limit) {}
223 LoopICmp() = default;
224 void dump() {
225 dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
226 << ", Limit = " << *Limit << "\n";
227 }
228};
229
230class LoopPredication {
231 const ScalarOptions &Opts;
232 AliasAnalysis *AA;
233 DominatorTree *DT;
234 ScalarEvolution *SE;
235 LoopInfo *LI;
236 MemorySSAUpdater *MSSAU;
237 AssumptionCache *AC;
238
239 Loop *L;
240 const DataLayout *DL;
241 BasicBlock *Preheader;
242 LoopICmp LatchCheck;
243
244 bool isSupportedStep(const SCEV* Step);
245 std::optional<LoopICmp> parseLoopICmp(ICmpInst *ICI);
246 std::optional<LoopICmp> parseLoopLatchICmp();
247
248 /// Return an insertion point suitable for inserting a safe to speculate
249 /// instruction whose only user will be 'User' which has operands 'Ops'. A
250 /// trivial result would be the at the User itself, but we try to return a
251 /// loop invariant location if possible.
252 Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops);
253 /// Same as above, *except* that this uses the SCEV definition of invariant
254 /// which is that an expression *can be made* invariant via SCEVExpander.
255 /// Thus, this version is only suitable for finding an insert point to be
256 /// passed to SCEVExpander!
257 Instruction *findInsertPt(const SCEVExpander &Expander, Instruction *User,
259
260 /// Return true if the value is known to produce a single fixed value across
261 /// all iterations on which it executes. Note that this does not imply
262 /// speculation safety. That must be established separately.
263 bool isLoopInvariantValue(const SCEV* S);
264
265 Value *expandCheck(SCEVExpander &Expander, Instruction *Guard,
266 ICmpInst::Predicate Pred, const SCEV *LHS,
267 const SCEV *RHS);
268
269 std::optional<Value *> widenICmpRangeCheck(ICmpInst *ICI,
270 SCEVExpander &Expander,
271 Instruction *Guard);
272 std::optional<Value *>
273 widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck, LoopICmp RangeCheck,
274 SCEVExpander &Expander,
275 Instruction *Guard);
276 std::optional<Value *>
277 widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck, LoopICmp RangeCheck,
278 SCEVExpander &Expander,
279 Instruction *Guard);
280 void widenChecks(SmallVectorImpl<Value *> &Checks,
281 SmallVectorImpl<Value *> &WidenedChecks,
282 SCEVExpander &Expander, Instruction *Guard);
283 bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
284 bool widenWidenableBranchGuardConditions(CondBrInst *Guard,
285 SCEVExpander &Expander);
286 // If the loop always exits through another block in the loop, we should not
287 // predicate based on the latch check. For example, the latch check can be a
288 // very coarse grained check and there can be more fine grained exit checks
289 // within the loop.
290 bool isLoopProfitableToPredicate();
291
292 bool predicateLoopExits(Loop *L, SCEVExpander &Rewriter);
293
294public:
295 LoopPredication(const ScalarOptions &Opts, AliasAnalysis *AA,
296 DominatorTree *DT, ScalarEvolution *SE, LoopInfo *LI,
297 MemorySSAUpdater *MSSAU, AssumptionCache *AC)
298 : Opts(Opts), AA(AA), DT(DT), SE(SE), LI(LI), MSSAU(MSSAU), AC(AC) {};
299 bool runOnLoop(Loop *L);
300};
301
302} // end namespace
303
306 LPMUpdater &U) {
307 std::unique_ptr<MemorySSAUpdater> MSSAU;
308 if (AR.MSSA)
309 MSSAU = std::make_unique<MemorySSAUpdater>(AR.MSSA);
310 const ScalarOptions &Opts = getScalarOptions(L);
311 LoopPredication LP(Opts, &AR.AA, &AR.DT, &AR.SE, &AR.LI,
312 MSSAU ? MSSAU.get() : nullptr, &AR.AC);
313 if (!LP.runOnLoop(&L))
314 return PreservedAnalyses::all();
315
317 if (AR.MSSA)
318 PA.preserve<MemorySSAAnalysis>();
319 return PA;
320}
321
322std::optional<LoopICmp> LoopPredication::parseLoopICmp(ICmpInst *ICI) {
323 auto Pred = ICI->getPredicate();
324 auto *LHS = ICI->getOperand(0);
325 auto *RHS = ICI->getOperand(1);
326
327 const SCEV *LHSS = SE->getSCEV(LHS);
328 if (isa<SCEVCouldNotCompute>(LHSS))
329 return std::nullopt;
330 const SCEV *RHSS = SE->getSCEV(RHS);
331 if (isa<SCEVCouldNotCompute>(RHSS))
332 return std::nullopt;
333
334 // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
335 if (SE->isLoopInvariant(LHSS, L)) {
336 std::swap(LHS, RHS);
337 std::swap(LHSS, RHSS);
339 }
340
342 if (!AR || AR->getLoop() != L)
343 return std::nullopt;
344
345 return LoopICmp(Pred, AR, RHSS);
346}
347
348Value *LoopPredication::expandCheck(SCEVExpander &Expander,
349 Instruction *Guard,
351 const SCEV *RHS) {
352 Type *Ty = LHS->getType();
353 assert(Ty == RHS->getType() && "expandCheck operands have different types?");
354
355 if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) {
356 IRBuilder<> Builder(Guard);
357 if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
358 return Builder.getTrue();
359 if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred),
360 LHS, RHS))
361 return Builder.getFalse();
362 }
363
364 Value *LHSV =
365 Expander.expandCodeFor(LHS, Ty, findInsertPt(Expander, Guard, {LHS}));
366 Value *RHSV =
367 Expander.expandCodeFor(RHS, Ty, findInsertPt(Expander, Guard, {RHS}));
368 IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV}));
369 return Builder.CreateICmp(Pred, LHSV, RHSV);
370}
371
372// Returns true if its safe to truncate the IV to RangeCheckType.
373// When the IV type is wider than the range operand type, we can still do loop
374// predication, by generating SCEVs for the range and latch that are of the
375// same type. We achieve this by generating a SCEV truncate expression for the
376// latch IV. This is done iff truncation of the IV is a safe operation,
377// without loss of information.
378// Another way to achieve this is by generating a wider type SCEV for the
379// range check operand, however, this needs a more involved check that
380// operands do not overflow. This can lead to loss of information when the
381// range operand is of the form: add i32 %offset, %iv. We need to prove that
382// sext(x + y) is same as sext(x) + sext(y).
383// This function returns true if we can safely represent the IV type in
384// the RangeCheckType without loss of information.
385static bool isSafeToTruncateWideIVType(const ScalarOptions &Opts,
386 const DataLayout &DL,
387 ScalarEvolution &SE,
388 const LoopICmp LatchCheck,
389 Type *RangeCheckType) {
390 if (!Opts.loop_predication_enable_iv_truncation)
391 return false;
392 assert(DL.getTypeSizeInBits(LatchCheck.IV->getType()).getFixedValue() >
393 DL.getTypeSizeInBits(RangeCheckType).getFixedValue() &&
394 "Expected latch check IV type to be larger than range check operand "
395 "type!");
396 // The start and end values of the IV should be known. This is to guarantee
397 // that truncating the wide type will not lose information.
398 auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
399 auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
400 if (!Limit || !Start)
401 return false;
402 // This check makes sure that the IV does not change sign during loop
403 // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
404 // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
405 // IV wraps around, and the truncation of the IV would lose the range of
406 // iterations between 2^32 and 2^64.
407 if (!SE.getMonotonicPredicateType(LatchCheck.IV, LatchCheck.Pred))
408 return false;
409 // The active bits should be less than the bits in the RangeCheckType. This
410 // guarantees that truncating the latch check to RangeCheckType is a safe
411 // operation.
412 auto RangeCheckTypeBitSize =
413 DL.getTypeSizeInBits(RangeCheckType).getFixedValue();
414 return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
415 Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
416}
417
418// Return an LoopICmp describing a latch check equivlent to LatchCheck but with
419// the requested type if safe to do so. May involve the use of a new IV.
420static std::optional<LoopICmp> generateLoopLatchCheck(const ScalarOptions &Opts,
421 const DataLayout &DL,
422 ScalarEvolution &SE,
423 const LoopICmp LatchCheck,
424 Type *RangeCheckType) {
425
426 auto *LatchType = LatchCheck.IV->getType();
427 if (RangeCheckType == LatchType)
428 return LatchCheck;
429 // For now, bail out if latch type is narrower than range type.
430 if (DL.getTypeSizeInBits(LatchType).getFixedValue() <
431 DL.getTypeSizeInBits(RangeCheckType).getFixedValue())
432 return std::nullopt;
433 if (!isSafeToTruncateWideIVType(Opts, DL, SE, LatchCheck, RangeCheckType))
434 return std::nullopt;
435 // We can now safely identify the truncated version of the IV and limit for
436 // RangeCheckType.
437 LoopICmp NewLatchCheck;
438 NewLatchCheck.Pred = LatchCheck.Pred;
439 NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
440 SE.getTruncateExpr(LatchCheck.IV, RangeCheckType));
441 if (!NewLatchCheck.IV)
442 return std::nullopt;
443 NewLatchCheck.Limit = SE.getTruncateExpr(LatchCheck.Limit, RangeCheckType);
444 LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType
445 << "can be represented as range check type:"
446 << *RangeCheckType << "\n");
447 LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
448 LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
449 return NewLatchCheck;
450}
451
452bool LoopPredication::isSupportedStep(const SCEV* Step) {
453 return Step->isOne() || (Step->isAllOnesValue() &&
454 Opts.loop_predication_enable_count_down_loop);
455}
456
457Instruction *LoopPredication::findInsertPt(Instruction *Use,
459 for (Value *Op : Ops)
460 if (!L->isLoopInvariant(Op))
461 return Use;
462 return Preheader->getTerminator();
463}
464
465Instruction *LoopPredication::findInsertPt(const SCEVExpander &Expander,
468 // Subtlety: SCEV considers things to be invariant if the value produced is
469 // the same across iterations. This is not the same as being able to
470 // evaluate outside the loop, which is what we actually need here.
471 for (const SCEV *Op : Ops)
472 if (!SE->isLoopInvariant(Op, L) ||
473 !Expander.isSafeToExpandAt(Op, Preheader->getTerminator()))
474 return Use;
475 return Preheader->getTerminator();
476}
477
478bool LoopPredication::isLoopInvariantValue(const SCEV* S) {
479 // Handling expressions which produce invariant results, but *haven't* yet
480 // been removed from the loop serves two important purposes.
481 // 1) Most importantly, it resolves a pass ordering cycle which would
482 // otherwise need us to iteration licm, loop-predication, and either
483 // loop-unswitch or loop-peeling to make progress on examples with lots of
484 // predicable range checks in a row. (Since, in the general case, we can't
485 // hoist the length checks until the dominating checks have been discharged
486 // as we can't prove doing so is safe.)
487 // 2) As a nice side effect, this exposes the value of peeling or unswitching
488 // much more obviously in the IR. Otherwise, the cost modeling for other
489 // transforms would end up needing to duplicate all of this logic to model a
490 // check which becomes predictable based on a modeled peel or unswitch.
491 //
492 // The cost of doing so in the worst case is an extra fill from the stack in
493 // the loop to materialize the loop invariant test value instead of checking
494 // against the original IV which is presumable in a register inside the loop.
495 // Such cases are presumably rare, and hint at missing oppurtunities for
496 // other passes.
497
498 if (SE->isLoopInvariant(S, L))
499 // Note: This the SCEV variant, so the original Value* may be within the
500 // loop even though SCEV has proven it is loop invariant.
501 return true;
502
503 // Handle a particular important case which SCEV doesn't yet know about which
504 // shows up in range checks on arrays with immutable lengths.
505 // TODO: This should be sunk inside SCEV.
506 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
507 if (const auto *LI = dyn_cast<LoadInst>(U->getValue()))
508 if (LI->isUnordered() && L->hasLoopInvariantOperands(LI))
509 if (!isModSet(AA->getModRefInfoMask(LI->getOperand(0))) ||
510 LI->hasMetadata(LLVMContext::MD_invariant_load))
511 return true;
512 return false;
513}
514
515std::optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
516 LoopICmp LatchCheck, LoopICmp RangeCheck, SCEVExpander &Expander,
517 Instruction *Guard) {
518 auto *Ty = RangeCheck.IV->getType();
519 // Generate the widened condition for the forward loop:
520 // guardStart u< guardLimit &&
521 // latchLimit <pred> guardLimit - 1 - guardStart + latchStart
522 // where <pred> depends on the latch condition predicate. See the file
523 // header comment for the reasoning.
524 // guardLimit - guardStart + latchStart - 1
525 const SCEV *GuardStart = RangeCheck.IV->getStart();
526 const SCEV *GuardLimit = RangeCheck.Limit;
527 const SCEV *LatchStart = LatchCheck.IV->getStart();
528 const SCEV *LatchLimit = LatchCheck.Limit;
529 // Subtlety: We need all the values to be *invariant* across all iterations,
530 // but we only need to check expansion safety for those which *aren't*
531 // already guaranteed to dominate the guard.
532 if (!isLoopInvariantValue(GuardStart) ||
533 !isLoopInvariantValue(GuardLimit) ||
534 !isLoopInvariantValue(LatchStart) ||
535 !isLoopInvariantValue(LatchLimit)) {
536 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
537 return std::nullopt;
538 }
539 if (!Expander.isSafeToExpandAt(LatchStart, Guard) ||
540 !Expander.isSafeToExpandAt(LatchLimit, Guard)) {
541 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
542 return std::nullopt;
543 }
544
545 // guardLimit - guardStart + latchStart - 1
546 const SCEV *RHS =
547 SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
548 SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
549 auto LimitCheckPred =
551
552 LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
553 LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n");
554 LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
555
556 auto *LimitCheck =
557 expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS);
558 auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred,
559 GuardStart, GuardLimit);
560 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
561 return Builder.CreateFreeze(
562 Builder.CreateAnd(FirstIterationCheck, LimitCheck));
563}
564
565std::optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
566 LoopICmp LatchCheck, LoopICmp RangeCheck, SCEVExpander &Expander,
567 Instruction *Guard) {
568 auto *Ty = RangeCheck.IV->getType();
569 const SCEV *GuardStart = RangeCheck.IV->getStart();
570 const SCEV *GuardLimit = RangeCheck.Limit;
571 const SCEV *LatchStart = LatchCheck.IV->getStart();
572 const SCEV *LatchLimit = LatchCheck.Limit;
573 // Subtlety: We need all the values to be *invariant* across all iterations,
574 // but we only need to check expansion safety for those which *aren't*
575 // already guaranteed to dominate the guard.
576 if (!isLoopInvariantValue(GuardStart) ||
577 !isLoopInvariantValue(GuardLimit) ||
578 !isLoopInvariantValue(LatchStart) ||
579 !isLoopInvariantValue(LatchLimit)) {
580 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
581 return std::nullopt;
582 }
583 if (!Expander.isSafeToExpandAt(LatchStart, Guard) ||
584 !Expander.isSafeToExpandAt(LatchLimit, Guard)) {
585 LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
586 return std::nullopt;
587 }
588 // The decrement of the latch check IV should be the same as the
589 // rangeCheckIV.
590 auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
591 if (RangeCheck.IV != PostDecLatchCheckIV) {
592 LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
593 << *PostDecLatchCheckIV
594 << " and RangeCheckIV: " << *RangeCheck.IV << "\n");
595 return std::nullopt;
596 }
597
598 // Generate the widened condition for CountDownLoop:
599 // guardStart u< guardLimit &&
600 // latchLimit <pred> 1.
601 // See the header comment for reasoning of the checks.
602 auto LimitCheckPred =
604 auto *FirstIterationCheck = expandCheck(Expander, Guard,
606 GuardStart, GuardLimit);
607 auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit,
608 SE->getOne(Ty));
609 IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
610 return Builder.CreateFreeze(
611 Builder.CreateAnd(FirstIterationCheck, LimitCheck));
612}
613
615 LoopICmp& RC) {
616 // LFTR canonicalizes checks to the ICMP_NE/EQ form; normalize back to the
617 // ULT/UGE form for ease of handling by our caller.
618 if (ICmpInst::isEquality(RC.Pred) &&
619 RC.IV->getStepRecurrence(*SE)->isOne() &&
620 SE->isKnownPredicate(ICmpInst::ICMP_ULE, RC.IV->getStart(), RC.Limit))
621 RC.Pred = RC.Pred == ICmpInst::ICMP_NE ?
623}
624
625/// If ICI can be widened to a loop invariant condition emits the loop
626/// invariant condition in the loop preheader and return it, otherwise
627/// returns std::nullopt.
628std::optional<Value *>
629LoopPredication::widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
630 Instruction *Guard) {
631 LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
632 LLVM_DEBUG(ICI->dump());
633
634 // parseLoopStructure guarantees that the latch condition is:
635 // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
636 // We are looking for the range checks of the form:
637 // i u< guardLimit
638 auto RangeCheck = parseLoopICmp(ICI);
639 if (!RangeCheck) {
640 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
641 return std::nullopt;
642 }
643 LLVM_DEBUG(dbgs() << "Guard check:\n");
644 LLVM_DEBUG(RangeCheck->dump());
645 if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
646 LLVM_DEBUG(dbgs() << "Unsupported range check predicate("
647 << RangeCheck->Pred << ")!\n");
648 return std::nullopt;
649 }
650 auto *RangeCheckIV = RangeCheck->IV;
651 if (!RangeCheckIV->isAffine()) {
652 LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n");
653 return std::nullopt;
654 }
655 const SCEV *Step = RangeCheckIV->getStepRecurrence(*SE);
656 // We cannot just compare with latch IV step because the latch and range IVs
657 // may have different types.
658 if (!isSupportedStep(Step)) {
659 LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
660 return std::nullopt;
661 }
662 auto *Ty = RangeCheckIV->getType();
663 auto CurrLatchCheckOpt =
664 generateLoopLatchCheck(Opts, *DL, *SE, LatchCheck, Ty);
665 if (!CurrLatchCheckOpt) {
666 LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check "
667 "corresponding to range type: "
668 << *Ty << "\n");
669 return std::nullopt;
670 }
671
672 LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
673 // At this point, the range and latch step should have the same type, but need
674 // not have the same value (we support both 1 and -1 steps).
675 assert(Step->getType() ==
676 CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
677 "Range and latch steps should be of same type!");
678 if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
679 LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n");
680 return std::nullopt;
681 }
682
683 if (Step->isOne())
684 return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
685 Expander, Guard);
686 else {
687 assert(Step->isAllOnesValue() && "Step should be -1!");
688 return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
689 Expander, Guard);
690 }
691}
692
693void LoopPredication::widenChecks(SmallVectorImpl<Value *> &Checks,
694 SmallVectorImpl<Value *> &WidenedChecks,
695 SCEVExpander &Expander, Instruction *Guard) {
696 for (auto &Check : Checks)
698 if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Guard)) {
699 WidenedChecks.push_back(Check);
700 Check = *NewRangeCheck;
701 }
702}
703
704bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
705 SCEVExpander &Expander) {
706 LLVM_DEBUG(dbgs() << "Processing guard:\n");
707 LLVM_DEBUG(Guard->dump());
708
709 TotalConsidered++;
711 SmallVector<Value *> WidenedChecks;
712 parseWidenableGuard(Guard, Checks);
713 widenChecks(Checks, WidenedChecks, Expander, Guard);
714 if (WidenedChecks.empty())
715 return false;
716
717 TotalWidened += WidenedChecks.size();
718
719 // Emit the new guard condition
720 IRBuilder<> Builder(findInsertPt(Guard, Checks));
721 Value *AllChecks = Builder.CreateAnd(Checks);
722 auto *OldCond = Guard->getOperand(0);
723 Guard->setOperand(0, AllChecks);
724 if (Opts.loop_predication_insert_assumes_of_predicated_guards_conditions) {
725 Builder.SetInsertPoint(&*++BasicBlock::iterator(Guard));
726 AC->registerAssumption(cast<AssumeInst>(Builder.CreateAssumption(OldCond)));
727 }
728 RecursivelyDeleteTriviallyDeadInstructions(OldCond, nullptr /* TLI */, MSSAU);
729
730 LLVM_DEBUG(dbgs() << "Widened checks = " << WidenedChecks.size() << "\n");
731 return true;
732}
733
734bool LoopPredication::widenWidenableBranchGuardConditions(
735 CondBrInst *BI, SCEVExpander &Expander) {
736 assert(isGuardAsWidenableBranch(BI) && "Must be!");
737 LLVM_DEBUG(dbgs() << "Processing guard:\n");
738 LLVM_DEBUG(BI->dump());
739
740 TotalConsidered++;
742 SmallVector<Value *> WidenedChecks;
743 parseWidenableGuard(BI, Checks);
744 // At the moment, our matching logic for wideable conditions implicitly
745 // assumes we preserve the form: (br (and Cond, WC())). FIXME
746 auto WC = extractWidenableCondition(BI);
747 Checks.push_back(WC);
748 widenChecks(Checks, WidenedChecks, Expander, BI);
749 if (WidenedChecks.empty())
750 return false;
751
752 TotalWidened += WidenedChecks.size();
753
754 // Emit the new guard condition
755 IRBuilder<> Builder(findInsertPt(BI, Checks));
756 Value *AllChecks = Builder.CreateAnd(Checks);
757 auto *OldCond = BI->getCondition();
758 BI->setCondition(AllChecks);
759 if (Opts.loop_predication_insert_assumes_of_predicated_guards_conditions) {
760 BasicBlock *IfTrueBB = BI->getSuccessor(0);
761 Builder.SetInsertPoint(IfTrueBB->getFirstInsertionPt());
762 // If this block has other predecessors, we might not be able to use Cond.
763 // In this case, create a Phi where every other input is `true` and input
764 // from guard block is Cond.
765 Value *AssumeCond = Builder.CreateAnd(WidenedChecks);
766 if (!IfTrueBB->getUniquePredecessor()) {
767 auto *GuardBB = BI->getParent();
768 auto *PN = Builder.CreatePHI(AssumeCond->getType(), pred_size(IfTrueBB),
769 "assume.cond");
770 for (auto *Pred : predecessors(IfTrueBB))
771 PN->addIncoming(Pred == GuardBB ? AssumeCond : Builder.getTrue(), Pred);
772 AssumeCond = PN;
773 }
774 AC->registerAssumption(
775 cast<AssumeInst>(Builder.CreateAssumption(AssumeCond)));
776 }
777 RecursivelyDeleteTriviallyDeadInstructions(OldCond, nullptr /* TLI */, MSSAU);
779 "Stopped being a guard after transform?");
780
781 LLVM_DEBUG(dbgs() << "Widened checks = " << WidenedChecks.size() << "\n");
782 return true;
783}
784
785std::optional<LoopICmp> LoopPredication::parseLoopLatchICmp() {
786 using namespace PatternMatch;
787
788 BasicBlock *LoopLatch = L->getLoopLatch();
789 if (!LoopLatch) {
790 LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
791 return std::nullopt;
792 }
793
794 auto *BI = dyn_cast<CondBrInst>(LoopLatch->getTerminator());
795 if (!BI) {
796 LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n");
797 return std::nullopt;
798 }
799 BasicBlock *TrueDest = BI->getSuccessor(0);
800 assert(
801 (TrueDest == L->getHeader() || BI->getSuccessor(1) == L->getHeader()) &&
802 "One of the latch's destinations must be the header");
803
804 auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
805 if (!ICI) {
806 LLVM_DEBUG(dbgs() << "Failed to match the latch condition!\n");
807 return std::nullopt;
808 }
809 auto Result = parseLoopICmp(ICI);
810 if (!Result) {
811 LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
812 return std::nullopt;
813 }
814
815 if (TrueDest != L->getHeader())
817
818 // Check affine first, so if it's not we don't try to compute the step
819 // recurrence.
820 if (!Result->IV->isAffine()) {
821 LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n");
822 return std::nullopt;
823 }
824
825 const SCEV *Step = Result->IV->getStepRecurrence(*SE);
826 if (!isSupportedStep(Step)) {
827 LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
828 return std::nullopt;
829 }
830
831 auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
832 if (Step->isOne()) {
835 } else {
836 assert(Step->isAllOnesValue() && "Step should be -1!");
839 }
840 };
841
842 normalizePredicate(SE, L, *Result);
843 if (IsUnsupportedPredicate(Step, Result->Pred)) {
844 LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
845 << ")!\n");
846 return std::nullopt;
847 }
848
849 return Result;
850}
851
852bool LoopPredication::isLoopProfitableToPredicate() {
853 if (Opts.loop_predication_skip_profitability_checks)
854 return true;
855
857 LI->getExitEdges(*L, ExitEdges);
858 // If there is only one exiting edge in the loop, it is always profitable to
859 // predicate the loop.
860 if (ExitEdges.size() == 1)
861 return true;
862
863 // Calculate the exiting probabilities of all exiting edges from the loop,
864 // starting with the LatchExitProbability.
865 // Heuristic for profitability: If any of the exiting blocks' probability of
866 // exiting the loop is larger than exiting through the latch block, it's not
867 // profitable to predicate the loop.
868 auto *LatchBlock = L->getLoopLatch();
869 assert(LatchBlock && "Should have a single latch at this point!");
870 auto *LatchTerm = LatchBlock->getTerminator();
871 assert(LatchTerm->getNumSuccessors() == 2 &&
872 "expected to be an exiting block with 2 succs!");
873 unsigned LatchBrExitIdx =
874 LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0;
875 // We compute branch probabilities without BPI. We do not rely on BPI since
876 // Loop predication is usually run in an LPM and BPI is only preserved
877 // lossily within loop pass managers, while BPI has an inherent notion of
878 // being complete for an entire function.
879
880 // If the latch exits into a deoptimize or an unreachable block, do not
881 // predicate on that latch check.
882 auto *LatchExitBlock = LatchTerm->getSuccessor(LatchBrExitIdx);
883 if (isa<UnreachableInst>(LatchTerm) ||
884 LatchExitBlock->getTerminatingDeoptimizeCall())
885 return false;
886
887 // Latch terminator has no valid profile data, so nothing to check
888 // profitability on.
889 if (!hasValidBranchWeightMD(*LatchTerm))
890 return true;
891
892 auto ComputeBranchProbability =
893 [&](const BasicBlock *ExitingBlock,
894 const BasicBlock *ExitBlock) -> BranchProbability {
895 auto *Term = ExitingBlock->getTerminator();
896 unsigned NumSucc = Term->getNumSuccessors();
897 if (MDNode *ProfileData = getValidBranchWeightMDNode(*Term)) {
898 SmallVector<uint32_t> Weights;
899 extractBranchWeights(ProfileData, Weights);
900 uint64_t Numerator = 0, Denominator = 0;
901 for (auto [i, Weight] : llvm::enumerate(Weights)) {
902 if (Term->getSuccessor(i) == ExitBlock)
903 Numerator += Weight;
904 Denominator += Weight;
905 }
906 // If all weights are zero act as if there was no profile data
907 if (Denominator == 0)
909 return BranchProbability::getBranchProbability(Numerator, Denominator);
910 } else {
911 assert(LatchBlock != ExitingBlock &&
912 "Latch term should always have profile data!");
913 // No profile data, so we choose the weight as 1/num_of_succ(Src)
915 }
916 };
917
918 BranchProbability LatchExitProbability =
919 ComputeBranchProbability(LatchBlock, LatchExitBlock);
920
921 // Protect against degenerate inputs provided by the user. Providing a value
922 // less than one, can invert the definition of profitable loop predication.
923 float ScaleFactor = Opts.loop_predication_latch_probability_scale;
924 if (ScaleFactor < 1) {
926 dbgs()
927 << "Ignored user setting for loop-predication-latch-probability-scale: "
928 << Opts.loop_predication_latch_probability_scale << "\n");
929 LLVM_DEBUG(dbgs() << "The value is set to 1.0\n");
930 ScaleFactor = 1.0;
931 }
932 const auto LatchProbabilityThreshold = LatchExitProbability * ScaleFactor;
933
934 for (const auto &ExitEdge : ExitEdges) {
935 BranchProbability ExitingBlockProbability =
936 ComputeBranchProbability(ExitEdge.first, ExitEdge.second);
937 // Some exiting edge has higher probability than the latch exiting edge.
938 // No longer profitable to predicate.
939 if (ExitingBlockProbability > LatchProbabilityThreshold)
940 return false;
941 }
942
943 // We have concluded that the most probable way to exit from the
944 // loop is through the latch (or there's no profile information and all
945 // exits are equally likely).
946 return true;
947}
948
949/// If we can (cheaply) find a widenable branch which controls entry into the
950/// loop, return it.
952 // Walk back through any unconditional executed blocks and see if we can find
953 // a widenable condition which seems to control execution of this loop. Note
954 // that we predict that maythrow calls are likely untaken and thus that it's
955 // profitable to widen a branch before a maythrow call with a condition
956 // afterwards even though that may cause the slow path to run in a case where
957 // it wouldn't have otherwise.
958 BasicBlock *BB = L->getLoopPreheader();
959 if (!BB)
960 return nullptr;
961 do {
963 if (BB == Pred->getSingleSuccessor()) {
964 BB = Pred;
965 continue;
966 }
967 break;
968 } while (true);
969
970 if (BasicBlock *Pred = BB->getSinglePredecessor()) {
971 if (auto *BI = dyn_cast<CondBrInst>(Pred->getTerminator()))
972 if (BI->getSuccessor(0) == BB && isWidenableBranch(BI))
973 return BI;
974 }
975 return nullptr;
976}
977
978/// Return the minimum of all analyzeable exit counts. This is an upper bound
979/// on the actual exit count. If there are not at least two analyzeable exits,
980/// returns SCEVCouldNotCompute.
982 DominatorTree &DT,
983 Loop *L) {
984 SmallVector<BasicBlock *, 16> ExitingBlocks;
985 L->getExitingBlocks(ExitingBlocks);
986
987 SmallVector<SCEVUse, 4> ExitCounts;
988 for (BasicBlock *ExitingBB : ExitingBlocks) {
989 SCEVUse ExitCount = SE.getExitCount(L, ExitingBB);
990 if (isa<SCEVCouldNotCompute>(ExitCount))
991 continue;
992 assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
993 "We should only have known counts for exiting blocks that "
994 "dominate latch!");
995 ExitCounts.push_back(ExitCount);
996 }
997 if (ExitCounts.size() < 2)
998 return SE.getCouldNotCompute();
999 return SE.getUMinFromMismatchedTypes(ExitCounts);
1000}
1001
1002/// This implements an analogous, but entirely distinct transform from the main
1003/// loop predication transform. This one is phrased in terms of using a
1004/// widenable branch *outside* the loop to allow us to simplify loop exits in a
1005/// following loop. This is close in spirit to the IndVarSimplify transform
1006/// of the same name, but is materially different widening loosens legality
1007/// sharply.
1008bool LoopPredication::predicateLoopExits(Loop *L, SCEVExpander &Rewriter) {
1009 // The transformation performed here aims to widen a widenable condition
1010 // above the loop such that all analyzeable exit leading to deopt are dead.
1011 // It assumes that the latch is the dominant exit for profitability and that
1012 // exits branching to deoptimizing blocks are rarely taken. It relies on the
1013 // semantics of widenable expressions for legality. (i.e. being able to fall
1014 // down the widenable path spuriously allows us to ignore exit order,
1015 // unanalyzeable exits, side effects, exceptional exits, and other challenges
1016 // which restrict the applicability of the non-WC based version of this
1017 // transform in IndVarSimplify.)
1018 //
1019 // NOTE ON POISON/UNDEF - We're hoisting an expression above guards which may
1020 // imply flags on the expression being hoisted and inserting new uses (flags
1021 // are only correct for current uses). The result is that we may be
1022 // inserting a branch on the value which can be either poison or undef. In
1023 // this case, the branch can legally go either way; we just need to avoid
1024 // introducing UB. This is achieved through the use of the freeze
1025 // instruction.
1026
1027 SmallVector<BasicBlock *, 16> ExitingBlocks;
1028 L->getExitingBlocks(ExitingBlocks);
1029
1030 if (ExitingBlocks.empty())
1031 return false; // Nothing to do.
1032
1033 auto *Latch = L->getLoopLatch();
1034 if (!Latch)
1035 return false;
1036
1037 auto *WidenableBR = FindWidenableTerminatorAboveLoop(L, *LI);
1038 if (!WidenableBR)
1039 return false;
1040
1041 const SCEV *LatchEC = SE->getExitCount(L, Latch);
1042 if (isa<SCEVCouldNotCompute>(LatchEC))
1043 return false; // profitability - want hot exit in analyzeable set
1044
1045 // At this point, we have found an analyzeable latch, and a widenable
1046 // condition above the loop. If we have a widenable exit within the loop
1047 // (for which we can't compute exit counts), drop the ability to further
1048 // widen so that we gain ability to analyze it's exit count and perform this
1049 // transform. TODO: It'd be nice to know for sure the exit became
1050 // analyzeable after dropping widenability.
1051 bool ChangedLoop = false;
1052
1053 for (auto *ExitingBB : ExitingBlocks) {
1054 if (LI->getLoopFor(ExitingBB) != L)
1055 continue;
1056
1057 auto *BI = dyn_cast<CondBrInst>(ExitingBB->getTerminator());
1058 if (!BI)
1059 continue;
1060
1061 if (auto WC = extractWidenableCondition(BI))
1062 if (L->contains(BI->getSuccessor(0))) {
1063 assert(WC->hasOneUse() && "Not appropriate widenable branch!");
1064 WC->user_back()->replaceUsesOfWith(
1065 WC, ConstantInt::getTrue(BI->getContext()));
1066 ChangedLoop = true;
1067 }
1068 }
1069 if (ChangedLoop)
1070 SE->forgetLoop(L);
1071
1072 // The insertion point for the widening should be at the widenably call, not
1073 // at the WidenableBR. If we do this at the widenableBR, we can incorrectly
1074 // change a loop-invariant condition to a loop-varying one.
1075 auto *IP = cast<Instruction>(WidenableBR->getCondition());
1076
1077 // The use of umin(all analyzeable exits) instead of latch is subtle, but
1078 // important for profitability. We may have a loop which hasn't been fully
1079 // canonicalized just yet. If the exit we chose to widen is provably never
1080 // taken, we want the widened form to *also* be provably never taken. We
1081 // can't guarantee this as a current unanalyzeable exit may later become
1082 // analyzeable, but we can at least avoid the obvious cases.
1083 const SCEV *MinEC = getMinAnalyzeableBackedgeTakenCount(*SE, *DT, L);
1084 if (isa<SCEVCouldNotCompute>(MinEC) || MinEC->getType()->isPointerTy() ||
1085 !SE->isLoopInvariant(MinEC, L) ||
1086 !Rewriter.isSafeToExpandAt(MinEC, IP))
1087 return ChangedLoop;
1088
1089 Rewriter.setInsertPoint(IP);
1090 IRBuilder<> B(IP);
1091
1092 bool InvalidateLoop = false;
1093 Value *MinECV = nullptr; // lazily generated if needed
1094 for (BasicBlock *ExitingBB : ExitingBlocks) {
1095 // If our exiting block exits multiple loops, we can only rewrite the
1096 // innermost one. Otherwise, we're changing how many times the innermost
1097 // loop runs before it exits.
1098 if (LI->getLoopFor(ExitingBB) != L)
1099 continue;
1100
1101 // Can't rewrite non-branch yet.
1102 auto *BI = dyn_cast<CondBrInst>(ExitingBB->getTerminator());
1103 if (!BI)
1104 continue;
1105
1106 // If already constant, nothing to do.
1107 if (isa<Constant>(BI->getCondition()))
1108 continue;
1109
1110 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
1111 if (isa<SCEVCouldNotCompute>(ExitCount) ||
1112 ExitCount->getType()->isPointerTy() ||
1113 !Rewriter.isSafeToExpandAt(ExitCount, WidenableBR))
1114 continue;
1115
1116 const bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));
1117 BasicBlock *ExitBB = BI->getSuccessor(ExitIfTrue ? 0 : 1);
1118 if (!ExitBB->getPostdominatingDeoptimizeCall())
1119 continue;
1120
1121 /// Here we can be fairly sure that executing this exit will most likely
1122 /// lead to executing llvm.experimental.deoptimize.
1123 /// This is a profitability heuristic, not a legality constraint.
1124
1125 // If we found a widenable exit condition, do two things:
1126 // 1) fold the widened exit test into the widenable condition
1127 // 2) fold the branch to untaken - avoids infinite looping
1128
1129 Value *ECV = Rewriter.expandCodeFor(ExitCount);
1130 if (!MinECV)
1131 MinECV = Rewriter.expandCodeFor(MinEC);
1132 Value *RHS = MinECV;
1133 if (ECV->getType() != RHS->getType()) {
1134 Type *WiderTy = SE->getWiderType(ECV->getType(), RHS->getType());
1135 ECV = B.CreateZExt(ECV, WiderTy);
1136 RHS = B.CreateZExt(RHS, WiderTy);
1137 }
1138 assert(!Latch || DT->dominates(ExitingBB, Latch));
1139 Value *NewCond = B.CreateICmp(ICmpInst::ICMP_UGT, ECV, RHS);
1140 // Freeze poison or undef to an arbitrary bit pattern to ensure we can
1141 // branch without introducing UB. See NOTE ON POISON/UNDEF above for
1142 // context.
1143 NewCond = B.CreateFreeze(NewCond);
1144
1145 widenWidenableBranch(WidenableBR, NewCond);
1146
1147 Value *OldCond = BI->getCondition();
1148 BI->setCondition(ConstantInt::get(OldCond->getType(), !ExitIfTrue));
1149 InvalidateLoop = true;
1150 }
1151
1152 if (InvalidateLoop)
1153 // We just mutated a bunch of loop exits changing there exit counts
1154 // widely. We need to force recomputation of the exit counts given these
1155 // changes. Note that all of the inserted exits are never taken, and
1156 // should be removed next time the CFG is modified.
1157 SE->forgetLoop(L);
1158
1159 // Always return `true` since we have moved the WidenableBR's condition.
1160 return true;
1161}
1162
1163bool LoopPredication::runOnLoop(Loop *Loop) {
1164 L = Loop;
1165
1166 LLVM_DEBUG(dbgs() << "Analyzing ");
1167 LLVM_DEBUG(L->dump());
1168
1169 Module *M = L->getHeader()->getModule();
1170
1171 // There is nothing to do if the module doesn't use guards
1172 auto *GuardDecl =
1173 Intrinsic::getDeclarationIfExists(M, Intrinsic::experimental_guard);
1174 bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty();
1175 auto *WCDecl = Intrinsic::getDeclarationIfExists(
1176 M, Intrinsic::experimental_widenable_condition);
1177 bool HasWidenableConditions =
1178 Opts.loop_predication_predicate_widenable_branches_to_deopt && WCDecl &&
1179 !WCDecl->use_empty();
1180 if (!HasIntrinsicGuards && !HasWidenableConditions)
1181 return false;
1182
1183 DL = &M->getDataLayout();
1184
1185 Preheader = L->getLoopPreheader();
1186 if (!Preheader)
1187 return false;
1188
1189 auto LatchCheckOpt = parseLoopLatchICmp();
1190 if (!LatchCheckOpt)
1191 return false;
1192 LatchCheck = *LatchCheckOpt;
1193
1194 LLVM_DEBUG(dbgs() << "Latch check:\n");
1195 LLVM_DEBUG(LatchCheck.dump());
1196
1197 if (!isLoopProfitableToPredicate()) {
1198 LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n");
1199 return false;
1200 }
1201 // Collect all the guards into a vector and process later, so as not
1202 // to invalidate the instruction iterator.
1204 SmallVector<CondBrInst *, 4> GuardsAsWidenableBranches;
1205 for (const auto BB : L->blocks()) {
1206 for (auto &I : *BB)
1207 if (isGuard(&I))
1209 if (Opts.loop_predication_predicate_widenable_branches_to_deopt &&
1210 isGuardAsWidenableBranch(BB->getTerminator()))
1211 GuardsAsWidenableBranches.push_back(
1212 cast<CondBrInst>(BB->getTerminator()));
1213 }
1214
1215 SCEVExpander Expander(*SE, "loop-predication");
1216 bool Changed = false;
1217 for (auto *Guard : Guards)
1218 Changed |= widenGuardConditions(Guard, Expander);
1219 for (auto *Guard : GuardsAsWidenableBranches)
1220 Changed |= widenWidenableBranchGuardConditions(Guard, Expander);
1221 Changed |= predicateLoopExits(L, Expander);
1222
1223 if (MSSAU && VerifyMemorySSA)
1224 MSSAU->getMemorySSA()->verifyMemorySSA();
1225 return Changed;
1226}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
Module.h This file contains the declarations for the Module class.
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static CondBrInst * FindWidenableTerminatorAboveLoop(Loop *L, LoopInfo &LI)
If we can (cheaply) find a widenable branch which controls entry into the loop, return it.
static void normalizePredicate(ScalarEvolution *SE, Loop *L, LoopICmp &RC)
static std::optional< LoopICmp > generateLoopLatchCheck(const ScalarOptions &Opts, const DataLayout &DL, ScalarEvolution &SE, const LoopICmp LatchCheck, Type *RangeCheckType)
static const SCEV * getMinAnalyzeableBackedgeTakenCount(ScalarEvolution &SE, DominatorTree &DT, Loop *L)
Return the minimum of all analyzeable exit counts.
static bool isSafeToTruncateWideIVType(const ScalarOptions &Opts, const DataLayout &DL, ScalarEvolution &SE, const LoopICmp LatchCheck, Type *RangeCheckType)
#define I(x, y, z)
Definition MD5.cpp:57
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
uint64_t IntrinsicInst * II
This file contains the declarations for profiling metadata utility functions.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
virt reg Virtual Register Rewriter
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
LLVM Basic Block Representation.
Definition BasicBlock.h:61
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
LLVM_ABI const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:169
LLVM_ABI const CallInst * getPostdominatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize that is present either in current ...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
@ ICMP_SLT
signed less than
Definition InstrTypes.h:769
@ ICMP_SLE
signed less or equal
Definition InstrTypes.h:770
@ ICMP_UGE
unsigned greater or equal
Definition InstrTypes.h:764
@ ICMP_UGT
unsigned greater than
Definition InstrTypes.h:763
@ ICMP_SGT
signed greater than
Definition InstrTypes.h:767
@ ICMP_ULT
unsigned less than
Definition InstrTypes.h:765
@ ICMP_NE
not equal
Definition InstrTypes.h:762
@ ICMP_SGE
signed greater or equal
Definition InstrTypes.h:768
@ ICMP_ULE
unsigned less or equal
Definition InstrTypes.h:766
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition InstrTypes.h:890
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE,...
Definition InstrTypes.h:852
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
Predicate getFlippedStrictnessPredicate() const
For predicate of kind "is X or equal to 0" returns the predicate "is X".
Definition InstrTypes.h:956
Conditional Branch instruction.
void setCondition(Value *V)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
This instruction compares its operands according to the predicate given to the constructor.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2814
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", bool HasSameSign=false)
Definition IRBuilder.h:2568
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
A wrapper class for inspecting calls to intrinsic functions.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
LLVM_ABI PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
Metadata node.
Definition Metadata.h:1087
An analysis that produces MemorySSA for a function.
Definition MemorySSA.h:930
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This node represents a polynomial recurrence on the trip count of the specified loop.
LLVM_ABI const SCEVAddRecExpr * getPostIncExpr(ScalarEvolution &SE) const
Return an expression representing the value of this expression one iteration of the loop ahead.
SCEVUse getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
This class uses information about analyze scalars to rewrite expressions in canonical form.
LLVM_ABI bool isSafeToExpandAt(const SCEV *S, const Instruction *InsertionPoint) const
Return true if the given expression is safe to expand in the sense that all materialized values are d...
LLVM_ABI Value * expandCodeFor(SCEVUse SH, Type *Ty, BasicBlock::iterator I)
Insert code to directly compute the specified SCEV expression into the program.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
This class represents an analyzed expression in the program.
LLVM_ABI bool isOne() const
Return true if the expression is a constant one.
LLVM_ABI bool isAllOnesValue() const
Return true if the expression is a constant all-ones value.
Type * getType() const
Return the LLVM type of this SCEV expression.
The main scalar evolution driver.
LLVM_ABI const SCEV * getTruncateExpr(SCEVUse Op, Type *Ty, unsigned Depth=0)
LLVM_ABI const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS, bool Sequential=false)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
LLVM_ABI std::optional< MonotonicPredicateType > getMonotonicPredicateType(const SCEVAddRecExpr *LHS, ICmpInst::Predicate Pred)
If, for all loop invariant X, the predicate "LHS `Pred` X" is monotonically increasing or decreasing,...
LLVM_ABI const SCEV * getCouldNotCompute()
LLVM_ABI const SCEV * getExitCount(const Loop *L, const BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
LLVM_ABI bool isKnownPredicate(CmpPredicate Pred, SCEVUse LHS, SCEVUse RHS, unsigned Depth=0)
Test if the given expression is known to satisfy the condition described by Pred, LHS,...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI void dump() const
Support for debugging, callable in GDB: V->dump()
const ParentTy * getParent() const
Definition ilist_node.h:34
Abstract Attribute helper functions.
Definition Attributor.h:166
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:523
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
SCEVUseT< const SCEV * > SCEVUse
LLVM_ABI Value * extractWidenableCondition(const User *U)
auto pred_size(const MachineBasicBlock *BB)
const ScalarOptions & getScalarOptions(const LLVMContext &C)
LLVM_ABI void parseWidenableGuard(const User *U, llvm::SmallVectorImpl< Value * > &Checks)
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
LLVM_ABI MDNode * getValidBranchWeightMDNode(const Instruction &I)
Get the valid branch weights metadata node.
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
LLVM_ABI bool hasValidBranchWeightMD(const Instruction &I)
Checks if an instructions has valid Branch Weight Metadata.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI bool VerifyMemorySSA
Enables verification of MemorySSA.
Definition MemorySSA.cpp:74
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
RNSuccIterator< NodeRef, BlockT, RegionT > succ_begin(NodeRef Node)
LLVM_ABI bool isWidenableBranch(const User *U)
Returns true iff U is a widenable branch (that is, extractWidenableCondition returns widenable condit...
LLVM_ABI bool isGuardAsWidenableBranch(const User *U)
Returns true iff U has semantics of a guard expressed in a form of a widenable conditional branch to ...
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
auto predecessors(const MachineBasicBlock *BB)
LLVM_ABI void widenWidenableBranch(CondBrInst *WidenableBR, Value *NewCond)
Given a branch we know is widenable (defined per Analysis/GuardUtils.h), widen it such that condition...
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...