63 #define DEBUG_TYPE "guard-widening" 65 STATISTIC(GuardsEliminated,
"Number of eliminated guards");
69 class GuardWideningImpl {
77 std::function<bool(BasicBlock*)> BlockFilter;
91 bool eliminateGuardViaWidening(
111 WS_IllegalOrNegative,
126 static StringRef scoreTypeToString(WideningScore WS);
131 WideningScore computeWideningScore(
Instruction *DominatedGuard,
132 Loop *DominatedGuardLoop,
134 Loop *DominatingGuardLoop);
139 return isAvailableAt(V, InsertPos, Visited);
171 : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
173 void setBase(
Value *NewBase) { Base = NewBase; }
174 void setOffset(
ConstantInt *NewOffset) { Offset = NewOffset; }
176 Value *getBase()
const {
return Base; }
178 const APInt &getOffsetValue()
const {
return getOffset()->getValue(); }
179 Value *getLength()
const {
return Length; };
180 ICmpInst *getCheckInst()
const {
return CheckInst; }
202 return parseRangeChecks(CheckCond, Checks, Visited);
217 bool isWideningCondProfitable(
Value *Cond0,
Value *Cond1) {
219 return widenCondCommon(Cond0, Cond1,
nullptr, ResultUnused);
226 widenCondCommon(ToWiden->
getOperand(0), NewCondition, ToWiden, Result);
227 setGuardCondition(ToWiden, Result);
235 : DT(DT), PDT(PDT), LI(LI), Root(Root), BlockFilter(BlockFilter) {}
242 bool GuardWideningImpl::run() {
244 bool Changed =
false;
248 auto *BB = (*DFI)->getBlock();
249 if (!BlockFilter(BB))
252 auto &CurrentList = GuardsInBlock[BB];
256 CurrentList.push_back(cast<Instruction>(&
I));
258 for (
auto *II : CurrentList)
259 Changed |= eliminateGuardViaWidening(II, DFI, GuardsInBlock);
263 for (
auto *II : EliminatedGuards)
264 if (!WidenedGuards.
count(II))
270 bool GuardWideningImpl::eliminateGuardViaWidening(
275 auto BestScoreSoFar = WS_IllegalOrNegative;
280 for (
unsigned i = 0, e = DFSI.
getPathLength(); i != e; ++i) {
281 auto *CurBB = DFSI.
getPath(i)->getBlock();
282 if (!BlockFilter(CurBB))
285 assert(GuardsInBlock.
count(CurBB) &&
"Must have been populated by now!");
286 const auto &GuardsInCurBB = GuardsInBlock.
find(CurBB)->second;
288 auto I = GuardsInCurBB.begin();
289 auto E = GuardsInCurBB.end();
294 for (
auto &
I : *CurBB) {
295 if (Index == GuardsInCurBB.size())
297 if (GuardsInCurBB[Index] == &
I)
300 assert(Index == GuardsInCurBB.size() &&
301 "Guards expected to be in order!");
305 assert((i == (e - 1)) == (GuardInst->
getParent() == CurBB) &&
"Bad DFS?");
311 assert(NewEnd !=
E &&
"GuardInst not in its own block?");
317 computeWideningScore(GuardInst, GuardInstLoop, Candidate, CurLoop);
318 LLVM_DEBUG(
dbgs() <<
"Score between " << *getGuardCondition(GuardInst)
319 <<
" and " << *getGuardCondition(Candidate) <<
" is " 320 << scoreTypeToString(Score) <<
"\n");
321 if (Score > BestScoreSoFar) {
322 BestScoreSoFar = Score;
323 BestSoFar = Candidate;
328 if (BestScoreSoFar == WS_IllegalOrNegative) {
329 LLVM_DEBUG(
dbgs() <<
"Did not eliminate guard " << *GuardInst <<
"\n");
333 assert(BestSoFar != GuardInst &&
"Should have never visited same guard!");
336 LLVM_DEBUG(
dbgs() <<
"Widening " << *GuardInst <<
" into " << *BestSoFar
337 <<
" with score " << scoreTypeToString(BestScoreSoFar)
339 widenGuard(BestSoFar, getGuardCondition(GuardInst));
341 EliminatedGuards.push_back(GuardInst);
342 WidenedGuards.
insert(BestSoFar);
349 "Bad guard intrinsic?");
353 void GuardWideningImpl::setGuardCondition(
Instruction *GuardInst,
357 "Bad guard intrinsic?");
363 return match(I, m_Intrinsic<Intrinsic::experimental_guard>());
366 void GuardWideningImpl::eliminateGuard(
Instruction *GuardInst) {
371 GuardWideningImpl::WideningScore GuardWideningImpl::computeWideningScore(
374 bool HoistingOutOfLoop =
false;
376 if (DominatingGuardLoop != DominatedGuardLoop) {
379 if (DominatingGuardLoop &&
380 !DominatingGuardLoop->
contains(DominatedGuardLoop))
381 return WS_IllegalOrNegative;
383 HoistingOutOfLoop =
true;
386 if (!isAvailableAt(getGuardCondition(DominatedGuard), DominatingGuard))
387 return WS_IllegalOrNegative;
397 if (isWideningCondProfitable(getGuardCondition(DominatedGuard),
398 getGuardCondition(DominatingGuard)))
399 return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
401 if (HoistingOutOfLoop)
407 auto MaybeHoistingOutOfIf = [&]() {
408 auto *DominatingBlock = DominatingGuard->
getParent();
409 auto *DominatedBlock = DominatedGuard->
getParent();
412 if (DominatedBlock == DominatingBlock)
415 if (DominatedBlock == DominatingBlock->getUniqueSuccessor())
418 if (!PDT)
return true;
423 return MaybeHoistingOutOfIf() ? WS_IllegalOrNegative : WS_Neutral;
433 Inst->mayReadFromMemory())
439 assert(!isa<PHINode>(Loc) &&
440 "PHIs should return false for isSafeToSpeculativelyExecute");
442 "We did a DFS from the block entry!");
443 return all_of(Inst->operands(),
444 [&](
Value *
Op) {
return isAvailableAt(
Op, Loc, Visited); });
453 !Inst->mayReadFromMemory() &&
"Should've checked with isAvailableAt!");
455 for (
Value *
Op : Inst->operands())
456 makeAvailableAt(
Op, Loc);
458 Inst->moveBefore(Loc);
461 bool GuardWideningImpl::widenCondCommon(
Value *Cond0,
Value *Cond1,
492 if (SubsetIntersect == SupersetIntersect &&
493 SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
496 Result =
new ICmpInst(InsertPt, Pred, LHS, NewRHS,
"wide.chk");
505 if (parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
506 combineRangeChecks(Checks, CombinedChecks)) {
509 for (
auto &RC : CombinedChecks) {
510 makeAvailableAt(RC.getCheckInst(), InsertPt);
512 Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result,
"",
515 Result = RC.getCheckInst();
527 makeAvailableAt(Cond0, InsertPt);
528 makeAvailableAt(Cond1, InsertPt);
530 Result = BinaryOperator::CreateAnd(Cond0, Cond1,
"wide.chk", InsertPt);
537 bool GuardWideningImpl::parseRangeChecks(
540 if (!Visited.
insert(CheckCond).second)
546 Value *AndLHS, *AndRHS;
548 return parseRangeChecks(AndLHS, Checks) &&
549 parseRangeChecks(AndRHS, Checks);
553 if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
558 Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
562 auto &DL = IC->getModule()->getDataLayout();
564 GuardWideningImpl::RangeCheck
Check(
585 "Unreachable instruction?");
589 Check.setBase(OpLHS);
597 Check.setBase(OpLHS);
609 bool GuardWideningImpl::combineRangeChecks(
612 unsigned OldCount = Checks.
size();
613 while (!Checks.
empty()) {
616 Value *CurrentBase = Checks.
front().getBase();
617 Value *CurrentLength = Checks.
front().getLength();
621 auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
622 return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
625 copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
628 assert(CurrentChecks.
size() != 0 &&
"We know we have at least one!");
630 if (CurrentChecks.
size() < 3) {
631 RangeChecksOut.
insert(RangeChecksOut.
end(), CurrentChecks.
begin(),
632 CurrentChecks.
end());
640 [&](
const GuardWideningImpl::RangeCheck &LHS,
641 const GuardWideningImpl::RangeCheck &RHS) {
642 return LHS.getOffsetValue().slt(RHS.getOffsetValue());
648 *MaxOffset = CurrentChecks.
back().getOffset();
650 unsigned BitWidth = MaxOffset->getValue().getBitWidth();
651 if ((MaxOffset->getValue() - MinOffset->getValue())
655 APInt MaxDiff = MaxOffset->getValue() - MinOffset->getValue();
656 const APInt &HighOffset = MaxOffset->getValue();
657 auto OffsetOK = [&](
const GuardWideningImpl::RangeCheck &RC) {
658 return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
705 assert(RangeChecksOut.
size() <= OldCount &&
"We pessimized!");
706 return RangeChecksOut.
size() != OldCount;
710 StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
712 case WS_IllegalOrNegative:
713 return "IllegalOrNegative";
718 case WS_VeryPositive:
719 return "VeryPositive";
731 if (!GuardWideningImpl(DT, &PDT, LI, DT.
getRootNode(),
751 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
752 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
753 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
754 return GuardWideningImpl(DT, &PDT, LI, DT.
getRootNode(),
768 struct LoopGuardWideningLegacyPass :
public LoopPass {
771 LoopGuardWideningLegacyPass() :
LoopPass(ID) {
778 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
779 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
780 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
781 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() :
nullptr;
786 return BB == RootBB || L->
contains(BB);
788 return GuardWideningImpl(DT, PDT, LI,
789 DT.
getNode(RootBB), BlockFilter).run();
812 "
Widen guards (within a single loop, as a loop
pass)",
818 "
Widen guards (within a single loop, as a loop pass)",
822 return new GuardWideningLegacyPass();
826 return new LoopGuardWideningLegacyPass();
Pass interface - Implemented by all 'passes'.
static bool Check(DecodeStatus &Out, DecodeStatus In)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Safe Stack instrumentation pass
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
ConstantRange unionWith(const ConstantRange &CR) const
Return the range that results from the union of this range with another range.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Compute iterated dominance frontiers using a linear time algorithm.
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...
Implements a dense probed hash-table based set.
void initializeGuardWideningLegacyPassPass(PassRegistry &)
LLVMContext & getContext() const
All values hold a context through their type.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
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)
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
NodeRef getPath(unsigned n) const
getPath - Return the n'th node in the path from the entry node to the current node.
unsigned getPathLength() const
getPathLength - Return the length of the path from the entry node to the current node, counting both nodes.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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)
BlockT * getHeader() const
ConstantRange intersectWith(const ConstantRange &CR) const
Return the range that results from the intersection of this range with another range.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
const APInt & getValue() const
Return the constant as an APInt value reference.
static Error getOffset(const SymbolRef &Sym, SectionRef Sec, uint64_t &Result)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
INITIALIZE_PASS_BEGIN(GuardWideningLegacyPass, "guard-widening", "Widen guards", false, false) INITIALIZE_PASS_END(GuardWideningLegacyPass
Value * getOperand(unsigned i) const
iterator find(const_arg_type_t< KeyT > Val)
static bool runOnFunction(Function &F, bool PostInlining)
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
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)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
std::pair< iterator, bool > insert(const ValueT &V)
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.
FunctionPass * createGuardWideningPass()
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.
FunctionPass class - This class is used to implement most global optimizations.
void setArgOperand(unsigned i, Value *v)
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
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.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static SDValue Widen(SelectionDAG *CurDAG, SDValue N)
void sort(IteratorTy Start, IteratorTy End)
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
void initializeLoopGuardWideningLegacyPassPass(PassRegistry &)
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.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Analysis pass which computes a PostDominatorTree.
This class represents a range of values.
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)
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 dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void emplace_back(ArgTypes &&... Args)
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
void preserveSet()
Mark an analysis set as preserved.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
bool isMinValue() const
Determine if this is the smallest unsigned value.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
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.
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.
print Print MemDeps of function
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.
Pass * createLoopGuardWideningPass()
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
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...
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)