1239310Sdim//===- llvm/Analysis/LoopInfoImpl.h - Natural Loop Calculator ---*- C++ -*-===//
2239310Sdim//
3239310Sdim//                     The LLVM Compiler Infrastructure
4239310Sdim//
5239310Sdim// This file is distributed under the University of Illinois Open Source
6239310Sdim// License. See LICENSE.TXT for details.
7239310Sdim//
8239310Sdim//===----------------------------------------------------------------------===//
9239310Sdim//
10239310Sdim// This is the generic implementation of LoopInfo used for both Loops and
11239310Sdim// MachineLoops.
12239310Sdim//
13239310Sdim//===----------------------------------------------------------------------===//
14239310Sdim
15249423Sdim#ifndef LLVM_ANALYSIS_LOOPINFOIMPL_H
16249423Sdim#define LLVM_ANALYSIS_LOOPINFOIMPL_H
17239310Sdim
18249423Sdim#include "llvm/ADT/PostOrderIterator.h"
19249423Sdim#include "llvm/ADT/STLExtras.h"
20239310Sdim#include "llvm/Analysis/LoopInfo.h"
21239310Sdim
22239310Sdimnamespace llvm {
23239310Sdim
24239310Sdim//===----------------------------------------------------------------------===//
25239310Sdim// APIs for simple analysis of the loop. See header notes.
26239310Sdim
27239310Sdim/// getExitingBlocks - Return all blocks inside the loop that have successors
28239310Sdim/// outside of the loop.  These are the blocks _inside of the current loop_
29239310Sdim/// which branch out.  The returned list is always unique.
30239310Sdim///
31239310Sdimtemplate<class BlockT, class LoopT>
32239310Sdimvoid LoopBase<BlockT, LoopT>::
33239310SdimgetExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
34239310Sdim  typedef GraphTraits<BlockT*> BlockTraits;
35239310Sdim  for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
36239310Sdim    for (typename BlockTraits::ChildIteratorType I =
37239310Sdim           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
38239310Sdim         I != E; ++I)
39263508Sdim      if (!contains(*I)) {
40239310Sdim        // Not in current loop? It must be an exit block.
41239310Sdim        ExitingBlocks.push_back(*BI);
42239310Sdim        break;
43239310Sdim      }
44239310Sdim}
45239310Sdim
46239310Sdim/// getExitingBlock - If getExitingBlocks would return exactly one block,
47239310Sdim/// return that block. Otherwise return null.
48239310Sdimtemplate<class BlockT, class LoopT>
49239310SdimBlockT *LoopBase<BlockT, LoopT>::getExitingBlock() const {
50239310Sdim  SmallVector<BlockT*, 8> ExitingBlocks;
51239310Sdim  getExitingBlocks(ExitingBlocks);
52239310Sdim  if (ExitingBlocks.size() == 1)
53239310Sdim    return ExitingBlocks[0];
54239310Sdim  return 0;
55239310Sdim}
56239310Sdim
57239310Sdim/// getExitBlocks - Return all of the successor blocks of this loop.  These
58239310Sdim/// are the blocks _outside of the current loop_ which are branched to.
59239310Sdim///
60239310Sdimtemplate<class BlockT, class LoopT>
61239310Sdimvoid LoopBase<BlockT, LoopT>::
62239310SdimgetExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
63239310Sdim  typedef GraphTraits<BlockT*> BlockTraits;
64239310Sdim  for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
65239310Sdim    for (typename BlockTraits::ChildIteratorType I =
66239310Sdim           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
67239310Sdim         I != E; ++I)
68263508Sdim      if (!contains(*I))
69239310Sdim        // Not in current loop? It must be an exit block.
70239310Sdim        ExitBlocks.push_back(*I);
71239310Sdim}
72239310Sdim
73239310Sdim/// getExitBlock - If getExitBlocks would return exactly one block,
74239310Sdim/// return that block. Otherwise return null.
75239310Sdimtemplate<class BlockT, class LoopT>
76239310SdimBlockT *LoopBase<BlockT, LoopT>::getExitBlock() const {
77239310Sdim  SmallVector<BlockT*, 8> ExitBlocks;
78239310Sdim  getExitBlocks(ExitBlocks);
79239310Sdim  if (ExitBlocks.size() == 1)
80239310Sdim    return ExitBlocks[0];
81239310Sdim  return 0;
82239310Sdim}
83239310Sdim
84239310Sdim/// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
85239310Sdimtemplate<class BlockT, class LoopT>
86239310Sdimvoid LoopBase<BlockT, LoopT>::
87239310SdimgetExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
88239310Sdim  typedef GraphTraits<BlockT*> BlockTraits;
89239310Sdim  for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
90239310Sdim    for (typename BlockTraits::ChildIteratorType I =
91239310Sdim           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
92239310Sdim         I != E; ++I)
93263508Sdim      if (!contains(*I))
94239310Sdim        // Not in current loop? It must be an exit block.
95239310Sdim        ExitEdges.push_back(Edge(*BI, *I));
96239310Sdim}
97239310Sdim
98239310Sdim/// getLoopPreheader - If there is a preheader for this loop, return it.  A
99239310Sdim/// loop has a preheader if there is only one edge to the header of the loop
100239310Sdim/// from outside of the loop.  If this is the case, the block branching to the
101239310Sdim/// header of the loop is the preheader node.
102239310Sdim///
103239310Sdim/// This method returns null if there is no preheader for the loop.
104239310Sdim///
105239310Sdimtemplate<class BlockT, class LoopT>
106239310SdimBlockT *LoopBase<BlockT, LoopT>::getLoopPreheader() const {
107239310Sdim  // Keep track of nodes outside the loop branching to the header...
108239310Sdim  BlockT *Out = getLoopPredecessor();
109239310Sdim  if (!Out) return 0;
110239310Sdim
111239310Sdim  // Make sure there is only one exit out of the preheader.
112239310Sdim  typedef GraphTraits<BlockT*> BlockTraits;
113239310Sdim  typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
114239310Sdim  ++SI;
115239310Sdim  if (SI != BlockTraits::child_end(Out))
116239310Sdim    return 0;  // Multiple exits from the block, must not be a preheader.
117239310Sdim
118239310Sdim  // The predecessor has exactly one successor, so it is a preheader.
119239310Sdim  return Out;
120239310Sdim}
121239310Sdim
122239310Sdim/// getLoopPredecessor - If the given loop's header has exactly one unique
123239310Sdim/// predecessor outside the loop, return it. Otherwise return null.
124239310Sdim/// This is less strict that the loop "preheader" concept, which requires
125239310Sdim/// the predecessor to have exactly one successor.
126239310Sdim///
127239310Sdimtemplate<class BlockT, class LoopT>
128239310SdimBlockT *LoopBase<BlockT, LoopT>::getLoopPredecessor() const {
129239310Sdim  // Keep track of nodes outside the loop branching to the header...
130239310Sdim  BlockT *Out = 0;
131239310Sdim
132239310Sdim  // Loop over the predecessors of the header node...
133239310Sdim  BlockT *Header = getHeader();
134239310Sdim  typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
135239310Sdim  for (typename InvBlockTraits::ChildIteratorType PI =
136239310Sdim         InvBlockTraits::child_begin(Header),
137239310Sdim         PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
138239310Sdim    typename InvBlockTraits::NodeType *N = *PI;
139239310Sdim    if (!contains(N)) {     // If the block is not in the loop...
140239310Sdim      if (Out && Out != N)
141239310Sdim        return 0;             // Multiple predecessors outside the loop
142239310Sdim      Out = N;
143239310Sdim    }
144239310Sdim  }
145239310Sdim
146239310Sdim  // Make sure there is only one exit out of the preheader.
147239310Sdim  assert(Out && "Header of loop has no predecessors from outside loop?");
148239310Sdim  return Out;
149239310Sdim}
150239310Sdim
151239310Sdim/// getLoopLatch - If there is a single latch block for this loop, return it.
152239310Sdim/// A latch block is a block that contains a branch back to the header.
153239310Sdimtemplate<class BlockT, class LoopT>
154239310SdimBlockT *LoopBase<BlockT, LoopT>::getLoopLatch() const {
155239310Sdim  BlockT *Header = getHeader();
156239310Sdim  typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
157239310Sdim  typename InvBlockTraits::ChildIteratorType PI =
158239310Sdim    InvBlockTraits::child_begin(Header);
159239310Sdim  typename InvBlockTraits::ChildIteratorType PE =
160239310Sdim    InvBlockTraits::child_end(Header);
161239310Sdim  BlockT *Latch = 0;
162239310Sdim  for (; PI != PE; ++PI) {
163239310Sdim    typename InvBlockTraits::NodeType *N = *PI;
164239310Sdim    if (contains(N)) {
165239310Sdim      if (Latch) return 0;
166239310Sdim      Latch = N;
167239310Sdim    }
168239310Sdim  }
169239310Sdim
170239310Sdim  return Latch;
171239310Sdim}
172239310Sdim
173239310Sdim//===----------------------------------------------------------------------===//
174239310Sdim// APIs for updating loop information after changing the CFG
175239310Sdim//
176239310Sdim
177239310Sdim/// addBasicBlockToLoop - This method is used by other analyses to update loop
178239310Sdim/// information.  NewBB is set to be a new member of the current loop.
179239310Sdim/// Because of this, it is added as a member of all parent loops, and is added
180239310Sdim/// to the specified LoopInfo object as being in the current basic block.  It
181239310Sdim/// is not valid to replace the loop header with this method.
182239310Sdim///
183239310Sdimtemplate<class BlockT, class LoopT>
184239310Sdimvoid LoopBase<BlockT, LoopT>::
185239310SdimaddBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LIB) {
186239310Sdim  assert((Blocks.empty() || LIB[getHeader()] == this) &&
187239310Sdim         "Incorrect LI specified for this loop!");
188239310Sdim  assert(NewBB && "Cannot add a null basic block to the loop!");
189239310Sdim  assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
190239310Sdim
191239310Sdim  LoopT *L = static_cast<LoopT *>(this);
192239310Sdim
193239310Sdim  // Add the loop mapping to the LoopInfo object...
194239310Sdim  LIB.BBMap[NewBB] = L;
195239310Sdim
196239310Sdim  // Add the basic block to this loop and all parent loops...
197239310Sdim  while (L) {
198263508Sdim    L->addBlockEntry(NewBB);
199239310Sdim    L = L->getParentLoop();
200239310Sdim  }
201239310Sdim}
202239310Sdim
203239310Sdim/// replaceChildLoopWith - This is used when splitting loops up.  It replaces
204239310Sdim/// the OldChild entry in our children list with NewChild, and updates the
205239310Sdim/// parent pointer of OldChild to be null and the NewChild to be this loop.
206239310Sdim/// This updates the loop depth of the new child.
207239310Sdimtemplate<class BlockT, class LoopT>
208239310Sdimvoid LoopBase<BlockT, LoopT>::
209239310SdimreplaceChildLoopWith(LoopT *OldChild, LoopT *NewChild) {
210239310Sdim  assert(OldChild->ParentLoop == this && "This loop is already broken!");
211239310Sdim  assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
212239310Sdim  typename std::vector<LoopT *>::iterator I =
213239310Sdim    std::find(SubLoops.begin(), SubLoops.end(), OldChild);
214239310Sdim  assert(I != SubLoops.end() && "OldChild not in loop!");
215239310Sdim  *I = NewChild;
216239310Sdim  OldChild->ParentLoop = 0;
217239310Sdim  NewChild->ParentLoop = static_cast<LoopT *>(this);
218239310Sdim}
219239310Sdim
220239310Sdim/// verifyLoop - Verify loop structure
221239310Sdimtemplate<class BlockT, class LoopT>
222239310Sdimvoid LoopBase<BlockT, LoopT>::verifyLoop() const {
223239310Sdim#ifndef NDEBUG
224239310Sdim  assert(!Blocks.empty() && "Loop header is missing");
225239310Sdim
226239310Sdim  // Setup for using a depth-first iterator to visit every block in the loop.
227239310Sdim  SmallVector<BlockT*, 8> ExitBBs;
228239310Sdim  getExitBlocks(ExitBBs);
229239310Sdim  llvm::SmallPtrSet<BlockT*, 8> VisitSet;
230239310Sdim  VisitSet.insert(ExitBBs.begin(), ExitBBs.end());
231239310Sdim  df_ext_iterator<BlockT*, llvm::SmallPtrSet<BlockT*, 8> >
232239310Sdim    BI = df_ext_begin(getHeader(), VisitSet),
233239310Sdim    BE = df_ext_end(getHeader(), VisitSet);
234239310Sdim
235239310Sdim  // Keep track of the number of BBs visited.
236239310Sdim  unsigned NumVisited = 0;
237239310Sdim
238239310Sdim  // Check the individual blocks.
239239310Sdim  for ( ; BI != BE; ++BI) {
240239310Sdim    BlockT *BB = *BI;
241239310Sdim    bool HasInsideLoopSuccs = false;
242239310Sdim    bool HasInsideLoopPreds = false;
243239310Sdim    SmallVector<BlockT *, 2> OutsideLoopPreds;
244239310Sdim
245239310Sdim    typedef GraphTraits<BlockT*> BlockTraits;
246239310Sdim    for (typename BlockTraits::ChildIteratorType SI =
247239310Sdim           BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
248239310Sdim         SI != SE; ++SI)
249263508Sdim      if (contains(*SI)) {
250239310Sdim        HasInsideLoopSuccs = true;
251239310Sdim        break;
252239310Sdim      }
253239310Sdim    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
254239310Sdim    for (typename InvBlockTraits::ChildIteratorType PI =
255239310Sdim           InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
256239310Sdim         PI != PE; ++PI) {
257239310Sdim      BlockT *N = *PI;
258263508Sdim      if (contains(N))
259239310Sdim        HasInsideLoopPreds = true;
260239310Sdim      else
261239310Sdim        OutsideLoopPreds.push_back(N);
262239310Sdim    }
263239310Sdim
264239310Sdim    if (BB == getHeader()) {
265239310Sdim        assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
266239310Sdim    } else if (!OutsideLoopPreds.empty()) {
267239310Sdim      // A non-header loop shouldn't be reachable from outside the loop,
268239310Sdim      // though it is permitted if the predecessor is not itself actually
269239310Sdim      // reachable.
270239310Sdim      BlockT *EntryBB = BB->getParent()->begin();
271239310Sdim        for (df_iterator<BlockT *> NI = df_begin(EntryBB),
272239310Sdim               NE = df_end(EntryBB); NI != NE; ++NI)
273239310Sdim          for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
274239310Sdim            assert(*NI != OutsideLoopPreds[i] &&
275239310Sdim                   "Loop has multiple entry points!");
276239310Sdim    }
277239310Sdim    assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
278239310Sdim    assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
279239310Sdim    assert(BB != getHeader()->getParent()->begin() &&
280239310Sdim           "Loop contains function entry block!");
281239310Sdim
282239310Sdim    NumVisited++;
283239310Sdim  }
284239310Sdim
285239310Sdim  assert(NumVisited == getNumBlocks() && "Unreachable block in loop");
286239310Sdim
287239310Sdim  // Check the subloops.
288239310Sdim  for (iterator I = begin(), E = end(); I != E; ++I)
289239310Sdim    // Each block in each subloop should be contained within this loop.
290239310Sdim    for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
291239310Sdim         BI != BE; ++BI) {
292263508Sdim        assert(contains(*BI) &&
293239310Sdim               "Loop does not contain all the blocks of a subloop!");
294239310Sdim    }
295239310Sdim
296239310Sdim  // Check the parent loop pointer.
297239310Sdim  if (ParentLoop) {
298239310Sdim    assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
299239310Sdim           ParentLoop->end() &&
300239310Sdim           "Loop is not a subloop of its parent!");
301239310Sdim  }
302239310Sdim#endif
303239310Sdim}
304239310Sdim
305239310Sdim/// verifyLoop - Verify loop structure of this loop and all nested loops.
306239310Sdimtemplate<class BlockT, class LoopT>
307239310Sdimvoid LoopBase<BlockT, LoopT>::verifyLoopNest(
308239310Sdim  DenseSet<const LoopT*> *Loops) const {
309239310Sdim  Loops->insert(static_cast<const LoopT *>(this));
310239310Sdim  // Verify this loop.
311239310Sdim  verifyLoop();
312239310Sdim  // Verify the subloops.
313239310Sdim  for (iterator I = begin(), E = end(); I != E; ++I)
314239310Sdim    (*I)->verifyLoopNest(Loops);
315239310Sdim}
316239310Sdim
317239310Sdimtemplate<class BlockT, class LoopT>
318239310Sdimvoid LoopBase<BlockT, LoopT>::print(raw_ostream &OS, unsigned Depth) const {
319239310Sdim  OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
320239310Sdim       << " containing: ";
321239310Sdim
322239310Sdim  for (unsigned i = 0; i < getBlocks().size(); ++i) {
323239310Sdim    if (i) OS << ",";
324239310Sdim    BlockT *BB = getBlocks()[i];
325239310Sdim    WriteAsOperand(OS, BB, false);
326239310Sdim    if (BB == getHeader())    OS << "<header>";
327239310Sdim    if (BB == getLoopLatch()) OS << "<latch>";
328239310Sdim    if (isLoopExiting(BB))    OS << "<exiting>";
329239310Sdim  }
330239310Sdim  OS << "\n";
331239310Sdim
332239310Sdim  for (iterator I = begin(), E = end(); I != E; ++I)
333239310Sdim    (*I)->print(OS, Depth+2);
334239310Sdim}
335239310Sdim
336239310Sdim//===----------------------------------------------------------------------===//
337239310Sdim/// Stable LoopInfo Analysis - Build a loop tree using stable iterators so the
338239310Sdim/// result does / not depend on use list (block predecessor) order.
339239310Sdim///
340239310Sdim
341239310Sdim/// Discover a subloop with the specified backedges such that: All blocks within
342239310Sdim/// this loop are mapped to this loop or a subloop. And all subloops within this
343239310Sdim/// loop have their parent loop set to this loop or a subloop.
344239310Sdimtemplate<class BlockT, class LoopT>
345239310Sdimstatic void discoverAndMapSubloop(LoopT *L, ArrayRef<BlockT*> Backedges,
346239310Sdim                                  LoopInfoBase<BlockT, LoopT> *LI,
347239310Sdim                                  DominatorTreeBase<BlockT> &DomTree) {
348239310Sdim  typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
349239310Sdim
350239310Sdim  unsigned NumBlocks = 0;
351239310Sdim  unsigned NumSubloops = 0;
352239310Sdim
353239310Sdim  // Perform a backward CFG traversal using a worklist.
354239310Sdim  std::vector<BlockT *> ReverseCFGWorklist(Backedges.begin(), Backedges.end());
355239310Sdim  while (!ReverseCFGWorklist.empty()) {
356239310Sdim    BlockT *PredBB = ReverseCFGWorklist.back();
357239310Sdim    ReverseCFGWorklist.pop_back();
358239310Sdim
359239310Sdim    LoopT *Subloop = LI->getLoopFor(PredBB);
360239310Sdim    if (!Subloop) {
361239310Sdim      if (!DomTree.isReachableFromEntry(PredBB))
362239310Sdim        continue;
363239310Sdim
364239310Sdim      // This is an undiscovered block. Map it to the current loop.
365239310Sdim      LI->changeLoopFor(PredBB, L);
366239310Sdim      ++NumBlocks;
367239310Sdim      if (PredBB == L->getHeader())
368239310Sdim          continue;
369239310Sdim      // Push all block predecessors on the worklist.
370239310Sdim      ReverseCFGWorklist.insert(ReverseCFGWorklist.end(),
371239310Sdim                                InvBlockTraits::child_begin(PredBB),
372239310Sdim                                InvBlockTraits::child_end(PredBB));
373239310Sdim    }
374239310Sdim    else {
375239310Sdim      // This is a discovered block. Find its outermost discovered loop.
376239310Sdim      while (LoopT *Parent = Subloop->getParentLoop())
377239310Sdim        Subloop = Parent;
378239310Sdim
379239310Sdim      // If it is already discovered to be a subloop of this loop, continue.
380239310Sdim      if (Subloop == L)
381239310Sdim        continue;
382239310Sdim
383239310Sdim      // Discover a subloop of this loop.
384239310Sdim      Subloop->setParentLoop(L);
385239310Sdim      ++NumSubloops;
386239310Sdim      NumBlocks += Subloop->getBlocks().capacity();
387239310Sdim      PredBB = Subloop->getHeader();
388239310Sdim      // Continue traversal along predecessors that are not loop-back edges from
389239310Sdim      // within this subloop tree itself. Note that a predecessor may directly
390239310Sdim      // reach another subloop that is not yet discovered to be a subloop of
391239310Sdim      // this loop, which we must traverse.
392239310Sdim      for (typename InvBlockTraits::ChildIteratorType PI =
393239310Sdim             InvBlockTraits::child_begin(PredBB),
394239310Sdim             PE = InvBlockTraits::child_end(PredBB); PI != PE; ++PI) {
395239310Sdim        if (LI->getLoopFor(*PI) != Subloop)
396239310Sdim          ReverseCFGWorklist.push_back(*PI);
397239310Sdim      }
398239310Sdim    }
399239310Sdim  }
400239310Sdim  L->getSubLoopsVector().reserve(NumSubloops);
401263508Sdim  L->reserveBlocks(NumBlocks);
402239310Sdim}
403239310Sdim
404239310Sdimnamespace {
405239310Sdim/// Populate all loop data in a stable order during a single forward DFS.
406239310Sdimtemplate<class BlockT, class LoopT>
407239310Sdimclass PopulateLoopsDFS {
408239310Sdim  typedef GraphTraits<BlockT*> BlockTraits;
409239310Sdim  typedef typename BlockTraits::ChildIteratorType SuccIterTy;
410239310Sdim
411239310Sdim  LoopInfoBase<BlockT, LoopT> *LI;
412239310Sdim  DenseSet<const BlockT *> VisitedBlocks;
413239310Sdim  std::vector<std::pair<BlockT*, SuccIterTy> > DFSStack;
414239310Sdim
415239310Sdimpublic:
416239310Sdim  PopulateLoopsDFS(LoopInfoBase<BlockT, LoopT> *li):
417239310Sdim    LI(li) {}
418239310Sdim
419239310Sdim  void traverse(BlockT *EntryBlock);
420239310Sdim
421239310Sdimprotected:
422239310Sdim  void insertIntoLoop(BlockT *Block);
423239310Sdim
424239310Sdim  BlockT *dfsSource() { return DFSStack.back().first; }
425239310Sdim  SuccIterTy &dfsSucc() { return DFSStack.back().second; }
426239310Sdim  SuccIterTy dfsSuccEnd() { return BlockTraits::child_end(dfsSource()); }
427239310Sdim
428239310Sdim  void pushBlock(BlockT *Block) {
429239310Sdim    DFSStack.push_back(std::make_pair(Block, BlockTraits::child_begin(Block)));
430239310Sdim  }
431239310Sdim};
432239310Sdim} // anonymous
433239310Sdim
434239310Sdim/// Top-level driver for the forward DFS within the loop.
435239310Sdimtemplate<class BlockT, class LoopT>
436239310Sdimvoid PopulateLoopsDFS<BlockT, LoopT>::traverse(BlockT *EntryBlock) {
437239310Sdim  pushBlock(EntryBlock);
438239310Sdim  VisitedBlocks.insert(EntryBlock);
439239310Sdim  while (!DFSStack.empty()) {
440239310Sdim    // Traverse the leftmost path as far as possible.
441239310Sdim    while (dfsSucc() != dfsSuccEnd()) {
442239310Sdim      BlockT *BB = *dfsSucc();
443239310Sdim      ++dfsSucc();
444239310Sdim      if (!VisitedBlocks.insert(BB).second)
445239310Sdim        continue;
446239310Sdim
447239310Sdim      // Push the next DFS successor onto the stack.
448239310Sdim      pushBlock(BB);
449239310Sdim    }
450239310Sdim    // Visit the top of the stack in postorder and backtrack.
451239310Sdim    insertIntoLoop(dfsSource());
452239310Sdim    DFSStack.pop_back();
453239310Sdim  }
454239310Sdim}
455239310Sdim
456239310Sdim/// Add a single Block to its ancestor loops in PostOrder. If the block is a
457239310Sdim/// subloop header, add the subloop to its parent in PostOrder, then reverse the
458239310Sdim/// Block and Subloop vectors of the now complete subloop to achieve RPO.
459239310Sdimtemplate<class BlockT, class LoopT>
460239310Sdimvoid PopulateLoopsDFS<BlockT, LoopT>::insertIntoLoop(BlockT *Block) {
461239310Sdim  LoopT *Subloop = LI->getLoopFor(Block);
462239310Sdim  if (Subloop && Block == Subloop->getHeader()) {
463239310Sdim    // We reach this point once per subloop after processing all the blocks in
464239310Sdim    // the subloop.
465239310Sdim    if (Subloop->getParentLoop())
466239310Sdim      Subloop->getParentLoop()->getSubLoopsVector().push_back(Subloop);
467239310Sdim    else
468239310Sdim      LI->addTopLevelLoop(Subloop);
469239310Sdim
470239310Sdim    // For convenience, Blocks and Subloops are inserted in postorder. Reverse
471239310Sdim    // the lists, except for the loop header, which is always at the beginning.
472263508Sdim    Subloop->reverseBlock(1);
473239310Sdim    std::reverse(Subloop->getSubLoopsVector().begin(),
474239310Sdim                 Subloop->getSubLoopsVector().end());
475239310Sdim
476239310Sdim    Subloop = Subloop->getParentLoop();
477239310Sdim  }
478239310Sdim  for (; Subloop; Subloop = Subloop->getParentLoop())
479263508Sdim    Subloop->addBlockEntry(Block);
480239310Sdim}
481239310Sdim
482239310Sdim/// Analyze LoopInfo discovers loops during a postorder DominatorTree traversal
483239310Sdim/// interleaved with backward CFG traversals within each subloop
484239310Sdim/// (discoverAndMapSubloop). The backward traversal skips inner subloops, so
485239310Sdim/// this part of the algorithm is linear in the number of CFG edges. Subloop and
486239310Sdim/// Block vectors are then populated during a single forward CFG traversal
487239310Sdim/// (PopulateLoopDFS).
488239310Sdim///
489239310Sdim/// During the two CFG traversals each block is seen three times:
490239310Sdim/// 1) Discovered and mapped by a reverse CFG traversal.
491239310Sdim/// 2) Visited during a forward DFS CFG traversal.
492239310Sdim/// 3) Reverse-inserted in the loop in postorder following forward DFS.
493239310Sdim///
494239310Sdim/// The Block vectors are inclusive, so step 3 requires loop-depth number of
495239310Sdim/// insertions per block.
496239310Sdimtemplate<class BlockT, class LoopT>
497239310Sdimvoid LoopInfoBase<BlockT, LoopT>::
498239310SdimAnalyze(DominatorTreeBase<BlockT> &DomTree) {
499239310Sdim
500239310Sdim  // Postorder traversal of the dominator tree.
501239310Sdim  DomTreeNodeBase<BlockT>* DomRoot = DomTree.getRootNode();
502239310Sdim  for (po_iterator<DomTreeNodeBase<BlockT>*> DomIter = po_begin(DomRoot),
503239310Sdim         DomEnd = po_end(DomRoot); DomIter != DomEnd; ++DomIter) {
504239310Sdim
505239310Sdim    BlockT *Header = DomIter->getBlock();
506239310Sdim    SmallVector<BlockT *, 4> Backedges;
507239310Sdim
508239310Sdim    // Check each predecessor of the potential loop header.
509239310Sdim    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
510239310Sdim    for (typename InvBlockTraits::ChildIteratorType PI =
511239310Sdim           InvBlockTraits::child_begin(Header),
512239310Sdim           PE = InvBlockTraits::child_end(Header); PI != PE; ++PI) {
513239310Sdim
514239310Sdim      BlockT *Backedge = *PI;
515239310Sdim
516239310Sdim      // If Header dominates predBB, this is a new loop. Collect the backedges.
517239310Sdim      if (DomTree.dominates(Header, Backedge)
518239310Sdim          && DomTree.isReachableFromEntry(Backedge)) {
519239310Sdim        Backedges.push_back(Backedge);
520239310Sdim      }
521239310Sdim    }
522239310Sdim    // Perform a backward CFG traversal to discover and map blocks in this loop.
523239310Sdim    if (!Backedges.empty()) {
524239310Sdim      LoopT *L = new LoopT(Header);
525239310Sdim      discoverAndMapSubloop(L, ArrayRef<BlockT*>(Backedges), this, DomTree);
526239310Sdim    }
527239310Sdim  }
528239310Sdim  // Perform a single forward CFG traversal to populate block and subloop
529239310Sdim  // vectors for all loops.
530239310Sdim  PopulateLoopsDFS<BlockT, LoopT> DFS(this);
531239310Sdim  DFS.traverse(DomRoot->getBlock());
532239310Sdim}
533239310Sdim
534239310Sdim// Debugging
535239310Sdimtemplate<class BlockT, class LoopT>
536239310Sdimvoid LoopInfoBase<BlockT, LoopT>::print(raw_ostream &OS) const {
537239310Sdim  for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
538239310Sdim    TopLevelLoops[i]->print(OS);
539239310Sdim#if 0
540239310Sdim  for (DenseMap<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
541239310Sdim         E = BBMap.end(); I != E; ++I)
542239310Sdim    OS << "BB '" << I->first->getName() << "' level = "
543239310Sdim       << I->second->getLoopDepth() << "\n";
544239310Sdim#endif
545239310Sdim}
546239310Sdim
547239310Sdim} // End llvm namespace
548239310Sdim
549239310Sdim#endif
550