24 #include "llvm/Config/llvm-config.h" 44 #ifdef EXPENSIVE_CHECKS 47 bool llvm::VerifyLoopInfo =
false;
115 BasicBlock *Incoming =
nullptr, *Backedge =
nullptr;
117 assert(PI !=
pred_end(H) &&
"Loop must have at least one backedge!");
141 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
155 if (
I.getType()->isTokenTy())
158 for (
const Use &U :
I.uses()) {
159 const Instruction *UI = cast<Instruction>(U.getUser());
161 if (
const PHINode *
P = dyn_cast<PHINode>(UI))
162 UserBB =
P->getIncomingBlock(U);
168 if (UserBB != &BB && !L.
contains(UserBB) &&
203 if (isa<IndirectBrInst>(BB->getTerminator()))
208 if (CS.cannotDuplicate())
220 "The loop should have no single latch at this point");
240 else if (MD != LoopID)
251 assert(LoopID &&
"Loop ID should not be null");
253 assert(LoopID->
getOperand(0) == LoopID &&
"Loop ID should refer to itself");
261 "The loop should have no single latch at this point");
280 for (
unsigned i = 1, ie = LoopID->
getNumOperands(); i < ie; ++i) {
281 bool IsUnrollMetadata =
false;
287 if (!IsUnrollMetadata)
308 if (!DesiredLoopIdMetadata)
318 if (!
I.mayReadOrWriteMemory())
331 bool LoopIdMDFound =
false;
333 if (MDOp == DesiredLoopIdMetadata) {
334 LoopIdMDFound =
true;
355 for (
unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
356 if (
DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
370 if (
DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
376 return LocRange(HeadBB->getTerminator()->getDebugLoc());
381 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 396 class UnloopUpdater {
414 : Unloop(*UL), LI(LInfo),
DFS(UL), FoundIB(
false) {}
416 void updateBlockParents();
418 void removeBlocksFromAncestors();
420 void updateSubloopParents();
429 void UnloopUpdater::updateBlockParents() {
430 if (Unloop.getNumBlocks()) {
436 Loop *L = LI->getLoopFor(POI);
437 Loop *NL = getNearestLoop(POI, L);
442 "uninitialized successor");
443 LI->changeLoopFor(POI, NL);
447 assert((FoundIB || Unloop.contains(L)) &&
"uninitialized successor");
453 bool Changed = FoundIB;
454 for (
unsigned NIters = 0; Changed; ++NIters) {
455 assert(NIters < Unloop.getNumBlocks() &&
"runaway iterative algorithm");
461 POE =
DFS.endPostorder();
464 Loop *L = LI->getLoopFor(*POI);
465 Loop *NL = getNearestLoop(*POI, L);
468 "uninitialized successor");
469 LI->changeLoopFor(*POI, NL);
477 void UnloopUpdater::removeBlocksFromAncestors() {
482 Loop *OuterParent = LI->getLoopFor(*BI);
483 if (Unloop.contains(OuterParent)) {
486 OuterParent = SubloopParents[OuterParent];
492 assert(OldParent &&
"new loop is not an ancestor of the original");
493 OldParent->removeBlockFromLoop(*BI);
499 void UnloopUpdater::updateSubloopParents() {
500 while (!Unloop.empty()) {
501 Loop *Subloop = *std::prev(Unloop.end());
504 assert(SubloopParents.count(Subloop) &&
"DFS failed to visit subloop");
505 if (
Loop *Parent = SubloopParents[Subloop])
506 Parent->addChildLoop(Subloop);
508 LI->addTopLevelLoop(Subloop);
521 Loop *NearLoop = BBLoop;
523 Loop *Subloop =
nullptr;
524 if (NearLoop != &Unloop && Unloop.
contains(NearLoop)) {
529 assert(Subloop &&
"subloop is not an ancestor of the original loop");
532 NearLoop = SubloopParents.insert({Subloop, &Unloop}).
first->second;
537 assert(!Subloop &&
"subloop blocks must have a successor");
540 for (; I !=
E; ++
I) {
544 Loop *L = LI->getLoopFor(*I);
548 assert((FoundIB || !
DFS.hasPostorder(*I)) &&
"should have seen IB");
551 if (L != &Unloop && Unloop.
contains(L)) {
560 L = SubloopParents[L];
571 if (NearLoop == &Unloop || !NearLoop || NearLoop->
contains(L))
575 SubloopParents[Subloop] = NearLoop;
605 if (getLoopFor(*
I) != Unloop)
610 changeLoopFor(*
I,
nullptr);
623 while (!Unloop->
empty())
631 UnloopUpdater Updater(Unloop,
this);
632 Updater.updateBlockParents();
635 Updater.removeBlocksFromAncestors();
638 Updater.updateSubloopParents();
643 assert(
I != ParentLoop->
end() &&
"Couldn't find loop");
675 OS << Banner <<
" (loop: ";
688 OS <<
"\n; Preheader:";
689 PreHeader->print(OS);
693 for (
auto *Block : L.
blocks())
697 OS <<
"Printing <null> block";
701 if (!ExitBlocks.
empty()) {
702 OS <<
"\n; Exit blocks";
703 for (
auto *Block : ExitBlocks)
707 OS <<
"Printing <null> block";
724 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
735 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
767 POE = Traversal.
end();
void push_back(const T &Elt)
Tracking metadata reference owned by Metadata.
LoopInfo run(Function &F, FunctionAnalysisManager &AM)
bool forcePrintModuleIR()
forcePrintModuleIR - returns true if IR printing passes should
BasicBlock * getLoopLatch() const
If there is a single latch block for this loop, return it.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Compute iterated dominance frontiers using a linear time algorithm.
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.
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
static MDString * get(LLVMContext &Context, StringRef Str)
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
LoopT * removeChildLoop(iterator I)
This removes the specified child from being a subloop of this loop.
BasicBlock * getLoopPreheader() const
If there is a preheader for this loop, return it.
LLVM_NODISCARD detail::scope_exit< typename std::decay< Callable >::type > make_scope_exit(Callable &&F)
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 all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass which computes a DominatorTree.
const MDOperand & getOperand(unsigned I) const
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
LLVMContext & getContext() const
Get the context in which this basic block lives.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
bool isInvalid() const
Return true if this loop is no longer valid.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
void print(raw_ostream &OS, unsigned Depth=0, bool Verbose=false) const
Print loop with all the BBs inside it.
iterator begin()
Instruction iterator methods.
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
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)
Traverse the blocks in a loop using a depth-first search.
static cl::opt< bool, true > VerifyLoopInfoX("verify-loop-info", cl::location(VerifyLoopInfo), cl::Hidden, cl::desc("Verify loop info (time consuming)"))
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.
POTIterator begin()
Postorder traversal over the graph.
std::vector< Loop *>::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
void erase(Loop *L)
Update LoopInfo after removing the last backedge from a loop.
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.
BasicBlock * 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 getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
std::vector< Loop *>::const_iterator iterator
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
op_range operands() const
void setLoopID(MDNode *LoopID) const
Set the llvm.loop loop id metadata for this loop.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
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)
StringRef getString() const
Core dominator tree base class.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
static bool runOnFunction(Function &F, bool PostInlining)
INITIALIZE_PASS_BEGIN(LoopInfoWrapperPass, "loops", "Natural Loop Information", true, true) INITIALIZE_PASS_END(LoopInfoWrapperPass
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.
LLVM Basic Block Representation.
This is an important class for using LLVM in a threaded context.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void setLoopAlreadyUnrolled()
Add llvm.loop.unroll.disable to this loop's loop id metadata.
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...
Represent the analysis usage information of a pass.
Interval::pred_iterator pred_end(Interval *I)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
DebugLoc getStartLoc() const
Return the debug location of the start of this loop.
A range representing the start and end location of a loop.
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
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
bool contains(const Loop *L) const
Return true if the specified loop is contained within in this loop.
Iterator for intrusive lists based on ilist_node.
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 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.
PHINode * getCanonicalInductionVariable() const
Check to see if the loop has a canonical induction variable: an integer recurrence that starts at 0 a...
Store the result of a depth first search within basic blocks contained by a single loop...
LocRange getLocRange() const
Return the source code span of the loop.
void setPreservesAll()
Set by analyses that do not transform their input at all.
Represents analyses that only rely on functions' control flow.
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
LoopT * getParentLoop() const
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
MDNode * getLoopID() const
Return the llvm.loop loop id metadata node for this loop if it is present.
const DebugLoc & getStart() const
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
std::vector< BasicBlock * >::const_iterator POIterator
Postorder list iterators.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
block_iterator block_end() const
bool isSafeToClone() const
Return true if the loop body is safe to clone in practice.
API to communicate dependencies between analyses during invalidation.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over <a particular IR unit>" (e...
bool isAnnotatedParallel() const
Returns true if the loop is annotated parallel.
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.
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...
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
The legacy pass manager's analysis pass to compute loop information.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
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.
unsigned getNumOperands() const
Return number of MDNode operands.
iterator_range< block_iterator > blocks() const
void printLoop(Loop &L, raw_ostream &OS, const std::string &Banner="")
Function to print a loop's contents as LLVM's text IR assembly.
block_iterator block_begin() const
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...