59 #define DEBUG_TYPE "guard-widening"
63 class GuardWideningImpl {
80 bool eliminateGuardViaWidening(
103 static StringRef scoreTypeToString(WideningScore WS);
108 WideningScore computeWideningScore(
IntrinsicInst *DominatedGuard,
109 Loop *DominatedGuardLoop,
111 Loop *DominatingGuardLoop);
116 return isAvailableAt(V, InsertPos, Visited);
148 : Base(Base),
Offset(Offset), Length(Length), CheckInst(CheckInst) {}
150 void setBase(
Value *NewBase) { Base = NewBase; }
151 void setOffset(
ConstantInt *NewOffset) { Offset = NewOffset; }
153 Value *getBase()
const {
return Base; }
155 const APInt &getOffsetValue()
const {
return getOffset()->getValue(); }
156 Value *getLength()
const {
return Length; };
157 ICmpInst *getCheckInst()
const {
return CheckInst; }
179 return parseRangeChecks(CheckCond, Checks, Visited);
194 bool isWideningCondProfitable(
Value *Cond0,
Value *Cond1) {
196 return widenCondCommon(Cond0, Cond1,
nullptr, ResultUnused);
203 widenCondCommon(ToWiden->
getArgOperand(0), NewCondition, ToWiden, Result);
204 ToWiden->setArgOperand(0, Result);
210 : DT(DT), PDT(PDT), LI(LI) {}
224 bool runOnFunction(
Function &
F)
override {
227 return GuardWideningImpl(
228 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
229 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree(),
230 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()).run();
243 bool GuardWideningImpl::run() {
244 using namespace llvm::PatternMatch;
247 bool Changed =
false;
249 for (
auto DFI =
df_begin(DT.getRootNode()), DFE =
df_end(DT.getRootNode());
251 auto *BB = (*DFI)->getBlock();
252 auto &CurrentList = GuardsInBlock[BB];
255 if (
match(&
I, m_Intrinsic<Intrinsic::experimental_guard>()))
256 CurrentList.push_back(cast<IntrinsicInst>(&
I));
258 for (
auto *II : CurrentList)
259 Changed |= eliminateGuardViaWidening(II, DFI, GuardsInBlock);
262 for (
auto *II : EliminatedGuards)
263 if (!WidenedGuards.count(II))
264 II->eraseFromParent();
269 bool GuardWideningImpl::eliminateGuardViaWidening(
274 auto BestScoreSoFar = WS_IllegalOrNegative;
275 auto *GuardInstLoop = LI.getLoopFor(GuardInst->
getParent());
279 for (
unsigned i = 0, e = DFSI.
getPathLength(); i != e; ++i) {
280 auto *CurBB = DFSI.
getPath(i)->getBlock();
281 auto *CurLoop = LI.getLoopFor(CurBB);
282 assert(GuardsInBlock.count(CurBB) &&
"Must have been populated by now!");
283 const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
285 auto I = GuardsInCurBB.begin();
286 auto E = GuardsInCurBB.end();
291 for (
auto &
I : *CurBB) {
292 if (Index == GuardsInCurBB.size())
294 if (GuardsInCurBB[Index] == &
I)
297 assert(Index == GuardsInCurBB.size() &&
298 "Guards expected to be in order!");
302 assert((i == (e - 1)) == (GuardInst->
getParent() == CurBB) &&
"Bad DFS?");
308 assert(NewEnd !=
E &&
"GuardInst not in its own block?");
314 computeWideningScore(GuardInst, GuardInstLoop, Candidate, CurLoop);
316 <<
" and " << *Candidate->getArgOperand(0) <<
" is "
317 << scoreTypeToString(Score) <<
"\n");
318 if (Score > BestScoreSoFar) {
319 BestScoreSoFar = Score;
320 BestSoFar = Candidate;
325 if (BestScoreSoFar == WS_IllegalOrNegative) {
326 DEBUG(
dbgs() <<
"Did not eliminate guard " << *GuardInst <<
"\n");
330 assert(BestSoFar != GuardInst &&
"Should have never visited same guard!");
331 assert(DT.dominates(BestSoFar, GuardInst) &&
"Should be!");
333 DEBUG(
dbgs() <<
"Widening " << *GuardInst <<
" into " << *BestSoFar
334 <<
" with score " << scoreTypeToString(BestScoreSoFar) <<
"\n");
337 EliminatedGuards.push_back(GuardInst);
338 WidenedGuards.insert(BestSoFar);
342 GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore(
345 bool HoistingOutOfLoop =
false;
347 if (DominatingGuardLoop != DominatedGuardLoop) {
348 if (DominatingGuardLoop &&
349 !DominatingGuardLoop->
contains(DominatedGuardLoop))
350 return WS_IllegalOrNegative;
352 HoistingOutOfLoop =
true;
355 if (!isAvailableAt(DominatedGuard->
getArgOperand(0), DominatingGuard))
356 return WS_IllegalOrNegative;
358 bool HoistingOutOfIf =
361 if (isWideningCondProfitable(DominatedGuard->
getArgOperand(0),
363 return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
365 if (HoistingOutOfLoop)
368 return HoistingOutOfIf ? WS_IllegalOrNegative : WS_Neutral;
374 if (!Inst || DT.dominates(Inst, Loc) || Visited.
count(Inst))
378 Inst->mayReadFromMemory())
384 assert(!isa<PHINode>(Loc) &&
385 "PHIs should return false for isSafeToSpeculativelyExecute");
386 assert(DT.isReachableFromEntry(Inst->getParent()) &&
387 "We did a DFS from the block entry!");
388 return all_of(Inst->operands(),
389 [&](
Value *
Op) {
return isAvailableAt(
Op, Loc, Visited); });
394 if (!Inst || DT.dominates(Inst, Loc))
398 !Inst->mayReadFromMemory() &&
"Should've checked with isAvailableAt!");
400 for (
Value *
Op : Inst->operands())
401 makeAvailableAt(
Op, Loc);
403 Inst->moveBefore(Loc);
406 bool GuardWideningImpl::widenCondCommon(
Value *Cond0,
Value *Cond1,
408 using namespace llvm::PatternMatch;
437 if (SubsetIntersect == SupersetIntersect &&
438 SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
441 Result =
new ICmpInst(InsertPt, Pred, LHS, NewRHS,
"wide.chk");
450 if (parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
451 combineRangeChecks(Checks, CombinedChecks)) {
454 for (
auto &RC : CombinedChecks) {
455 makeAvailableAt(RC.getCheckInst(), InsertPt);
457 Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result,
"",
460 Result = RC.getCheckInst();
472 makeAvailableAt(Cond0, InsertPt);
473 makeAvailableAt(Cond1, InsertPt);
475 Result = BinaryOperator::CreateAnd(Cond0, Cond1,
"wide.chk", InsertPt);
482 bool GuardWideningImpl::parseRangeChecks(
485 if (!Visited.
insert(CheckCond).second)
488 using namespace llvm::PatternMatch;
491 Value *AndLHS, *AndRHS;
493 return parseRangeChecks(AndLHS, Checks) &&
494 parseRangeChecks(AndRHS, Checks);
498 if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
503 Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
507 auto &
DL = IC->getModule()->getDataLayout();
509 GuardWideningImpl::RangeCheck
Check(
529 assert((!BaseInst || DT.isReachableFromEntry(BaseInst->getParent())) &&
530 "Unreachable instruction?");
534 Check.setBase(OpLHS);
542 Check.setBase(OpLHS);
554 bool GuardWideningImpl::combineRangeChecks(
557 unsigned OldCount = Checks.
size();
558 while (!Checks.
empty()) {
561 Value *CurrentBase = Checks.
front().getBase();
562 Value *CurrentLength = Checks.
front().getLength();
566 auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
567 return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
570 copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
573 assert(CurrentChecks.
size() != 0 &&
"We know we have at least one!");
575 if (CurrentChecks.
size() < 3) {
576 RangeChecksOut.
insert(RangeChecksOut.
end(), CurrentChecks.
begin(),
577 CurrentChecks.
end());
585 [&](
const GuardWideningImpl::RangeCheck &LHS,
586 const GuardWideningImpl::RangeCheck &RHS) {
587 return LHS.getOffsetValue().slt(RHS.getOffsetValue());
593 *MaxOffset = CurrentChecks.
back().getOffset();
595 unsigned BitWidth = MaxOffset->getValue().getBitWidth();
596 if ((MaxOffset->getValue() - MinOffset->getValue())
600 APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
601 const APInt &HighOffset = MaxOffset->getValue();
602 auto OffsetOK = [&](
const GuardWideningImpl::RangeCheck &RC) {
603 return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
650 assert(RangeChecksOut.
size() <= OldCount &&
"We pessimized!");
651 return RangeChecksOut.
size() != OldCount;
659 if (!GuardWideningImpl(DT, PDT, LI).run())
667 StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
669 case WS_IllegalOrNegative:
670 return "IllegalOrNegative";
675 case WS_VeryPositive:
676 return "VeryPositive";
693 return new GuardWideningLegacyPass();
static bool Check(DecodeStatus &Out, DecodeStatus In)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
void push_back(const T &Elt)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P)
Provide wrappers to std::copy_if which take ranges instead of having to pass begin/end explicitly...
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
Implements a dense probed hash-table based set.
void initializeGuardWideningLegacyPassPass(PassRegistry &)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass which computes a DominatorTree.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
const APInt & getValue() const
Return the constant as an APInt value reference.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void setName(const Twine &Name)
Change the name of the value.
Analysis pass that exposes the LoopInfo for a function.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
LLVM_NODISCARD bool empty() const
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
ConstantRange unionWith(const ConstantRange &CR) const
Return the range that results from the union of this range with another range.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
NodeRef getPath(unsigned n) const
getPath - Return the n'th node in the path from the entry node to the current node.
A set of analyses that are preserved following a run of a transformation pass.
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
LLVM Basic Block Representation.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
bool isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr)
Returns true if the give value is known to be non-negative.
df_iterator< T > df_end(const T &G)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static void PrintTypes(formatted_raw_ostream &OS, ArrayRef< MVT > Types)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Represent the analysis usage information of a pass.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass,"guard-widening","Widen guards", false, false) INITIALIZE_PASS_END(GuardWideningLegacyPass
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVMContext & getContext() const
All values hold a context through their type.
static SDValue Widen(SelectionDAG *CurDAG, SDValue N)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Analysis pass which computes a PostDominatorTree.
This class represents a range of values.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
static ConstantInt * getTrue(LLVMContext &Context)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
df_iterator< T > df_begin(const T &G)
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
Class for arbitrary precision integers.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
Represents analyses that only rely on functions' control flow.
iterator insert(iterator I, T &&Elt)
bool isMinValue() const
Determine if this is the smallest unsigned value.
llvm_unreachable("Unknown RegBank!")
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void emplace_back(ArgTypes &&...Args)
Represents a single loop in the control flow graph.
void preserveSet()
Mark an analysis set as preserved.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
void setArgOperand(unsigned i, Value *v)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM Value Representation.
FunctionPass * createGuardWideningPass()
This class implements an extremely fast bulk output stream that can only output to a stream...
The legacy pass manager's analysis pass to compute loop information.
StringRef - Represent a constant reference to a string, i.e.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
unsigned getPathLength() const
getPathLength - Return the length of the path from the entry node to the current node, counting both nodes.
const BasicBlock * getParent() const
A wrapper class for inspecting calls to intrinsic functions.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)