82 #define DEBUG_TYPE "loop-unswitch" 84 STATISTIC(NumBranches,
"Number of branches unswitched");
85 STATISTIC(NumSwitches,
"Number of switches unswitched");
86 STATISTIC(NumGuards,
"Number of guards unswitched");
87 STATISTIC(NumSelects ,
"Number of selects unswitched");
88 STATISTIC(NumTrivial ,
"Number of unswitches that are trivial");
89 STATISTIC(NumSimplify,
"Number of simplifications of unswitched code");
90 STATISTIC(TotalInsts,
"Total number of instructions analyzed");
100 class LUAnalysisCache {
101 using UnswitchedValsMap =
103 using UnswitchedValsIt = UnswitchedValsMap::iterator;
105 struct LoopProperties {
106 unsigned CanBeUnswitchedCount;
107 unsigned WasUnswitchedCount;
108 unsigned SizeEstimation;
109 UnswitchedValsMap UnswitchedVals;
114 using LoopPropsMap = std::map<const Loop *, LoopProperties>;
115 using LoopPropsMapIt = LoopPropsMap::iterator;
117 LoopPropsMap LoopsProperties;
118 UnswitchedValsMap *CurLoopInstructions =
nullptr;
119 LoopProperties *CurrentLoopProperties =
nullptr;
138 LUAnalysisCache() : MaxSize(
Threshold) {}
146 void forgetLoop(
const Loop *L);
158 bool CostAllowsUnswitching();
163 void cloneData(
const Loop *NewLoop,
const Loop *OldLoop,
167 class LoopUnswitch :
public LoopPass {
174 std::vector<Loop*> LoopProcessWorklist;
176 LUAnalysisCache BranchesInfo;
178 bool OptimizeForSize;
179 bool redoLoop =
false;
181 Loop *currentLoop =
nullptr;
192 std::vector<BasicBlock*> LoopBlocks;
194 std::vector<BasicBlock*> NewBlocks;
196 bool hasBranchDivergence;
201 explicit LoopUnswitch(
bool Os =
false,
bool hasBranchDivergence =
false)
202 :
LoopPass(ID), OptimizeForSize(Os),
203 hasBranchDivergence(hasBranchDivergence) {
208 bool processCurrentLoop();
209 bool isUnreachableDueToPreviousUnswitching(
BasicBlock *);
217 if (hasBranchDivergence)
223 void releaseMemory()
override {
224 BranchesInfo.forgetLoop(currentLoop);
227 void initLoopData() {
234 void SplitExitEdges(
Loop *L,
237 bool TryTrivialLoopUnswitch(
bool &Changed);
246 void RewriteLoopBodyWithConditionConstant(
Loop *L,
Value *LIC,
249 void EmitPreheaderBranchOnCondition(
Value *LIC,
Constant *Val,
255 void SimplifyCode(std::vector<Instruction*> &Worklist,
Loop *L);
269 LoopPropsMapIt PropsIt;
271 std::tie(PropsIt, Inserted) =
272 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
274 LoopProperties &Props = PropsIt->second;
295 Props.SizeEstimation = Metrics.
NumInsts;
296 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
297 Props.WasUnswitchedCount = 0;
298 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
302 <<
", contents cannot be " 309 CurrentLoopProperties = &Props;
310 CurLoopInstructions = &Props.UnswitchedVals;
316 void LUAnalysisCache::forgetLoop(
const Loop *L) {
317 LoopPropsMapIt LIt = LoopsProperties.find(L);
319 if (LIt != LoopsProperties.end()) {
320 LoopProperties &Props = LIt->second;
321 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
322 Props.SizeEstimation;
323 LoopsProperties.erase(LIt);
326 CurrentLoopProperties =
nullptr;
327 CurLoopInstructions =
nullptr;
334 (*CurLoopInstructions)[
SI].insert(V);
338 bool LUAnalysisCache::isUnswitched(
const SwitchInst *SI,
const Value *V) {
339 return (*CurLoopInstructions)[
SI].count(V);
342 bool LUAnalysisCache::CostAllowsUnswitching() {
343 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
349 void LUAnalysisCache::cloneData(
const Loop *NewLoop,
const Loop *OldLoop,
351 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
352 LoopProperties &OldLoopProps = *CurrentLoopProperties;
353 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
357 --OldLoopProps.CanBeUnswitchedCount;
358 ++OldLoopProps.WasUnswitchedCount;
359 NewLoopProps.WasUnswitchedCount = 0;
360 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
361 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
362 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
364 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
369 for (UnswitchedValsIt
I = Insts.begin();
I != Insts.end(); ++
I) {
372 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
373 assert(NewInst &&
"All instructions that are in SrcBB must be in VMap.");
375 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
391 return new LoopUnswitch(Os, hasBranchDivergence);
416 auto CacheIt = Cache.
find(Cond);
417 if (CacheIt != Cache.
end())
418 return CacheIt->second;
428 if (isa<Constant>(Cond))
return nullptr;
440 if (BO->getOpcode() == Instruction::And ||
441 BO->getOpcode() == Instruction::Or) {
444 switch (ParentChain) {
446 NewChain = BO->getOpcode() == Instruction::And ?
OC_OpChainAnd :
450 NewChain = BO->getOpcode() == Instruction::Or ?
OC_OpChainOr :
454 NewChain = BO->getOpcode() == Instruction::And ?
OC_OpChainAnd :
468 ParentChain = NewChain;
473 ParentChain, Cache)) {
479 ParentChain = NewChain;
481 ParentChain, Cache)) {
488 Cache[Cond] =
nullptr;
505 "Do not expect a partial LIV with mixed operator chain");
506 return {FCond, OpChain};
513 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
515 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
517 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
525 bool Changed =
false;
529 Changed |= processCurrentLoop();
537 bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(
BasicBlock *BB) {
540 while (currentLoop->
contains(DomBB)) {
544 DomBB = Node->getBlock();
550 if (!isa<ConstantInt>(Cond))
578 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
581 auto hasUndefInPHI = [](
PHINode &PN) {
582 for (
Value *Opd : PN.incoming_values()) {
583 if (isa<UndefValue>(Opd))
590 if ((LPHI && hasUndefInPHI(*LPHI)) || (RPHI && hasUndefInPHI(*RPHI)))
594 if (isa<UndefValue>(SI.getTrueValue()) ||
595 isa<UndefValue>(SI.getFalseValue()))
601 if ((LSI && hasUndefInSelect(*LSI)) || (RSI && hasUndefInSelect(*RSI)))
607 bool LoopUnswitch::processCurrentLoop() {
608 bool Changed =
false;
627 if (!BranchesInfo.countLoop(
628 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
634 if (TryTrivialLoopUnswitch(Changed)) {
640 if (OptimizeForSize ||
660 for (
const auto BB : currentLoop->
blocks()) {
661 for (
auto &
I : *BB) {
666 if (
auto *II = dyn_cast<InvokeInst>(&
I))
667 if (!II->getUnwindDest()->canSplitPredecessors())
669 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
670 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
701 if (SanitizeMemory &&
705 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
709 if (isUnreachableDueToPreviousUnswitching(*
I))
714 if (BI->isConditional()) {
718 currentLoop, Changed).
first;
725 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
729 std::tie(LoopCond, OpChain) =
733 if (LoopCond && NumCases) {
744 if (BranchesInfo.isUnswitched(SI, AllZero))
747 UnswitchVal = AllZero;
752 if (BranchesInfo.isUnswitched(SI, AllOne))
755 UnswitchVal = AllOne;
758 "Expect to unswitch on trivial chain");
762 for (
auto Case : SI->
cases()) {
763 Constant *UnswitchValCandidate = Case.getCaseValue();
764 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
765 UnswitchVal = UnswitchValCandidate;
774 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
780 BranchesInfo.setUnswitched(SI, UnswitchVal);
789 if (
SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
791 currentLoop, Changed).
first;
792 if (LoopCond && UnswitchIfProfitable(LoopCond,
810 std::set<BasicBlock*> &Visited) {
811 if (!Visited.insert(BB).second) {
819 if (ExitBB)
return false;
834 if (
I.mayHaveSideEffects())
844 std::set<BasicBlock*> Visited;
855 bool LoopUnswitch::UnswitchIfProfitable(
Value *LoopCond,
Constant *Val,
858 if (!BranchesInfo.CostAllowsUnswitching()) {
861 <<
" at non-trivial condition '" << *Val
862 <<
"' == " << *LoopCond <<
"\n" 863 <<
". Cost too high.\n");
866 if (hasBranchDivergence &&
867 getAnalysis<DivergenceAnalysis>().isDivergent(LoopCond)) {
870 <<
" at non-trivial condition '" << *Val
871 <<
"' == " << *LoopCond <<
"\n" 872 <<
". Condition is divergent.\n");
876 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
907 void LoopUnswitch::EmitPreheaderBranchOnCondition(
Value *LIC,
Constant *Val,
913 assert(TrueDest != FalseDest &&
"Branch targets should be different");
916 Value *BranchVal = LIC;
917 bool Swapped =
false;
918 if (!isa<ConstantInt>(Val) ||
930 auto *OldBranchParent = OldBranch->
getParent();
934 IRBuilder<>(OldBranch).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
946 if (TrueDest != OldBranchSucc)
948 if (FalseDest != OldBranchSucc)
952 if (OldBranchSucc != TrueDest && OldBranchSucc != FalseDest) {
976 <<
" blocks] in Function " 978 <<
" on cond: " << *Val <<
" == " << *Cond <<
"\n");
981 if (
auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
982 SEWP->getSE().forgetTopmostLoop(L);
1003 assert(OldBranch &&
"Failed to split the preheader");
1004 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH, OldBranch, TI);
1017 RewriteLoopBodyWithConditionConstant(L, Cond, Val,
false);
1027 bool LoopUnswitch::TryTrivialLoopUnswitch(
bool &Changed) {
1053 if (!currentLoop->
contains(CurrentBB) || !Visited.
insert(CurrentBB).second)
1060 if (
I.mayHaveSideEffects())
1063 if (
BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1064 if (BI->isUnconditional()) {
1065 CurrentBB = BI->getSuccessor(0);
1067 CurrentBB = BI->getSuccessor(0);
1069 CurrentBB = BI->getSuccessor(1);
1074 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1087 CurrentTerm = CurrentBB->getTerminator();
1095 if (
BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1097 if (!BI->isConditional())
1101 currentLoop, Changed).
first;
1105 if (!LoopCond || LoopCond != BI->getCondition())
1113 BI->getSuccessor(0)))) {
1116 BI->getSuccessor(1)))) {
1122 if (!LoopExitBB || isa<PHINode>(LoopExitBB->
begin()))
1128 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1132 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1135 currentLoop, Changed).
first;
1148 for (
auto Case : SI->
cases()) {
1150 if ((LoopExitCandidate =
1157 if (BranchesInfo.isUnswitched(SI, CaseVal))
1159 LoopExitBB = LoopExitCandidate;
1167 if (!LoopExitBB || isa<PHINode>(LoopExitBB->
begin()))
1170 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1174 BranchesInfo.setUnswitched(SI, CondVal);
1183 void LoopUnswitch::SplitExitEdges(
Loop *L,
1186 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i) {
1201 void LoopUnswitch::UnswitchNontrivialCondition(
Value *LIC,
Constant *Val,
1206 <<
" blocks] in Function " << F->
getName() <<
" when '" 1207 << *Val <<
"' == " << *LIC <<
"\n");
1211 if (
auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1212 SEWP->getSE().forgetTopmostLoop(L);
1220 LoopBlocks.push_back(NewPreheader);
1230 SplitExitEdges(L, ExitBlocks);
1237 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.
begin(), ExitBlocks.
end());
1242 NewBlocks.reserve(LoopBlocks.size());
1244 for (
unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
1247 NewBlocks.push_back(NewBB);
1248 VMap[LoopBlocks[i]] = NewBB;
1256 NewBlocks[0]->getIterator(), F->
end());
1263 BranchesInfo.cloneData(NewLoop, L, VMap);
1272 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i) {
1273 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
1275 if (
Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
1276 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
1279 "Exit block should have been split to have one successor!");
1284 for (
PHINode &PN : ExitSucc->phis()) {
1285 Value *V = PN.getIncomingValueForBlock(ExitBlocks[i]);
1288 PN.addIncoming(V, NewExit);
1293 &*ExitSucc->getFirstInsertionPt());
1306 for (
unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1310 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
1311 if (II->getIntrinsicID() == Intrinsic::assume)
1319 "Preheader splitting did not work correctly!");
1322 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1330 LoopProcessWorklist.push_back(NewLoop);
1342 RewriteLoopBodyWithConditionConstant(L, LIC, Val,
false);
1347 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1348 LICHandle && !isa<Constant>(LICHandle))
1349 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val,
true);
1354 std::vector<Instruction*> &Worklist) {
1356 Worklist.erase(
std::remove(Worklist.begin(), Worklist.end(),
I),
1363 std::vector<Instruction*> &Worklist,
1365 LLVM_DEBUG(
dbgs() <<
"Replace with '" << *V <<
"': " << *I <<
"\n");
1370 Worklist.push_back(
Use);
1374 Worklist.push_back(cast<Instruction>(U));
1386 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(
Loop *L,
Value *LIC,
1389 assert(!isa<Constant>(LIC) &&
"Why are we unswitching on a constant?");
1400 std::vector<Instruction*> Worklist;
1405 if (IsEqual || (isa<ConstantInt>(Val) &&
1412 !cast<ConstantInt>(Val)->getZExtValue());
1418 Worklist.push_back(UI);
1424 SimplifyCode(Worklist, L);
1438 if (
Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
1454 Worklist.push_back(UI);
1458 if (!SI || !isa<ConstantInt>(Val))
continue;
1481 if (Latch && DT->
dominates(SISucc, Latch))
1506 PN.setIncomingValue(PN.getBasicBlockIndex(Switch),
1515 SimplifyCode(Worklist, L);
1526 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist,
Loop *L) {
1528 while (!Worklist.empty()) {
1530 Worklist.pop_back();
1539 Worklist.push_back(
Use);
1557 if (
BranchInst *BI = dyn_cast<BranchInst>(I)) {
1558 if (BI->isUnconditional()) {
1564 if (!SinglePred)
continue;
1565 assert(SinglePred == Pred &&
"CFG broken");
1583 BI->eraseFromParent();
1608 if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
Pass interface - Implemented by all 'passes'.
static void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value *> &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop)...
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
void initializeLoopUnswitchPass(PassRegistry &)
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
static IntegerType * getInt1Ty(LLVMContext &C)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
Compute iterated dominance frontiers using a linear time algorithm.
BasicBlock * SplitBlock(BasicBlock *Old, Instruction *SplitPt, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the specified block at the specified instruction - everything before SplitPt stays in Old and e...
ArrayRef< BasicBlock *>::const_iterator block_iterator
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
OperatorChain
Operator chain lattice.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
An immutable pass that tracks lazily created AssumptionCache objects.
Value * getCondition() const
A cache of @llvm.assume calls within a function.
LLVMContext & getContext() const
All values hold a context through their type.
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
Value * getCondition() const
bool isVectorTy() const
True if this is an instance of VectorType.
bool notDuplicatable
True if this function cannot be duplicated.
LLVMContext & getContext() const
Get the context in which this basic block lives.
ConstantInt * findCaseDest(BasicBlock *BB)
Finds the unique case value for a given successor.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
static void ReplaceUsesOfWith(Instruction *I, Value *V, std::vector< Instruction *> &Worklist, Loop *L, LPPassManager *LPM)
When we find that I really equals V, remove I from the program, replacing all uses with V and update ...
static Loop * CloneLoop(Loop *L, Loop *PL, ValueToValueMapTy &VM, LoopInfo *LI, LPPassManager *LPM)
Recursively clone the specified loop and all of its children, mapping the blocks with the specified m...
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Option class for critical edge splitting.
static constexpr UpdateKind Delete
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
A Use represents the edge between a Value definition and its users.
bool isIntegerTy() const
True if this is an instance of IntegerType.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
This file contains the simple types necessary to represent the attributes associated with functions a...
BlockT * getHeader() const
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
void computeLoopSafetyInfo(LoopSafetyInfo *, Loop *)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
static bool isEqual(const Function &Caller, const Function &Callee)
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
iterator find(const KeyT &Val)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Value * getOperand(unsigned i) const
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Interval::succ_iterator succ_end(Interval *I)
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
iterator find(const_arg_type_t< KeyT > Val)
static Value * FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed, OperatorChain &ParentChain, DenseMap< Value *, Value *> &Cache)
Cond is a condition that occurs in L.
void applyUpdates(ArrayRef< UpdateType > Updates)
Inform the dominator tree about a sequence of CFG edge insertions and deletions and perform a batch u...
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
initializer< Ty > init(const Ty &Val)
The landingpad instruction holds all of the information necessary to generate correct exception handl...
Subclasses of this class are all able to terminate a basic block.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
This function has undefined behavior.
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static void RemoveFromWorklist(Instruction *I, std::vector< Instruction *> &Worklist)
Remove all instances of I from the worklist vector specified.
const Instruction & front() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Represent the analysis usage information of a pass.
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value *> &EphValues)
Add information about a block to the current state.
void splice(iterator where, iplist_impl &L2)
static bool isTrivialLoopExitBlockHelper(Loop *L, BasicBlock *BB, BasicBlock *&ExitBB, std::set< BasicBlock *> &Visited)
Check to see if all paths from BB exit the loop with no side effects (including infinite loops)...
This instruction compares its operands according to the predicate given to the constructor.
Interval::pred_iterator pred_end(Interval *I)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
self_iterator getIterator()
static bool EqualityPropUnSafe(Value &LoopCond)
FIXME: Remove this workaround when freeze related patches are done.
INITIALIZE_PASS_BEGIN(LoopUnswitch, "loop-unswitch", "Unswitch loops", false, false) INITIALIZE_PASS_END(LoopUnswitch
static Constant * getAllOnesValue(Type *Ty)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void deleteSimpleAnalysisValue(Value *V, Loop *L)
deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes that implement simple anal...
const InstListType & getInstList() const
Return the underlying instruction list container.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
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.
Module.h This file contains the declarations for the Module class.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
LoopT * AllocateLoop(ArgsTy &&... Args)
CriticalEdgeSplittingOptions & setPreserveLCSSA()
CHAIN = SC CHAIN, Imm128 - System call.
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.
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
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.
BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, DebugInfoFinder *DIFinder=nullptr)
CloneBasicBlock - Return a copy of the specified basic block, but without embedding the block into a ...
Pass * createLoopUnswitchPass(bool OptimizeForSize=false, bool hasBranchDivergence=false)
iterator_range< user_iterator > users()
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM...
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LoopT * getParentLoop() const
Predicate getPredicate() const
Return the predicate for this instruction.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Captures loop safety information.
void registerAssumption(CallInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
void addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
void cloneBasicBlockSimpleAnalysis(BasicBlock *From, BasicBlock *To, Loop *L)
SimpleAnalysis - Provides simple interface to update analysis info maintained by various passes...
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
DomTreeNodeBase< NodeT > * addNewBlock(NodeT *BB, NodeT *DomBB)
Add a new node to the dominator tree information.
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
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)
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
block_iterator block_end() const
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
CaseIt case_default()
Returns an iterator that points to the default case.
bool isUnconditional() const
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
bool replacementPreservesLCSSAForm(Instruction *From, Value *To)
Returns true if replacing From with To everywhere is guaranteed to preserve LCSSA form...
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
unsigned NumInsts
Number of instructions in the analyzed blocks.
iterator_range< block_iterator > blocks() const
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo)
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
static BasicBlock * isTrivialLoopExitBlock(Loop *L, BasicBlock *BB)
Return true if the specified block unconditionally leads to an exit from the specified loop...
block_iterator block_begin() const
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
void removeBlock(BlockT *BB)
This method completely removes BB from all data structures, including all of the Loop objects it is n...
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const