14 #ifndef LLVM_ANALYSIS_LOOPINFOIMPL_H 15 #define LLVM_ANALYSIS_LOOPINFOIMPL_H 33 template <
class BlockT,
class LoopT>
36 assert(!isInvalid() &&
"Loop not in a valid state!");
37 for (
const auto BB : blocks())
38 for (
auto *Succ : children<BlockT *>(BB))
48 template <
class BlockT,
class LoopT>
50 assert(!isInvalid() &&
"Loop not in a valid state!");
52 getExitingBlocks(ExitingBlocks);
53 if (ExitingBlocks.
size() == 1)
54 return ExitingBlocks[0];
61 template <
class BlockT,
class LoopT>
64 assert(!isInvalid() &&
"Loop not in a valid state!");
65 for (
const auto BB : blocks())
66 for (
auto *Succ : children<BlockT *>(BB))
74 template <
class BlockT,
class LoopT>
76 assert(!isInvalid() &&
"Loop not in a valid state!");
78 getExitBlocks(ExitBlocks);
79 if (ExitBlocks.
size() == 1)
84 template <
class BlockT,
class LoopT>
89 getUniqueExitBlocks(UniqueExitBlocks);
90 for (BlockT *EB : UniqueExitBlocks)
100 template <
class BlockT,
class LoopT,
typename PredicateT>
104 assert(!L->isInvalid() &&
"Loop not in a valid state!");
107 for (BlockT *BB : Filtered)
108 for (BlockT *
Successor : children<BlockT *>(BB))
114 template <
class BlockT,
class LoopT>
118 [](
const BlockT *BB) {
return true; });
121 template <
class BlockT,
class LoopT>
124 const BlockT *Latch = getLoopLatch();
125 assert(Latch &&
"Latch block must exists");
127 [Latch](
const BlockT *BB) {
return BB != Latch; });
130 template <
class BlockT,
class LoopT>
133 getUniqueExitBlocks(UniqueExitBlocks);
134 if (UniqueExitBlocks.
size() == 1)
135 return UniqueExitBlocks[0];
140 template <
class BlockT,
class LoopT>
143 assert(!isInvalid() &&
"Loop not in a valid state!");
144 for (
const auto BB : blocks())
145 for (
auto *Succ : children<BlockT *>(BB))
159 template <
class BlockT,
class LoopT>
161 assert(!isInvalid() &&
"Loop not in a valid state!");
163 BlockT *Out = getLoopPredecessor();
168 if (!Out->isLegalToHoistInto())
173 typename BlockTraits::ChildIteratorType
SI = BlockTraits::child_begin(Out);
175 if (SI != BlockTraits::child_end(Out))
187 template <
class BlockT,
class LoopT>
189 assert(!isInvalid() &&
"Loop not in a valid state!");
191 BlockT *Out =
nullptr;
194 BlockT *Header = getHeader();
197 if (Out && Out != Pred)
208 template <
class BlockT,
class LoopT>
210 assert(!isInvalid() &&
"Loop not in a valid state!");
211 BlockT *Header = getHeader();
212 BlockT *Latch =
nullptr;
234 template <
class BlockT,
class LoopT>
237 assert(!isInvalid() &&
"Loop not in a valid state!");
239 if (!Blocks.empty()) {
240 auto SameHeader = LIB[getHeader()];
241 assert(
contains(SameHeader) && getHeader() == SameHeader->getHeader() &&
242 "Incorrect LI specified for this loop!");
245 assert(NewBB &&
"Cannot add a null basic block to the loop!");
246 assert(!LIB[NewBB] &&
"BasicBlock already in the loop!");
248 LoopT *L =
static_cast<LoopT *
>(
this);
251 LIB.BBMap[NewBB] = L;
255 L->addBlockEntry(NewBB);
256 L = L->getParentLoop();
264 template <
class BlockT,
class LoopT>
267 assert(!isInvalid() &&
"Loop not in a valid state!");
268 assert(OldChild->ParentLoop ==
this &&
"This loop is already broken!");
269 assert(!NewChild->ParentLoop &&
"NewChild already has a parent!");
270 typename std::vector<LoopT *>::iterator
I =
find(SubLoops, OldChild);
271 assert(I != SubLoops.end() &&
"OldChild not in loop!");
273 OldChild->ParentLoop =
nullptr;
274 NewChild->ParentLoop =
static_cast<LoopT *
>(
this);
278 template <
class BlockT,
class LoopT>
280 assert(!isInvalid() &&
"Loop not in a valid state!");
282 assert(!Blocks.empty() &&
"Loop header is missing");
286 getExitBlocks(ExitBBs);
288 VisitSet.
insert(ExitBBs.begin(), ExitBBs.end());
297 for (; BI != BE; ++BI) {
302 [&](BlockT *
B) {
return contains(B); }) &&
303 "Loop block has no in-loop successors!");
307 [&](BlockT *B) {
return contains(B); }) &&
308 "Loop block has no in-loop predecessors!");
318 if (BB == getHeader()) {
319 assert(!OutsideLoopPreds.
empty() &&
"Loop is unreachable!");
320 }
else if (!OutsideLoopPreds.
empty()) {
324 BlockT *EntryBB = &BB->getParent()->front();
326 for (
unsigned i = 0,
e = OutsideLoopPreds.
size(); i !=
e; ++i)
327 assert(CB != OutsideLoopPreds[i] &&
328 "Loop has multiple entry points!");
331 "Loop contains function entry block!");
336 if (VisitedBBs.
size() != getNumBlocks()) {
337 dbgs() <<
"The following blocks are unreachable in the loop: ";
338 for (
auto BB : Blocks) {
339 if (!VisitedBBs.
count(BB)) {
340 dbgs() << *BB <<
"\n";
343 assert(
false &&
"Unreachable block in loop");
349 for (
block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
352 "Loop does not contain all the blocks of a subloop!");
358 "Loop is not a subloop of its parent!");
364 template <
class BlockT,
class LoopT>
367 assert(!isInvalid() &&
"Loop not in a valid state!");
368 Loops->
insert(static_cast<const LoopT *>(
this));
373 (*I)->verifyLoopNest(Loops);
376 template <
class BlockT,
class LoopT>
378 bool Verbose)
const {
380 if (static_cast<const LoopT *>(
this)->isAnnotatedParallel())
382 OS <<
"Loop at depth " << getLoopDepth() <<
" containing: ";
384 BlockT *
H = getHeader();
385 for (
unsigned i = 0; i < getBlocks().size(); ++i) {
386 BlockT *BB = getBlocks()[i];
390 BB->printAsOperand(OS,
false);
398 if (isLoopExiting(BB))
406 (*I)->print(OS, Depth + 2);
417 template <
class BlockT,
class LoopT>
423 unsigned NumBlocks = 0;
424 unsigned NumSubloops = 0;
427 std::vector<BlockT *> ReverseCFGWorklist(Backedges.
begin(), Backedges.
end());
428 while (!ReverseCFGWorklist.empty()) {
429 BlockT *PredBB = ReverseCFGWorklist.back();
430 ReverseCFGWorklist.pop_back();
440 if (PredBB == L->getHeader())
443 ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
444 InvBlockTraits::child_begin(PredBB),
445 InvBlockTraits::child_end(PredBB));
448 while (LoopT *Parent = Subloop->getParentLoop())
456 Subloop->setParentLoop(L);
458 NumBlocks += Subloop->getBlocksVector().capacity();
459 PredBB = Subloop->getHeader();
466 ReverseCFGWorklist.push_back(Pred);
470 L->getSubLoopsVector().reserve(NumSubloops);
471 L->reserveBlocks(NumBlocks);
477 typedef typename BlockTraits::ChildIteratorType SuccIterTy;
491 template <
class BlockT,
class LoopT>
500 template <
class BlockT,
class LoopT>
502 LoopT *Subloop = LI->getLoopFor(Block);
503 if (Subloop && Block == Subloop->getHeader()) {
506 if (Subloop->getParentLoop())
507 Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
509 LI->addTopLevelLoop(Subloop);
513 Subloop->reverseBlock(1);
515 Subloop->getSubLoopsVector().end());
517 Subloop = Subloop->getParentLoop();
519 for (; Subloop; Subloop = Subloop->getParentLoop())
520 Subloop->addBlockEntry(Block);
537 template <
class BlockT,
class LoopT>
543 BlockT *Header = DomNode->getBlock();
549 if (DomTree.
dominates(Header, Backedge) &&
555 if (!Backedges.
empty()) {
556 LoopT *L = AllocateLoop(Header);
566 template <
class BlockT,
class LoopT>
574 for (LoopT *RootL :
reverse(*
this)) {
575 auto PreOrderLoopsInRootL = RootL->getLoopsInPreorder();
576 PreOrderLoops.
append(PreOrderLoopsInRootL.begin(),
577 PreOrderLoopsInRootL.end());
580 return PreOrderLoops;
583 template <
class BlockT,
class LoopT>
592 for (LoopT *RootL : *
this) {
594 "Must start with an empty preorder walk worklist.");
600 PreOrderWorklist.
append(L->begin(), L->end());
602 }
while (!PreOrderWorklist.
empty());
605 return PreOrderLoops;
609 template <
class BlockT,
class LoopT>
611 for (
unsigned i = 0; i < TopLevelLoops.size(); ++i)
612 TopLevelLoops[i]->
print(OS);
615 E = BBMap.end();
I !=
E; ++
I)
616 OS <<
"BB '" <<
I->first->getName() <<
"' level = " 617 <<
I->second->getLoopDepth() <<
"\n";
621 template <
typename T>
628 template <
class BlockT,
class LoopT>
632 LoopHeaders[L.getHeader()] = &L;
638 template <
class BlockT,
class LoopT>
641 BlockT *
H = L->getHeader();
642 BlockT *OtherH = OtherL->getHeader();
644 "Mismatched headers even though found in the same map entry!");
646 assert(L->getLoopDepth() == OtherL->getLoopDepth() &&
647 "Mismatched loop depth!");
648 const LoopT *ParentL = L, *OtherParentL = OtherL;
650 assert(ParentL->getHeader() == OtherParentL->getHeader() &&
651 "Mismatched parent loop headers!");
652 ParentL = ParentL->getParentLoop();
653 OtherParentL = OtherParentL->getParentLoop();
656 for (
const LoopT *SubL : *L) {
657 BlockT *SubH = SubL->getHeader();
658 const LoopT *OtherSubL = OtherLoopHeaders.
lookup(SubH);
659 assert(OtherSubL &&
"Inner loop is missing in computed loop info!");
660 OtherLoopHeaders.
erase(SubH);
664 std::vector<BlockT *> BBs = L->getBlocks();
665 std::vector<BlockT *> OtherBBs = OtherL->getBlocks();
667 "Mismatched basic blocks in the loops!");
673 [&OtherBlocksSet](
const BlockT *BB) {
674 return OtherBlocksSet.
count(BB);
676 "Mismatched basic blocks in BlocksSets!");
680 template <
class BlockT,
class LoopT>
685 assert(!(*I)->getParentLoop() &&
"Top-level loop has a parent!");
686 (*I)->verifyLoopNest(&Loops);
691 for (
auto &
Entry : BBMap) {
692 const BlockT *BB =
Entry.first;
693 LoopT *L =
Entry.second;
695 assert(L->contains(BB) &&
"orphaned block");
696 for (LoopT *ChildLoop : *L)
697 assert(!ChildLoop->contains(BB) &&
698 "BBMap should point to the innermost loop containing BB");
709 for (LoopT *L : OtherLI)
715 for (LoopT *L : *
this) {
716 BlockT *Header = L->getHeader();
717 const LoopT *OtherL = OtherLoopHeaders.
lookup(Header);
718 assert(OtherL &&
"Top level loop is missing in computed loop info!");
720 OtherLoopHeaders.
erase(Header);
727 if (!OtherLoopHeaders.
empty()) {
728 for (
const auto &HeaderAndLoop : OtherLoopHeaders)
729 dbgs() <<
"Found new loop: " << *HeaderAndLoop.second <<
"\n";
const_iterator end(StringRef path)
Get end iterator over path.
reference emplace_back(ArgTypes &&... Args)
iterator_range< typename GraphTraits< GraphType >::ChildIteratorType > children(const typename GraphTraits< GraphType >::NodeRef &G)
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
This class represents lattice values for constants.
static void compareLoops(const LoopT *L, const LoopT *OtherL, DenseMap< BlockT *, const LoopT *> &OtherLoopHeaders)
bool compareVectors(std::vector< T > &BB1, std::vector< T > &BB2)
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
Implements a dense probed hash-table based set.
void push_back(const T &Elt)
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
static void discoverAndMapSubloop(LoopT *L, ArrayRef< BlockT *> Backedges, LoopInfoBase< BlockT, LoopT > *LI, const DomTreeBase< BlockT > &DomTree)
Stable LoopInfo Analysis - Build a loop tree using stable iterators so the result does / not depend o...
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
bool isReachableFromEntry(const NodeT *A) const
isReachableFromEntry - Return true if A is dominated by the entry block of the function containing it...
void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild)
This is used when splitting loops up.
void insertIntoLoop(BlockT *Block)
Add a single Block to its ancestor loops in PostOrder.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
return AArch64::GPR64RegClass contains(Reg)
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.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
std::vector< Loop *>::const_iterator iterator
iterator/begin/end - The interface to the top-level loops in the current function.
void addInnerLoopsToHeadersMap(DenseMap< BlockT *, const LoopT *> &LoopHeaders, const LoopInfoBase< BlockT, LoopT > &LI, const LoopT &L)
void getExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all of the successor blocks of this loop.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
std::vector< Loop *>::const_iterator iterator
void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase< BlockT, LoopT > &LI)
This method is used by other analyses to update loop information.
void traverse(BlockT *EntryBlock)
Top-level driver for the forward DFS within the loop.
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Core dominator tree base class.
bool erase(const KeyT &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
PopulateLoopsDFS(LoopInfoBase< BlockT, LoopT > *li)
df_ext_iterator< T, SetTy > df_ext_end(const T &G, SetTy &S)
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
std::pair< iterator, bool > insert(const ValueT &V)
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.
df_ext_iterator< T, SetTy > df_ext_begin(const T &G, SetTy &S)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
iterator_range< po_iterator< T > > post_order(const T &G)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
BlockT * getUniqueExitBlock() const
If getUniqueExitBlocks would return exactly one block, return that block.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
void getUniqueNonLatchExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop except successors from Latch block are not considered...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
void sort(IteratorTy Start, IteratorTy End)
void getExitEdges(SmallVectorImpl< Edge > &ExitEdges) const
Return all pairs of (inside_block,outside_block).
BlockT * getLoopPredecessor() const
If the given loop's header has exactly one unique predecessor outside the loop, return it...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void print(raw_ostream &OS) const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
LLVM_NODISCARD T pop_back_val()
std::pair< iterator, bool > insert(NodeRef N)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void getUniqueExitBlocksHelper(const LoopT *L, SmallVectorImpl< BlockT *> &ExitBlocks, PredicateT Pred)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
bool dominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
dominates - Returns true iff A dominates B.
void verifyLoopNest(DenseSet< const LoopT *> *Loops) const
Verify loop structure of this loop and all nested loops.
LLVM_NODISCARD bool empty() const
SmallVector< LoopT *, 4 > getLoopsInReverseSiblingPreorder()
Return all of the loops in the function in preorder across the loop nests, with siblings in reverse p...
void changeLoopFor(BlockT *BB, LoopT *L)
Change the top-level loop that contains BB to the specified loop.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
LLVM_NODISCARD bool empty() const
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
SmallVector< LoopT *, 4 > getLoopsInPreorder()
Return all of the loops in the function in preorder across the loop nests, with siblings in forward p...
iterator_range< df_iterator< T > > depth_first(const T &G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const Function * getParent(const Value *V)
This class implements an extremely fast bulk output stream that can only output to a stream...
void verifyLoop() const
Verify loop structure.
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
UnaryPredicate for_each(R &&Range, UnaryPredicate P)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly...
BlockT * getExitingBlock() const
If getExitingBlocks would return exactly one block, return that block.
Populate all loop data in a stable order during a single forward DFS.
This class builds and contains all of the top-level loop structures in the specified function...
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.