LoopInfoImpl.h revision b9598e41bc5187cfe8fb6345a90be27e6967958f
1//===- llvm/Analysis/LoopInfoImpl.h - Natural Loop Calculator ---*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is the generic implementation of LoopInfo used for both Loops and
11// MachineLoops.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ANALYSIS_LOOP_INFO_IMPL_H
16#define LLVM_ANALYSIS_LOOP_INFO_IMPL_H
17
18#include "llvm/Analysis/LoopInfo.h"
19#include "llvm/ADT/PostOrderIterator.h"
20
21namespace llvm {
22
23//===----------------------------------------------------------------------===//
24// APIs for simple analysis of the loop. See header notes.
25
26/// getExitingBlocks - Return all blocks inside the loop that have successors
27/// outside of the loop.  These are the blocks _inside of the current loop_
28/// which branch out.  The returned list is always unique.
29///
30template<class BlockT, class LoopT>
31void LoopBase<BlockT, LoopT>::
32getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
33  // Sort the blocks vector so that we can use binary search to do quick
34  // lookups.
35  SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
36  std::sort(LoopBBs.begin(), LoopBBs.end());
37
38  typedef GraphTraits<BlockT*> BlockTraits;
39  for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
40    for (typename BlockTraits::ChildIteratorType I =
41           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
42         I != E; ++I)
43      if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
44        // Not in current loop? It must be an exit block.
45        ExitingBlocks.push_back(*BI);
46        break;
47      }
48}
49
50/// getExitingBlock - If getExitingBlocks would return exactly one block,
51/// return that block. Otherwise return null.
52template<class BlockT, class LoopT>
53BlockT *LoopBase<BlockT, LoopT>::getExitingBlock() const {
54  SmallVector<BlockT*, 8> ExitingBlocks;
55  getExitingBlocks(ExitingBlocks);
56  if (ExitingBlocks.size() == 1)
57    return ExitingBlocks[0];
58  return 0;
59}
60
61/// getExitBlocks - Return all of the successor blocks of this loop.  These
62/// are the blocks _outside of the current loop_ which are branched to.
63///
64template<class BlockT, class LoopT>
65void LoopBase<BlockT, LoopT>::
66getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
67  // Sort the blocks vector so that we can use binary search to do quick
68  // lookups.
69  SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
70  std::sort(LoopBBs.begin(), LoopBBs.end());
71
72  typedef GraphTraits<BlockT*> BlockTraits;
73  for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
74    for (typename BlockTraits::ChildIteratorType I =
75           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
76         I != E; ++I)
77      if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
78        // Not in current loop? It must be an exit block.
79        ExitBlocks.push_back(*I);
80}
81
82/// getExitBlock - If getExitBlocks would return exactly one block,
83/// return that block. Otherwise return null.
84template<class BlockT, class LoopT>
85BlockT *LoopBase<BlockT, LoopT>::getExitBlock() const {
86  SmallVector<BlockT*, 8> ExitBlocks;
87  getExitBlocks(ExitBlocks);
88  if (ExitBlocks.size() == 1)
89    return ExitBlocks[0];
90  return 0;
91}
92
93/// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
94template<class BlockT, class LoopT>
95void LoopBase<BlockT, LoopT>::
96getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
97  // Sort the blocks vector so that we can use binary search to do quick
98  // lookups.
99  SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
100  array_pod_sort(LoopBBs.begin(), LoopBBs.end());
101
102  typedef GraphTraits<BlockT*> BlockTraits;
103  for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
104    for (typename BlockTraits::ChildIteratorType I =
105           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
106         I != E; ++I)
107      if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
108        // Not in current loop? It must be an exit block.
109        ExitEdges.push_back(Edge(*BI, *I));
110}
111
112/// getLoopPreheader - If there is a preheader for this loop, return it.  A
113/// loop has a preheader if there is only one edge to the header of the loop
114/// from outside of the loop.  If this is the case, the block branching to the
115/// header of the loop is the preheader node.
116///
117/// This method returns null if there is no preheader for the loop.
118///
119template<class BlockT, class LoopT>
120BlockT *LoopBase<BlockT, LoopT>::getLoopPreheader() const {
121  // Keep track of nodes outside the loop branching to the header...
122  BlockT *Out = getLoopPredecessor();
123  if (!Out) return 0;
124
125  // Make sure there is only one exit out of the preheader.
126  typedef GraphTraits<BlockT*> BlockTraits;
127  typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
128  ++SI;
129  if (SI != BlockTraits::child_end(Out))
130    return 0;  // Multiple exits from the block, must not be a preheader.
131
132  // The predecessor has exactly one successor, so it is a preheader.
133  return Out;
134}
135
136/// getLoopPredecessor - If the given loop's header has exactly one unique
137/// predecessor outside the loop, return it. Otherwise return null.
138/// This is less strict that the loop "preheader" concept, which requires
139/// the predecessor to have exactly one successor.
140///
141template<class BlockT, class LoopT>
142BlockT *LoopBase<BlockT, LoopT>::getLoopPredecessor() const {
143  // Keep track of nodes outside the loop branching to the header...
144  BlockT *Out = 0;
145
146  // Loop over the predecessors of the header node...
147  BlockT *Header = getHeader();
148  typedef GraphTraits<BlockT*> BlockTraits;
149  typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
150  for (typename InvBlockTraits::ChildIteratorType PI =
151         InvBlockTraits::child_begin(Header),
152         PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
153    typename InvBlockTraits::NodeType *N = *PI;
154    if (!contains(N)) {     // If the block is not in the loop...
155      if (Out && Out != N)
156        return 0;             // Multiple predecessors outside the loop
157      Out = N;
158    }
159  }
160
161  // Make sure there is only one exit out of the preheader.
162  assert(Out && "Header of loop has no predecessors from outside loop?");
163  return Out;
164}
165
166/// getLoopLatch - If there is a single latch block for this loop, return it.
167/// A latch block is a block that contains a branch back to the header.
168template<class BlockT, class LoopT>
169BlockT *LoopBase<BlockT, LoopT>::getLoopLatch() const {
170  BlockT *Header = getHeader();
171  typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
172  typename InvBlockTraits::ChildIteratorType PI =
173    InvBlockTraits::child_begin(Header);
174  typename InvBlockTraits::ChildIteratorType PE =
175    InvBlockTraits::child_end(Header);
176  BlockT *Latch = 0;
177  for (; PI != PE; ++PI) {
178    typename InvBlockTraits::NodeType *N = *PI;
179    if (contains(N)) {
180      if (Latch) return 0;
181      Latch = N;
182    }
183  }
184
185  return Latch;
186}
187
188//===----------------------------------------------------------------------===//
189// APIs for updating loop information after changing the CFG
190//
191
192/// addBasicBlockToLoop - This method is used by other analyses to update loop
193/// information.  NewBB is set to be a new member of the current loop.
194/// Because of this, it is added as a member of all parent loops, and is added
195/// to the specified LoopInfo object as being in the current basic block.  It
196/// is not valid to replace the loop header with this method.
197///
198template<class BlockT, class LoopT>
199void LoopBase<BlockT, LoopT>::
200addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
201  assert((Blocks.empty() || LIB[getHeader()] == this) &&
202         "Incorrect LI specified for this loop!");
203  assert(NewBB && "Cannot add a null basic block to the loop!");
204  assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
205
206  LoopT *L = static_cast<LoopT *>(this);
207
208  // Add the loop mapping to the LoopInfo object...
209  LIB.BBMap[NewBB] = L;
210
211  // Add the basic block to this loop and all parent loops...
212  while (L) {
213    L->Blocks.push_back(NewBB);
214    L = L->getParentLoop();
215  }
216}
217
218/// replaceChildLoopWith - This is used when splitting loops up.  It replaces
219/// the OldChild entry in our children list with NewChild, and updates the
220/// parent pointer of OldChild to be null and the NewChild to be this loop.
221/// This updates the loop depth of the new child.
222template<class BlockT, class LoopT>
223void LoopBase<BlockT, LoopT>::
224replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild) {
225  assert(OldChild->ParentLoop == this && "This loop is already broken!");
226  assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
227  typename std::vector<LoopT *>::iterator I =
228    std::find(SubLoops.begin(), SubLoops.end(), OldChild);
229  assert(I != SubLoops.end() && "OldChild not in loop!");
230  *I = NewChild;
231  OldChild->ParentLoop = 0;
232  NewChild->ParentLoop = static_cast<LoopT *>(this);
233}
234
235/// verifyLoop - Verify loop structure
236template<class BlockT, class LoopT>
237void LoopBase<BlockT, LoopT>::verifyLoop() const {
238#ifndef NDEBUG
239  assert(!Blocks.empty() && "Loop header is missing");
240
241  // Setup for using a depth-first iterator to visit every block in the loop.
242  SmallVector<BlockT*, 8> ExitBBs;
243  getExitBlocks(ExitBBs);
244  llvm::SmallPtrSet<BlockT*, 8> VisitSet;
245  VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
246  df_ext_iterator<BlockT*, llvm::SmallPtrSet<BlockT*, 8> >
247    BI = df_ext_begin(getHeader(), VisitSet),
248    BE = df_ext_end(getHeader(), VisitSet);
249
250  // Keep track of the number of BBs visited.
251  unsigned NumVisited = 0;
252
253  // Sort the blocks vector so that we can use binary search to do quick
254  // lookups.
255  SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
256  std::sort(LoopBBs.begin(), LoopBBs.end());
257
258  // Check the individual blocks.
259  for ( ; BI != BE; ++BI) {
260    BlockT *BB = *BI;
261    bool HasInsideLoopSuccs = false;
262    bool HasInsideLoopPreds = false;
263    SmallVector<BlockT *, 2> OutsideLoopPreds;
264
265    typedef GraphTraits<BlockT*> BlockTraits;
266    for (typename BlockTraits::ChildIteratorType SI =
267           BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
268         SI != SE; ++SI)
269      if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) {
270        HasInsideLoopSuccs = true;
271        break;
272      }
273    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
274    for (typename InvBlockTraits::ChildIteratorType PI =
275           InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
276         PI != PE; ++PI) {
277      BlockT *N = *PI;
278      if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), N))
279        HasInsideLoopPreds = true;
280      else
281        OutsideLoopPreds.push_back(N);
282    }
283
284    if (BB == getHeader()) {
285        assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
286    } else if (!OutsideLoopPreds.empty()) {
287      // A non-header loop shouldn't be reachable from outside the loop,
288      // though it is permitted if the predecessor is not itself actually
289      // reachable.
290      BlockT *EntryBB = BB->getParent()->begin();
291        for (df_iterator<BlockT *> NI = df_begin(EntryBB),
292               NE = df_end(EntryBB); NI != NE; ++NI)
293          for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
294            assert(*NI != OutsideLoopPreds[i] &&
295                   "Loop has multiple entry points!");
296    }
297    assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
298    assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
299    assert(BB != getHeader()->getParent()->begin() &&
300           "Loop contains function entry block!");
301
302    NumVisited++;
303  }
304
305  assert(NumVisited == getNumBlocks() && "Unreachable block in loop");
306
307  // Check the subloops.
308  for (iterator I = begin(), E = end(); I != E; ++I)
309    // Each block in each subloop should be contained within this loop.
310    for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
311         BI != BE; ++BI) {
312        assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) &&
313               "Loop does not contain all the blocks of a subloop!");
314    }
315
316  // Check the parent loop pointer.
317  if (ParentLoop) {
318    assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
319           ParentLoop->end() &&
320           "Loop is not a subloop of its parent!");
321  }
322#endif
323}
324
325/// verifyLoop - Verify loop structure of this loop and all nested loops.
326template<class BlockT, class LoopT>
327void LoopBase<BlockT, LoopT>::verifyLoopNest(
328  DenseSet<const LoopT*> *Loops) const {
329  Loops->insert(static_cast<const LoopT *>(this));
330  // Verify this loop.
331  verifyLoop();
332  // Verify the subloops.
333  for (iterator I = begin(), E = end(); I != E; ++I)
334    (*I)->verifyLoopNest(Loops);
335}
336
337template<class BlockT, class LoopT>
338void LoopBase<BlockT, LoopT>::print(raw_ostream &OS, unsigned Depth) const {
339  OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
340       << " containing: ";
341
342  for (unsigned i = 0; i < getBlocks().size(); ++i) {
343    if (i) OS << ",";
344    BlockT *BB = getBlocks()[i];
345    WriteAsOperand(OS, BB, false);
346    if (BB == getHeader())    OS << "<header>";
347    if (BB == getLoopLatch()) OS << "<latch>";
348    if (isLoopExiting(BB))    OS << "<exiting>";
349  }
350  OS << "\n";
351
352  for (iterator I = begin(), E = end(); I != E; ++I)
353    (*I)->print(OS, Depth+2);
354}
355
356//===----------------------------------------------------------------------===//
357/// LoopInfo - This class builds and contains all of the top level loop
358/// structures in the specified function.
359///
360
361template<class BlockT, class LoopT>
362void LoopInfoBase<BlockT, LoopT>::Calculate(DominatorTreeBase<BlockT> &DT) {
363  BlockT *RootNode = DT.getRootNode()->getBlock();
364
365  for (df_iterator<BlockT*> NI = df_begin(RootNode),
366         NE = df_end(RootNode); NI != NE; ++NI)
367    if (LoopT *L = ConsiderForLoop(*NI, DT))
368      TopLevelLoops.push_back(L);
369}
370
371template<class BlockT, class LoopT>
372LoopT *LoopInfoBase<BlockT, LoopT>::
373ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
374  if (BBMap.count(BB)) return 0; // Haven't processed this node?
375
376  std::vector<BlockT *> TodoStack;
377
378  // Scan the predecessors of BB, checking to see if BB dominates any of
379  // them.  This identifies backedges which target this node...
380  typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
381  for (typename InvBlockTraits::ChildIteratorType I =
382         InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
383       I != E; ++I) {
384    typename InvBlockTraits::NodeType *N = *I;
385    // If BB dominates its predecessor...
386    if (DT.dominates(BB, N) && DT.isReachableFromEntry(N))
387      TodoStack.push_back(N);
388  }
389
390  if (TodoStack.empty()) return 0;  // No backedges to this block...
391
392  // Create a new loop to represent this basic block...
393  LoopT *L = new LoopT(BB);
394  BBMap[BB] = L;
395
396  while (!TodoStack.empty()) {  // Process all the nodes in the loop
397    BlockT *X = TodoStack.back();
398    TodoStack.pop_back();
399
400    if (!L->contains(X) &&         // As of yet unprocessed??
401        DT.isReachableFromEntry(X)) {
402      // Check to see if this block already belongs to a loop.  If this occurs
403      // then we have a case where a loop that is supposed to be a child of
404      // the current loop was processed before the current loop.  When this
405      // occurs, this child loop gets added to a part of the current loop,
406      // making it a sibling to the current loop.  We have to reparent this
407      // loop.
408      if (LoopT *SubLoop =
409          const_cast<LoopT *>(getLoopFor(X)))
410        if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
411          // Remove the subloop from its current parent...
412          assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
413          LoopT *SLP = SubLoop->ParentLoop;  // SubLoopParent
414          typename std::vector<LoopT *>::iterator I =
415            std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
416          assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
417          SLP->SubLoops.erase(I);   // Remove from parent...
418
419          // Add the subloop to THIS loop...
420          SubLoop->ParentLoop = L;
421          L->SubLoops.push_back(SubLoop);
422        }
423
424      // Normal case, add the block to our loop...
425      L->Blocks.push_back(X);
426
427      typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
428
429      // Add all of the predecessors of X to the end of the work stack...
430      TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
431                       InvBlockTraits::child_end(X));
432    }
433  }
434
435  // If there are any loops nested within this loop, create them now!
436  for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
437         E = L->Blocks.end(); I != E; ++I)
438    if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
439      L->SubLoops.push_back(NewLoop);
440      NewLoop->ParentLoop = L;
441    }
442
443  // Add the basic blocks that comprise this loop to the BBMap so that this
444  // loop can be found for them.
445  //
446  for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
447         E = L->Blocks.end(); I != E; ++I)
448    BBMap.insert(std::make_pair(*I, L));
449
450  // Now that we have a list of all of the child loops of this loop, check to
451  // see if any of them should actually be nested inside of each other.  We
452  // can accidentally pull loops our of their parents, so we must make sure to
453  // organize the loop nests correctly now.
454  {
455    std::map<BlockT *, LoopT *> ContainingLoops;
456    for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
457      LoopT *Child = L->SubLoops[i];
458      assert(Child->getParentLoop() == L && "Not proper child loop?");
459
460      if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
461        // If there is already a loop which contains this loop, move this loop
462        // into the containing loop.
463        MoveSiblingLoopInto(Child, ContainingLoop);
464        --i;  // The loop got removed from the SubLoops list.
465      } else {
466        // This is currently considered to be a top-level loop.  Check to see
467        // if any of the contained blocks are loop headers for subloops we
468        // have already processed.
469        for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
470          LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
471          if (BlockLoop == 0) {   // Child block not processed yet...
472            BlockLoop = Child;
473          } else if (BlockLoop != Child) {
474            LoopT *SubLoop = BlockLoop;
475            // Reparent all of the blocks which used to belong to BlockLoops
476            for (unsigned j = 0, f = SubLoop->Blocks.size(); j != f; ++j)
477              ContainingLoops[SubLoop->Blocks[j]] = Child;
478
479            // There is already a loop which contains this block, that means
480            // that we should reparent the loop which the block is currently
481            // considered to belong to to be a child of this loop.
482            MoveSiblingLoopInto(SubLoop, Child);
483            --i;  // We just shrunk the SubLoops list.
484          }
485        }
486      }
487    }
488  }
489
490  return L;
491}
492
493/// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
494/// of the NewParent Loop, instead of being a sibling of it.
495template<class BlockT, class LoopT>
496void LoopInfoBase<BlockT, LoopT>::
497MoveSiblingLoopInto(LoopT *NewChild, LoopT *NewParent) {
498  LoopT *OldParent = NewChild->getParentLoop();
499  assert(OldParent && OldParent == NewParent->getParentLoop() &&
500         NewChild != NewParent && "Not sibling loops!");
501
502  // Remove NewChild from being a child of OldParent
503  typename std::vector<LoopT *>::iterator I =
504    std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
505              NewChild);
506  assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
507  OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
508  NewChild->ParentLoop = 0;
509
510  InsertLoopInto(NewChild, NewParent);
511}
512
513/// InsertLoopInto - This inserts loop L into the specified parent loop.  If
514/// the parent loop contains a loop which should contain L, the loop gets
515/// inserted into L instead.
516template<class BlockT, class LoopT>
517void LoopInfoBase<BlockT, LoopT>::InsertLoopInto(LoopT *L, LoopT *Parent) {
518  BlockT *LHeader = L->getHeader();
519  assert(Parent->contains(LHeader) &&
520         "This loop should not be inserted here!");
521
522  // Check to see if it belongs in a child loop...
523  for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
524       i != e; ++i)
525    if (Parent->SubLoops[i]->contains(LHeader)) {
526      InsertLoopInto(L, Parent->SubLoops[i]);
527      return;
528    }
529
530  // If not, insert it here!
531  Parent->SubLoops.push_back(L);
532  L->ParentLoop = Parent;
533}
534
535//===----------------------------------------------------------------------===//
536/// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
537/// result does / not depend on use list (block predecessor) order.
538///
539
540/// Discover a subloop with the specified backedges such that: All blocks within
541/// this loop are mapped to this loop or a subloop. And all subloops within this
542/// loop have their parent loop set to this loop or a subloop.
543template<class BlockT, class LoopT>
544static void discoverAndMapSubloop(LoopT *L, ArrayRef<BlockT*> Backedges,
545                                  LoopInfoBase<BlockT, LoopT> *LI,
546                                  DominatorTreeBase<BlockT> &DomTree) {
547  typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
548
549  unsigned NumBlocks = 0;
550  unsigned NumSubloops = 0;
551
552  // Perform a backward CFG traversal using a worklist.
553  std::vector<BlockT *> ReverseCFGWorklist(Backedges.begin(), Backedges.end());
554  while (!ReverseCFGWorklist.empty()) {
555    BlockT *PredBB = ReverseCFGWorklist.back();
556    ReverseCFGWorklist.pop_back();
557
558    LoopT *Subloop = LI->getLoopFor(PredBB);
559    if (!Subloop) {
560      if (!DomTree.isReachableFromEntry(PredBB))
561        continue;
562
563      // This is an undiscovered block. Map it to the current loop.
564      LI->changeLoopFor(PredBB, L);
565      ++NumBlocks;
566      if (PredBB == L->getHeader())
567          continue;
568      // Push all block predecessors on the worklist.
569      ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
570                                InvBlockTraits::child_begin(PredBB),
571                                InvBlockTraits::child_end(PredBB));
572    }
573    else {
574      // This is a discovered block. Find its outermost discovered loop.
575      while (LoopT *Parent = Subloop->getParentLoop())
576        Subloop = Parent;
577
578      // If it is already discovered to be a subloop of this loop, continue.
579      if (Subloop == L)
580        continue;
581
582      // Discover a subloop of this loop.
583      Subloop->setParentLoop(L);
584      ++NumSubloops;
585      NumBlocks += Subloop->getBlocks().capacity();
586      PredBB = Subloop->getHeader();
587      // Continue traversal along predecessors that are not loop-back edges from
588      // within this subloop tree itself. Note that a predecessor may directly
589      // reach another subloop that is not yet discovered to be a subloop of
590      // this loop, which we must traverse.
591      for (typename InvBlockTraits::ChildIteratorType PI =
592             InvBlockTraits::child_begin(PredBB),
593             PE = InvBlockTraits::child_end(PredBB); PI != PE; ++PI) {
594        if (LI->getLoopFor(*PI) != Subloop)
595          ReverseCFGWorklist.push_back(*PI);
596      }
597    }
598  }
599  L->getSubLoopsVector().reserve(NumSubloops);
600  L->getBlocksVector().reserve(NumBlocks);
601}
602
603namespace {
604/// Populate all loop data in a stable order during a single forward DFS.
605template<class BlockT, class LoopT>
606class PopulateLoopsDFS {
607  typedef GraphTraits<BlockT*> BlockTraits;
608  typedef typename BlockTraits::ChildIteratorType SuccIterTy;
609
610  LoopInfoBase<BlockT, LoopT> *LI;
611  DenseSet<const BlockT *> VisitedBlocks;
612  std::vector<std::pair<BlockT*, SuccIterTy> > DFSStack;
613
614public:
615  PopulateLoopsDFS(LoopInfoBase<BlockT, LoopT> *li):
616    LI(li) {}
617
618  void traverse(BlockT *EntryBlock);
619
620protected:
621  void insertIntoLoop(BlockT *Block);
622
623  BlockT *dfsSource() { return DFSStack.back().first; }
624  SuccIterTy &dfsSucc() { return DFSStack.back().second; }
625  SuccIterTy dfsSuccEnd() { return BlockTraits::child_end(dfsSource()); }
626
627  void pushBlock(BlockT *Block) {
628    DFSStack.push_back(std::make_pair(Block, BlockTraits::child_begin(Block)));
629  }
630};
631} // anonymous
632
633/// Top-level driver for the forward DFS within the loop.
634template<class BlockT, class LoopT>
635void PopulateLoopsDFS<BlockT, LoopT>::traverse(BlockT *EntryBlock) {
636  pushBlock(EntryBlock);
637  VisitedBlocks.insert(EntryBlock);
638  while (!DFSStack.empty()) {
639    // Traverse the leftmost path as far as possible.
640    while (dfsSucc() != dfsSuccEnd()) {
641      BlockT *BB = *dfsSucc();
642      ++dfsSucc();
643      if (!VisitedBlocks.insert(BB).second)
644        continue;
645
646      // Push the next DFS successor onto the stack.
647      pushBlock(BB);
648    }
649    // Visit the top of the stack in postorder and backtrack.
650    insertIntoLoop(dfsSource());
651    DFSStack.pop_back();
652  }
653}
654
655/// Add a single Block to its ancestor loops in PostOrder. If the block is a
656/// subloop header, add the subloop to its parent in PostOrder, then reverse the
657/// Block and Subloop vectors of the now complete subloop to achieve RPO.
658template<class BlockT, class LoopT>
659void PopulateLoopsDFS<BlockT, LoopT>::insertIntoLoop(BlockT *Block) {
660  LoopT *Subloop = LI->getLoopFor(Block);
661  if (Subloop && Block == Subloop->getHeader()) {
662    // We reach this point once per subloop after processing all the blocks in
663    // the subloop.
664    if (Subloop->getParentLoop())
665      Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
666    else
667      LI->addTopLevelLoop(Subloop);
668
669    // For convenience, Blocks and Subloops are inserted in postorder. Reverse
670    // the lists, except for the loop header, which is always at the beginning.
671    std::reverse(Subloop->getBlocksVector().begin()+1,
672                 Subloop->getBlocksVector().end());
673    std::reverse(Subloop->getSubLoopsVector().begin(),
674                 Subloop->getSubLoopsVector().end());
675
676    Subloop = Subloop->getParentLoop();
677  }
678  for (; Subloop; Subloop = Subloop->getParentLoop())
679    Subloop->getBlocksVector().push_back(Block);
680}
681
682/// Analyze LoopInfo discovers loops during a postorder DominatorTree traversal
683/// interleaved with backward CFG traversals within each subloop
684/// (discoverAndMapSubloop). The backward traversal skips inner subloops, so
685/// this part of the algorithm is linear in the number of CFG edges. Subloop and
686/// Block vectors are then populated during a single forward CFG traversal
687/// (PopulateLoopDFS).
688///
689/// During the two CFG traversals each block is seen three times:
690/// 1) Discovered and mapped by a reverse CFG traversal.
691/// 2) Visited during a forward DFS CFG traversal.
692/// 3) Reverse-inserted in the loop in postorder following forward DFS.
693///
694/// The Block vectors are inclusive, so step 3 requires loop-depth number of
695/// insertions per block.
696template<class BlockT, class LoopT>
697void LoopInfoBase<BlockT, LoopT>::
698Analyze(DominatorTreeBase<BlockT> &DomTree) {
699
700  // Postorder traversal of the dominator tree.
701  DomTreeNodeBase<BlockT>* DomRoot = DomTree.getRootNode();
702  for (po_iterator<DomTreeNodeBase<BlockT>*> DomIter = po_begin(DomRoot),
703         DomEnd = po_end(DomRoot); DomIter != DomEnd; ++DomIter) {
704
705    BlockT *Header = DomIter->getBlock();
706    SmallVector<BlockT *, 4> Backedges;
707
708    // Check each predecessor of the potential loop header.
709    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
710    for (typename InvBlockTraits::ChildIteratorType PI =
711           InvBlockTraits::child_begin(Header),
712           PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
713
714      BlockT *Backedge = *PI;
715
716      // If Header dominates predBB, this is a new loop. Collect the backedges.
717      if (DomTree.dominates(Header, Backedge)
718          && DomTree.isReachableFromEntry(Backedge)) {
719        Backedges.push_back(Backedge);
720      }
721    }
722    // Perform a backward CFG traversal to discover and map blocks in this loop.
723    if (!Backedges.empty()) {
724      LoopT *L = new LoopT(Header);
725      discoverAndMapSubloop(L, ArrayRef<BlockT*>(Backedges), this, DomTree);
726    }
727  }
728  // Perform a single forward CFG traversal to populate block and subloop
729  // vectors for all loops.
730  PopulateLoopsDFS<BlockT, LoopT> DFS(this);
731  DFS.traverse(DomRoot->getBlock());
732}
733
734// Debugging
735template<class BlockT, class LoopT>
736void LoopInfoBase<BlockT, LoopT>::print(raw_ostream &OS) const {
737  for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
738    TopLevelLoops[i]->print(OS);
739#if 0
740  for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
741         E = BBMap.end(); I != E; ++I)
742    OS << "BB '" << I->first->getName() << "' level = "
743       << I->second->getLoopDepth() << "\n";
744#endif
745}
746
747} // End llvm namespace
748
749#endif
750