66 #define DEBUG_TYPE "loop-unswitch"
68 STATISTIC(NumBranches,
"Number of branches unswitched");
69 STATISTIC(NumSwitches,
"Number of switches unswitched");
70 STATISTIC(NumGuards,
"Number of guards unswitched");
71 STATISTIC(NumSelects ,
"Number of selects unswitched");
72 STATISTIC(NumTrivial ,
"Number of unswitches that are trivial");
73 STATISTIC(NumSimplify,
"Number of simplifications of unswitched code");
74 STATISTIC(TotalInsts,
"Total number of instructions analyzed");
84 class LUAnalysisCache {
89 typedef UnswitchedValsMap::iterator UnswitchedValsIt;
91 struct LoopProperties {
92 unsigned CanBeUnswitchedCount;
93 unsigned WasUnswitchedCount;
94 unsigned SizeEstimation;
95 UnswitchedValsMap UnswitchedVals;
100 typedef std::map<const Loop*, LoopProperties> LoopPropsMap;
101 typedef LoopPropsMap::iterator LoopPropsMapIt;
103 LoopPropsMap LoopsProperties;
104 UnswitchedValsMap *CurLoopInstructions;
105 LoopProperties *CurrentLoopProperties;
125 : CurLoopInstructions(nullptr), CurrentLoopProperties(nullptr),
134 void forgetLoop(
const Loop *
L);
146 bool CostAllowsUnswitching();
151 void cloneData(
const Loop *NewLoop,
const Loop *OldLoop,
155 class LoopUnswitch :
public LoopPass {
162 std::vector<Loop*> LoopProcessWorklist;
164 LUAnalysisCache BranchesInfo;
166 bool OptimizeForSize;
180 std::vector<BasicBlock*> LoopBlocks;
182 std::vector<BasicBlock*> NewBlocks;
184 bool hasBranchDivergence;
188 explicit LoopUnswitch(
bool Os =
false,
bool hasBranchDivergence =
false) :
190 currentLoop(nullptr), DT(nullptr), loopHeader(nullptr),
191 loopPreheader(nullptr), hasBranchDivergence(hasBranchDivergence) {
196 bool processCurrentLoop();
197 bool isUnreachableDueToPreviousUnswitching(
BasicBlock *);
204 if (hasBranchDivergence)
211 void releaseMemory()
override {
212 BranchesInfo.forgetLoop(currentLoop);
215 void initLoopData() {
216 loopHeader = currentLoop->getHeader();
217 loopPreheader = currentLoop->getLoopPreheader();
222 void SplitExitEdges(
Loop *
L,
225 bool TryTrivialLoopUnswitch(
bool &Changed);
234 void RewriteLoopBodyWithConditionConstant(
Loop *
L,
Value *LIC,
237 void EmitPreheaderBranchOnCondition(
Value *LIC,
Constant *Val,
243 void SimplifyCode(std::vector<Instruction*> &Worklist,
Loop *
L);
257 LoopPropsMapIt PropsIt;
259 std::tie(PropsIt, Inserted) =
260 LoopsProperties.insert(std::make_pair(L, LoopProperties()));
262 LoopProperties &Props = PropsIt->second;
283 Props.SizeEstimation = Metrics.
NumInsts;
284 Props.CanBeUnswitchedCount = MaxSize / (Props.SizeEstimation);
285 Props.WasUnswitchedCount = 0;
286 MaxSize -= Props.SizeEstimation * Props.CanBeUnswitchedCount;
290 << L->
getHeader()->getName() <<
", contents cannot be "
297 CurrentLoopProperties = &Props;
298 CurLoopInstructions = &Props.UnswitchedVals;
304 void LUAnalysisCache::forgetLoop(
const Loop *L) {
306 LoopPropsMapIt LIt = LoopsProperties.find(L);
308 if (LIt != LoopsProperties.end()) {
309 LoopProperties &Props = LIt->second;
310 MaxSize += (Props.CanBeUnswitchedCount + Props.WasUnswitchedCount) *
311 Props.SizeEstimation;
312 LoopsProperties.erase(LIt);
315 CurrentLoopProperties =
nullptr;
316 CurLoopInstructions =
nullptr;
322 void LUAnalysisCache::setUnswitched(
const SwitchInst *SI,
const Value *V) {
323 (*CurLoopInstructions)[SI].insert(V);
327 bool LUAnalysisCache::isUnswitched(
const SwitchInst *SI,
const Value *V) {
328 return (*CurLoopInstructions)[SI].count(V);
331 bool LUAnalysisCache::CostAllowsUnswitching() {
332 return CurrentLoopProperties->CanBeUnswitchedCount > 0;
338 void LUAnalysisCache::cloneData(
const Loop *NewLoop,
const Loop *OldLoop,
341 LoopProperties &NewLoopProps = LoopsProperties[NewLoop];
342 LoopProperties &OldLoopProps = *CurrentLoopProperties;
343 UnswitchedValsMap &Insts = OldLoopProps.UnswitchedVals;
347 --OldLoopProps.CanBeUnswitchedCount;
348 ++OldLoopProps.WasUnswitchedCount;
349 NewLoopProps.WasUnswitchedCount = 0;
350 unsigned Quota = OldLoopProps.CanBeUnswitchedCount;
351 NewLoopProps.CanBeUnswitchedCount = Quota / 2;
352 OldLoopProps.CanBeUnswitchedCount = Quota - Quota / 2;
354 NewLoopProps.SizeEstimation = OldLoopProps.SizeEstimation;
359 for (UnswitchedValsIt
I = Insts.begin();
I != Insts.end(); ++
I) {
362 const SwitchInst *NewInst = cast_or_null<SwitchInst>(NewI);
363 assert(NewInst &&
"All instructions that are in SrcBB must be in VMap.");
365 NewLoopProps.UnswitchedVals[NewInst] = OldLoopProps.UnswitchedVals[OldInst];
380 return new LoopUnswitch(Os, hasBranchDivergence);
405 auto CacheIt = Cache.
find(Cond);
406 if (CacheIt != Cache.
end())
407 return CacheIt->second;
417 if (isa<Constant>(Cond))
return nullptr;
429 if (BO->getOpcode() == Instruction::And ||
430 BO->getOpcode() == Instruction::Or) {
433 switch (ParentChain) {
435 NewChain = BO->getOpcode() == Instruction::And ?
OC_OpChainAnd :
439 NewChain = BO->getOpcode() == Instruction::Or ?
OC_OpChainOr :
443 NewChain = BO->getOpcode() == Instruction::And ?
OC_OpChainAnd :
457 ParentChain = NewChain;
462 ParentChain, Cache)) {
468 ParentChain = NewChain;
470 ParentChain, Cache)) {
477 Cache[Cond] =
nullptr;
494 "Do not expect a partial LIV with mixed operator chain");
495 return {FCond, OpChain};
502 AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
504 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
506 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
508 Function *
F = currentLoop->getHeader()->getParent();
514 bool Changed =
false;
516 assert(currentLoop->isLCSSAForm(*DT));
518 Changed |= processCurrentLoop();
529 bool LoopUnswitch::isUnreachableDueToPreviousUnswitching(
BasicBlock *BB) {
530 auto *Node = DT->getNode(BB)->getIDom();
532 while (currentLoop->contains(DomBB)) {
535 Node = DT->getNode(DomBB)->getIDom();
536 DomBB = Node->getBlock();
542 if (!isa<ConstantInt>(Cond))
550 if (DT->dominates(UnreachableSucc, BB))
557 bool LoopUnswitch::processCurrentLoop() {
558 bool Changed =
false;
567 if (!currentLoop->isSafeToClone())
571 if (!currentLoop->hasDedicatedExits())
577 if (!BranchesInfo.countLoop(
578 currentLoop, getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
579 *currentLoop->getHeader()->getParent()),
584 if (TryTrivialLoopUnswitch(Changed)) {
604 for (
const auto BB : currentLoop->blocks()) {
605 for (
auto &
I : *BB) {
610 if (
auto *II = dyn_cast<InvokeInst>(&
I))
611 if (!II->getUnwindDest()->canSplitPredecessors())
613 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
614 if (II->getIntrinsicID() == Intrinsic::experimental_guard)
621 if (OptimizeForSize ||
622 loopHeader->getParent()->hasFnAttribute(Attribute::OptimizeForSize))
642 E = currentLoop->block_end();
I !=
E; ++
I) {
651 if (SanitizeMemory &&
655 if (
BranchInst *BI = dyn_cast<BranchInst>(TI)) {
659 if (isUnreachableDueToPreviousUnswitching(*
I))
664 if (BI->isConditional()) {
668 currentLoop, Changed).
first;
675 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
679 std::tie(LoopCond, OpChain) =
683 if (LoopCond && NumCases) {
694 if (BranchesInfo.isUnswitched(SI, AllZero))
697 UnswitchVal = AllZero;
702 if (BranchesInfo.isUnswitched(SI, AllOne))
705 UnswitchVal = AllOne;
708 "Expect to unswitch on trivial chain");
712 for (
auto Case : SI->
cases()) {
713 Constant *UnswitchValCandidate = Case.getCaseValue();
714 if (!BranchesInfo.isUnswitched(SI, UnswitchValCandidate)) {
715 UnswitchVal = UnswitchValCandidate;
724 if (UnswitchIfProfitable(LoopCond, UnswitchVal)) {
730 BranchesInfo.setUnswitched(SI, UnswitchVal);
739 if (
SelectInst *SI = dyn_cast<SelectInst>(BBI)) {
741 currentLoop, Changed).
first;
742 if (LoopCond && UnswitchIfProfitable(LoopCond,
760 std::set<BasicBlock*> &Visited) {
761 if (!Visited.insert(BB).second) {
769 if (ExitBB)
return false;
784 if (
I.mayHaveSideEffects())
794 std::set<BasicBlock*> Visited;
805 bool LoopUnswitch::UnswitchIfProfitable(
Value *LoopCond,
Constant *Val,
808 if (!BranchesInfo.CostAllowsUnswitching()) {
810 << currentLoop->getHeader()->getName()
811 <<
" at non-trivial condition '" << *Val
812 <<
"' == " << *LoopCond <<
"\n"
813 <<
". Cost too high.\n");
816 if (hasBranchDivergence &&
817 getAnalysis<DivergenceAnalysis>().isDivergent(LoopCond)) {
819 << currentLoop->getHeader()->getName()
820 <<
" at non-trivial condition '" << *Val
821 <<
"' == " << *LoopCond <<
"\n"
822 <<
". Condition is divergent.\n");
826 UnswitchNontrivialCondition(LoopCond, Val, currentLoop, TI);
856 void LoopUnswitch::EmitPreheaderBranchOnCondition(
Value *LIC,
Constant *Val,
863 Value *BranchVal = LIC;
864 bool Swapped =
false;
865 if (!isa<ConstantInt>(Val) ||
876 IRBuilder<>(InsertPt).CreateCondBr(BranchVal, TrueDest, FalseDest, TI);
895 DEBUG(
dbgs() <<
"loop-unswitch: Trivial-Unswitch loop %"
896 << loopHeader->getName() <<
" [" << L->
getBlocks().size()
897 <<
" blocks] in Function "
898 << L->
getHeader()->getParent()->getName() <<
" on cond: " << *Val
899 <<
" == " << *Cond <<
"\n");
919 EmitPreheaderBranchOnCondition(Cond, Val, NewExit, NewPH,
920 loopPreheader->getTerminator(), TI);
921 LPM->deleteSimpleAnalysisValue(loopPreheader->getTerminator(),
L);
930 RewriteLoopBodyWithConditionConstant(L, Cond, Val,
false);
940 bool LoopUnswitch::TryTrivialLoopUnswitch(
bool &Changed) {
941 BasicBlock *CurrentBB = currentLoop->getHeader();
966 if (!currentLoop->contains(CurrentBB) || !Visited.
insert(CurrentBB).second)
973 if (
I.mayHaveSideEffects())
976 if (
BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
987 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1000 CurrentTerm = CurrentBB->getTerminator();
1008 if (
BranchInst *BI = dyn_cast<BranchInst>(CurrentTerm)) {
1014 currentLoop, Changed).
first;
1035 if (!LoopExitBB || isa<PHINode>(LoopExitBB->
begin()))
1038 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1042 }
else if (
SwitchInst *SI = dyn_cast<SwitchInst>(CurrentTerm)) {
1045 currentLoop, Changed).
first;
1058 for (
auto Case : SI->
cases()) {
1060 if ((LoopExitCandidate =
1067 if (BranchesInfo.isUnswitched(SI, CaseVal))
1069 LoopExitBB = LoopExitCandidate;
1077 if (!LoopExitBB || isa<PHINode>(LoopExitBB->
begin()))
1080 UnswitchTrivialCondition(currentLoop, LoopCond, CondVal, LoopExitBB,
1084 BranchesInfo.setUnswitched(SI, CondVal);
1093 void LoopUnswitch::SplitExitEdges(
Loop *L,
1096 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i) {
1111 void LoopUnswitch::UnswitchNontrivialCondition(
Value *LIC,
Constant *Val,
1114 DEBUG(
dbgs() <<
"loop-unswitch: Unswitching loop %"
1115 << loopHeader->getName() <<
" [" << L->
getBlocks().size()
1116 <<
" blocks] in Function " << F->
getName()
1117 <<
" when '" << *Val <<
"' == " << *LIC <<
"\n");
1119 if (
auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>())
1120 SEWP->getSE().forgetLoop(L);
1128 LoopBlocks.push_back(NewPreheader);
1138 SplitExitEdges(L, ExitBlocks);
1145 LoopBlocks.insert(LoopBlocks.end(), ExitBlocks.
begin(), ExitBlocks.
end());
1150 NewBlocks.reserve(LoopBlocks.size());
1152 for (
unsigned i = 0, e = LoopBlocks.size(); i != e; ++i) {
1155 NewBlocks.push_back(NewBB);
1156 VMap[LoopBlocks[i]] = NewBB;
1157 LPM->cloneBasicBlockSimpleAnalysis(LoopBlocks[i], NewBB, L);
1164 NewBlocks[0]->getIterator(), F->
end());
1171 BranchesInfo.cloneData(NewLoop, L, VMap);
1180 for (
unsigned i = 0, e = ExitBlocks.
size(); i != e; ++i) {
1181 BasicBlock *NewExit = cast<BasicBlock>(VMap[ExitBlocks[i]]);
1183 if (
Loop *ExitBBLoop = LI->getLoopFor(ExitBlocks[i]))
1184 ExitBBLoop->addBasicBlockToLoop(NewExit, *LI);
1187 "Exit block should have been split to have one successor!");
1202 &*ExitSucc->getFirstInsertionPt());
1215 for (
unsigned i = 0, e = NewBlocks.size(); i != e; ++i) {
1219 if (
auto *II = dyn_cast<IntrinsicInst>(&
I))
1220 if (II->getIntrinsicID() == Intrinsic::assume)
1226 BranchInst *OldBR = cast<BranchInst>(loopPreheader->getTerminator());
1228 "Preheader splitting did not work correctly!");
1231 EmitPreheaderBranchOnCondition(LIC, Val, NewBlocks[0], LoopBlocks[0], OldBR,
1233 LPM->deleteSimpleAnalysisValue(OldBR, L);
1248 RewriteLoopBodyWithConditionConstant(L, LIC, Val,
false);
1253 if (!LoopProcessWorklist.empty() && LoopProcessWorklist.back() == NewLoop &&
1254 LICHandle && !isa<Constant>(LICHandle))
1255 RewriteLoopBodyWithConditionConstant(NewLoop, LICHandle, Val,
true);
1260 std::vector<Instruction*> &Worklist) {
1262 Worklist.erase(
std::remove(Worklist.begin(), Worklist.end(),
I),
1269 std::vector<Instruction*> &Worklist,
1271 DEBUG(
dbgs() <<
"Replace with '" << *V <<
"': " << *I <<
"\n");
1276 Worklist.push_back(
Use);
1280 Worklist.push_back(cast<Instruction>(U));
1292 void LoopUnswitch::RewriteLoopBodyWithConditionConstant(
Loop *L,
Value *LIC,
1295 assert(!isa<Constant>(LIC) &&
"Why are we unswitching on a constant?");
1306 std::vector<Instruction*> Worklist;
1311 if (IsEqual || (isa<ConstantInt>(Val) &&
1318 !cast<ConstantInt>(Val)->getZExtValue());
1324 Worklist.push_back(UI);
1330 SimplifyCode(Worklist, L);
1344 if (
Value *Replacement = SimplifyInstructionWithNotEqual(UI, LIC, Val)) {
1345 if (LI->replacementPreservesLCSSAForm(UI, Replacement)) {
1360 Worklist.push_back(UI);
1364 if (!SI || !isa<ConstantInt>(Val))
continue;
1387 if (Latch && DT->dominates(SISucc, Latch))
1419 DT->addNewBlock(Abort, NewSISucc);
1422 SimplifyCode(Worklist, L);
1433 void LoopUnswitch::SimplifyCode(std::vector<Instruction*> &Worklist,
Loop *L) {
1435 while (!Worklist.empty()) {
1437 Worklist.pop_back();
1441 DEBUG(
dbgs() <<
"Remove dead instruction '" << *I <<
"\n");
1446 Worklist.push_back(
Use);
1447 LPM->deleteSimpleAnalysisValue(I, L);
1458 if (LI->replacementPreservesLCSSAForm(I, V)) {
1464 if (
BranchInst *BI = dyn_cast<BranchInst>(I)) {
1471 if (!SinglePred)
continue;
1472 assert(SinglePred == Pred &&
"CFG broken");
1488 LPM->deleteSimpleAnalysisValue(BI, L);
1493 LI->removeBlock(Succ);
1494 LPM->deleteSimpleAnalysisValue(Succ, L);
1515 if ((Op0 == Invariant && Op1 == Val) || (Op0 == Val && Op1 == Invariant)) {
Pass interface - Implemented by all 'passes'.
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.
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.
STATISTIC(NumFunctions,"Total number of functions")
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...
This is the interface for a simple mod/ref and alias analysis over globals.
INITIALIZE_PASS_BEGIN(LoopUnswitch,"loop-unswitch","Unswitch loops", false, false) INITIALIZE_PASS_END(LoopUnswitch
OperatorChain
Operator chain lattice.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
unsigned getNumOperands() const
An immutable pass that tracks lazily created AssumptionCache objects.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
A cache of .assume calls within a function.
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
LoopT * getParentLoop() const
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
const Instruction & front() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool notDuplicatable
True if this function cannot be duplicated.
const std::vector< BlockT * > & getBlocks() const
Get a list of the basic blocks which make up this loop.
BlockT * getHeader() const
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.
StringRef getName() const
Return a constant reference to the value's name.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
iterator begin()
Instruction iterator methods.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isUnconditional() const
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.
Option class for critical edge splitting.
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
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...
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 addChildLoop(LoopT *NewChild)
Add the specified loop to be a child of this loop.
BasicBlock * getSuccessor(unsigned i) const
iterator find(const KeyT &Val)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
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 void RemoveFromWorklist(Instruction *I, std::vector< Instruction * > &Worklist)
Remove all instances of I from the worklist vector specified.
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 LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
Conditional or Unconditional Branch instruction.
bool isVectorTy() const
True if this is an instance of VectorType.
This function has undefined behavior.
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
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 splice(iterator where, iplist_impl &L2)
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
const InstListType & getInstList() const
Return the underlying instruction list container.
This instruction compares its operands according to the predicate given to the constructor.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
Value * getOperand(unsigned i) const
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
self_iterator getIterator()
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Predicate getPredicate() const
Return the predicate for this instruction.
static Constant * getAllOnesValue(Type *Ty)
Get the all ones value.
static Value * FindLIVLoopCondition(Value *Cond, Loop *L, bool &Changed, OperatorChain &ParentChain, DenseMap< Value *, Value * > &Cache)
Cond is a condition that occurs in L.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
void getUniqueExitBlocks(SmallVectorImpl< BasicBlock * > &ExitBlocks) const
Return all unique successor blocks of this loop.
LLVMContext & getContext() const
All values hold a context through their type.
void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
bool isConditional() const
void deleteSimpleAnalysisValue(Value *V, Loop *L)
deleteSimpleAnalysisValue - Invoke deleteAnalysisValue hook for all passes that implement simple anal...
Iterator for intrusive lists based on ilist_node.
const BasicBlockListType & getBasicBlockList() const
Get the underlying elements of the Function...
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.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
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...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Type * getType() const
All values are typed, get the type of this value.
Utility to calculate the size and a few similar metrics for a set of basic blocks.
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)
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...
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
CaseIt findCaseValue(const ConstantInt *C)
Search all of the case values for the specified constant.
static ConstantInt * getTrue(LLVMContext &Context)
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
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.
void push_back(pointer val)
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 ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
bool isIntegerTy() const
True if this is an instance of IntegerType.
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)
std::vector< BlockT * >::const_iterator block_iterator
Value * getCondition() const
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
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)...
block_iterator block_end() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Value * getCondition() const
Captures loop safety information.
void registerAssumption(CallInst *CI)
Add an .assume intrinsic to this function's cache.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Represents a single loop in the control flow graph.
SymbolTableList< BasicBlock >::iterator eraseFromParent()
Unlink 'this' from the containing function and delete it.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
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)
CaseIt case_default()
Returns an iterator that points to the default case.
unsigned getNumCases() const
Return the number of 'cases' in this switch instruction, excluding the default case.
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...
void analyzeBasicBlock(const BasicBlock *BB, const TargetTransformInfo &TTI, const SmallPtrSetImpl< const Value * > &EphValues)
Add information about a block to the current state.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVMContext & getContext() const
Get the context in which this basic block lives.
Module * getParent()
Get the module that this global value is contained inside of...
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.
BasicBlockT * getCaseSuccessor() const
Resolves successor for current case.
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 ...
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the edge connecting specified block.
block_iterator block_begin() const
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...
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)...
void setIncomingValue(unsigned i, Value *V)
unsigned NumInsts
Number of instructions in the analyzed blocks.
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. ...
static BasicBlock * isTrivialLoopExitBlock(Loop *L, BasicBlock *BB)
Return true if the specified block unconditionally leads to an exit from the specified loop...
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
const BasicBlock * getParent() const
A wrapper class for inspecting calls to intrinsic functions.