67 #define DEBUG_TYPE "guard-widening" 69 STATISTIC(GuardsEliminated,
"Number of eliminated guards");
70 STATISTIC(CondBranchEliminated,
"Number of eliminated conditional branches");
74 cl::desc(
"Whether or not we should widen guards " 75 "expressed as branches by widenable conditions"),
83 assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
84 "Bad guard intrinsic?");
85 return GI->getArgOperand(0);
92 return cast<BranchInst>(
I)->getCondition();
99 assert(GI->getIntrinsicID() == Intrinsic::experimental_guard &&
100 "Bad guard intrinsic?");
101 GI->setArgOperand(0, NewCond);
104 cast<BranchInst>(
I)->setCondition(NewCond);
108 static void eliminateGuard(
Instruction *GuardInst) {
113 class GuardWideningImpl {
121 std::function<bool(BasicBlock*)> BlockFilter;
135 bool eliminateInstrViaWidening(
138 GuardsPerBlock,
bool InvertCondition =
false);
143 WS_IllegalOrNegative,
158 static StringRef scoreTypeToString(WideningScore WS);
163 WideningScore computeWideningScore(
Instruction *DominatedInstr,
170 return isAvailableAt(V, InsertPos, Visited);
188 Value *&Result,
bool InvertCondition);
203 : Base(Base), Offset(Offset), Length(Length), CheckInst(CheckInst) {}
205 void setBase(
const Value *NewBase) { Base = NewBase; }
206 void setOffset(
const ConstantInt *NewOffset) { Offset = NewOffset; }
208 const Value *getBase()
const {
return Base; }
210 const APInt &getOffsetValue()
const {
return getOffset()->getValue(); }
211 const Value *getLength()
const {
return Length; };
212 ICmpInst *getCheckInst()
const {
return CheckInst; }
234 return parseRangeChecks(CheckCond, Checks, Visited);
249 bool isWideningCondProfitable(
Value *Cond0,
Value *Cond1,
bool InvertCond) {
251 return widenCondCommon(Cond0, Cond1,
nullptr, ResultUnused,
259 bool InvertCondition) {
262 widenCondCommon(getCondition(ToWiden), NewCondition, ToWiden, Result,
268 setCondition(ToWiden, Result);
276 : DT(DT), PDT(PDT), LI(LI), Root(Root), BlockFilter(BlockFilter)
292 bool GuardWideningImpl::run() {
294 bool Changed =
false;
297 auto *BB = (*DFI)->getBlock();
298 if (!BlockFilter(BB))
301 auto &CurrentList = GuardsInBlock[BB];
305 CurrentList.push_back(cast<Instruction>(&I));
307 for (
auto *II : CurrentList)
308 Changed |= eliminateInstrViaWidening(II, DFI, GuardsInBlock);
311 assert(EliminatedGuardsAndBranches.
empty() || Changed);
312 for (
auto *I : EliminatedGuardsAndBranches)
313 if (!WidenedGuards.
count(I)) {
314 assert(isa<ConstantInt>(getCondition(I)) &&
"Should be!");
318 assert(isa<BranchInst>(I) &&
319 "Eliminated something other than guard or branch?");
320 ++CondBranchEliminated;
327 bool GuardWideningImpl::eliminateInstrViaWidening(
330 GuardsInBlock,
bool InvertCondition) {
334 if (isa<ConstantInt>(getCondition(Instr)))
338 auto BestScoreSoFar = WS_IllegalOrNegative;
343 auto *CurBB = DFSI.
getPath(i)->getBlock();
344 if (!BlockFilter(CurBB))
346 assert(GuardsInBlock.count(CurBB) &&
"Must have been populated by now!");
347 const auto &GuardsInCurBB = GuardsInBlock.find(CurBB)->second;
349 auto I = GuardsInCurBB.begin();
351 ?
std::find(GuardsInCurBB.begin(), GuardsInCurBB.end(), Instr)
352 : GuardsInCurBB.end();
357 for (
auto &I : *CurBB) {
358 if (Index == GuardsInCurBB.size())
360 if (GuardsInCurBB[Index] == &I)
363 assert(Index == GuardsInCurBB.size() &&
364 "Guards expected to be in order!");
371 auto Score = computeWideningScore(Instr, Candidate, InvertCondition);
373 <<
" and " << *getCondition(Candidate) <<
" is " 374 << scoreTypeToString(Score) <<
"\n");
375 if (Score > BestScoreSoFar) {
376 BestScoreSoFar = Score;
377 BestSoFar = Candidate;
382 if (BestScoreSoFar == WS_IllegalOrNegative) {
383 LLVM_DEBUG(
dbgs() <<
"Did not eliminate guard " << *Instr <<
"\n");
387 assert(BestSoFar != Instr &&
"Should have never visited same guard!");
390 LLVM_DEBUG(
dbgs() <<
"Widening " << *Instr <<
" into " << *BestSoFar
391 <<
" with score " << scoreTypeToString(BestScoreSoFar)
393 widenGuard(BestSoFar, getCondition(Instr), InvertCondition);
394 auto NewGuardCondition = InvertCondition
397 setCondition(Instr, NewGuardCondition);
398 EliminatedGuardsAndBranches.
push_back(Instr);
399 WidenedGuards.
insert(BestSoFar);
403 GuardWideningImpl::WideningScore
404 GuardWideningImpl::computeWideningScore(
Instruction *DominatedInstr,
409 bool HoistingOutOfLoop =
false;
411 if (DominatingGuardLoop != DominatedInstrLoop) {
414 if (DominatingGuardLoop &&
415 !DominatingGuardLoop->
contains(DominatedInstrLoop))
416 return WS_IllegalOrNegative;
418 HoistingOutOfLoop =
true;
421 if (!isAvailableAt(getCondition(DominatedInstr), DominatingGuard))
422 return WS_IllegalOrNegative;
432 if (isWideningCondProfitable(getCondition(DominatedInstr),
433 getCondition(DominatingGuard), InvertCond))
434 return HoistingOutOfLoop ? WS_VeryPositive : WS_Positive;
436 if (HoistingOutOfLoop)
442 auto MaybeHoistingOutOfIf = [&]() {
443 auto *DominatingBlock = DominatingGuard->
getParent();
444 auto *DominatedBlock = DominatedInstr->
getParent();
446 DominatingBlock = cast<BranchInst>(DominatingGuard)->getSuccessor(0);
449 if (DominatedBlock == DominatingBlock)
452 if (DominatedBlock == DominatingBlock->getUniqueSuccessor())
455 if (!PDT)
return true;
456 return !PDT->
dominates(DominatedBlock, DominatingBlock);
459 return MaybeHoistingOutOfIf() ? WS_IllegalOrNegative : WS_Neutral;
462 bool GuardWideningImpl::isAvailableAt(
470 Inst->mayReadFromMemory())
476 assert(!isa<PHINode>(Loc) &&
477 "PHIs should return false for isSafeToSpeculativelyExecute");
479 "We did a DFS from the block entry!");
480 return all_of(Inst->operands(),
481 [&](
Value *
Op) {
return isAvailableAt(
Op, Loc, Visited); });
490 !Inst->mayReadFromMemory() &&
"Should've checked with isAvailableAt!");
492 for (
Value *
Op : Inst->operands())
493 makeAvailableAt(
Op, Loc);
495 Inst->moveBefore(Loc);
498 bool GuardWideningImpl::widenCondCommon(
Value *Cond0,
Value *Cond1,
500 bool InvertCondition) {
532 if (SubsetIntersect == SupersetIntersect &&
533 SubsetIntersect.getEquivalentICmp(Pred, NewRHSAP)) {
536 Result =
new ICmpInst(InsertPt, Pred, LHS, NewRHS,
"wide.chk");
546 if (!InvertCondition &&
547 parseRangeChecks(Cond0, Checks) && parseRangeChecks(Cond1, Checks) &&
548 combineRangeChecks(Checks, CombinedChecks)) {
551 for (
auto &RC : CombinedChecks) {
552 makeAvailableAt(RC.getCheckInst(), InsertPt);
554 Result = BinaryOperator::CreateAnd(RC.getCheckInst(), Result,
"",
557 Result = RC.getCheckInst();
559 assert(Result &&
"Failed to find result value");
569 makeAvailableAt(Cond0, InsertPt);
570 makeAvailableAt(Cond1, InsertPt);
573 Result = BinaryOperator::CreateAnd(Cond0, Cond1,
"wide.chk", InsertPt);
580 bool GuardWideningImpl::parseRangeChecks(
583 if (!Visited.
insert(CheckCond).second)
589 Value *AndLHS, *AndRHS;
591 return parseRangeChecks(AndLHS, Checks) &&
592 parseRangeChecks(AndRHS, Checks);
596 if (!IC || !IC->getOperand(0)->getType()->isIntegerTy() ||
601 const Value *CmpLHS = IC->getOperand(0), *CmpRHS = IC->getOperand(1);
605 auto &DL = IC->getModule()->getDataLayout();
607 GuardWideningImpl::RangeCheck
Check(
628 "Unreachable instruction?");
632 Check.setBase(OpLHS);
640 Check.setBase(OpLHS);
652 bool GuardWideningImpl::combineRangeChecks(
655 unsigned OldCount = Checks.
size();
656 while (!Checks.
empty()) {
659 const Value *CurrentBase = Checks.
front().getBase();
660 const Value *CurrentLength = Checks.
front().getLength();
664 auto IsCurrentCheck = [&](GuardWideningImpl::RangeCheck &RC) {
665 return RC.getBase() == CurrentBase && RC.getLength() == CurrentLength;
668 copy_if(Checks, std::back_inserter(CurrentChecks), IsCurrentCheck);
671 assert(CurrentChecks.
size() != 0 &&
"We know we have at least one!");
673 if (CurrentChecks.
size() < 3) {
674 RangeChecksOut.
insert(RangeChecksOut.
end(), CurrentChecks.
begin(),
675 CurrentChecks.
end());
682 llvm::sort(CurrentChecks, [&](
const GuardWideningImpl::RangeCheck &LHS,
683 const GuardWideningImpl::RangeCheck &RHS) {
684 return LHS.getOffsetValue().slt(RHS.getOffsetValue());
693 if ((MaxOffset->
getValue() - MinOffset->getValue())
697 APInt MaxDiff = MaxOffset->
getValue() - MinOffset->getValue();
699 auto OffsetOK = [&](
const GuardWideningImpl::RangeCheck &RC) {
700 return (HighOffset - RC.getOffsetValue()).ult(MaxDiff);
747 assert(RangeChecksOut.
size() <= OldCount &&
"We pessimized!");
748 return RangeChecksOut.
size() != OldCount;
752 StringRef GuardWideningImpl::scoreTypeToString(WideningScore WS) {
754 case WS_IllegalOrNegative:
755 return "IllegalOrNegative";
760 case WS_VeryPositive:
761 return "VeryPositive";
773 if (!GuardWideningImpl(DT, &PDT, LI, DT.
getRootNode(),
789 return BB == RootBB || L.
contains(BB);
791 if (!GuardWideningImpl(AR.
DT,
nullptr, AR.
LI, AR.
DT.
getNode(RootBB),
809 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
810 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
811 auto &PDT = getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
812 return GuardWideningImpl(DT, &PDT, LI, DT.
getRootNode(),
826 struct LoopGuardWideningLegacyPass :
public LoopPass {
829 LoopGuardWideningLegacyPass() :
LoopPass(ID) {
836 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
837 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
838 auto *PDTWP = getAnalysisIfAvailable<PostDominatorTreeWrapperPass>();
839 auto *PDT = PDTWP ? &PDTWP->getPostDomTree() :
nullptr;
844 return BB == RootBB || L->
contains(BB);
846 return GuardWideningImpl(DT, PDT, LI,
847 DT.
getNode(RootBB), BlockFilter).run();
870 "
Widen guards (within a single loop, as a loop
pass)",
876 "
Widen guards (within a single loop, as a loop pass)",
880 return new GuardWideningLegacyPass();
884 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)
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, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
reference emplace_back(ArgTypes &&... Args)
static ConstantInt * getFalse(LLVMContext &Context)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
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...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
#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...
Implements a dense probed hash-table based set.
void push_back(const T &Elt)
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")
void setWidenableBranchCond(BranchInst *WidenableBR, Value *Cond)
Given a branch we know is widenable (defined per Analysis/GuardUtils.h), set it's condition such that...
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Analysis pass which computes a DominatorTree.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
unsigned getBitWidth() const
Return the number of bits in the APInt.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
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, PreferredRangeType Type=Smallest) 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)
bool isKnownNonNegative(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Returns true if the give value is known to be non-negative.
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
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
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.
bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
df_iterator< T > df_end(const T &G)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< iterator, bool > insert(const ValueT &V)
static bool isSupportedGuardInstruction(const Instruction *Insn)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static cl::opt< bool > WidenBranchGuards("guard-widening-widen-branch-guards", cl::Hidden, cl::desc("Whether or not we should widen guards " "expressed as branches by widenable conditions"), cl::init(true))
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Represent the analysis usage information of a pass.
bool parseWidenableBranch(const User *U, Value *&Condition, Value *&WidenableCondition, BasicBlock *&IfTrueBB, BasicBlock *&IfFalseBB)
If U is widenable branch looking like: cond = ...
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.
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)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
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.
modulo schedule Modulo Schedule test pass
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)
bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental.guard intrinsic.
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)
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.
ConstantRange unionWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the union of this range with another range.
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.
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.
bool isGuardAsWidenableBranch(const User *U)
Returns true iff U has semantics of a guard expressed in a form of a widenable conditional branch to ...
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.
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)