24 #include "llvm/Config/llvm-config.h" 45 #ifdef EXPENSIVE_CHECKS 48 bool llvm::VerifyLoopInfo =
false;
116 BasicBlock *Incoming =
nullptr, *Backedge =
nullptr;
118 assert(PI !=
pred_end(H) &&
"Loop must have at least one backedge!");
142 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
156 if (
I.getType()->isTokenTy())
159 for (
const Use &U :
I.uses()) {
160 const Instruction *UI = cast<Instruction>(U.getUser());
162 if (
const PHINode *
P = dyn_cast<PHINode>(UI))
163 UserBB =
P->getIncomingBlock(U);
169 if (UserBB != &BB && !L.
contains(UserBB) &&
204 if (isa<IndirectBrInst>(BB->getTerminator()))
209 if (CS.cannotDuplicate())
230 else if (MD != LoopID)
241 "Loop ID needs at least one operand");
243 "Loop ID should refer to itself");
265 for (
unsigned i = 1, ie = LoopID->
getNumOperands(); i < ie; ++i) {
266 bool IsUnrollMetadata =
false;
272 if (!IsUnrollMetadata)
293 if (!DesiredLoopIdMetadata)
296 MDNode *ParallelAccesses =
299 ParallelAccessGroups;
300 if (ParallelAccesses) {
302 MDNode *AccGroup = cast<MDNode>(MD.get());
304 "List item must be an access group");
305 ParallelAccessGroups.
insert(AccGroup);
316 if (!
I.mayReadOrWriteMemory())
320 auto ContainsAccessGroup = [&ParallelAccessGroups](
MDNode *AG) ->
bool {
321 if (AG->getNumOperands() == 0) {
323 return ParallelAccessGroups.
count(AG);
326 for (
const MDOperand &AccessListItem : AG->operands()) {
327 MDNode *AccGroup = cast<MDNode>(AccessListItem.get());
329 "List item must be an access group");
330 if (ParallelAccessGroups.
count(AccGroup))
336 if (ContainsAccessGroup(AccessGroup))
350 bool LoopIdMDFound =
false;
352 if (MDOp == DesiredLoopIdMetadata) {
353 LoopIdMDFound =
true;
374 for (
unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
375 if (
DILocation *L = dyn_cast<DILocation>(LoopID->getOperand(i))) {
389 if (
DebugLoc DL = PHeadBB->getTerminator()->getDebugLoc())
395 return LocRange(HeadBB->getTerminator()->getDebugLoc());
400 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 415 class UnloopUpdater {
433 : Unloop(*UL), LI(LInfo),
DFS(UL), FoundIB(
false) {}
435 void updateBlockParents();
437 void removeBlocksFromAncestors();
439 void updateSubloopParents();
448 void UnloopUpdater::updateBlockParents() {
449 if (Unloop.getNumBlocks()) {
455 Loop *L = LI->getLoopFor(POI);
456 Loop *NL = getNearestLoop(POI, L);
461 "uninitialized successor");
462 LI->changeLoopFor(POI, NL);
466 assert((FoundIB || Unloop.contains(L)) &&
"uninitialized successor");
472 bool Changed = FoundIB;
473 for (
unsigned NIters = 0; Changed; ++NIters) {
474 assert(NIters < Unloop.getNumBlocks() &&
"runaway iterative algorithm");
480 POE =
DFS.endPostorder();
483 Loop *L = LI->getLoopFor(*POI);
484 Loop *NL = getNearestLoop(*POI, L);
487 "uninitialized successor");
488 LI->changeLoopFor(*POI, NL);
496 void UnloopUpdater::removeBlocksFromAncestors() {
501 Loop *OuterParent = LI->getLoopFor(*BI);
502 if (Unloop.contains(OuterParent)) {
505 OuterParent = SubloopParents[OuterParent];
511 assert(OldParent &&
"new loop is not an ancestor of the original");
512 OldParent->removeBlockFromLoop(*BI);
518 void UnloopUpdater::updateSubloopParents() {
519 while (!Unloop.empty()) {
520 Loop *Subloop = *std::prev(Unloop.end());
523 assert(SubloopParents.count(Subloop) &&
"DFS failed to visit subloop");
524 if (
Loop *Parent = SubloopParents[Subloop])
525 Parent->addChildLoop(Subloop);
527 LI->addTopLevelLoop(Subloop);
540 Loop *NearLoop = BBLoop;
542 Loop *Subloop =
nullptr;
543 if (NearLoop != &Unloop && Unloop.
contains(NearLoop)) {
548 assert(Subloop &&
"subloop is not an ancestor of the original loop");
551 NearLoop = SubloopParents.insert({Subloop, &Unloop}).
first->second;
556 assert(!Subloop &&
"subloop blocks must have a successor");
559 for (; I !=
E; ++
I) {
563 Loop *L = LI->getLoopFor(*I);
567 assert((FoundIB || !
DFS.hasPostorder(*I)) &&
"should have seen IB");
570 if (L != &Unloop && Unloop.
contains(L)) {
579 L = SubloopParents[L];
590 if (NearLoop == &Unloop || !NearLoop || NearLoop->
contains(L))
594 SubloopParents[Subloop] = NearLoop;
624 if (getLoopFor(*
I) != Unloop)
629 changeLoopFor(*
I,
nullptr);
642 while (!Unloop->
empty())
650 UnloopUpdater Updater(Unloop,
this);
651 Updater.updateBlockParents();
654 Updater.removeBlocksFromAncestors();
657 Updater.updateSubloopParents();
662 assert(
I != ParentLoop->
end() &&
"Couldn't find loop");
694 OS << Banner <<
" (loop: ";
707 OS <<
"\n; Preheader:";
708 PreHeader->print(OS);
712 for (
auto *Block : L.
blocks())
716 OS <<
"Printing <null> block";
720 if (!ExitBlocks.
empty()) {
721 OS <<
"\n; Exit blocks";
722 for (
auto *Block : ExitBlocks)
726 OS <<
"Printing <null> block";
777 LI.analyze(getAnalysis<DominatorTreeWrapperPass>().getDomTree());
788 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
820 POE = Traversal.
end();
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.
This class represents lattice values for constants.
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.
void push_back(const T &Elt)
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
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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.
amdgpu Simplify well known AMD library false Value Value const Twine & Name
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 getLoopLatches(SmallVectorImpl< BasicBlock * > &LoopLatches) const
Return all loop latch blocks of this loop.
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 * findOptionMDForLoop(const Loop *TheLoop, StringRef Name)
Find string metadata for a 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
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.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
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)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
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.
iterator_range< decltype(adl_begin(std::declval< T >)))> drop_begin(T &&t, int n)
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.
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...
MDNode * findOptionMDForLoopID(MDNode *LoopID, StringRef Name)
Find and return the loop attribute node for the attribute Name in LoopID.
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.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
bool invalidate(Function &F, const PreservedAnalyses &PA, FunctionAnalysisManager::Invalidator &)
Handle invalidation explicitly.
LoopT * getParentLoop() const
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
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.
This file defines passes to print out IR in various granularities.
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.
succ_range successors(Instruction *I)
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.
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.
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)
bool isValidAsAccessGroup(MDNode *AccGroup)
Return whether an MDNode might represent an access group.
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...