1 //===- llvm/Analysis/LoopInfoImpl.h - Natural Loop Calculator ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is the generic implementation of LoopInfo used for both Loops and
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_ANALYSIS_LOOPINFOIMPL_H
16 #define LLVM_ANALYSIS_LOOPINFOIMPL_H
18 #include "llvm/ADT/DepthFirstIterator.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/SetVector.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/IR/Dominators.h"
27 //===----------------------------------------------------------------------===//
28 // APIs for simple analysis of the loop. See header notes.
30 /// getExitingBlocks - Return all blocks inside the loop that have successors
31 /// outside of the loop. These are the blocks _inside of the current loop_
32 /// which branch out. The returned list is always unique.
34 template<class BlockT, class LoopT>
35 void LoopBase<BlockT, LoopT>::
36 getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
37 typedef GraphTraits<BlockT*> BlockTraits;
38 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
39 for (typename BlockTraits::ChildIteratorType I =
40 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
43 // Not in current loop? It must be an exit block.
44 ExitingBlocks.push_back(*BI);
49 /// getExitingBlock - If getExitingBlocks would return exactly one block,
50 /// return that block. Otherwise return null.
51 template<class BlockT, class LoopT>
52 BlockT *LoopBase<BlockT, LoopT>::getExitingBlock() const {
53 SmallVector<BlockT*, 8> ExitingBlocks;
54 getExitingBlocks(ExitingBlocks);
55 if (ExitingBlocks.size() == 1)
56 return ExitingBlocks[0];
60 /// getExitBlocks - Return all of the successor blocks of this loop. These
61 /// are the blocks _outside of the current loop_ which are branched to.
63 template<class BlockT, class LoopT>
64 void LoopBase<BlockT, LoopT>::
65 getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
66 typedef GraphTraits<BlockT*> BlockTraits;
67 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
68 for (typename BlockTraits::ChildIteratorType I =
69 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
72 // Not in current loop? It must be an exit block.
73 ExitBlocks.push_back(*I);
76 /// getExitBlock - If getExitBlocks would return exactly one block,
77 /// return that block. Otherwise return null.
78 template<class BlockT, class LoopT>
79 BlockT *LoopBase<BlockT, LoopT>::getExitBlock() const {
80 SmallVector<BlockT*, 8> ExitBlocks;
81 getExitBlocks(ExitBlocks);
82 if (ExitBlocks.size() == 1)
87 /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
88 template<class BlockT, class LoopT>
89 void LoopBase<BlockT, LoopT>::
90 getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
91 typedef GraphTraits<BlockT*> BlockTraits;
92 for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
93 for (typename BlockTraits::ChildIteratorType I =
94 BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
97 // Not in current loop? It must be an exit block.
98 ExitEdges.push_back(Edge(*BI, *I));
101 /// getLoopPreheader - If there is a preheader for this loop, return it. A
102 /// loop has a preheader if there is only one edge to the header of the loop
103 /// from outside of the loop. If this is the case, the block branching to the
104 /// header of the loop is the preheader node.
106 /// This method returns null if there is no preheader for the loop.
108 template<class BlockT, class LoopT>
109 BlockT *LoopBase<BlockT, LoopT>::getLoopPreheader() const {
110 // Keep track of nodes outside the loop branching to the header...
111 BlockT *Out = getLoopPredecessor();
112 if (!Out) return nullptr;
114 // Make sure there is only one exit out of the preheader.
115 typedef GraphTraits<BlockT*> BlockTraits;
116 typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
118 if (SI != BlockTraits::child_end(Out))
119 return nullptr; // Multiple exits from the block, must not be a preheader.
121 // The predecessor has exactly one successor, so it is a preheader.
125 /// getLoopPredecessor - If the given loop's header has exactly one unique
126 /// predecessor outside the loop, return it. Otherwise return null.
127 /// This is less strict that the loop "preheader" concept, which requires
128 /// the predecessor to have exactly one successor.
130 template<class BlockT, class LoopT>
131 BlockT *LoopBase<BlockT, LoopT>::getLoopPredecessor() const {
132 // Keep track of nodes outside the loop branching to the header...
133 BlockT *Out = nullptr;
135 // Loop over the predecessors of the header node...
136 BlockT *Header = getHeader();
137 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
138 for (typename InvBlockTraits::ChildIteratorType PI =
139 InvBlockTraits::child_begin(Header),
140 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
141 typename InvBlockTraits::NodeRef N = *PI;
142 if (!contains(N)) { // If the block is not in the loop...
144 return nullptr; // Multiple predecessors outside the loop
149 // Make sure there is only one exit out of the preheader.
150 assert(Out && "Header of loop has no predecessors from outside loop?");
154 /// getLoopLatch - If there is a single latch block for this loop, return it.
155 /// A latch block is a block that contains a branch back to the header.
156 template<class BlockT, class LoopT>
157 BlockT *LoopBase<BlockT, LoopT>::getLoopLatch() const {
158 BlockT *Header = getHeader();
159 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
160 typename InvBlockTraits::ChildIteratorType PI =
161 InvBlockTraits::child_begin(Header);
162 typename InvBlockTraits::ChildIteratorType PE =
163 InvBlockTraits::child_end(Header);
164 BlockT *Latch = nullptr;
165 for (; PI != PE; ++PI) {
166 typename InvBlockTraits::NodeRef N = *PI;
168 if (Latch) return nullptr;
176 //===----------------------------------------------------------------------===//
177 // APIs for updating loop information after changing the CFG
180 /// addBasicBlockToLoop - This method is used by other analyses to update loop
181 /// information. NewBB is set to be a new member of the current loop.
182 /// Because of this, it is added as a member of all parent loops, and is added
183 /// to the specified LoopInfo object as being in the current basic block. It
184 /// is not valid to replace the loop header with this method.
186 template<class BlockT, class LoopT>
187 void LoopBase<BlockT, LoopT>::
188 addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
190 if (!Blocks.empty()) {
191 auto SameHeader = LIB[getHeader()];
192 assert(contains(SameHeader) && getHeader() == SameHeader->getHeader()
193 && "Incorrect LI specified for this loop!");
196 assert(NewBB && "Cannot add a null basic block to the loop!");
197 assert(!LIB[NewBB] && "BasicBlock already in the loop!");
199 LoopT *L = static_cast<LoopT *>(this);
201 // Add the loop mapping to the LoopInfo object...
202 LIB.BBMap[NewBB] = L;
204 // Add the basic block to this loop and all parent loops...
206 L->addBlockEntry(NewBB);
207 L = L->getParentLoop();
211 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
212 /// the OldChild entry in our children list with NewChild, and updates the
213 /// parent pointer of OldChild to be null and the NewChild to be this loop.
214 /// This updates the loop depth of the new child.
215 template<class BlockT, class LoopT>
216 void LoopBase<BlockT, LoopT>::
217 replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild) {
218 assert(OldChild->ParentLoop == this && "This loop is already broken!");
219 assert(!NewChild->ParentLoop && "NewChild already has a parent!");
220 typename std::vector<LoopT *>::iterator I = find(SubLoops, OldChild);
221 assert(I != SubLoops.end() && "OldChild not in loop!");
223 OldChild->ParentLoop = nullptr;
224 NewChild->ParentLoop = static_cast<LoopT *>(this);
227 /// verifyLoop - Verify loop structure
228 template<class BlockT, class LoopT>
229 void LoopBase<BlockT, LoopT>::verifyLoop() const {
231 assert(!Blocks.empty() && "Loop header is missing");
233 // Setup for using a depth-first iterator to visit every block in the loop.
234 SmallVector<BlockT*, 8> ExitBBs;
235 getExitBlocks(ExitBBs);
236 df_iterator_default_set<BlockT*> VisitSet;
237 VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
238 df_ext_iterator<BlockT*, df_iterator_default_set<BlockT*>>
239 BI = df_ext_begin(getHeader(), VisitSet),
240 BE = df_ext_end(getHeader(), VisitSet);
242 // Keep track of the number of BBs visited.
243 unsigned NumVisited = 0;
245 // Check the individual blocks.
246 for ( ; BI != BE; ++BI) {
249 assert(std::any_of(GraphTraits<BlockT*>::child_begin(BB),
250 GraphTraits<BlockT*>::child_end(BB),
251 [&](BlockT *B){return contains(B);}) &&
252 "Loop block has no in-loop successors!");
254 assert(std::any_of(GraphTraits<Inverse<BlockT*> >::child_begin(BB),
255 GraphTraits<Inverse<BlockT*> >::child_end(BB),
256 [&](BlockT *B){return contains(B);}) &&
257 "Loop block has no in-loop predecessors!");
259 SmallVector<BlockT *, 2> OutsideLoopPreds;
260 std::for_each(GraphTraits<Inverse<BlockT*> >::child_begin(BB),
261 GraphTraits<Inverse<BlockT*> >::child_end(BB),
262 [&](BlockT *B){if (!contains(B))
263 OutsideLoopPreds.push_back(B);
266 if (BB == getHeader()) {
267 assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
268 } else if (!OutsideLoopPreds.empty()) {
269 // A non-header loop shouldn't be reachable from outside the loop,
270 // though it is permitted if the predecessor is not itself actually
272 BlockT *EntryBB = &BB->getParent()->front();
273 for (BlockT *CB : depth_first(EntryBB))
274 for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
275 assert(CB != OutsideLoopPreds[i] &&
276 "Loop has multiple entry points!");
278 assert(BB != &getHeader()->getParent()->front() &&
279 "Loop contains function entry block!");
284 assert(NumVisited == getNumBlocks() && "Unreachable block in loop");
286 // Check the subloops.
287 for (iterator I = begin(), E = end(); I != E; ++I)
288 // Each block in each subloop should be contained within this loop.
289 for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
291 assert(contains(*BI) &&
292 "Loop does not contain all the blocks of a subloop!");
295 // Check the parent loop pointer.
297 assert(is_contained(*ParentLoop, this) &&
298 "Loop is not a subloop of its parent!");
303 /// verifyLoop - Verify loop structure of this loop and all nested loops.
304 template<class BlockT, class LoopT>
305 void LoopBase<BlockT, LoopT>::verifyLoopNest(
306 DenseSet<const LoopT*> *Loops) const {
307 Loops->insert(static_cast<const LoopT *>(this));
310 // Verify the subloops.
311 for (iterator I = begin(), E = end(); I != E; ++I)
312 (*I)->verifyLoopNest(Loops);
315 template<class BlockT, class LoopT>
316 void LoopBase<BlockT, LoopT>::print(raw_ostream &OS, unsigned Depth,
317 bool Verbose) const {
318 OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
321 BlockT *H = getHeader();
322 for (unsigned i = 0; i < getBlocks().size(); ++i) {
323 BlockT *BB = getBlocks()[i];
326 BB->printAsOperand(OS, false);
329 if (BB == H) OS << "<header>";
330 if (isLoopLatch(BB)) OS << "<latch>";
331 if (isLoopExiting(BB)) OS << "<exiting>";
337 for (iterator I = begin(), E = end(); I != E; ++I)
338 (*I)->print(OS, Depth+2);
341 //===----------------------------------------------------------------------===//
342 /// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
343 /// result does / not depend on use list (block predecessor) order.
346 /// Discover a subloop with the specified backedges such that: All blocks within
347 /// this loop are mapped to this loop or a subloop. And all subloops within this
348 /// loop have their parent loop set to this loop or a subloop.
349 template<class BlockT, class LoopT>
350 static void discoverAndMapSubloop(LoopT *L, ArrayRef<BlockT*> Backedges,
351 LoopInfoBase<BlockT, LoopT> *LI,
352 const DominatorTreeBase<BlockT> &DomTree) {
353 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
355 unsigned NumBlocks = 0;
356 unsigned NumSubloops = 0;
358 // Perform a backward CFG traversal using a worklist.
359 std::vector<BlockT *> ReverseCFGWorklist(Backedges.begin(), Backedges.end());
360 while (!ReverseCFGWorklist.empty()) {
361 BlockT *PredBB = ReverseCFGWorklist.back();
362 ReverseCFGWorklist.pop_back();
364 LoopT *Subloop = LI->getLoopFor(PredBB);
366 if (!DomTree.isReachableFromEntry(PredBB))
369 // This is an undiscovered block. Map it to the current loop.
370 LI->changeLoopFor(PredBB, L);
372 if (PredBB == L->getHeader())
374 // Push all block predecessors on the worklist.
375 ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
376 InvBlockTraits::child_begin(PredBB),
377 InvBlockTraits::child_end(PredBB));
380 // This is a discovered block. Find its outermost discovered loop.
381 while (LoopT *Parent = Subloop->getParentLoop())
384 // If it is already discovered to be a subloop of this loop, continue.
388 // Discover a subloop of this loop.
389 Subloop->setParentLoop(L);
391 NumBlocks += Subloop->getBlocks().capacity();
392 PredBB = Subloop->getHeader();
393 // Continue traversal along predecessors that are not loop-back edges from
394 // within this subloop tree itself. Note that a predecessor may directly
395 // reach another subloop that is not yet discovered to be a subloop of
396 // this loop, which we must traverse.
397 for (typename InvBlockTraits::ChildIteratorType PI =
398 InvBlockTraits::child_begin(PredBB),
399 PE = InvBlockTraits::child_end(PredBB); PI != PE; ++PI) {
400 if (LI->getLoopFor(*PI) != Subloop)
401 ReverseCFGWorklist.push_back(*PI);
405 L->getSubLoopsVector().reserve(NumSubloops);
406 L->reserveBlocks(NumBlocks);
409 /// Populate all loop data in a stable order during a single forward DFS.
410 template<class BlockT, class LoopT>
411 class PopulateLoopsDFS {
412 typedef GraphTraits<BlockT*> BlockTraits;
413 typedef typename BlockTraits::ChildIteratorType SuccIterTy;
415 LoopInfoBase<BlockT, LoopT> *LI;
417 PopulateLoopsDFS(LoopInfoBase<BlockT, LoopT> *li):
420 void traverse(BlockT *EntryBlock);
423 void insertIntoLoop(BlockT *Block);
426 /// Top-level driver for the forward DFS within the loop.
427 template<class BlockT, class LoopT>
428 void PopulateLoopsDFS<BlockT, LoopT>::traverse(BlockT *EntryBlock) {
429 for (BlockT *BB : post_order(EntryBlock))
433 /// Add a single Block to its ancestor loops in PostOrder. If the block is a
434 /// subloop header, add the subloop to its parent in PostOrder, then reverse the
435 /// Block and Subloop vectors of the now complete subloop to achieve RPO.
436 template<class BlockT, class LoopT>
437 void PopulateLoopsDFS<BlockT, LoopT>::insertIntoLoop(BlockT *Block) {
438 LoopT *Subloop = LI->getLoopFor(Block);
439 if (Subloop && Block == Subloop->getHeader()) {
440 // We reach this point once per subloop after processing all the blocks in
442 if (Subloop->getParentLoop())
443 Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
445 LI->addTopLevelLoop(Subloop);
447 // For convenience, Blocks and Subloops are inserted in postorder. Reverse
448 // the lists, except for the loop header, which is always at the beginning.
449 Subloop->reverseBlock(1);
450 std::reverse(Subloop->getSubLoopsVector().begin(),
451 Subloop->getSubLoopsVector().end());
453 Subloop = Subloop->getParentLoop();
455 for (; Subloop; Subloop = Subloop->getParentLoop())
456 Subloop->addBlockEntry(Block);
459 /// Analyze LoopInfo discovers loops during a postorder DominatorTree traversal
460 /// interleaved with backward CFG traversals within each subloop
461 /// (discoverAndMapSubloop). The backward traversal skips inner subloops, so
462 /// this part of the algorithm is linear in the number of CFG edges. Subloop and
463 /// Block vectors are then populated during a single forward CFG traversal
464 /// (PopulateLoopDFS).
466 /// During the two CFG traversals each block is seen three times:
467 /// 1) Discovered and mapped by a reverse CFG traversal.
468 /// 2) Visited during a forward DFS CFG traversal.
469 /// 3) Reverse-inserted in the loop in postorder following forward DFS.
471 /// The Block vectors are inclusive, so step 3 requires loop-depth number of
472 /// insertions per block.
473 template<class BlockT, class LoopT>
474 void LoopInfoBase<BlockT, LoopT>::
475 analyze(const DominatorTreeBase<BlockT> &DomTree) {
477 // Postorder traversal of the dominator tree.
478 const DomTreeNodeBase<BlockT> *DomRoot = DomTree.getRootNode();
479 for (auto DomNode : post_order(DomRoot)) {
481 BlockT *Header = DomNode->getBlock();
482 SmallVector<BlockT *, 4> Backedges;
484 // Check each predecessor of the potential loop header.
485 typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
486 for (typename InvBlockTraits::ChildIteratorType PI =
487 InvBlockTraits::child_begin(Header),
488 PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
490 BlockT *Backedge = *PI;
492 // If Header dominates predBB, this is a new loop. Collect the backedges.
493 if (DomTree.dominates(Header, Backedge)
494 && DomTree.isReachableFromEntry(Backedge)) {
495 Backedges.push_back(Backedge);
498 // Perform a backward CFG traversal to discover and map blocks in this loop.
499 if (!Backedges.empty()) {
500 LoopT *L = new LoopT(Header);
501 discoverAndMapSubloop(L, ArrayRef<BlockT*>(Backedges), this, DomTree);
504 // Perform a single forward CFG traversal to populate block and subloop
505 // vectors for all loops.
506 PopulateLoopsDFS<BlockT, LoopT> DFS(this);
507 DFS.traverse(DomRoot->getBlock());
511 template<class BlockT, class LoopT>
512 void LoopInfoBase<BlockT, LoopT>::print(raw_ostream &OS) const {
513 for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
514 TopLevelLoops[i]->print(OS);
516 for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
517 E = BBMap.end(); I != E; ++I)
518 OS << "BB '" << I->first->getName() << "' level = "
519 << I->second->getLoopDepth() << "\n";
523 template <typename T>
524 bool compareVectors(std::vector<T> &BB1, std::vector<T> &BB2) {
525 std::sort(BB1.begin(), BB1.end());
526 std::sort(BB2.begin(), BB2.end());
530 template <class BlockT, class LoopT>
532 addInnerLoopsToHeadersMap(DenseMap<BlockT *, const LoopT *> &LoopHeaders,
533 const LoopInfoBase<BlockT, LoopT> &LI,
535 LoopHeaders[L.getHeader()] = &L;
537 addInnerLoopsToHeadersMap(LoopHeaders, LI, *SL);
540 template <class BlockT, class LoopT>
541 void LoopInfoBase<BlockT, LoopT>::verify(
542 const DominatorTreeBase<BlockT> &DomTree) const {
543 DenseSet<const LoopT*> Loops;
544 for (iterator I = begin(), E = end(); I != E; ++I) {
545 assert(!(*I)->getParentLoop() && "Top-level loop has a parent!");
546 (*I)->verifyLoopNest(&Loops);
549 // Verify that blocks are mapped to valid loops.
551 for (auto &Entry : BBMap) {
552 const BlockT *BB = Entry.first;
553 LoopT *L = Entry.second;
554 assert(Loops.count(L) && "orphaned loop");
555 assert(L->contains(BB) && "orphaned block");
558 // Recompute LoopInfo to verify loops structure.
559 LoopInfoBase<BlockT, LoopT> OtherLI;
560 OtherLI.analyze(DomTree);
562 DenseMap<BlockT *, const LoopT *> LoopHeaders1;
563 DenseMap<BlockT *, const LoopT *> LoopHeaders2;
565 for (LoopT *L : *this)
566 addInnerLoopsToHeadersMap(LoopHeaders1, *this, *L);
567 for (LoopT *L : OtherLI)
568 addInnerLoopsToHeadersMap(LoopHeaders2, OtherLI, *L);
569 assert(LoopHeaders1.size() == LoopHeaders2.size() &&
570 "LoopInfo is incorrect.");
572 auto compareLoops = [&](const LoopT *L1, const LoopT *L2) {
573 BlockT *H1 = L1->getHeader();
574 BlockT *H2 = L2->getHeader();
577 std::vector<BlockT *> BB1 = L1->getBlocks();
578 std::vector<BlockT *> BB2 = L2->getBlocks();
579 if (!compareVectors(BB1, BB2))
582 std::vector<BlockT *> SubLoopHeaders1;
583 std::vector<BlockT *> SubLoopHeaders2;
585 SubLoopHeaders1.push_back(L->getHeader());
587 SubLoopHeaders2.push_back(L->getHeader());
589 if (!compareVectors(SubLoopHeaders1, SubLoopHeaders2))
594 for (auto &I : LoopHeaders1) {
596 bool LoopsMatch = compareLoops(LoopHeaders1[H], LoopHeaders2[H]);
597 assert(LoopsMatch && "LoopInfo is incorrect.");
602 } // End llvm namespace