42 #ifdef EXPENSIVE_CHECKS
49 cl::desc(
"Verify loop info (time consuming)"));
113 BasicBlock *Incoming =
nullptr, *Backedge =
nullptr;
116 "Loop must have at least one backedge!");
118 if (PI ==
pred_end(H))
return nullptr;
120 if (PI !=
pred_end(H))
return nullptr;
138 Inc->getOperand(0) == PN)
139 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
153 if (
I.getType()->isTokenTy())
156 for (
const Use &U :
I.uses()) {
157 const Instruction *UI = cast<Instruction>(U.getUser());
159 if (
const PHINode *
P = dyn_cast<PHINode>(UI))
160 UserBB =
P->getIncomingBlock(U);
166 if (UserBB != &BB && !L.
contains(UserBB) &&
201 if (isa<IndirectBrInst>(BB->getTerminator()))
206 if (CS.cannotDuplicate())
218 "The loop should have no single latch at this point");
238 else if (MD != LoopID)
249 assert(LoopID &&
"Loop ID should not be null");
251 assert(LoopID->
getOperand(0) == LoopID &&
"Loop ID should refer to itself");
272 if (!DesiredLoopIdMetadata)
282 if (!
I.mayReadOrWriteMemory())
295 bool LoopIdMDFound =
false;
297 if (MDOp == DesiredLoopIdMetadata) {
298 LoopIdMDFound =
true;
321 for (
unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
322 if (
DILocation *
L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
336 if (
DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
342 return LocRange(HeadBB->getTerminator()->getDebugLoc());
363 "getUniqueExitBlocks assumes the loop has canonical form exits!");
367 SwitchExitBlocks.
clear();
405 if (UniqueExitBlocks.
size() == 1)
406 return UniqueExitBlocks[0];
410 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
427 class UnloopUpdater {
445 Unloop(*UL), LI(LInfo),
DFS(UL), FoundIB(
false) {}
447 void updateBlockParents();
449 void removeBlocksFromAncestors();
451 void updateSubloopParents();
460 void UnloopUpdater::updateBlockParents() {
461 if (Unloop.getNumBlocks()) {
467 Loop *
L = LI->getLoopFor(POI);
468 Loop *NL = getNearestLoop(POI, L);
473 "uninitialized successor");
474 LI->changeLoopFor(POI, NL);
479 assert((FoundIB || Unloop.contains(L)) &&
"uninitialized successor");
485 bool Changed = FoundIB;
486 for (
unsigned NIters = 0; Changed; ++NIters) {
487 assert(NIters < Unloop.getNumBlocks() &&
"runaway iterative algorithm");
493 POE =
DFS.endPostorder(); POI != POE; ++POI) {
495 Loop *L = LI->getLoopFor(*POI);
496 Loop *NL = getNearestLoop(*POI, L);
499 "uninitialized successor");
500 LI->changeLoopFor(*POI, NL);
508 void UnloopUpdater::removeBlocksFromAncestors() {
512 BE = Unloop.block_end(); BI != BE; ++BI) {
513 Loop *OuterParent = LI->getLoopFor(*BI);
514 if (Unloop.contains(OuterParent)) {
517 OuterParent = SubloopParents[OuterParent];
523 assert(OldParent &&
"new loop is not an ancestor of the original");
524 OldParent->removeBlockFromLoop(*BI);
530 void UnloopUpdater::updateSubloopParents() {
531 while (!Unloop.empty()) {
532 Loop *Subloop = *std::prev(Unloop.end());
535 assert(SubloopParents.count(Subloop) &&
"DFS failed to visit subloop");
536 if (
Loop *Parent = SubloopParents[Subloop])
537 Parent->addChildLoop(Subloop);
539 LI->addTopLevelLoop(Subloop);
552 Loop *NearLoop = BBLoop;
554 Loop *Subloop =
nullptr;
555 if (NearLoop != &Unloop && Unloop.
contains(NearLoop)) {
560 assert(Subloop &&
"subloop is not an ancestor of the original loop");
563 NearLoop = SubloopParents.insert({Subloop, &Unloop}).
first->second;
568 assert(!Subloop &&
"subloop blocks must have a successor");
571 for (; I !=
E; ++
I) {
575 Loop *L = LI->getLoopFor(*I);
579 assert((FoundIB || !
DFS.hasPostorder(*I)) &&
"should have seen IB");
582 if (L != &Unloop && Unloop.
contains(L)) {
591 L = SubloopParents[
L];
602 if (NearLoop == &Unloop || !NearLoop || NearLoop->
contains(L))
606 SubloopParents[Subloop] = NearLoop;
628 RemovedLoops.push_back(Unloop);
648 assert(I !=
end() &&
"Couldn't find loop");
656 while (!Unloop->
empty())
664 UnloopUpdater Updater(Unloop,
this);
665 Updater.updateBlockParents();
668 Updater.removeBlocksFromAncestors();
671 Updater.updateSubloopParents();
676 assert(I != ParentLoop->
end() &&
"Couldn't find loop");
706 for (
auto *Block : L.
blocks())
710 OS <<
"Printing <null> block";
724 bool LoopInfoWrapperPass::runOnFunction(
Function &) {
726 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
737 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
769 POE = Traversal.
end(); POI != POE; ++POI) ;
void push_back(const T &Elt)
Tracking metadata reference owned by Metadata.
LoopInfo run(Function &F, FunctionAnalysisManager &AM)
BasicBlock * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LoopT * removeLoop(iterator I)
This removes the specified top-level loop from this loop info object.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
A Module instance is used to store all the information related to an LLVM module. ...
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
unsigned getNumOperands() const
Return number of MDNode operands.
void invalidate()
Invalidate the loop, indicating that it is no longer a loop.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
LoopT * getParentLoop() const
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Analysis pass which computes a DominatorTree.
void print(raw_ostream &OS) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
BlockT * getHeader() const
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
std::vector< LoopT * >::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
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)
Traverse the blocks in a loop using a depth-first search.
A Use represents the edge between a Value definition and its users.
POTIterator begin()
Postorder traversal over the graph.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Analysis pass that exposes the LoopInfo for a function.
void print(raw_ostream &O, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
void getExitBlocks(SmallVectorImpl< BlockT * > &ExitBlocks) const
Return all of the successor blocks of this loop.
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 getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool mayReadFromMemory() const
Return true if this instruction may read memory.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
static cl::opt< bool, true > VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo), cl::desc("Verify loop info (time consuming)"))
void perform(LoopInfo *LI)
Traverse the loop blocks and store the DFS result.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Interval::succ_iterator succ_end(Interval *I)
iterator_range< block_iterator > blocks() const
Core dominator tree base class.
Function Alias Analysis false
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
LLVM Basic Block Representation.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const DebugLoc & getStart() const
void analyze(const DominatorTreeBase< BlockT, false > &DomTree)
Create the loop forest using a stable algorithm.
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...
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
Represent the analysis usage information of a pass.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
Interval::pred_iterator pred_end(Interval *I)
void markAsRemoved(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
void getUniqueExitBlocks(SmallVectorImpl< BasicBlock * > &ExitBlocks) const
Return all unique successor blocks of this loop.
A range representing the start and end location of a loop.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
const MDOperand & getOperand(unsigned I) const
Iterator for intrusive lists based on ilist_node.
INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass,"loops","Natural Loop Information", true, true) INITIALIZE_PASS_END(LoopInfoWrapperPass
This is the shared class of boolean and integer constants.
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 isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
pred_range predecessors(BasicBlock *BB)
void addTopLevelLoop(LoopT *New)
This adds the specified loop to the collection of top-level loops.
bool VerifyLoopInfo
Enables verification of loop info.
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.
Store the result of a depth first search within basic blocks contained by a single loop...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
void setPreservesAll()
Set by analyses that do not transform their input at all.
std::vector< BlockT * >::const_iterator block_iterator
Represents analyses that only rely on functions' control flow.
block_iterator block_end() const
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Represents a single loop in the control flow graph.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
std::vector< BasicBlock * >::const_iterator POIterator
Postorder list iterators.
LocRange getLocRange() const
Return the source code span of the loop.
op_range operands() const
API to communicate dependencies between analyses during invalidation.
bool isInvalid()
Return true if this loop is no longer valid.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over \<a particular IR unit\>" (e...
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.
succ_range successors(BasicBlock *BB)
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
This class implements an extremely fast bulk output stream that can only output to a stream...
block_iterator block_begin() const
The legacy pass manager's analysis pass to compute loop information.
A container for analyses that lazily runs them and caches their results.
void print(raw_ostream &OS, unsigned Depth=0, bool Verbose=false) const
Print loop with all the BBs inside it.
Legacy analysis pass which computes a DominatorTree.
std::vector< LoopT * >::const_iterator iterator
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...
This header defines various interfaces for pass management in LLVM.
void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
A special type used by analysis passes to provide an address that identifies that particular analysis...
LocationClass< Ty > location(Ty &L)
const BasicBlock * getParent() const
static bool isBlockInLCSSAForm(const Loop &L, const BasicBlock &BB, DominatorTree &DT)
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.