10b57cec5SDimitry Andric //===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // The LoopPredication pass tries to convert loop variant range checks to loop
100b57cec5SDimitry Andric // invariant by widening checks across loop iterations. For example, it will
110b57cec5SDimitry Andric // convert
120b57cec5SDimitry Andric //
130b57cec5SDimitry Andric // for (i = 0; i < n; i++) {
140b57cec5SDimitry Andric // guard(i < len);
150b57cec5SDimitry Andric // ...
160b57cec5SDimitry Andric // }
170b57cec5SDimitry Andric //
180b57cec5SDimitry Andric // to
190b57cec5SDimitry Andric //
200b57cec5SDimitry Andric // for (i = 0; i < n; i++) {
210b57cec5SDimitry Andric // guard(n - 1 < len);
220b57cec5SDimitry Andric // ...
230b57cec5SDimitry Andric // }
240b57cec5SDimitry Andric //
250b57cec5SDimitry Andric // After this transformation the condition of the guard is loop invariant, so
260b57cec5SDimitry Andric // loop-unswitch can later unswitch the loop by this condition which basically
270b57cec5SDimitry Andric // predicates the loop by the widened condition:
280b57cec5SDimitry Andric //
290b57cec5SDimitry Andric // if (n - 1 < len)
300b57cec5SDimitry Andric // for (i = 0; i < n; i++) {
310b57cec5SDimitry Andric // ...
320b57cec5SDimitry Andric // }
330b57cec5SDimitry Andric // else
340b57cec5SDimitry Andric // deoptimize
350b57cec5SDimitry Andric //
360b57cec5SDimitry Andric // It's tempting to rely on SCEV here, but it has proven to be problematic.
370b57cec5SDimitry Andric // Generally the facts SCEV provides about the increment step of add
380b57cec5SDimitry Andric // recurrences are true if the backedge of the loop is taken, which implicitly
390b57cec5SDimitry Andric // assumes that the guard doesn't fail. Using these facts to optimize the
400b57cec5SDimitry Andric // guard results in a circular logic where the guard is optimized under the
410b57cec5SDimitry Andric // assumption that it never fails.
420b57cec5SDimitry Andric //
430b57cec5SDimitry Andric // For example, in the loop below the induction variable will be marked as nuw
440b57cec5SDimitry Andric // basing on the guard. Basing on nuw the guard predicate will be considered
450b57cec5SDimitry Andric // monotonic. Given a monotonic condition it's tempting to replace the induction
460b57cec5SDimitry Andric // variable in the condition with its value on the last iteration. But this
470b57cec5SDimitry Andric // transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
480b57cec5SDimitry Andric //
490b57cec5SDimitry Andric // for (int i = b; i != e; i++)
500b57cec5SDimitry Andric // guard(i u< len)
510b57cec5SDimitry Andric //
520b57cec5SDimitry Andric // One of the ways to reason about this problem is to use an inductive proof
530b57cec5SDimitry Andric // approach. Given the loop:
540b57cec5SDimitry Andric //
550b57cec5SDimitry Andric // if (B(0)) {
560b57cec5SDimitry Andric // do {
570b57cec5SDimitry Andric // I = PHI(0, I.INC)
580b57cec5SDimitry Andric // I.INC = I + Step
590b57cec5SDimitry Andric // guard(G(I));
600b57cec5SDimitry Andric // } while (B(I));
610b57cec5SDimitry Andric // }
620b57cec5SDimitry Andric //
630b57cec5SDimitry Andric // where B(x) and G(x) are predicates that map integers to booleans, we want a
640b57cec5SDimitry Andric // loop invariant expression M such the following program has the same semantics
650b57cec5SDimitry Andric // as the above:
660b57cec5SDimitry Andric //
670b57cec5SDimitry Andric // if (B(0)) {
680b57cec5SDimitry Andric // do {
690b57cec5SDimitry Andric // I = PHI(0, I.INC)
700b57cec5SDimitry Andric // I.INC = I + Step
710b57cec5SDimitry Andric // guard(G(0) && M);
720b57cec5SDimitry Andric // } while (B(I));
730b57cec5SDimitry Andric // }
740b57cec5SDimitry Andric //
750b57cec5SDimitry Andric // One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
760b57cec5SDimitry Andric //
770b57cec5SDimitry Andric // Informal proof that the transformation above is correct:
780b57cec5SDimitry Andric //
790b57cec5SDimitry Andric // By the definition of guards we can rewrite the guard condition to:
800b57cec5SDimitry Andric // G(I) && G(0) && M
810b57cec5SDimitry Andric //
820b57cec5SDimitry Andric // Let's prove that for each iteration of the loop:
830b57cec5SDimitry Andric // G(0) && M => G(I)
840b57cec5SDimitry Andric // And the condition above can be simplified to G(Start) && M.
850b57cec5SDimitry Andric //
860b57cec5SDimitry Andric // Induction base.
870b57cec5SDimitry Andric // G(0) && M => G(0)
880b57cec5SDimitry Andric //
890b57cec5SDimitry Andric // Induction step. Assuming G(0) && M => G(I) on the subsequent
900b57cec5SDimitry Andric // iteration:
910b57cec5SDimitry Andric //
920b57cec5SDimitry Andric // B(I) is true because it's the backedge condition.
930b57cec5SDimitry Andric // G(I) is true because the backedge is guarded by this condition.
940b57cec5SDimitry Andric //
950b57cec5SDimitry Andric // So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
960b57cec5SDimitry Andric //
970b57cec5SDimitry Andric // Note that we can use anything stronger than M, i.e. any condition which
980b57cec5SDimitry Andric // implies M.
990b57cec5SDimitry Andric //
1000b57cec5SDimitry Andric // When S = 1 (i.e. forward iterating loop), the transformation is supported
1010b57cec5SDimitry Andric // when:
1020b57cec5SDimitry Andric // * The loop has a single latch with the condition of the form:
1030b57cec5SDimitry Andric // B(X) = latchStart + X <pred> latchLimit,
1040b57cec5SDimitry Andric // where <pred> is u<, u<=, s<, or s<=.
1050b57cec5SDimitry Andric // * The guard condition is of the form
1060b57cec5SDimitry Andric // G(X) = guardStart + X u< guardLimit
1070b57cec5SDimitry Andric //
1080b57cec5SDimitry Andric // For the ult latch comparison case M is:
1090b57cec5SDimitry Andric // forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
1100b57cec5SDimitry Andric // guardStart + X + 1 u< guardLimit
1110b57cec5SDimitry Andric //
1120b57cec5SDimitry Andric // The only way the antecedent can be true and the consequent can be false is
1130b57cec5SDimitry Andric // if
1140b57cec5SDimitry Andric // X == guardLimit - 1 - guardStart
1150b57cec5SDimitry Andric // (and guardLimit is non-zero, but we won't use this latter fact).
1160b57cec5SDimitry Andric // If X == guardLimit - 1 - guardStart then the second half of the antecedent is
1170b57cec5SDimitry Andric // latchStart + guardLimit - 1 - guardStart u< latchLimit
1180b57cec5SDimitry Andric // and its negation is
1190b57cec5SDimitry Andric // latchStart + guardLimit - 1 - guardStart u>= latchLimit
1200b57cec5SDimitry Andric //
1210b57cec5SDimitry Andric // In other words, if
1220b57cec5SDimitry Andric // latchLimit u<= latchStart + guardLimit - 1 - guardStart
1230b57cec5SDimitry Andric // then:
1240b57cec5SDimitry Andric // (the ranges below are written in ConstantRange notation, where [A, B) is the
1250b57cec5SDimitry Andric // set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
1260b57cec5SDimitry Andric //
1270b57cec5SDimitry Andric // forall X . guardStart + X u< guardLimit &&
1280b57cec5SDimitry Andric // latchStart + X u< latchLimit =>
1290b57cec5SDimitry Andric // guardStart + X + 1 u< guardLimit
1300b57cec5SDimitry Andric // == forall X . guardStart + X u< guardLimit &&
1310b57cec5SDimitry Andric // latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
1320b57cec5SDimitry Andric // guardStart + X + 1 u< guardLimit
1330b57cec5SDimitry Andric // == forall X . (guardStart + X) in [0, guardLimit) &&
1340b57cec5SDimitry Andric // (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
1350b57cec5SDimitry Andric // (guardStart + X + 1) in [0, guardLimit)
1360b57cec5SDimitry Andric // == forall X . X in [-guardStart, guardLimit - guardStart) &&
1370b57cec5SDimitry Andric // X in [-latchStart, guardLimit - 1 - guardStart) =>
1380b57cec5SDimitry Andric // X in [-guardStart - 1, guardLimit - guardStart - 1)
1390b57cec5SDimitry Andric // == true
1400b57cec5SDimitry Andric //
1410b57cec5SDimitry Andric // So the widened condition is:
1420b57cec5SDimitry Andric // guardStart u< guardLimit &&
1430b57cec5SDimitry Andric // latchStart + guardLimit - 1 - guardStart u>= latchLimit
1440b57cec5SDimitry Andric // Similarly for ule condition the widened condition is:
1450b57cec5SDimitry Andric // guardStart u< guardLimit &&
1460b57cec5SDimitry Andric // latchStart + guardLimit - 1 - guardStart u> latchLimit
1470b57cec5SDimitry Andric // For slt condition the widened condition is:
1480b57cec5SDimitry Andric // guardStart u< guardLimit &&
1490b57cec5SDimitry Andric // latchStart + guardLimit - 1 - guardStart s>= latchLimit
1500b57cec5SDimitry Andric // For sle condition the widened condition is:
1510b57cec5SDimitry Andric // guardStart u< guardLimit &&
1520b57cec5SDimitry Andric // latchStart + guardLimit - 1 - guardStart s> latchLimit
1530b57cec5SDimitry Andric //
1540b57cec5SDimitry Andric // When S = -1 (i.e. reverse iterating loop), the transformation is supported
1550b57cec5SDimitry Andric // when:
1560b57cec5SDimitry Andric // * The loop has a single latch with the condition of the form:
1570b57cec5SDimitry Andric // B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=.
1580b57cec5SDimitry Andric // * The guard condition is of the form
1590b57cec5SDimitry Andric // G(X) = X - 1 u< guardLimit
1600b57cec5SDimitry Andric //
1610b57cec5SDimitry Andric // For the ugt latch comparison case M is:
1620b57cec5SDimitry Andric // forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit
1630b57cec5SDimitry Andric //
1640b57cec5SDimitry Andric // The only way the antecedent can be true and the consequent can be false is if
1650b57cec5SDimitry Andric // X == 1.
1660b57cec5SDimitry Andric // If X == 1 then the second half of the antecedent is
1670b57cec5SDimitry Andric // 1 u> latchLimit, and its negation is latchLimit u>= 1.
1680b57cec5SDimitry Andric //
1690b57cec5SDimitry Andric // So the widened condition is:
1700b57cec5SDimitry Andric // guardStart u< guardLimit && latchLimit u>= 1.
1710b57cec5SDimitry Andric // Similarly for sgt condition the widened condition is:
1720b57cec5SDimitry Andric // guardStart u< guardLimit && latchLimit s>= 1.
1730b57cec5SDimitry Andric // For uge condition the widened condition is:
1740b57cec5SDimitry Andric // guardStart u< guardLimit && latchLimit u> 1.
1750b57cec5SDimitry Andric // For sge condition the widened condition is:
1760b57cec5SDimitry Andric // guardStart u< guardLimit && latchLimit s> 1.
1770b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1780b57cec5SDimitry Andric
1790b57cec5SDimitry Andric #include "llvm/Transforms/Scalar/LoopPredication.h"
1800b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
1810b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
1820b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
1830b57cec5SDimitry Andric #include "llvm/Analysis/GuardUtils.h"
1840b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
1850b57cec5SDimitry Andric #include "llvm/Analysis/LoopPass.h"
1860b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
1870b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
1880b57cec5SDimitry Andric #include "llvm/IR/Function.h"
1890b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
1900b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
1910b57cec5SDimitry Andric #include "llvm/IR/Module.h"
1920b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
193480093f4SDimitry Andric #include "llvm/InitializePasses.h"
1940b57cec5SDimitry Andric #include "llvm/Pass.h"
195480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
1960b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
1970b57cec5SDimitry Andric #include "llvm/Transforms/Scalar.h"
198480093f4SDimitry Andric #include "llvm/Transforms/Utils/GuardUtils.h"
1990b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
2000b57cec5SDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
2015ffd83dbSDimitry Andric #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
2020b57cec5SDimitry Andric
2030b57cec5SDimitry Andric #define DEBUG_TYPE "loop-predication"
2040b57cec5SDimitry Andric
2050b57cec5SDimitry Andric STATISTIC(TotalConsidered, "Number of guards considered");
2060b57cec5SDimitry Andric STATISTIC(TotalWidened, "Number of checks widened");
2070b57cec5SDimitry Andric
2080b57cec5SDimitry Andric using namespace llvm;
2090b57cec5SDimitry Andric
2100b57cec5SDimitry Andric static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
2110b57cec5SDimitry Andric cl::Hidden, cl::init(true));
2120b57cec5SDimitry Andric
2130b57cec5SDimitry Andric static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
2140b57cec5SDimitry Andric cl::Hidden, cl::init(true));
2150b57cec5SDimitry Andric
2160b57cec5SDimitry Andric static cl::opt<bool>
2170b57cec5SDimitry Andric SkipProfitabilityChecks("loop-predication-skip-profitability-checks",
2180b57cec5SDimitry Andric cl::Hidden, cl::init(false));
2190b57cec5SDimitry Andric
2200b57cec5SDimitry Andric // This is the scale factor for the latch probability. We use this during
2210b57cec5SDimitry Andric // profitability analysis to find other exiting blocks that have a much higher
2220b57cec5SDimitry Andric // probability of exiting the loop instead of loop exiting via latch.
2230b57cec5SDimitry Andric // This value should be greater than 1 for a sane profitability check.
2240b57cec5SDimitry Andric static cl::opt<float> LatchExitProbabilityScale(
2250b57cec5SDimitry Andric "loop-predication-latch-probability-scale", cl::Hidden, cl::init(2.0),
2260b57cec5SDimitry Andric cl::desc("scale factor for the latch probability. Value should be greater "
2270b57cec5SDimitry Andric "than 1. Lower values are ignored"));
2280b57cec5SDimitry Andric
2290b57cec5SDimitry Andric static cl::opt<bool> PredicateWidenableBranchGuards(
2300b57cec5SDimitry Andric "loop-predication-predicate-widenable-branches-to-deopt", cl::Hidden,
2310b57cec5SDimitry Andric cl::desc("Whether or not we should predicate guards "
2320b57cec5SDimitry Andric "expressed as widenable branches to deoptimize blocks"),
2330b57cec5SDimitry Andric cl::init(true));
2340b57cec5SDimitry Andric
2350b57cec5SDimitry Andric namespace {
2360b57cec5SDimitry Andric /// Represents an induction variable check:
2370b57cec5SDimitry Andric /// icmp Pred, <induction variable>, <loop invariant limit>
2380b57cec5SDimitry Andric struct LoopICmp {
2390b57cec5SDimitry Andric ICmpInst::Predicate Pred;
2400b57cec5SDimitry Andric const SCEVAddRecExpr *IV;
2410b57cec5SDimitry Andric const SCEV *Limit;
LoopICmp__anon06f493b30111::LoopICmp2420b57cec5SDimitry Andric LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
2430b57cec5SDimitry Andric const SCEV *Limit)
2440b57cec5SDimitry Andric : Pred(Pred), IV(IV), Limit(Limit) {}
LoopICmp__anon06f493b30111::LoopICmp2450b57cec5SDimitry Andric LoopICmp() {}
dump__anon06f493b30111::LoopICmp2460b57cec5SDimitry Andric void dump() {
2470b57cec5SDimitry Andric dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
2480b57cec5SDimitry Andric << ", Limit = " << *Limit << "\n";
2490b57cec5SDimitry Andric }
2500b57cec5SDimitry Andric };
2510b57cec5SDimitry Andric
2520b57cec5SDimitry Andric class LoopPredication {
2530b57cec5SDimitry Andric AliasAnalysis *AA;
254480093f4SDimitry Andric DominatorTree *DT;
2550b57cec5SDimitry Andric ScalarEvolution *SE;
256480093f4SDimitry Andric LoopInfo *LI;
2570b57cec5SDimitry Andric BranchProbabilityInfo *BPI;
2580b57cec5SDimitry Andric
2590b57cec5SDimitry Andric Loop *L;
2600b57cec5SDimitry Andric const DataLayout *DL;
2610b57cec5SDimitry Andric BasicBlock *Preheader;
2620b57cec5SDimitry Andric LoopICmp LatchCheck;
2630b57cec5SDimitry Andric
2640b57cec5SDimitry Andric bool isSupportedStep(const SCEV* Step);
2650b57cec5SDimitry Andric Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI);
2660b57cec5SDimitry Andric Optional<LoopICmp> parseLoopLatchICmp();
2670b57cec5SDimitry Andric
2680b57cec5SDimitry Andric /// Return an insertion point suitable for inserting a safe to speculate
2690b57cec5SDimitry Andric /// instruction whose only user will be 'User' which has operands 'Ops'. A
2700b57cec5SDimitry Andric /// trivial result would be the at the User itself, but we try to return a
2710b57cec5SDimitry Andric /// loop invariant location if possible.
2720b57cec5SDimitry Andric Instruction *findInsertPt(Instruction *User, ArrayRef<Value*> Ops);
2730b57cec5SDimitry Andric /// Same as above, *except* that this uses the SCEV definition of invariant
2740b57cec5SDimitry Andric /// which is that an expression *can be made* invariant via SCEVExpander.
2750b57cec5SDimitry Andric /// Thus, this version is only suitable for finding an insert point to be be
2760b57cec5SDimitry Andric /// passed to SCEVExpander!
2770b57cec5SDimitry Andric Instruction *findInsertPt(Instruction *User, ArrayRef<const SCEV*> Ops);
2780b57cec5SDimitry Andric
2790b57cec5SDimitry Andric /// Return true if the value is known to produce a single fixed value across
2800b57cec5SDimitry Andric /// all iterations on which it executes. Note that this does not imply
2815ffd83dbSDimitry Andric /// speculation safety. That must be established separately.
2820b57cec5SDimitry Andric bool isLoopInvariantValue(const SCEV* S);
2830b57cec5SDimitry Andric
2840b57cec5SDimitry Andric Value *expandCheck(SCEVExpander &Expander, Instruction *Guard,
2850b57cec5SDimitry Andric ICmpInst::Predicate Pred, const SCEV *LHS,
2860b57cec5SDimitry Andric const SCEV *RHS);
2870b57cec5SDimitry Andric
2880b57cec5SDimitry Andric Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
2890b57cec5SDimitry Andric Instruction *Guard);
2900b57cec5SDimitry Andric Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
2910b57cec5SDimitry Andric LoopICmp RangeCheck,
2920b57cec5SDimitry Andric SCEVExpander &Expander,
2930b57cec5SDimitry Andric Instruction *Guard);
2940b57cec5SDimitry Andric Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
2950b57cec5SDimitry Andric LoopICmp RangeCheck,
2960b57cec5SDimitry Andric SCEVExpander &Expander,
2970b57cec5SDimitry Andric Instruction *Guard);
2980b57cec5SDimitry Andric unsigned collectChecks(SmallVectorImpl<Value *> &Checks, Value *Condition,
2990b57cec5SDimitry Andric SCEVExpander &Expander, Instruction *Guard);
3000b57cec5SDimitry Andric bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
3010b57cec5SDimitry Andric bool widenWidenableBranchGuardConditions(BranchInst *Guard, SCEVExpander &Expander);
3020b57cec5SDimitry Andric // If the loop always exits through another block in the loop, we should not
3030b57cec5SDimitry Andric // predicate based on the latch check. For example, the latch check can be a
3040b57cec5SDimitry Andric // very coarse grained check and there can be more fine grained exit checks
3050b57cec5SDimitry Andric // within the loop. We identify such unprofitable loops through BPI.
3060b57cec5SDimitry Andric bool isLoopProfitableToPredicate();
3070b57cec5SDimitry Andric
308480093f4SDimitry Andric bool predicateLoopExits(Loop *L, SCEVExpander &Rewriter);
309480093f4SDimitry Andric
3100b57cec5SDimitry Andric public:
LoopPredication(AliasAnalysis * AA,DominatorTree * DT,ScalarEvolution * SE,LoopInfo * LI,BranchProbabilityInfo * BPI)311480093f4SDimitry Andric LoopPredication(AliasAnalysis *AA, DominatorTree *DT,
312480093f4SDimitry Andric ScalarEvolution *SE, LoopInfo *LI,
3130b57cec5SDimitry Andric BranchProbabilityInfo *BPI)
314480093f4SDimitry Andric : AA(AA), DT(DT), SE(SE), LI(LI), BPI(BPI) {};
3150b57cec5SDimitry Andric bool runOnLoop(Loop *L);
3160b57cec5SDimitry Andric };
3170b57cec5SDimitry Andric
3180b57cec5SDimitry Andric class LoopPredicationLegacyPass : public LoopPass {
3190b57cec5SDimitry Andric public:
3200b57cec5SDimitry Andric static char ID;
LoopPredicationLegacyPass()3210b57cec5SDimitry Andric LoopPredicationLegacyPass() : LoopPass(ID) {
3220b57cec5SDimitry Andric initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric
getAnalysisUsage(AnalysisUsage & AU) const3250b57cec5SDimitry Andric void getAnalysisUsage(AnalysisUsage &AU) const override {
3260b57cec5SDimitry Andric AU.addRequired<BranchProbabilityInfoWrapperPass>();
3270b57cec5SDimitry Andric getLoopAnalysisUsage(AU);
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric
runOnLoop(Loop * L,LPPassManager & LPM)3300b57cec5SDimitry Andric bool runOnLoop(Loop *L, LPPassManager &LPM) override {
3310b57cec5SDimitry Andric if (skipLoop(L))
3320b57cec5SDimitry Andric return false;
3330b57cec5SDimitry Andric auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
334480093f4SDimitry Andric auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
335480093f4SDimitry Andric auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3360b57cec5SDimitry Andric BranchProbabilityInfo &BPI =
3370b57cec5SDimitry Andric getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
3380b57cec5SDimitry Andric auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
339480093f4SDimitry Andric LoopPredication LP(AA, DT, SE, LI, &BPI);
3400b57cec5SDimitry Andric return LP.runOnLoop(L);
3410b57cec5SDimitry Andric }
3420b57cec5SDimitry Andric };
3430b57cec5SDimitry Andric
3440b57cec5SDimitry Andric char LoopPredicationLegacyPass::ID = 0;
3455ffd83dbSDimitry Andric } // end namespace
3460b57cec5SDimitry Andric
3470b57cec5SDimitry Andric INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
3480b57cec5SDimitry Andric "Loop predication", false, false)
INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)3490b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)
3500b57cec5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(LoopPass)
3510b57cec5SDimitry Andric INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
3520b57cec5SDimitry Andric "Loop predication", false, false)
3530b57cec5SDimitry Andric
3540b57cec5SDimitry Andric Pass *llvm::createLoopPredicationPass() {
3550b57cec5SDimitry Andric return new LoopPredicationLegacyPass();
3560b57cec5SDimitry Andric }
3570b57cec5SDimitry Andric
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater & U)3580b57cec5SDimitry Andric PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
3590b57cec5SDimitry Andric LoopStandardAnalysisResults &AR,
3600b57cec5SDimitry Andric LPMUpdater &U) {
3610b57cec5SDimitry Andric Function *F = L.getHeader()->getParent();
3625ffd83dbSDimitry Andric // For the new PM, we also can't use BranchProbabilityInfo as an analysis
3635ffd83dbSDimitry Andric // pass. Function analyses need to be preserved across loop transformations
3645ffd83dbSDimitry Andric // but BPI is not preserved, hence a newly built one is needed.
365*af732203SDimitry Andric BranchProbabilityInfo BPI(*F, AR.LI, &AR.TLI, &AR.DT, nullptr);
3665ffd83dbSDimitry Andric LoopPredication LP(&AR.AA, &AR.DT, &AR.SE, &AR.LI, &BPI);
3670b57cec5SDimitry Andric if (!LP.runOnLoop(&L))
3680b57cec5SDimitry Andric return PreservedAnalyses::all();
3690b57cec5SDimitry Andric
3700b57cec5SDimitry Andric return getLoopPassPreservedAnalyses();
3710b57cec5SDimitry Andric }
3720b57cec5SDimitry Andric
3730b57cec5SDimitry Andric Optional<LoopICmp>
parseLoopICmp(ICmpInst * ICI)3740b57cec5SDimitry Andric LoopPredication::parseLoopICmp(ICmpInst *ICI) {
3750b57cec5SDimitry Andric auto Pred = ICI->getPredicate();
3760b57cec5SDimitry Andric auto *LHS = ICI->getOperand(0);
3770b57cec5SDimitry Andric auto *RHS = ICI->getOperand(1);
3780b57cec5SDimitry Andric
3790b57cec5SDimitry Andric const SCEV *LHSS = SE->getSCEV(LHS);
3800b57cec5SDimitry Andric if (isa<SCEVCouldNotCompute>(LHSS))
3810b57cec5SDimitry Andric return None;
3820b57cec5SDimitry Andric const SCEV *RHSS = SE->getSCEV(RHS);
3830b57cec5SDimitry Andric if (isa<SCEVCouldNotCompute>(RHSS))
3840b57cec5SDimitry Andric return None;
3850b57cec5SDimitry Andric
3860b57cec5SDimitry Andric // Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
3870b57cec5SDimitry Andric if (SE->isLoopInvariant(LHSS, L)) {
3880b57cec5SDimitry Andric std::swap(LHS, RHS);
3890b57cec5SDimitry Andric std::swap(LHSS, RHSS);
3900b57cec5SDimitry Andric Pred = ICmpInst::getSwappedPredicate(Pred);
3910b57cec5SDimitry Andric }
3920b57cec5SDimitry Andric
3930b57cec5SDimitry Andric const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
3940b57cec5SDimitry Andric if (!AR || AR->getLoop() != L)
3950b57cec5SDimitry Andric return None;
3960b57cec5SDimitry Andric
3970b57cec5SDimitry Andric return LoopICmp(Pred, AR, RHSS);
3980b57cec5SDimitry Andric }
3990b57cec5SDimitry Andric
expandCheck(SCEVExpander & Expander,Instruction * Guard,ICmpInst::Predicate Pred,const SCEV * LHS,const SCEV * RHS)4000b57cec5SDimitry Andric Value *LoopPredication::expandCheck(SCEVExpander &Expander,
4010b57cec5SDimitry Andric Instruction *Guard,
4020b57cec5SDimitry Andric ICmpInst::Predicate Pred, const SCEV *LHS,
4030b57cec5SDimitry Andric const SCEV *RHS) {
4040b57cec5SDimitry Andric Type *Ty = LHS->getType();
4050b57cec5SDimitry Andric assert(Ty == RHS->getType() && "expandCheck operands have different types?");
4060b57cec5SDimitry Andric
4070b57cec5SDimitry Andric if (SE->isLoopInvariant(LHS, L) && SE->isLoopInvariant(RHS, L)) {
4080b57cec5SDimitry Andric IRBuilder<> Builder(Guard);
4090b57cec5SDimitry Andric if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
4100b57cec5SDimitry Andric return Builder.getTrue();
4110b57cec5SDimitry Andric if (SE->isLoopEntryGuardedByCond(L, ICmpInst::getInversePredicate(Pred),
4120b57cec5SDimitry Andric LHS, RHS))
4130b57cec5SDimitry Andric return Builder.getFalse();
4140b57cec5SDimitry Andric }
4150b57cec5SDimitry Andric
4160b57cec5SDimitry Andric Value *LHSV = Expander.expandCodeFor(LHS, Ty, findInsertPt(Guard, {LHS}));
4170b57cec5SDimitry Andric Value *RHSV = Expander.expandCodeFor(RHS, Ty, findInsertPt(Guard, {RHS}));
4180b57cec5SDimitry Andric IRBuilder<> Builder(findInsertPt(Guard, {LHSV, RHSV}));
4190b57cec5SDimitry Andric return Builder.CreateICmp(Pred, LHSV, RHSV);
4200b57cec5SDimitry Andric }
4210b57cec5SDimitry Andric
4220b57cec5SDimitry Andric
4230b57cec5SDimitry Andric // Returns true if its safe to truncate the IV to RangeCheckType.
4240b57cec5SDimitry Andric // When the IV type is wider than the range operand type, we can still do loop
4250b57cec5SDimitry Andric // predication, by generating SCEVs for the range and latch that are of the
4260b57cec5SDimitry Andric // same type. We achieve this by generating a SCEV truncate expression for the
4270b57cec5SDimitry Andric // latch IV. This is done iff truncation of the IV is a safe operation,
4280b57cec5SDimitry Andric // without loss of information.
4290b57cec5SDimitry Andric // Another way to achieve this is by generating a wider type SCEV for the
4300b57cec5SDimitry Andric // range check operand, however, this needs a more involved check that
4310b57cec5SDimitry Andric // operands do not overflow. This can lead to loss of information when the
4320b57cec5SDimitry Andric // range operand is of the form: add i32 %offset, %iv. We need to prove that
4330b57cec5SDimitry Andric // sext(x + y) is same as sext(x) + sext(y).
4340b57cec5SDimitry Andric // This function returns true if we can safely represent the IV type in
4350b57cec5SDimitry Andric // the RangeCheckType without loss of information.
isSafeToTruncateWideIVType(const DataLayout & DL,ScalarEvolution & SE,const LoopICmp LatchCheck,Type * RangeCheckType)4360b57cec5SDimitry Andric static bool isSafeToTruncateWideIVType(const DataLayout &DL,
4370b57cec5SDimitry Andric ScalarEvolution &SE,
4380b57cec5SDimitry Andric const LoopICmp LatchCheck,
4390b57cec5SDimitry Andric Type *RangeCheckType) {
4400b57cec5SDimitry Andric if (!EnableIVTruncation)
4410b57cec5SDimitry Andric return false;
442*af732203SDimitry Andric assert(DL.getTypeSizeInBits(LatchCheck.IV->getType()).getFixedSize() >
443*af732203SDimitry Andric DL.getTypeSizeInBits(RangeCheckType).getFixedSize() &&
4440b57cec5SDimitry Andric "Expected latch check IV type to be larger than range check operand "
4450b57cec5SDimitry Andric "type!");
4460b57cec5SDimitry Andric // The start and end values of the IV should be known. This is to guarantee
4470b57cec5SDimitry Andric // that truncating the wide type will not lose information.
4480b57cec5SDimitry Andric auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
4490b57cec5SDimitry Andric auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
4500b57cec5SDimitry Andric if (!Limit || !Start)
4510b57cec5SDimitry Andric return false;
4520b57cec5SDimitry Andric // This check makes sure that the IV does not change sign during loop
4530b57cec5SDimitry Andric // iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
4540b57cec5SDimitry Andric // LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
4550b57cec5SDimitry Andric // IV wraps around, and the truncation of the IV would lose the range of
4560b57cec5SDimitry Andric // iterations between 2^32 and 2^64.
457*af732203SDimitry Andric if (!SE.getMonotonicPredicateType(LatchCheck.IV, LatchCheck.Pred))
4580b57cec5SDimitry Andric return false;
4590b57cec5SDimitry Andric // The active bits should be less than the bits in the RangeCheckType. This
4600b57cec5SDimitry Andric // guarantees that truncating the latch check to RangeCheckType is a safe
4610b57cec5SDimitry Andric // operation.
462*af732203SDimitry Andric auto RangeCheckTypeBitSize =
463*af732203SDimitry Andric DL.getTypeSizeInBits(RangeCheckType).getFixedSize();
4640b57cec5SDimitry Andric return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
4650b57cec5SDimitry Andric Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
4660b57cec5SDimitry Andric }
4670b57cec5SDimitry Andric
4680b57cec5SDimitry Andric
4690b57cec5SDimitry Andric // Return an LoopICmp describing a latch check equivlent to LatchCheck but with
4700b57cec5SDimitry Andric // 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)4710b57cec5SDimitry Andric static Optional<LoopICmp> generateLoopLatchCheck(const DataLayout &DL,
4720b57cec5SDimitry Andric ScalarEvolution &SE,
4730b57cec5SDimitry Andric const LoopICmp LatchCheck,
4740b57cec5SDimitry Andric Type *RangeCheckType) {
4750b57cec5SDimitry Andric
4760b57cec5SDimitry Andric auto *LatchType = LatchCheck.IV->getType();
4770b57cec5SDimitry Andric if (RangeCheckType == LatchType)
4780b57cec5SDimitry Andric return LatchCheck;
4790b57cec5SDimitry Andric // For now, bail out if latch type is narrower than range type.
480*af732203SDimitry Andric if (DL.getTypeSizeInBits(LatchType).getFixedSize() <
481*af732203SDimitry Andric DL.getTypeSizeInBits(RangeCheckType).getFixedSize())
4820b57cec5SDimitry Andric return None;
4830b57cec5SDimitry Andric if (!isSafeToTruncateWideIVType(DL, SE, LatchCheck, RangeCheckType))
4840b57cec5SDimitry Andric return None;
4850b57cec5SDimitry Andric // We can now safely identify the truncated version of the IV and limit for
4860b57cec5SDimitry Andric // RangeCheckType.
4870b57cec5SDimitry Andric LoopICmp NewLatchCheck;
4880b57cec5SDimitry Andric NewLatchCheck.Pred = LatchCheck.Pred;
4890b57cec5SDimitry Andric NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
4900b57cec5SDimitry Andric SE.getTruncateExpr(LatchCheck.IV, RangeCheckType));
4910b57cec5SDimitry Andric if (!NewLatchCheck.IV)
4920b57cec5SDimitry Andric return None;
4930b57cec5SDimitry Andric NewLatchCheck.Limit = SE.getTruncateExpr(LatchCheck.Limit, RangeCheckType);
4940b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "IV of type: " << *LatchType
4950b57cec5SDimitry Andric << "can be represented as range check type:"
4960b57cec5SDimitry Andric << *RangeCheckType << "\n");
4970b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
4980b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
4990b57cec5SDimitry Andric return NewLatchCheck;
5000b57cec5SDimitry Andric }
5010b57cec5SDimitry Andric
isSupportedStep(const SCEV * Step)5020b57cec5SDimitry Andric bool LoopPredication::isSupportedStep(const SCEV* Step) {
5030b57cec5SDimitry Andric return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
5040b57cec5SDimitry Andric }
5050b57cec5SDimitry Andric
findInsertPt(Instruction * Use,ArrayRef<Value * > Ops)5060b57cec5SDimitry Andric Instruction *LoopPredication::findInsertPt(Instruction *Use,
5070b57cec5SDimitry Andric ArrayRef<Value*> Ops) {
5080b57cec5SDimitry Andric for (Value *Op : Ops)
5090b57cec5SDimitry Andric if (!L->isLoopInvariant(Op))
5100b57cec5SDimitry Andric return Use;
5110b57cec5SDimitry Andric return Preheader->getTerminator();
5120b57cec5SDimitry Andric }
5130b57cec5SDimitry Andric
findInsertPt(Instruction * Use,ArrayRef<const SCEV * > Ops)5140b57cec5SDimitry Andric Instruction *LoopPredication::findInsertPt(Instruction *Use,
5150b57cec5SDimitry Andric ArrayRef<const SCEV*> Ops) {
5160b57cec5SDimitry Andric // Subtlety: SCEV considers things to be invariant if the value produced is
5170b57cec5SDimitry Andric // the same across iterations. This is not the same as being able to
5180b57cec5SDimitry Andric // evaluate outside the loop, which is what we actually need here.
5190b57cec5SDimitry Andric for (const SCEV *Op : Ops)
5200b57cec5SDimitry Andric if (!SE->isLoopInvariant(Op, L) ||
5210b57cec5SDimitry Andric !isSafeToExpandAt(Op, Preheader->getTerminator(), *SE))
5220b57cec5SDimitry Andric return Use;
5230b57cec5SDimitry Andric return Preheader->getTerminator();
5240b57cec5SDimitry Andric }
5250b57cec5SDimitry Andric
isLoopInvariantValue(const SCEV * S)5260b57cec5SDimitry Andric bool LoopPredication::isLoopInvariantValue(const SCEV* S) {
5270b57cec5SDimitry Andric // Handling expressions which produce invariant results, but *haven't* yet
5280b57cec5SDimitry Andric // been removed from the loop serves two important purposes.
5290b57cec5SDimitry Andric // 1) Most importantly, it resolves a pass ordering cycle which would
5300b57cec5SDimitry Andric // otherwise need us to iteration licm, loop-predication, and either
5310b57cec5SDimitry Andric // loop-unswitch or loop-peeling to make progress on examples with lots of
5320b57cec5SDimitry Andric // predicable range checks in a row. (Since, in the general case, we can't
5330b57cec5SDimitry Andric // hoist the length checks until the dominating checks have been discharged
5340b57cec5SDimitry Andric // as we can't prove doing so is safe.)
5350b57cec5SDimitry Andric // 2) As a nice side effect, this exposes the value of peeling or unswitching
5360b57cec5SDimitry Andric // much more obviously in the IR. Otherwise, the cost modeling for other
5370b57cec5SDimitry Andric // transforms would end up needing to duplicate all of this logic to model a
5380b57cec5SDimitry Andric // check which becomes predictable based on a modeled peel or unswitch.
5390b57cec5SDimitry Andric //
5400b57cec5SDimitry Andric // The cost of doing so in the worst case is an extra fill from the stack in
5410b57cec5SDimitry Andric // the loop to materialize the loop invariant test value instead of checking
5420b57cec5SDimitry Andric // against the original IV which is presumable in a register inside the loop.
5430b57cec5SDimitry Andric // Such cases are presumably rare, and hint at missing oppurtunities for
5440b57cec5SDimitry Andric // other passes.
5450b57cec5SDimitry Andric
5460b57cec5SDimitry Andric if (SE->isLoopInvariant(S, L))
5470b57cec5SDimitry Andric // Note: This the SCEV variant, so the original Value* may be within the
5480b57cec5SDimitry Andric // loop even though SCEV has proven it is loop invariant.
5490b57cec5SDimitry Andric return true;
5500b57cec5SDimitry Andric
5510b57cec5SDimitry Andric // Handle a particular important case which SCEV doesn't yet know about which
5520b57cec5SDimitry Andric // shows up in range checks on arrays with immutable lengths.
5530b57cec5SDimitry Andric // TODO: This should be sunk inside SCEV.
5540b57cec5SDimitry Andric if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S))
5550b57cec5SDimitry Andric if (const auto *LI = dyn_cast<LoadInst>(U->getValue()))
5560b57cec5SDimitry Andric if (LI->isUnordered() && L->hasLoopInvariantOperands(LI))
5570b57cec5SDimitry Andric if (AA->pointsToConstantMemory(LI->getOperand(0)) ||
5588bcb0991SDimitry Andric LI->hasMetadata(LLVMContext::MD_invariant_load))
5590b57cec5SDimitry Andric return true;
5600b57cec5SDimitry Andric return false;
5610b57cec5SDimitry Andric }
5620b57cec5SDimitry Andric
widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,LoopICmp RangeCheck,SCEVExpander & Expander,Instruction * Guard)5630b57cec5SDimitry Andric Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
5640b57cec5SDimitry Andric LoopICmp LatchCheck, LoopICmp RangeCheck,
5650b57cec5SDimitry Andric SCEVExpander &Expander, Instruction *Guard) {
5660b57cec5SDimitry Andric auto *Ty = RangeCheck.IV->getType();
5670b57cec5SDimitry Andric // Generate the widened condition for the forward loop:
5680b57cec5SDimitry Andric // guardStart u< guardLimit &&
5690b57cec5SDimitry Andric // latchLimit <pred> guardLimit - 1 - guardStart + latchStart
5700b57cec5SDimitry Andric // where <pred> depends on the latch condition predicate. See the file
5710b57cec5SDimitry Andric // header comment for the reasoning.
5720b57cec5SDimitry Andric // guardLimit - guardStart + latchStart - 1
5730b57cec5SDimitry Andric const SCEV *GuardStart = RangeCheck.IV->getStart();
5740b57cec5SDimitry Andric const SCEV *GuardLimit = RangeCheck.Limit;
5750b57cec5SDimitry Andric const SCEV *LatchStart = LatchCheck.IV->getStart();
5760b57cec5SDimitry Andric const SCEV *LatchLimit = LatchCheck.Limit;
5770b57cec5SDimitry Andric // Subtlety: We need all the values to be *invariant* across all iterations,
5780b57cec5SDimitry Andric // but we only need to check expansion safety for those which *aren't*
5790b57cec5SDimitry Andric // already guaranteed to dominate the guard.
5800b57cec5SDimitry Andric if (!isLoopInvariantValue(GuardStart) ||
5810b57cec5SDimitry Andric !isLoopInvariantValue(GuardLimit) ||
5820b57cec5SDimitry Andric !isLoopInvariantValue(LatchStart) ||
5830b57cec5SDimitry Andric !isLoopInvariantValue(LatchLimit)) {
5840b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
5850b57cec5SDimitry Andric return None;
5860b57cec5SDimitry Andric }
5870b57cec5SDimitry Andric if (!isSafeToExpandAt(LatchStart, Guard, *SE) ||
5880b57cec5SDimitry Andric !isSafeToExpandAt(LatchLimit, Guard, *SE)) {
5890b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
5900b57cec5SDimitry Andric return None;
5910b57cec5SDimitry Andric }
5920b57cec5SDimitry Andric
5930b57cec5SDimitry Andric // guardLimit - guardStart + latchStart - 1
5940b57cec5SDimitry Andric const SCEV *RHS =
5950b57cec5SDimitry Andric SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
5960b57cec5SDimitry Andric SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
5970b57cec5SDimitry Andric auto LimitCheckPred =
5980b57cec5SDimitry Andric ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
5990b57cec5SDimitry Andric
6000b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
6010b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "RHS: " << *RHS << "\n");
6020b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
6030b57cec5SDimitry Andric
6040b57cec5SDimitry Andric auto *LimitCheck =
6050b57cec5SDimitry Andric expandCheck(Expander, Guard, LimitCheckPred, LatchLimit, RHS);
6060b57cec5SDimitry Andric auto *FirstIterationCheck = expandCheck(Expander, Guard, RangeCheck.Pred,
6070b57cec5SDimitry Andric GuardStart, GuardLimit);
6080b57cec5SDimitry Andric IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
6090b57cec5SDimitry Andric return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
6100b57cec5SDimitry Andric }
6110b57cec5SDimitry Andric
widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,LoopICmp RangeCheck,SCEVExpander & Expander,Instruction * Guard)6120b57cec5SDimitry Andric Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
6130b57cec5SDimitry Andric LoopICmp LatchCheck, LoopICmp RangeCheck,
6140b57cec5SDimitry Andric SCEVExpander &Expander, Instruction *Guard) {
6150b57cec5SDimitry Andric auto *Ty = RangeCheck.IV->getType();
6160b57cec5SDimitry Andric const SCEV *GuardStart = RangeCheck.IV->getStart();
6170b57cec5SDimitry Andric const SCEV *GuardLimit = RangeCheck.Limit;
6180b57cec5SDimitry Andric const SCEV *LatchStart = LatchCheck.IV->getStart();
6190b57cec5SDimitry Andric const SCEV *LatchLimit = LatchCheck.Limit;
6200b57cec5SDimitry Andric // Subtlety: We need all the values to be *invariant* across all iterations,
6210b57cec5SDimitry Andric // but we only need to check expansion safety for those which *aren't*
6220b57cec5SDimitry Andric // already guaranteed to dominate the guard.
6230b57cec5SDimitry Andric if (!isLoopInvariantValue(GuardStart) ||
6240b57cec5SDimitry Andric !isLoopInvariantValue(GuardLimit) ||
6250b57cec5SDimitry Andric !isLoopInvariantValue(LatchStart) ||
6260b57cec5SDimitry Andric !isLoopInvariantValue(LatchLimit)) {
6270b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
6280b57cec5SDimitry Andric return None;
6290b57cec5SDimitry Andric }
6300b57cec5SDimitry Andric if (!isSafeToExpandAt(LatchStart, Guard, *SE) ||
6310b57cec5SDimitry Andric !isSafeToExpandAt(LatchLimit, Guard, *SE)) {
6320b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Can't expand limit check!\n");
6330b57cec5SDimitry Andric return None;
6340b57cec5SDimitry Andric }
6350b57cec5SDimitry Andric // The decrement of the latch check IV should be the same as the
6360b57cec5SDimitry Andric // rangeCheckIV.
6370b57cec5SDimitry Andric auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
6380b57cec5SDimitry Andric if (RangeCheck.IV != PostDecLatchCheckIV) {
6390b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
6400b57cec5SDimitry Andric << *PostDecLatchCheckIV
6410b57cec5SDimitry Andric << " and RangeCheckIV: " << *RangeCheck.IV << "\n");
6420b57cec5SDimitry Andric return None;
6430b57cec5SDimitry Andric }
6440b57cec5SDimitry Andric
6450b57cec5SDimitry Andric // Generate the widened condition for CountDownLoop:
6460b57cec5SDimitry Andric // guardStart u< guardLimit &&
6470b57cec5SDimitry Andric // latchLimit <pred> 1.
6480b57cec5SDimitry Andric // See the header comment for reasoning of the checks.
6490b57cec5SDimitry Andric auto LimitCheckPred =
6500b57cec5SDimitry Andric ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
6510b57cec5SDimitry Andric auto *FirstIterationCheck = expandCheck(Expander, Guard,
6520b57cec5SDimitry Andric ICmpInst::ICMP_ULT,
6530b57cec5SDimitry Andric GuardStart, GuardLimit);
6540b57cec5SDimitry Andric auto *LimitCheck = expandCheck(Expander, Guard, LimitCheckPred, LatchLimit,
6550b57cec5SDimitry Andric SE->getOne(Ty));
6560b57cec5SDimitry Andric IRBuilder<> Builder(findInsertPt(Guard, {FirstIterationCheck, LimitCheck}));
6570b57cec5SDimitry Andric return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
6580b57cec5SDimitry Andric }
6590b57cec5SDimitry Andric
normalizePredicate(ScalarEvolution * SE,Loop * L,LoopICmp & RC)6600b57cec5SDimitry Andric static void normalizePredicate(ScalarEvolution *SE, Loop *L,
6610b57cec5SDimitry Andric LoopICmp& RC) {
6620b57cec5SDimitry Andric // LFTR canonicalizes checks to the ICMP_NE/EQ form; normalize back to the
6630b57cec5SDimitry Andric // ULT/UGE form for ease of handling by our caller.
6640b57cec5SDimitry Andric if (ICmpInst::isEquality(RC.Pred) &&
6650b57cec5SDimitry Andric RC.IV->getStepRecurrence(*SE)->isOne() &&
6660b57cec5SDimitry Andric SE->isKnownPredicate(ICmpInst::ICMP_ULE, RC.IV->getStart(), RC.Limit))
6670b57cec5SDimitry Andric RC.Pred = RC.Pred == ICmpInst::ICMP_NE ?
6680b57cec5SDimitry Andric ICmpInst::ICMP_ULT : ICmpInst::ICMP_UGE;
6690b57cec5SDimitry Andric }
6700b57cec5SDimitry Andric
6710b57cec5SDimitry Andric
6720b57cec5SDimitry Andric /// If ICI can be widened to a loop invariant condition emits the loop
6730b57cec5SDimitry Andric /// invariant condition in the loop preheader and return it, otherwise
6740b57cec5SDimitry Andric /// returns None.
widenICmpRangeCheck(ICmpInst * ICI,SCEVExpander & Expander,Instruction * Guard)6750b57cec5SDimitry Andric Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
6760b57cec5SDimitry Andric SCEVExpander &Expander,
6770b57cec5SDimitry Andric Instruction *Guard) {
6780b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
6790b57cec5SDimitry Andric LLVM_DEBUG(ICI->dump());
6800b57cec5SDimitry Andric
6810b57cec5SDimitry Andric // parseLoopStructure guarantees that the latch condition is:
6820b57cec5SDimitry Andric // ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
6830b57cec5SDimitry Andric // We are looking for the range checks of the form:
6840b57cec5SDimitry Andric // i u< guardLimit
6850b57cec5SDimitry Andric auto RangeCheck = parseLoopICmp(ICI);
6860b57cec5SDimitry Andric if (!RangeCheck) {
6870b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
6880b57cec5SDimitry Andric return None;
6890b57cec5SDimitry Andric }
6900b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Guard check:\n");
6910b57cec5SDimitry Andric LLVM_DEBUG(RangeCheck->dump());
6920b57cec5SDimitry Andric if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
6930b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Unsupported range check predicate("
6940b57cec5SDimitry Andric << RangeCheck->Pred << ")!\n");
6950b57cec5SDimitry Andric return None;
6960b57cec5SDimitry Andric }
6970b57cec5SDimitry Andric auto *RangeCheckIV = RangeCheck->IV;
6980b57cec5SDimitry Andric if (!RangeCheckIV->isAffine()) {
6990b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Range check IV is not affine!\n");
7000b57cec5SDimitry Andric return None;
7010b57cec5SDimitry Andric }
7020b57cec5SDimitry Andric auto *Step = RangeCheckIV->getStepRecurrence(*SE);
7030b57cec5SDimitry Andric // We cannot just compare with latch IV step because the latch and range IVs
7040b57cec5SDimitry Andric // may have different types.
7050b57cec5SDimitry Andric if (!isSupportedStep(Step)) {
7060b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
7070b57cec5SDimitry Andric return None;
7080b57cec5SDimitry Andric }
7090b57cec5SDimitry Andric auto *Ty = RangeCheckIV->getType();
7100b57cec5SDimitry Andric auto CurrLatchCheckOpt = generateLoopLatchCheck(*DL, *SE, LatchCheck, Ty);
7110b57cec5SDimitry Andric if (!CurrLatchCheckOpt) {
7120b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Failed to generate a loop latch check "
7130b57cec5SDimitry Andric "corresponding to range type: "
7140b57cec5SDimitry Andric << *Ty << "\n");
7150b57cec5SDimitry Andric return None;
7160b57cec5SDimitry Andric }
7170b57cec5SDimitry Andric
7180b57cec5SDimitry Andric LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
7190b57cec5SDimitry Andric // At this point, the range and latch step should have the same type, but need
7200b57cec5SDimitry Andric // not have the same value (we support both 1 and -1 steps).
7210b57cec5SDimitry Andric assert(Step->getType() ==
7220b57cec5SDimitry Andric CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
7230b57cec5SDimitry Andric "Range and latch steps should be of same type!");
7240b57cec5SDimitry Andric if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
7250b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Range and latch have different step values!\n");
7260b57cec5SDimitry Andric return None;
7270b57cec5SDimitry Andric }
7280b57cec5SDimitry Andric
7290b57cec5SDimitry Andric if (Step->isOne())
7300b57cec5SDimitry Andric return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
7310b57cec5SDimitry Andric Expander, Guard);
7320b57cec5SDimitry Andric else {
7330b57cec5SDimitry Andric assert(Step->isAllOnesValue() && "Step should be -1!");
7340b57cec5SDimitry Andric return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
7350b57cec5SDimitry Andric Expander, Guard);
7360b57cec5SDimitry Andric }
7370b57cec5SDimitry Andric }
7380b57cec5SDimitry Andric
collectChecks(SmallVectorImpl<Value * > & Checks,Value * Condition,SCEVExpander & Expander,Instruction * Guard)7390b57cec5SDimitry Andric unsigned LoopPredication::collectChecks(SmallVectorImpl<Value *> &Checks,
7400b57cec5SDimitry Andric Value *Condition,
7410b57cec5SDimitry Andric SCEVExpander &Expander,
7420b57cec5SDimitry Andric Instruction *Guard) {
7430b57cec5SDimitry Andric unsigned NumWidened = 0;
7440b57cec5SDimitry Andric // The guard condition is expected to be in form of:
7450b57cec5SDimitry Andric // cond1 && cond2 && cond3 ...
7460b57cec5SDimitry Andric // Iterate over subconditions looking for icmp conditions which can be
7470b57cec5SDimitry Andric // widened across loop iterations. Widening these conditions remember the
7480b57cec5SDimitry Andric // resulting list of subconditions in Checks vector.
7490b57cec5SDimitry Andric SmallVector<Value *, 4> Worklist(1, Condition);
7500b57cec5SDimitry Andric SmallPtrSet<Value *, 4> Visited;
7510b57cec5SDimitry Andric Value *WideableCond = nullptr;
7520b57cec5SDimitry Andric do {
7530b57cec5SDimitry Andric Value *Condition = Worklist.pop_back_val();
7540b57cec5SDimitry Andric if (!Visited.insert(Condition).second)
7550b57cec5SDimitry Andric continue;
7560b57cec5SDimitry Andric
7570b57cec5SDimitry Andric Value *LHS, *RHS;
7580b57cec5SDimitry Andric using namespace llvm::PatternMatch;
7590b57cec5SDimitry Andric if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
7600b57cec5SDimitry Andric Worklist.push_back(LHS);
7610b57cec5SDimitry Andric Worklist.push_back(RHS);
7620b57cec5SDimitry Andric continue;
7630b57cec5SDimitry Andric }
7640b57cec5SDimitry Andric
7650b57cec5SDimitry Andric if (match(Condition,
7660b57cec5SDimitry Andric m_Intrinsic<Intrinsic::experimental_widenable_condition>())) {
7670b57cec5SDimitry Andric // Pick any, we don't care which
7680b57cec5SDimitry Andric WideableCond = Condition;
7690b57cec5SDimitry Andric continue;
7700b57cec5SDimitry Andric }
7710b57cec5SDimitry Andric
7720b57cec5SDimitry Andric if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
7730b57cec5SDimitry Andric if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander,
7740b57cec5SDimitry Andric Guard)) {
7750b57cec5SDimitry Andric Checks.push_back(NewRangeCheck.getValue());
7760b57cec5SDimitry Andric NumWidened++;
7770b57cec5SDimitry Andric continue;
7780b57cec5SDimitry Andric }
7790b57cec5SDimitry Andric }
7800b57cec5SDimitry Andric
7810b57cec5SDimitry Andric // Save the condition as is if we can't widen it
7820b57cec5SDimitry Andric Checks.push_back(Condition);
7830b57cec5SDimitry Andric } while (!Worklist.empty());
7840b57cec5SDimitry Andric // At the moment, our matching logic for wideable conditions implicitly
7850b57cec5SDimitry Andric // assumes we preserve the form: (br (and Cond, WC())). FIXME
7860b57cec5SDimitry Andric // Note that if there were multiple calls to wideable condition in the
7870b57cec5SDimitry Andric // traversal, we only need to keep one, and which one is arbitrary.
7880b57cec5SDimitry Andric if (WideableCond)
7890b57cec5SDimitry Andric Checks.push_back(WideableCond);
7900b57cec5SDimitry Andric return NumWidened;
7910b57cec5SDimitry Andric }
7920b57cec5SDimitry Andric
widenGuardConditions(IntrinsicInst * Guard,SCEVExpander & Expander)7930b57cec5SDimitry Andric bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
7940b57cec5SDimitry Andric SCEVExpander &Expander) {
7950b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Processing guard:\n");
7960b57cec5SDimitry Andric LLVM_DEBUG(Guard->dump());
7970b57cec5SDimitry Andric
7980b57cec5SDimitry Andric TotalConsidered++;
7990b57cec5SDimitry Andric SmallVector<Value *, 4> Checks;
8000b57cec5SDimitry Andric unsigned NumWidened = collectChecks(Checks, Guard->getOperand(0), Expander,
8010b57cec5SDimitry Andric Guard);
8020b57cec5SDimitry Andric if (NumWidened == 0)
8030b57cec5SDimitry Andric return false;
8040b57cec5SDimitry Andric
8050b57cec5SDimitry Andric TotalWidened += NumWidened;
8060b57cec5SDimitry Andric
8070b57cec5SDimitry Andric // Emit the new guard condition
8080b57cec5SDimitry Andric IRBuilder<> Builder(findInsertPt(Guard, Checks));
8090b57cec5SDimitry Andric Value *AllChecks = Builder.CreateAnd(Checks);
8100b57cec5SDimitry Andric auto *OldCond = Guard->getOperand(0);
8110b57cec5SDimitry Andric Guard->setOperand(0, AllChecks);
8120b57cec5SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(OldCond);
8130b57cec5SDimitry Andric
8140b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
8150b57cec5SDimitry Andric return true;
8160b57cec5SDimitry Andric }
8170b57cec5SDimitry Andric
widenWidenableBranchGuardConditions(BranchInst * BI,SCEVExpander & Expander)8180b57cec5SDimitry Andric bool LoopPredication::widenWidenableBranchGuardConditions(
8190b57cec5SDimitry Andric BranchInst *BI, SCEVExpander &Expander) {
8200b57cec5SDimitry Andric assert(isGuardAsWidenableBranch(BI) && "Must be!");
8210b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Processing guard:\n");
8220b57cec5SDimitry Andric LLVM_DEBUG(BI->dump());
8230b57cec5SDimitry Andric
8240b57cec5SDimitry Andric TotalConsidered++;
8250b57cec5SDimitry Andric SmallVector<Value *, 4> Checks;
8260b57cec5SDimitry Andric unsigned NumWidened = collectChecks(Checks, BI->getCondition(),
8270b57cec5SDimitry Andric Expander, BI);
8280b57cec5SDimitry Andric if (NumWidened == 0)
8290b57cec5SDimitry Andric return false;
8300b57cec5SDimitry Andric
8310b57cec5SDimitry Andric TotalWidened += NumWidened;
8320b57cec5SDimitry Andric
8330b57cec5SDimitry Andric // Emit the new guard condition
8340b57cec5SDimitry Andric IRBuilder<> Builder(findInsertPt(BI, Checks));
8350b57cec5SDimitry Andric Value *AllChecks = Builder.CreateAnd(Checks);
8360b57cec5SDimitry Andric auto *OldCond = BI->getCondition();
8370b57cec5SDimitry Andric BI->setCondition(AllChecks);
838480093f4SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(OldCond);
8390b57cec5SDimitry Andric assert(isGuardAsWidenableBranch(BI) &&
8400b57cec5SDimitry Andric "Stopped being a guard after transform?");
8410b57cec5SDimitry Andric
8420b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
8430b57cec5SDimitry Andric return true;
8440b57cec5SDimitry Andric }
8450b57cec5SDimitry Andric
parseLoopLatchICmp()8460b57cec5SDimitry Andric Optional<LoopICmp> LoopPredication::parseLoopLatchICmp() {
8470b57cec5SDimitry Andric using namespace PatternMatch;
8480b57cec5SDimitry Andric
8490b57cec5SDimitry Andric BasicBlock *LoopLatch = L->getLoopLatch();
8500b57cec5SDimitry Andric if (!LoopLatch) {
8510b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
8520b57cec5SDimitry Andric return None;
8530b57cec5SDimitry Andric }
8540b57cec5SDimitry Andric
8550b57cec5SDimitry Andric auto *BI = dyn_cast<BranchInst>(LoopLatch->getTerminator());
8560b57cec5SDimitry Andric if (!BI || !BI->isConditional()) {
8570b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Failed to match the latch terminator!\n");
8580b57cec5SDimitry Andric return None;
8590b57cec5SDimitry Andric }
8600b57cec5SDimitry Andric BasicBlock *TrueDest = BI->getSuccessor(0);
8610b57cec5SDimitry Andric assert(
8620b57cec5SDimitry Andric (TrueDest == L->getHeader() || BI->getSuccessor(1) == L->getHeader()) &&
8630b57cec5SDimitry Andric "One of the latch's destinations must be the header");
8640b57cec5SDimitry Andric
8650b57cec5SDimitry Andric auto *ICI = dyn_cast<ICmpInst>(BI->getCondition());
8660b57cec5SDimitry Andric if (!ICI) {
8670b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Failed to match the latch condition!\n");
8680b57cec5SDimitry Andric return None;
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric auto Result = parseLoopICmp(ICI);
8710b57cec5SDimitry Andric if (!Result) {
8720b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
8730b57cec5SDimitry Andric return None;
8740b57cec5SDimitry Andric }
8750b57cec5SDimitry Andric
8760b57cec5SDimitry Andric if (TrueDest != L->getHeader())
8770b57cec5SDimitry Andric Result->Pred = ICmpInst::getInversePredicate(Result->Pred);
8780b57cec5SDimitry Andric
8790b57cec5SDimitry Andric // Check affine first, so if it's not we don't try to compute the step
8800b57cec5SDimitry Andric // recurrence.
8810b57cec5SDimitry Andric if (!Result->IV->isAffine()) {
8820b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "The induction variable is not affine!\n");
8830b57cec5SDimitry Andric return None;
8840b57cec5SDimitry Andric }
8850b57cec5SDimitry Andric
8860b57cec5SDimitry Andric auto *Step = Result->IV->getStepRecurrence(*SE);
8870b57cec5SDimitry Andric if (!isSupportedStep(Step)) {
8880b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
8890b57cec5SDimitry Andric return None;
8900b57cec5SDimitry Andric }
8910b57cec5SDimitry Andric
8920b57cec5SDimitry Andric auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
8930b57cec5SDimitry Andric if (Step->isOne()) {
8940b57cec5SDimitry Andric return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
8950b57cec5SDimitry Andric Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
8960b57cec5SDimitry Andric } else {
8970b57cec5SDimitry Andric assert(Step->isAllOnesValue() && "Step should be -1!");
8980b57cec5SDimitry Andric return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT &&
8990b57cec5SDimitry Andric Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE;
9000b57cec5SDimitry Andric }
9010b57cec5SDimitry Andric };
9020b57cec5SDimitry Andric
9030b57cec5SDimitry Andric normalizePredicate(SE, L, *Result);
9040b57cec5SDimitry Andric if (IsUnsupportedPredicate(Step, Result->Pred)) {
9050b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
9060b57cec5SDimitry Andric << ")!\n");
9070b57cec5SDimitry Andric return None;
9080b57cec5SDimitry Andric }
9090b57cec5SDimitry Andric
9100b57cec5SDimitry Andric return Result;
9110b57cec5SDimitry Andric }
9120b57cec5SDimitry Andric
9130b57cec5SDimitry Andric
isLoopProfitableToPredicate()9140b57cec5SDimitry Andric bool LoopPredication::isLoopProfitableToPredicate() {
9150b57cec5SDimitry Andric if (SkipProfitabilityChecks || !BPI)
9160b57cec5SDimitry Andric return true;
9170b57cec5SDimitry Andric
9180b57cec5SDimitry Andric SmallVector<std::pair<BasicBlock *, BasicBlock *>, 8> ExitEdges;
9190b57cec5SDimitry Andric L->getExitEdges(ExitEdges);
9200b57cec5SDimitry Andric // If there is only one exiting edge in the loop, it is always profitable to
9210b57cec5SDimitry Andric // predicate the loop.
9220b57cec5SDimitry Andric if (ExitEdges.size() == 1)
9230b57cec5SDimitry Andric return true;
9240b57cec5SDimitry Andric
9250b57cec5SDimitry Andric // Calculate the exiting probabilities of all exiting edges from the loop,
9260b57cec5SDimitry Andric // starting with the LatchExitProbability.
9270b57cec5SDimitry Andric // Heuristic for profitability: If any of the exiting blocks' probability of
9280b57cec5SDimitry Andric // exiting the loop is larger than exiting through the latch block, it's not
9290b57cec5SDimitry Andric // profitable to predicate the loop.
9300b57cec5SDimitry Andric auto *LatchBlock = L->getLoopLatch();
9310b57cec5SDimitry Andric assert(LatchBlock && "Should have a single latch at this point!");
9320b57cec5SDimitry Andric auto *LatchTerm = LatchBlock->getTerminator();
9330b57cec5SDimitry Andric assert(LatchTerm->getNumSuccessors() == 2 &&
9340b57cec5SDimitry Andric "expected to be an exiting block with 2 succs!");
9350b57cec5SDimitry Andric unsigned LatchBrExitIdx =
9360b57cec5SDimitry Andric LatchTerm->getSuccessor(0) == L->getHeader() ? 1 : 0;
9370b57cec5SDimitry Andric BranchProbability LatchExitProbability =
9380b57cec5SDimitry Andric BPI->getEdgeProbability(LatchBlock, LatchBrExitIdx);
9390b57cec5SDimitry Andric
9400b57cec5SDimitry Andric // Protect against degenerate inputs provided by the user. Providing a value
9410b57cec5SDimitry Andric // less than one, can invert the definition of profitable loop predication.
9420b57cec5SDimitry Andric float ScaleFactor = LatchExitProbabilityScale;
9430b57cec5SDimitry Andric if (ScaleFactor < 1) {
9440b57cec5SDimitry Andric LLVM_DEBUG(
9450b57cec5SDimitry Andric dbgs()
9460b57cec5SDimitry Andric << "Ignored user setting for loop-predication-latch-probability-scale: "
9470b57cec5SDimitry Andric << LatchExitProbabilityScale << "\n");
9480b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "The value is set to 1.0\n");
9490b57cec5SDimitry Andric ScaleFactor = 1.0;
9500b57cec5SDimitry Andric }
9510b57cec5SDimitry Andric const auto LatchProbabilityThreshold =
9520b57cec5SDimitry Andric LatchExitProbability * ScaleFactor;
9530b57cec5SDimitry Andric
9540b57cec5SDimitry Andric for (const auto &ExitEdge : ExitEdges) {
9550b57cec5SDimitry Andric BranchProbability ExitingBlockProbability =
9560b57cec5SDimitry Andric BPI->getEdgeProbability(ExitEdge.first, ExitEdge.second);
9570b57cec5SDimitry Andric // Some exiting edge has higher probability than the latch exiting edge.
9580b57cec5SDimitry Andric // No longer profitable to predicate.
9590b57cec5SDimitry Andric if (ExitingBlockProbability > LatchProbabilityThreshold)
9600b57cec5SDimitry Andric return false;
9610b57cec5SDimitry Andric }
9620b57cec5SDimitry Andric // Using BPI, we have concluded that the most probable way to exit from the
9630b57cec5SDimitry Andric // loop is through the latch (or there's no profile information and all
9640b57cec5SDimitry Andric // exits are equally likely).
9650b57cec5SDimitry Andric return true;
9660b57cec5SDimitry Andric }
9670b57cec5SDimitry Andric
968480093f4SDimitry Andric /// If we can (cheaply) find a widenable branch which controls entry into the
969480093f4SDimitry Andric /// loop, return it.
FindWidenableTerminatorAboveLoop(Loop * L,LoopInfo & LI)970480093f4SDimitry Andric static BranchInst *FindWidenableTerminatorAboveLoop(Loop *L, LoopInfo &LI) {
971480093f4SDimitry Andric // Walk back through any unconditional executed blocks and see if we can find
972480093f4SDimitry Andric // a widenable condition which seems to control execution of this loop. Note
973480093f4SDimitry Andric // that we predict that maythrow calls are likely untaken and thus that it's
974480093f4SDimitry Andric // profitable to widen a branch before a maythrow call with a condition
975480093f4SDimitry Andric // afterwards even though that may cause the slow path to run in a case where
976480093f4SDimitry Andric // it wouldn't have otherwise.
977480093f4SDimitry Andric BasicBlock *BB = L->getLoopPreheader();
978480093f4SDimitry Andric if (!BB)
979480093f4SDimitry Andric return nullptr;
980480093f4SDimitry Andric do {
981480093f4SDimitry Andric if (BasicBlock *Pred = BB->getSinglePredecessor())
982480093f4SDimitry Andric if (BB == Pred->getSingleSuccessor()) {
983480093f4SDimitry Andric BB = Pred;
984480093f4SDimitry Andric continue;
985480093f4SDimitry Andric }
986480093f4SDimitry Andric break;
987480093f4SDimitry Andric } while (true);
988480093f4SDimitry Andric
989480093f4SDimitry Andric if (BasicBlock *Pred = BB->getSinglePredecessor()) {
990480093f4SDimitry Andric auto *Term = Pred->getTerminator();
991480093f4SDimitry Andric
992480093f4SDimitry Andric Value *Cond, *WC;
993480093f4SDimitry Andric BasicBlock *IfTrueBB, *IfFalseBB;
994480093f4SDimitry Andric if (parseWidenableBranch(Term, Cond, WC, IfTrueBB, IfFalseBB) &&
995480093f4SDimitry Andric IfTrueBB == BB)
996480093f4SDimitry Andric return cast<BranchInst>(Term);
997480093f4SDimitry Andric }
998480093f4SDimitry Andric return nullptr;
999480093f4SDimitry Andric }
1000480093f4SDimitry Andric
1001480093f4SDimitry Andric /// Return the minimum of all analyzeable exit counts. This is an upper bound
1002480093f4SDimitry Andric /// on the actual exit count. If there are not at least two analyzeable exits,
1003480093f4SDimitry Andric /// returns SCEVCouldNotCompute.
getMinAnalyzeableBackedgeTakenCount(ScalarEvolution & SE,DominatorTree & DT,Loop * L)1004480093f4SDimitry Andric static const SCEV *getMinAnalyzeableBackedgeTakenCount(ScalarEvolution &SE,
1005480093f4SDimitry Andric DominatorTree &DT,
1006480093f4SDimitry Andric Loop *L) {
1007480093f4SDimitry Andric SmallVector<BasicBlock *, 16> ExitingBlocks;
1008480093f4SDimitry Andric L->getExitingBlocks(ExitingBlocks);
1009480093f4SDimitry Andric
1010480093f4SDimitry Andric SmallVector<const SCEV *, 4> ExitCounts;
1011480093f4SDimitry Andric for (BasicBlock *ExitingBB : ExitingBlocks) {
1012480093f4SDimitry Andric const SCEV *ExitCount = SE.getExitCount(L, ExitingBB);
1013480093f4SDimitry Andric if (isa<SCEVCouldNotCompute>(ExitCount))
1014480093f4SDimitry Andric continue;
1015480093f4SDimitry Andric assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
1016480093f4SDimitry Andric "We should only have known counts for exiting blocks that "
1017480093f4SDimitry Andric "dominate latch!");
1018480093f4SDimitry Andric ExitCounts.push_back(ExitCount);
1019480093f4SDimitry Andric }
1020480093f4SDimitry Andric if (ExitCounts.size() < 2)
1021480093f4SDimitry Andric return SE.getCouldNotCompute();
1022480093f4SDimitry Andric return SE.getUMinFromMismatchedTypes(ExitCounts);
1023480093f4SDimitry Andric }
1024480093f4SDimitry Andric
1025480093f4SDimitry Andric /// This implements an analogous, but entirely distinct transform from the main
1026480093f4SDimitry Andric /// loop predication transform. This one is phrased in terms of using a
1027480093f4SDimitry Andric /// widenable branch *outside* the loop to allow us to simplify loop exits in a
1028480093f4SDimitry Andric /// following loop. This is close in spirit to the IndVarSimplify transform
1029480093f4SDimitry Andric /// of the same name, but is materially different widening loosens legality
1030480093f4SDimitry Andric /// sharply.
predicateLoopExits(Loop * L,SCEVExpander & Rewriter)1031480093f4SDimitry Andric bool LoopPredication::predicateLoopExits(Loop *L, SCEVExpander &Rewriter) {
1032480093f4SDimitry Andric // The transformation performed here aims to widen a widenable condition
1033480093f4SDimitry Andric // above the loop such that all analyzeable exit leading to deopt are dead.
1034480093f4SDimitry Andric // It assumes that the latch is the dominant exit for profitability and that
1035480093f4SDimitry Andric // exits branching to deoptimizing blocks are rarely taken. It relies on the
1036480093f4SDimitry Andric // semantics of widenable expressions for legality. (i.e. being able to fall
1037480093f4SDimitry Andric // down the widenable path spuriously allows us to ignore exit order,
1038480093f4SDimitry Andric // unanalyzeable exits, side effects, exceptional exits, and other challenges
1039480093f4SDimitry Andric // which restrict the applicability of the non-WC based version of this
1040480093f4SDimitry Andric // transform in IndVarSimplify.)
1041480093f4SDimitry Andric //
1042480093f4SDimitry Andric // NOTE ON POISON/UNDEF - We're hoisting an expression above guards which may
1043480093f4SDimitry Andric // imply flags on the expression being hoisted and inserting new uses (flags
1044480093f4SDimitry Andric // are only correct for current uses). The result is that we may be
1045480093f4SDimitry Andric // inserting a branch on the value which can be either poison or undef. In
1046480093f4SDimitry Andric // this case, the branch can legally go either way; we just need to avoid
1047480093f4SDimitry Andric // introducing UB. This is achieved through the use of the freeze
1048480093f4SDimitry Andric // instruction.
1049480093f4SDimitry Andric
1050480093f4SDimitry Andric SmallVector<BasicBlock *, 16> ExitingBlocks;
1051480093f4SDimitry Andric L->getExitingBlocks(ExitingBlocks);
1052480093f4SDimitry Andric
1053480093f4SDimitry Andric if (ExitingBlocks.empty())
1054480093f4SDimitry Andric return false; // Nothing to do.
1055480093f4SDimitry Andric
1056480093f4SDimitry Andric auto *Latch = L->getLoopLatch();
1057480093f4SDimitry Andric if (!Latch)
1058480093f4SDimitry Andric return false;
1059480093f4SDimitry Andric
1060480093f4SDimitry Andric auto *WidenableBR = FindWidenableTerminatorAboveLoop(L, *LI);
1061480093f4SDimitry Andric if (!WidenableBR)
1062480093f4SDimitry Andric return false;
1063480093f4SDimitry Andric
1064480093f4SDimitry Andric const SCEV *LatchEC = SE->getExitCount(L, Latch);
1065480093f4SDimitry Andric if (isa<SCEVCouldNotCompute>(LatchEC))
1066480093f4SDimitry Andric return false; // profitability - want hot exit in analyzeable set
1067480093f4SDimitry Andric
1068480093f4SDimitry Andric // At this point, we have found an analyzeable latch, and a widenable
1069480093f4SDimitry Andric // condition above the loop. If we have a widenable exit within the loop
1070480093f4SDimitry Andric // (for which we can't compute exit counts), drop the ability to further
1071480093f4SDimitry Andric // widen so that we gain ability to analyze it's exit count and perform this
1072480093f4SDimitry Andric // transform. TODO: It'd be nice to know for sure the exit became
1073480093f4SDimitry Andric // analyzeable after dropping widenability.
1074480093f4SDimitry Andric {
1075480093f4SDimitry Andric bool Invalidate = false;
1076480093f4SDimitry Andric
1077480093f4SDimitry Andric for (auto *ExitingBB : ExitingBlocks) {
1078480093f4SDimitry Andric if (LI->getLoopFor(ExitingBB) != L)
1079480093f4SDimitry Andric continue;
1080480093f4SDimitry Andric
1081480093f4SDimitry Andric auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
1082480093f4SDimitry Andric if (!BI)
1083480093f4SDimitry Andric continue;
1084480093f4SDimitry Andric
1085480093f4SDimitry Andric Use *Cond, *WC;
1086480093f4SDimitry Andric BasicBlock *IfTrueBB, *IfFalseBB;
1087480093f4SDimitry Andric if (parseWidenableBranch(BI, Cond, WC, IfTrueBB, IfFalseBB) &&
1088480093f4SDimitry Andric L->contains(IfTrueBB)) {
1089480093f4SDimitry Andric WC->set(ConstantInt::getTrue(IfTrueBB->getContext()));
1090480093f4SDimitry Andric Invalidate = true;
1091480093f4SDimitry Andric }
1092480093f4SDimitry Andric }
1093480093f4SDimitry Andric if (Invalidate)
1094480093f4SDimitry Andric SE->forgetLoop(L);
1095480093f4SDimitry Andric }
1096480093f4SDimitry Andric
1097480093f4SDimitry Andric // The use of umin(all analyzeable exits) instead of latch is subtle, but
1098480093f4SDimitry Andric // important for profitability. We may have a loop which hasn't been fully
1099480093f4SDimitry Andric // canonicalized just yet. If the exit we chose to widen is provably never
1100480093f4SDimitry Andric // taken, we want the widened form to *also* be provably never taken. We
1101480093f4SDimitry Andric // can't guarantee this as a current unanalyzeable exit may later become
1102480093f4SDimitry Andric // analyzeable, but we can at least avoid the obvious cases.
1103480093f4SDimitry Andric const SCEV *MinEC = getMinAnalyzeableBackedgeTakenCount(*SE, *DT, L);
1104480093f4SDimitry Andric if (isa<SCEVCouldNotCompute>(MinEC) || MinEC->getType()->isPointerTy() ||
1105480093f4SDimitry Andric !SE->isLoopInvariant(MinEC, L) ||
1106480093f4SDimitry Andric !isSafeToExpandAt(MinEC, WidenableBR, *SE))
1107480093f4SDimitry Andric return false;
1108480093f4SDimitry Andric
1109480093f4SDimitry Andric // Subtlety: We need to avoid inserting additional uses of the WC. We know
1110480093f4SDimitry Andric // that it can only have one transitive use at the moment, and thus moving
1111480093f4SDimitry Andric // that use to just before the branch and inserting code before it and then
1112480093f4SDimitry Andric // modifying the operand is legal.
1113480093f4SDimitry Andric auto *IP = cast<Instruction>(WidenableBR->getCondition());
1114480093f4SDimitry Andric IP->moveBefore(WidenableBR);
1115480093f4SDimitry Andric Rewriter.setInsertPoint(IP);
1116480093f4SDimitry Andric IRBuilder<> B(IP);
1117480093f4SDimitry Andric
1118480093f4SDimitry Andric bool Changed = false;
1119480093f4SDimitry Andric Value *MinECV = nullptr; // lazily generated if needed
1120480093f4SDimitry Andric for (BasicBlock *ExitingBB : ExitingBlocks) {
1121480093f4SDimitry Andric // If our exiting block exits multiple loops, we can only rewrite the
1122480093f4SDimitry Andric // innermost one. Otherwise, we're changing how many times the innermost
1123480093f4SDimitry Andric // loop runs before it exits.
1124480093f4SDimitry Andric if (LI->getLoopFor(ExitingBB) != L)
1125480093f4SDimitry Andric continue;
1126480093f4SDimitry Andric
1127480093f4SDimitry Andric // Can't rewrite non-branch yet.
1128480093f4SDimitry Andric auto *BI = dyn_cast<BranchInst>(ExitingBB->getTerminator());
1129480093f4SDimitry Andric if (!BI)
1130480093f4SDimitry Andric continue;
1131480093f4SDimitry Andric
1132480093f4SDimitry Andric // If already constant, nothing to do.
1133480093f4SDimitry Andric if (isa<Constant>(BI->getCondition()))
1134480093f4SDimitry Andric continue;
1135480093f4SDimitry Andric
1136480093f4SDimitry Andric const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
1137480093f4SDimitry Andric if (isa<SCEVCouldNotCompute>(ExitCount) ||
1138480093f4SDimitry Andric ExitCount->getType()->isPointerTy() ||
1139480093f4SDimitry Andric !isSafeToExpandAt(ExitCount, WidenableBR, *SE))
1140480093f4SDimitry Andric continue;
1141480093f4SDimitry Andric
1142480093f4SDimitry Andric const bool ExitIfTrue = !L->contains(*succ_begin(ExitingBB));
1143480093f4SDimitry Andric BasicBlock *ExitBB = BI->getSuccessor(ExitIfTrue ? 0 : 1);
11445ffd83dbSDimitry Andric if (!ExitBB->getPostdominatingDeoptimizeCall())
1145480093f4SDimitry Andric continue;
1146480093f4SDimitry Andric
11475ffd83dbSDimitry Andric /// Here we can be fairly sure that executing this exit will most likely
11485ffd83dbSDimitry Andric /// lead to executing llvm.experimental.deoptimize.
11495ffd83dbSDimitry Andric /// This is a profitability heuristic, not a legality constraint.
11505ffd83dbSDimitry Andric
1151480093f4SDimitry Andric // If we found a widenable exit condition, do two things:
1152480093f4SDimitry Andric // 1) fold the widened exit test into the widenable condition
1153480093f4SDimitry Andric // 2) fold the branch to untaken - avoids infinite looping
1154480093f4SDimitry Andric
1155480093f4SDimitry Andric Value *ECV = Rewriter.expandCodeFor(ExitCount);
1156480093f4SDimitry Andric if (!MinECV)
1157480093f4SDimitry Andric MinECV = Rewriter.expandCodeFor(MinEC);
1158480093f4SDimitry Andric Value *RHS = MinECV;
1159480093f4SDimitry Andric if (ECV->getType() != RHS->getType()) {
1160480093f4SDimitry Andric Type *WiderTy = SE->getWiderType(ECV->getType(), RHS->getType());
1161480093f4SDimitry Andric ECV = B.CreateZExt(ECV, WiderTy);
1162480093f4SDimitry Andric RHS = B.CreateZExt(RHS, WiderTy);
1163480093f4SDimitry Andric }
1164480093f4SDimitry Andric assert(!Latch || DT->dominates(ExitingBB, Latch));
1165480093f4SDimitry Andric Value *NewCond = B.CreateICmp(ICmpInst::ICMP_UGT, ECV, RHS);
1166480093f4SDimitry Andric // Freeze poison or undef to an arbitrary bit pattern to ensure we can
1167480093f4SDimitry Andric // branch without introducing UB. See NOTE ON POISON/UNDEF above for
1168480093f4SDimitry Andric // context.
1169480093f4SDimitry Andric NewCond = B.CreateFreeze(NewCond);
1170480093f4SDimitry Andric
1171480093f4SDimitry Andric widenWidenableBranch(WidenableBR, NewCond);
1172480093f4SDimitry Andric
1173480093f4SDimitry Andric Value *OldCond = BI->getCondition();
1174480093f4SDimitry Andric BI->setCondition(ConstantInt::get(OldCond->getType(), !ExitIfTrue));
1175480093f4SDimitry Andric Changed = true;
1176480093f4SDimitry Andric }
1177480093f4SDimitry Andric
1178480093f4SDimitry Andric if (Changed)
1179480093f4SDimitry Andric // We just mutated a bunch of loop exits changing there exit counts
1180480093f4SDimitry Andric // widely. We need to force recomputation of the exit counts given these
1181480093f4SDimitry Andric // changes. Note that all of the inserted exits are never taken, and
1182480093f4SDimitry Andric // should be removed next time the CFG is modified.
1183480093f4SDimitry Andric SE->forgetLoop(L);
1184480093f4SDimitry Andric return Changed;
1185480093f4SDimitry Andric }
1186480093f4SDimitry Andric
runOnLoop(Loop * Loop)11870b57cec5SDimitry Andric bool LoopPredication::runOnLoop(Loop *Loop) {
11880b57cec5SDimitry Andric L = Loop;
11890b57cec5SDimitry Andric
11900b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Analyzing ");
11910b57cec5SDimitry Andric LLVM_DEBUG(L->dump());
11920b57cec5SDimitry Andric
11930b57cec5SDimitry Andric Module *M = L->getHeader()->getModule();
11940b57cec5SDimitry Andric
11950b57cec5SDimitry Andric // There is nothing to do if the module doesn't use guards
11960b57cec5SDimitry Andric auto *GuardDecl =
11970b57cec5SDimitry Andric M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
11980b57cec5SDimitry Andric bool HasIntrinsicGuards = GuardDecl && !GuardDecl->use_empty();
11990b57cec5SDimitry Andric auto *WCDecl = M->getFunction(
12000b57cec5SDimitry Andric Intrinsic::getName(Intrinsic::experimental_widenable_condition));
12010b57cec5SDimitry Andric bool HasWidenableConditions =
12020b57cec5SDimitry Andric PredicateWidenableBranchGuards && WCDecl && !WCDecl->use_empty();
12030b57cec5SDimitry Andric if (!HasIntrinsicGuards && !HasWidenableConditions)
12040b57cec5SDimitry Andric return false;
12050b57cec5SDimitry Andric
12060b57cec5SDimitry Andric DL = &M->getDataLayout();
12070b57cec5SDimitry Andric
12080b57cec5SDimitry Andric Preheader = L->getLoopPreheader();
12090b57cec5SDimitry Andric if (!Preheader)
12100b57cec5SDimitry Andric return false;
12110b57cec5SDimitry Andric
12120b57cec5SDimitry Andric auto LatchCheckOpt = parseLoopLatchICmp();
12130b57cec5SDimitry Andric if (!LatchCheckOpt)
12140b57cec5SDimitry Andric return false;
12150b57cec5SDimitry Andric LatchCheck = *LatchCheckOpt;
12160b57cec5SDimitry Andric
12170b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Latch check:\n");
12180b57cec5SDimitry Andric LLVM_DEBUG(LatchCheck.dump());
12190b57cec5SDimitry Andric
12200b57cec5SDimitry Andric if (!isLoopProfitableToPredicate()) {
12210b57cec5SDimitry Andric LLVM_DEBUG(dbgs() << "Loop not profitable to predicate!\n");
12220b57cec5SDimitry Andric return false;
12230b57cec5SDimitry Andric }
12240b57cec5SDimitry Andric // Collect all the guards into a vector and process later, so as not
12250b57cec5SDimitry Andric // to invalidate the instruction iterator.
12260b57cec5SDimitry Andric SmallVector<IntrinsicInst *, 4> Guards;
12270b57cec5SDimitry Andric SmallVector<BranchInst *, 4> GuardsAsWidenableBranches;
12280b57cec5SDimitry Andric for (const auto BB : L->blocks()) {
12290b57cec5SDimitry Andric for (auto &I : *BB)
12300b57cec5SDimitry Andric if (isGuard(&I))
12310b57cec5SDimitry Andric Guards.push_back(cast<IntrinsicInst>(&I));
12320b57cec5SDimitry Andric if (PredicateWidenableBranchGuards &&
12330b57cec5SDimitry Andric isGuardAsWidenableBranch(BB->getTerminator()))
12340b57cec5SDimitry Andric GuardsAsWidenableBranches.push_back(
12350b57cec5SDimitry Andric cast<BranchInst>(BB->getTerminator()));
12360b57cec5SDimitry Andric }
12370b57cec5SDimitry Andric
12380b57cec5SDimitry Andric SCEVExpander Expander(*SE, *DL, "loop-predication");
12390b57cec5SDimitry Andric bool Changed = false;
12400b57cec5SDimitry Andric for (auto *Guard : Guards)
12410b57cec5SDimitry Andric Changed |= widenGuardConditions(Guard, Expander);
12420b57cec5SDimitry Andric for (auto *Guard : GuardsAsWidenableBranches)
12430b57cec5SDimitry Andric Changed |= widenWidenableBranchGuardConditions(Guard, Expander);
1244480093f4SDimitry Andric Changed |= predicateLoopExits(L, Expander);
12450b57cec5SDimitry Andric return Changed;
12460b57cec5SDimitry Andric }
1247