2017-01-26 00:00:44 +08:00
|
|
|
//===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
|
|
|
|
//
|
|
|
|
// The LLVM Compiler Infrastructure
|
|
|
|
//
|
|
|
|
// This file is distributed under the University of Illinois Open Source
|
|
|
|
// License. See LICENSE.TXT for details.
|
|
|
|
//
|
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
//
|
|
|
|
// The LoopPredication pass tries to convert loop variant range checks to loop
|
|
|
|
// invariant by widening checks across loop iterations. For example, it will
|
|
|
|
// convert
|
|
|
|
//
|
|
|
|
// for (i = 0; i < n; i++) {
|
|
|
|
// guard(i < len);
|
|
|
|
// ...
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// to
|
|
|
|
//
|
|
|
|
// for (i = 0; i < n; i++) {
|
|
|
|
// guard(n - 1 < len);
|
|
|
|
// ...
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// After this transformation the condition of the guard is loop invariant, so
|
|
|
|
// loop-unswitch can later unswitch the loop by this condition which basically
|
|
|
|
// predicates the loop by the widened condition:
|
|
|
|
//
|
|
|
|
// if (n - 1 < len)
|
|
|
|
// for (i = 0; i < n; i++) {
|
|
|
|
// ...
|
|
|
|
// }
|
|
|
|
// else
|
|
|
|
// deoptimize
|
|
|
|
//
|
2017-09-22 21:13:57 +08:00
|
|
|
// It's tempting to rely on SCEV here, but it has proven to be problematic.
|
|
|
|
// Generally the facts SCEV provides about the increment step of add
|
|
|
|
// recurrences are true if the backedge of the loop is taken, which implicitly
|
|
|
|
// assumes that the guard doesn't fail. Using these facts to optimize the
|
|
|
|
// guard results in a circular logic where the guard is optimized under the
|
|
|
|
// assumption that it never fails.
|
|
|
|
//
|
|
|
|
// For example, in the loop below the induction variable will be marked as nuw
|
|
|
|
// basing on the guard. Basing on nuw the guard predicate will be considered
|
|
|
|
// monotonic. Given a monotonic condition it's tempting to replace the induction
|
|
|
|
// variable in the condition with its value on the last iteration. But this
|
|
|
|
// transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
|
|
|
|
//
|
|
|
|
// for (int i = b; i != e; i++)
|
|
|
|
// guard(i u< len)
|
|
|
|
//
|
|
|
|
// One of the ways to reason about this problem is to use an inductive proof
|
|
|
|
// approach. Given the loop:
|
|
|
|
//
|
2017-10-27 22:46:17 +08:00
|
|
|
// if (B(0)) {
|
2017-09-22 21:13:57 +08:00
|
|
|
// do {
|
2017-10-27 22:46:17 +08:00
|
|
|
// I = PHI(0, I.INC)
|
2017-09-22 21:13:57 +08:00
|
|
|
// I.INC = I + Step
|
|
|
|
// guard(G(I));
|
2017-10-27 22:46:17 +08:00
|
|
|
// } while (B(I));
|
2017-09-22 21:13:57 +08:00
|
|
|
// }
|
|
|
|
//
|
|
|
|
// where B(x) and G(x) are predicates that map integers to booleans, we want a
|
|
|
|
// loop invariant expression M such the following program has the same semantics
|
|
|
|
// as the above:
|
|
|
|
//
|
2017-10-27 22:46:17 +08:00
|
|
|
// if (B(0)) {
|
2017-09-22 21:13:57 +08:00
|
|
|
// do {
|
2017-10-27 22:46:17 +08:00
|
|
|
// I = PHI(0, I.INC)
|
2017-09-22 21:13:57 +08:00
|
|
|
// I.INC = I + Step
|
2017-10-27 22:46:17 +08:00
|
|
|
// guard(G(0) && M);
|
|
|
|
// } while (B(I));
|
2017-09-22 21:13:57 +08:00
|
|
|
// }
|
|
|
|
//
|
2017-10-27 22:46:17 +08:00
|
|
|
// One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
|
2017-09-22 21:13:57 +08:00
|
|
|
//
|
|
|
|
// Informal proof that the transformation above is correct:
|
|
|
|
//
|
|
|
|
// By the definition of guards we can rewrite the guard condition to:
|
2017-10-27 22:46:17 +08:00
|
|
|
// G(I) && G(0) && M
|
2017-09-22 21:13:57 +08:00
|
|
|
//
|
|
|
|
// Let's prove that for each iteration of the loop:
|
2017-10-27 22:46:17 +08:00
|
|
|
// G(0) && M => G(I)
|
2017-09-22 21:13:57 +08:00
|
|
|
// And the condition above can be simplified to G(Start) && M.
|
|
|
|
//
|
|
|
|
// Induction base.
|
2017-10-27 22:46:17 +08:00
|
|
|
// G(0) && M => G(0)
|
2017-09-22 21:13:57 +08:00
|
|
|
//
|
2017-10-27 22:46:17 +08:00
|
|
|
// Induction step. Assuming G(0) && M => G(I) on the subsequent
|
2017-09-22 21:13:57 +08:00
|
|
|
// iteration:
|
|
|
|
//
|
2017-10-27 22:46:17 +08:00
|
|
|
// B(I) is true because it's the backedge condition.
|
2017-09-22 21:13:57 +08:00
|
|
|
// G(I) is true because the backedge is guarded by this condition.
|
|
|
|
//
|
2017-10-27 22:46:17 +08:00
|
|
|
// So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
|
2017-09-22 21:13:57 +08:00
|
|
|
//
|
|
|
|
// Note that we can use anything stronger than M, i.e. any condition which
|
|
|
|
// implies M.
|
|
|
|
//
|
|
|
|
// For now the transformation is limited to the following case:
|
2017-10-13 04:40:27 +08:00
|
|
|
// * The loop has a single latch with the condition of the form:
|
2017-10-27 22:46:17 +08:00
|
|
|
// B(X) = latchStart + X <pred> latchLimit,
|
|
|
|
// where <pred> is u<, u<=, s<, or s<=.
|
2017-09-22 21:13:57 +08:00
|
|
|
// * The step of the IV used in the latch condition is 1.
|
2017-10-27 22:46:17 +08:00
|
|
|
// * The guard condition is of the form
|
|
|
|
// G(X) = guardStart + X u< guardLimit
|
2017-09-22 21:13:57 +08:00
|
|
|
//
|
2017-10-13 04:40:27 +08:00
|
|
|
// For the ult latch comparison case M is:
|
2017-10-27 22:46:17 +08:00
|
|
|
// forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
|
|
|
|
// guardStart + X + 1 u< guardLimit
|
2017-09-22 21:13:57 +08:00
|
|
|
//
|
2017-10-27 22:46:17 +08:00
|
|
|
// The only way the antecedent can be true and the consequent can be false is
|
2017-09-22 21:13:57 +08:00
|
|
|
// if
|
2017-10-27 22:46:17 +08:00
|
|
|
// X == guardLimit - 1 - guardStart
|
2017-09-22 21:13:57 +08:00
|
|
|
// (and guardLimit is non-zero, but we won't use this latter fact).
|
2017-10-27 22:46:17 +08:00
|
|
|
// If X == guardLimit - 1 - guardStart then the second half of the antecedent is
|
|
|
|
// latchStart + guardLimit - 1 - guardStart u< latchLimit
|
2017-09-22 21:13:57 +08:00
|
|
|
// and its negation is
|
2017-10-27 22:46:17 +08:00
|
|
|
// latchStart + guardLimit - 1 - guardStart u>= latchLimit
|
2017-09-22 21:13:57 +08:00
|
|
|
//
|
2017-10-27 22:46:17 +08:00
|
|
|
// In other words, if
|
|
|
|
// latchLimit u<= latchStart + guardLimit - 1 - guardStart
|
|
|
|
// then:
|
2017-09-22 21:13:57 +08:00
|
|
|
// (the ranges below are written in ConstantRange notation, where [A, B) is the
|
|
|
|
// set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
|
|
|
|
//
|
2017-10-27 22:46:17 +08:00
|
|
|
// forall X . guardStart + X u< guardLimit &&
|
|
|
|
// latchStart + X u< latchLimit =>
|
|
|
|
// guardStart + X + 1 u< guardLimit
|
|
|
|
// == forall X . guardStart + X u< guardLimit &&
|
|
|
|
// latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
|
|
|
|
// guardStart + X + 1 u< guardLimit
|
|
|
|
// == forall X . (guardStart + X) in [0, guardLimit) &&
|
|
|
|
// (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
|
|
|
|
// (guardStart + X + 1) in [0, guardLimit)
|
|
|
|
// == forall X . X in [-guardStart, guardLimit - guardStart) &&
|
|
|
|
// X in [-latchStart, guardLimit - 1 - guardStart) =>
|
|
|
|
// X in [-guardStart - 1, guardLimit - guardStart - 1)
|
2017-09-22 21:13:57 +08:00
|
|
|
// == true
|
|
|
|
//
|
|
|
|
// So the widened condition is:
|
2017-10-27 22:46:17 +08:00
|
|
|
// guardStart u< guardLimit &&
|
|
|
|
// latchStart + guardLimit - 1 - guardStart u>= latchLimit
|
|
|
|
// Similarly for ule condition the widened condition is:
|
|
|
|
// guardStart u< guardLimit &&
|
|
|
|
// latchStart + guardLimit - 1 - guardStart u> latchLimit
|
|
|
|
// For slt condition the widened condition is:
|
|
|
|
// guardStart u< guardLimit &&
|
|
|
|
// latchStart + guardLimit - 1 - guardStart s>= latchLimit
|
|
|
|
// For sle condition the widened condition is:
|
|
|
|
// guardStart u< guardLimit &&
|
|
|
|
// latchStart + guardLimit - 1 - guardStart s> latchLimit
|
2017-09-22 21:13:57 +08:00
|
|
|
//
|
2017-01-26 00:00:44 +08:00
|
|
|
//===----------------------------------------------------------------------===//
|
|
|
|
|
|
|
|
#include "llvm/Transforms/Scalar/LoopPredication.h"
|
|
|
|
#include "llvm/Analysis/LoopInfo.h"
|
|
|
|
#include "llvm/Analysis/LoopPass.h"
|
|
|
|
#include "llvm/Analysis/ScalarEvolution.h"
|
|
|
|
#include "llvm/Analysis/ScalarEvolutionExpander.h"
|
|
|
|
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
|
|
|
|
#include "llvm/IR/Function.h"
|
|
|
|
#include "llvm/IR/GlobalValue.h"
|
|
|
|
#include "llvm/IR/IntrinsicInst.h"
|
|
|
|
#include "llvm/IR/Module.h"
|
|
|
|
#include "llvm/IR/PatternMatch.h"
|
2017-06-06 19:49:48 +08:00
|
|
|
#include "llvm/Pass.h"
|
2017-01-26 00:00:44 +08:00
|
|
|
#include "llvm/Support/Debug.h"
|
|
|
|
#include "llvm/Transforms/Scalar.h"
|
|
|
|
#include "llvm/Transforms/Utils/LoopUtils.h"
|
|
|
|
|
|
|
|
#define DEBUG_TYPE "loop-predication"
|
|
|
|
|
|
|
|
using namespace llvm;
|
|
|
|
|
2017-11-03 05:21:02 +08:00
|
|
|
static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
|
|
|
|
cl::Hidden, cl::init(true));
|
|
|
|
|
2017-01-26 00:00:44 +08:00
|
|
|
namespace {
|
|
|
|
class LoopPredication {
|
2017-05-19 22:02:46 +08:00
|
|
|
/// Represents an induction variable check:
|
|
|
|
/// icmp Pred, <induction variable>, <loop invariant limit>
|
|
|
|
struct LoopICmp {
|
|
|
|
ICmpInst::Predicate Pred;
|
|
|
|
const SCEVAddRecExpr *IV;
|
|
|
|
const SCEV *Limit;
|
2017-05-22 20:01:32 +08:00
|
|
|
LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
|
|
|
|
const SCEV *Limit)
|
2017-05-19 22:02:46 +08:00
|
|
|
: Pred(Pred), IV(IV), Limit(Limit) {}
|
|
|
|
LoopICmp() {}
|
|
|
|
};
|
2017-05-22 20:01:32 +08:00
|
|
|
|
|
|
|
ScalarEvolution *SE;
|
|
|
|
|
|
|
|
Loop *L;
|
|
|
|
const DataLayout *DL;
|
|
|
|
BasicBlock *Preheader;
|
2017-09-22 21:13:57 +08:00
|
|
|
LoopICmp LatchCheck;
|
2017-05-22 20:01:32 +08:00
|
|
|
|
2017-09-22 21:13:57 +08:00
|
|
|
Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) {
|
|
|
|
return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0),
|
|
|
|
ICI->getOperand(1));
|
|
|
|
}
|
|
|
|
Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
|
|
|
|
Value *RHS);
|
|
|
|
|
|
|
|
Optional<LoopICmp> parseLoopLatchICmp();
|
2017-05-19 22:02:46 +08:00
|
|
|
|
2017-05-19 22:00:58 +08:00
|
|
|
Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder,
|
|
|
|
ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
|
|
|
|
Instruction *InsertAt);
|
|
|
|
|
2017-01-26 00:00:44 +08:00
|
|
|
Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
|
|
|
|
IRBuilder<> &Builder);
|
|
|
|
bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
|
|
|
|
|
2017-11-03 05:21:02 +08:00
|
|
|
// When the IV type is wider than the range operand type, we can still do loop
|
|
|
|
// predication, by generating SCEVs for the range and latch that are of the
|
|
|
|
// same type. We achieve this by generating a SCEV truncate expression for the
|
|
|
|
// latch IV. This is done iff truncation of the IV is a safe operation,
|
|
|
|
// without loss of information.
|
|
|
|
// Another way to achieve this is by generating a wider type SCEV for the
|
|
|
|
// range check operand, however, this needs a more involved check that
|
|
|
|
// operands do not overflow. This can lead to loss of information when the
|
|
|
|
// range operand is of the form: add i32 %offset, %iv. We need to prove that
|
|
|
|
// sext(x + y) is same as sext(x) + sext(y).
|
|
|
|
// This function returns true if we can safely represent the IV type in
|
|
|
|
// the RangeCheckType without loss of information.
|
|
|
|
bool isSafeToTruncateWideIVType(Type *RangeCheckType);
|
|
|
|
// Return the loopLatchCheck corresponding to the RangeCheckType if safe to do
|
|
|
|
// so.
|
|
|
|
Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType);
|
2017-01-26 00:00:44 +08:00
|
|
|
public:
|
|
|
|
LoopPredication(ScalarEvolution *SE) : SE(SE){};
|
|
|
|
bool runOnLoop(Loop *L);
|
|
|
|
};
|
|
|
|
|
|
|
|
class LoopPredicationLegacyPass : public LoopPass {
|
|
|
|
public:
|
|
|
|
static char ID;
|
|
|
|
LoopPredicationLegacyPass() : LoopPass(ID) {
|
|
|
|
initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
|
|
|
|
}
|
|
|
|
|
|
|
|
void getAnalysisUsage(AnalysisUsage &AU) const override {
|
|
|
|
getLoopAnalysisUsage(AU);
|
|
|
|
}
|
|
|
|
|
|
|
|
bool runOnLoop(Loop *L, LPPassManager &LPM) override {
|
|
|
|
if (skipLoop(L))
|
|
|
|
return false;
|
|
|
|
auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
|
|
|
|
LoopPredication LP(SE);
|
|
|
|
return LP.runOnLoop(L);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
char LoopPredicationLegacyPass::ID = 0;
|
|
|
|
} // end namespace llvm
|
|
|
|
|
|
|
|
INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
|
|
|
|
"Loop predication", false, false)
|
|
|
|
INITIALIZE_PASS_DEPENDENCY(LoopPass)
|
|
|
|
INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
|
|
|
|
"Loop predication", false, false)
|
|
|
|
|
|
|
|
Pass *llvm::createLoopPredicationPass() {
|
|
|
|
return new LoopPredicationLegacyPass();
|
|
|
|
}
|
|
|
|
|
|
|
|
PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
|
|
|
|
LoopStandardAnalysisResults &AR,
|
|
|
|
LPMUpdater &U) {
|
|
|
|
LoopPredication LP(&AR.SE);
|
|
|
|
if (!LP.runOnLoop(&L))
|
|
|
|
return PreservedAnalyses::all();
|
|
|
|
|
|
|
|
return getLoopPassPreservedAnalyses();
|
|
|
|
}
|
|
|
|
|
2017-05-19 22:02:46 +08:00
|
|
|
Optional<LoopPredication::LoopICmp>
|
2017-09-22 21:13:57 +08:00
|
|
|
LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
|
|
|
|
Value *RHS) {
|
2017-05-19 22:02:46 +08:00
|
|
|
const SCEV *LHSS = SE->getSCEV(LHS);
|
|
|
|
if (isa<SCEVCouldNotCompute>(LHSS))
|
|
|
|
return None;
|
|
|
|
const SCEV *RHSS = SE->getSCEV(RHS);
|
|
|
|
if (isa<SCEVCouldNotCompute>(RHSS))
|
|
|
|
return None;
|
|
|
|
|
|
|
|
// Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
|
|
|
|
if (SE->isLoopInvariant(LHSS, L)) {
|
|
|
|
std::swap(LHS, RHS);
|
|
|
|
std::swap(LHSS, RHSS);
|
|
|
|
Pred = ICmpInst::getSwappedPredicate(Pred);
|
|
|
|
}
|
|
|
|
|
|
|
|
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
|
|
|
|
if (!AR || AR->getLoop() != L)
|
|
|
|
return None;
|
|
|
|
|
|
|
|
return LoopICmp(Pred, AR, RHSS);
|
|
|
|
}
|
|
|
|
|
2017-05-19 22:00:58 +08:00
|
|
|
Value *LoopPredication::expandCheck(SCEVExpander &Expander,
|
|
|
|
IRBuilder<> &Builder,
|
|
|
|
ICmpInst::Predicate Pred, const SCEV *LHS,
|
|
|
|
const SCEV *RHS, Instruction *InsertAt) {
|
2017-09-22 21:13:57 +08:00
|
|
|
// TODO: we can check isLoopEntryGuardedByCond before emitting the check
|
|
|
|
|
2017-05-19 22:00:58 +08:00
|
|
|
Type *Ty = LHS->getType();
|
|
|
|
assert(Ty == RHS->getType() && "expandCheck operands have different types?");
|
2017-10-13 05:21:17 +08:00
|
|
|
|
|
|
|
if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
|
|
|
|
return Builder.getTrue();
|
|
|
|
|
2017-05-19 22:00:58 +08:00
|
|
|
Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt);
|
|
|
|
Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt);
|
|
|
|
return Builder.CreateICmp(Pred, LHSV, RHSV);
|
|
|
|
}
|
|
|
|
|
2017-11-03 05:21:02 +08:00
|
|
|
Optional<LoopPredication::LoopICmp>
|
|
|
|
LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) {
|
|
|
|
|
|
|
|
auto *LatchType = LatchCheck.IV->getType();
|
|
|
|
if (RangeCheckType == LatchType)
|
|
|
|
return LatchCheck;
|
|
|
|
// For now, bail out if latch type is narrower than range type.
|
|
|
|
if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType))
|
|
|
|
return None;
|
|
|
|
if (!isSafeToTruncateWideIVType(RangeCheckType))
|
|
|
|
return None;
|
|
|
|
// We can now safely identify the truncated version of the IV and limit for
|
|
|
|
// RangeCheckType.
|
|
|
|
LoopICmp NewLatchCheck;
|
|
|
|
NewLatchCheck.Pred = LatchCheck.Pred;
|
|
|
|
NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
|
|
|
|
SE->getTruncateExpr(LatchCheck.IV, RangeCheckType));
|
|
|
|
if (!NewLatchCheck.IV)
|
|
|
|
return None;
|
|
|
|
NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType);
|
|
|
|
DEBUG(dbgs() << "IV of type: " << *LatchType
|
|
|
|
<< "can be represented as range check type:" << *RangeCheckType
|
|
|
|
<< "\n");
|
|
|
|
DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
|
|
|
|
DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
|
|
|
|
return NewLatchCheck;
|
|
|
|
}
|
|
|
|
|
2017-01-26 00:00:44 +08:00
|
|
|
/// If ICI can be widened to a loop invariant condition emits the loop
|
|
|
|
/// invariant condition in the loop preheader and return it, otherwise
|
|
|
|
/// returns None.
|
|
|
|
Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
|
|
|
|
SCEVExpander &Expander,
|
|
|
|
IRBuilder<> &Builder) {
|
|
|
|
DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
|
|
|
|
DEBUG(ICI->dump());
|
|
|
|
|
2017-09-22 21:13:57 +08:00
|
|
|
// parseLoopStructure guarantees that the latch condition is:
|
2017-10-13 04:40:27 +08:00
|
|
|
// ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
|
2017-09-22 21:13:57 +08:00
|
|
|
// We are looking for the range checks of the form:
|
|
|
|
// i u< guardLimit
|
2017-05-19 22:02:46 +08:00
|
|
|
auto RangeCheck = parseLoopICmp(ICI);
|
2017-05-22 20:06:57 +08:00
|
|
|
if (!RangeCheck) {
|
|
|
|
DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
|
2017-01-26 00:00:44 +08:00
|
|
|
return None;
|
2017-05-22 20:06:57 +08:00
|
|
|
}
|
2017-09-22 21:13:57 +08:00
|
|
|
if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
|
|
|
|
DEBUG(dbgs() << "Unsupported range check predicate(" << RangeCheck->Pred
|
|
|
|
<< ")!\n");
|
2017-01-26 00:00:44 +08:00
|
|
|
return None;
|
2017-09-22 21:13:57 +08:00
|
|
|
}
|
|
|
|
auto *RangeCheckIV = RangeCheck->IV;
|
2017-10-27 22:46:17 +08:00
|
|
|
if (!RangeCheckIV->isAffine()) {
|
|
|
|
DEBUG(dbgs() << "Range check IV is not affine!\n");
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
auto *Step = RangeCheckIV->getStepRecurrence(*SE);
|
2017-11-03 05:21:02 +08:00
|
|
|
// We cannot just compare with latch IV step because the latch and range IVs
|
|
|
|
// may have different types.
|
|
|
|
if (!Step->isOne()) {
|
2017-10-27 22:46:17 +08:00
|
|
|
DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
|
2017-01-26 00:00:44 +08:00
|
|
|
return None;
|
|
|
|
}
|
2017-11-03 05:21:02 +08:00
|
|
|
auto *Ty = RangeCheckIV->getType();
|
|
|
|
auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty);
|
|
|
|
if (!CurrLatchCheckOpt) {
|
|
|
|
DEBUG(dbgs() << "Failed to generate a loop latch check "
|
|
|
|
"corresponding to range type: "
|
|
|
|
<< *Ty << "\n");
|
|
|
|
return None;
|
|
|
|
}
|
2017-01-26 00:00:44 +08:00
|
|
|
|
2017-11-03 05:21:02 +08:00
|
|
|
LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
|
|
|
|
// At this point the range check step and latch step should have the same
|
|
|
|
// value and type.
|
|
|
|
assert(Step == CurrLatchCheck.IV->getStepRecurrence(*SE) &&
|
|
|
|
"Range and latch should have same step recurrence!");
|
2017-10-13 04:40:27 +08:00
|
|
|
// Generate the widened condition:
|
2017-10-27 22:46:17 +08:00
|
|
|
// guardStart u< guardLimit &&
|
|
|
|
// latchLimit <pred> guardLimit - 1 - guardStart + latchStart
|
2017-10-13 04:40:27 +08:00
|
|
|
// where <pred> depends on the latch condition predicate. See the file
|
|
|
|
// header comment for the reasoning.
|
2017-10-27 22:46:17 +08:00
|
|
|
const SCEV *GuardStart = RangeCheckIV->getStart();
|
|
|
|
const SCEV *GuardLimit = RangeCheck->Limit;
|
2017-11-03 05:21:02 +08:00
|
|
|
const SCEV *LatchStart = CurrLatchCheck.IV->getStart();
|
|
|
|
const SCEV *LatchLimit = CurrLatchCheck.Limit;
|
2017-10-27 22:46:17 +08:00
|
|
|
|
|
|
|
// guardLimit - guardStart + latchStart - 1
|
|
|
|
const SCEV *RHS =
|
|
|
|
SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
|
|
|
|
SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
|
|
|
|
|
2017-10-13 04:40:27 +08:00
|
|
|
ICmpInst::Predicate LimitCheckPred;
|
2017-11-03 05:21:02 +08:00
|
|
|
switch (CurrLatchCheck.Pred) {
|
2017-10-13 04:40:27 +08:00
|
|
|
case ICmpInst::ICMP_ULT:
|
|
|
|
LimitCheckPred = ICmpInst::ICMP_ULE;
|
|
|
|
break;
|
|
|
|
case ICmpInst::ICMP_ULE:
|
|
|
|
LimitCheckPred = ICmpInst::ICMP_ULT;
|
|
|
|
break;
|
|
|
|
case ICmpInst::ICMP_SLT:
|
|
|
|
LimitCheckPred = ICmpInst::ICMP_SLE;
|
|
|
|
break;
|
|
|
|
case ICmpInst::ICMP_SLE:
|
|
|
|
LimitCheckPred = ICmpInst::ICMP_SLT;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
llvm_unreachable("Unsupported loop latch!");
|
|
|
|
}
|
2017-01-26 00:00:44 +08:00
|
|
|
|
2017-10-27 22:46:17 +08:00
|
|
|
DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
|
|
|
|
DEBUG(dbgs() << "RHS: " << *RHS << "\n");
|
|
|
|
DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
|
|
|
|
|
2017-09-22 21:13:57 +08:00
|
|
|
auto CanExpand = [this](const SCEV *S) {
|
|
|
|
return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
|
|
|
|
};
|
2017-10-27 22:46:17 +08:00
|
|
|
if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
|
|
|
|
!CanExpand(LatchLimit) || !CanExpand(RHS)) {
|
|
|
|
DEBUG(dbgs() << "Can't expand limit check!\n");
|
2017-09-22 21:13:57 +08:00
|
|
|
return None;
|
2017-10-27 22:46:17 +08:00
|
|
|
}
|
2017-01-26 00:00:44 +08:00
|
|
|
|
2017-02-27 23:44:49 +08:00
|
|
|
Instruction *InsertAt = Preheader->getTerminator();
|
2017-10-27 22:46:17 +08:00
|
|
|
auto *LimitCheck =
|
|
|
|
expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS, InsertAt);
|
2017-10-13 05:21:17 +08:00
|
|
|
auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck->Pred,
|
2017-10-27 22:46:17 +08:00
|
|
|
GuardStart, GuardLimit, InsertAt);
|
2017-09-22 21:13:57 +08:00
|
|
|
return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
|
2017-01-26 00:00:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
|
|
|
|
SCEVExpander &Expander) {
|
|
|
|
DEBUG(dbgs() << "Processing guard:\n");
|
|
|
|
DEBUG(Guard->dump());
|
|
|
|
|
|
|
|
IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
|
|
|
|
|
|
|
|
// The guard condition is expected to be in form of:
|
|
|
|
// cond1 && cond2 && cond3 ...
|
|
|
|
// Iterate over subconditions looking for for icmp conditions which can be
|
|
|
|
// widened across loop iterations. Widening these conditions remember the
|
|
|
|
// resulting list of subconditions in Checks vector.
|
|
|
|
SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0));
|
|
|
|
SmallPtrSet<Value *, 4> Visited;
|
|
|
|
|
|
|
|
SmallVector<Value *, 4> Checks;
|
|
|
|
|
|
|
|
unsigned NumWidened = 0;
|
|
|
|
do {
|
|
|
|
Value *Condition = Worklist.pop_back_val();
|
|
|
|
if (!Visited.insert(Condition).second)
|
|
|
|
continue;
|
|
|
|
|
|
|
|
Value *LHS, *RHS;
|
|
|
|
using namespace llvm::PatternMatch;
|
|
|
|
if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
|
|
|
|
Worklist.push_back(LHS);
|
|
|
|
Worklist.push_back(RHS);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
|
|
|
|
if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
|
|
|
|
Checks.push_back(NewRangeCheck.getValue());
|
|
|
|
NumWidened++;
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Save the condition as is if we can't widen it
|
|
|
|
Checks.push_back(Condition);
|
|
|
|
} while (Worklist.size() != 0);
|
|
|
|
|
|
|
|
if (NumWidened == 0)
|
|
|
|
return false;
|
|
|
|
|
|
|
|
// Emit the new guard condition
|
|
|
|
Builder.SetInsertPoint(Guard);
|
|
|
|
Value *LastCheck = nullptr;
|
|
|
|
for (auto *Check : Checks)
|
|
|
|
if (!LastCheck)
|
|
|
|
LastCheck = Check;
|
|
|
|
else
|
|
|
|
LastCheck = Builder.CreateAnd(LastCheck, Check);
|
|
|
|
Guard->setOperand(0, LastCheck);
|
|
|
|
|
|
|
|
DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
2017-09-22 21:13:57 +08:00
|
|
|
Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() {
|
|
|
|
using namespace PatternMatch;
|
|
|
|
|
|
|
|
BasicBlock *LoopLatch = L->getLoopLatch();
|
|
|
|
if (!LoopLatch) {
|
|
|
|
DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
ICmpInst::Predicate Pred;
|
|
|
|
Value *LHS, *RHS;
|
|
|
|
BasicBlock *TrueDest, *FalseDest;
|
|
|
|
|
|
|
|
if (!match(LoopLatch->getTerminator(),
|
|
|
|
m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest,
|
|
|
|
FalseDest))) {
|
|
|
|
DEBUG(dbgs() << "Failed to match the latch terminator!\n");
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) &&
|
|
|
|
"One of the latch's destinations must be the header");
|
|
|
|
if (TrueDest != L->getHeader())
|
|
|
|
Pred = ICmpInst::getInversePredicate(Pred);
|
|
|
|
|
|
|
|
auto Result = parseLoopICmp(Pred, LHS, RHS);
|
|
|
|
if (!Result) {
|
|
|
|
DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (Result->Pred != ICmpInst::ICMP_ULT &&
|
2017-10-13 04:40:27 +08:00
|
|
|
Result->Pred != ICmpInst::ICMP_SLT &&
|
|
|
|
Result->Pred != ICmpInst::ICMP_ULE &&
|
|
|
|
Result->Pred != ICmpInst::ICMP_SLE) {
|
2017-09-22 21:13:57 +08:00
|
|
|
DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
|
|
|
|
<< ")!\n");
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check affine first, so if it's not we don't try to compute the step
|
|
|
|
// recurrence.
|
|
|
|
if (!Result->IV->isAffine()) {
|
|
|
|
DEBUG(dbgs() << "The induction variable is not affine!\n");
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
auto *Step = Result->IV->getStepRecurrence(*SE);
|
|
|
|
if (!Step->isOne()) {
|
|
|
|
DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
return Result;
|
|
|
|
}
|
|
|
|
|
2017-11-03 05:21:02 +08:00
|
|
|
// Returns true if its safe to truncate the IV to RangeCheckType.
|
|
|
|
bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) {
|
|
|
|
if (!EnableIVTruncation)
|
|
|
|
return false;
|
|
|
|
assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) >
|
|
|
|
DL->getTypeSizeInBits(RangeCheckType) &&
|
|
|
|
"Expected latch check IV type to be larger than range check operand "
|
|
|
|
"type!");
|
|
|
|
// The start and end values of the IV should be known. This is to guarantee
|
|
|
|
// that truncating the wide type will not lose information.
|
|
|
|
auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
|
|
|
|
auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
|
|
|
|
if (!Limit || !Start)
|
|
|
|
return false;
|
|
|
|
// This check makes sure that the IV does not change sign during loop
|
|
|
|
// iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
|
|
|
|
// LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
|
|
|
|
// IV wraps around, and the truncation of the IV would lose the range of
|
|
|
|
// iterations between 2^32 and 2^64.
|
|
|
|
bool Increasing;
|
|
|
|
if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing))
|
|
|
|
return false;
|
|
|
|
// The active bits should be less than the bits in the RangeCheckType. This
|
|
|
|
// guarantees that truncating the latch check to RangeCheckType is a safe
|
|
|
|
// operation.
|
|
|
|
auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType);
|
|
|
|
return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
|
|
|
|
Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
|
|
|
|
}
|
|
|
|
|
2017-01-26 00:00:44 +08:00
|
|
|
bool LoopPredication::runOnLoop(Loop *Loop) {
|
|
|
|
L = Loop;
|
|
|
|
|
|
|
|
DEBUG(dbgs() << "Analyzing ");
|
|
|
|
DEBUG(L->dump());
|
|
|
|
|
|
|
|
Module *M = L->getHeader()->getModule();
|
|
|
|
|
|
|
|
// There is nothing to do if the module doesn't use guards
|
|
|
|
auto *GuardDecl =
|
|
|
|
M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
|
|
|
|
if (!GuardDecl || GuardDecl->use_empty())
|
|
|
|
return false;
|
|
|
|
|
|
|
|
DL = &M->getDataLayout();
|
|
|
|
|
|
|
|
Preheader = L->getLoopPreheader();
|
|
|
|
if (!Preheader)
|
|
|
|
return false;
|
|
|
|
|
2017-09-22 21:13:57 +08:00
|
|
|
auto LatchCheckOpt = parseLoopLatchICmp();
|
|
|
|
if (!LatchCheckOpt)
|
|
|
|
return false;
|
|
|
|
LatchCheck = *LatchCheckOpt;
|
|
|
|
|
2017-01-26 00:00:44 +08:00
|
|
|
// Collect all the guards into a vector and process later, so as not
|
|
|
|
// to invalidate the instruction iterator.
|
|
|
|
SmallVector<IntrinsicInst *, 4> Guards;
|
|
|
|
for (const auto BB : L->blocks())
|
|
|
|
for (auto &I : *BB)
|
|
|
|
if (auto *II = dyn_cast<IntrinsicInst>(&I))
|
|
|
|
if (II->getIntrinsicID() == Intrinsic::experimental_guard)
|
|
|
|
Guards.push_back(II);
|
|
|
|
|
2017-05-19 21:59:34 +08:00
|
|
|
if (Guards.empty())
|
|
|
|
return false;
|
|
|
|
|
2017-01-26 00:00:44 +08:00
|
|
|
SCEVExpander Expander(*SE, *DL, "loop-predication");
|
|
|
|
|
|
|
|
bool Changed = false;
|
|
|
|
for (auto *Guard : Guards)
|
|
|
|
Changed |= widenGuardConditions(Guard, Expander);
|
|
|
|
|
|
|
|
return Changed;
|
|
|
|
}
|