LoopInfo.h revision 7ed47a13356daed2a34cd2209a31f92552e3bdd8
1//===- llvm/Analysis/LoopInfo.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 file defines the LoopInfo class that is used to identify natural loops
11// and determine the loop depth of various nodes of the CFG.  Note that natural
12// loops may actually be several loops that share the same header node.
13//
14// This analysis calculates the nesting structure of loops in a function.  For
15// each natural loop identified, this analysis identifies natural loops
16// contained entirely within the loop and the basic blocks the make up the loop.
17//
18// It can calculate on the fly various bits of information, for example:
19//
20//  * whether there is a preheader for the loop
21//  * the number of back edges to the header
22//  * whether or not a particular block branches out of the loop
23//  * the successor blocks of the loop
24//  * the loop depth
25//  * the trip count
26//  * etc...
27//
28//===----------------------------------------------------------------------===//
29
30#ifndef LLVM_ANALYSIS_LOOP_INFO_H
31#define LLVM_ANALYSIS_LOOP_INFO_H
32
33#include "llvm/Pass.h"
34#include "llvm/Constants.h"
35#include "llvm/Instructions.h"
36#include "llvm/ADT/DepthFirstIterator.h"
37#include "llvm/ADT/GraphTraits.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/Analysis/Dominators.h"
41#include "llvm/Support/CFG.h"
42#include "llvm/Support/Streams.h"
43#include <algorithm>
44#include <ostream>
45
46template<typename T>
47static void RemoveFromVector(std::vector<T*> &V, T *N) {
48  typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
49  assert(I != V.end() && "N is not in this list!");
50  V.erase(I);
51}
52
53namespace llvm {
54
55class DominatorTree;
56class LoopInfo;
57class PHINode;
58class Instruction;
59template<class N> class LoopInfoBase;
60
61//===----------------------------------------------------------------------===//
62/// LoopBase class - Instances of this class are used to represent loops that are
63/// detected in the flow graph
64///
65template<class BlockT>
66class LoopBase {
67  LoopBase<BlockT> *ParentLoop;
68  std::vector<LoopBase<BlockT>*> SubLoops; // Loops contained entirely within this one
69  std::vector<BlockT*> Blocks;   // First entry is the header node
70
71  LoopBase(const LoopBase<BlockT> &);                  // DO NOT IMPLEMENT
72  const LoopBase<BlockT> &operator=(const LoopBase<BlockT> &); // DO NOT IMPLEMENT
73public:
74  /// Loop ctor - This creates an empty loop.
75  LoopBase() : ParentLoop(0) {}
76  ~LoopBase() {
77    for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
78      delete SubLoops[i];
79  }
80
81  unsigned getLoopDepth() const {
82    unsigned D = 0;
83    for (const LoopBase<BlockT> *CurLoop = this; CurLoop;
84         CurLoop = CurLoop->ParentLoop)
85      ++D;
86    return D;
87  }
88  BlockT *getHeader() const { return Blocks.front(); }
89  LoopBase<BlockT> *getParentLoop() const { return ParentLoop; }
90
91  /// contains - Return true of the specified basic block is in this loop
92  ///
93  bool contains(const BlockT *BB) const {
94    return std::find(Blocks.begin(), Blocks.end(), BB) != Blocks.end();
95  }
96
97  /// iterator/begin/end - Return the loops contained entirely within this loop.
98  ///
99  const std::vector<LoopBase<BlockT>*> &getSubLoops() const { return SubLoops; }
100  typedef typename std::vector<LoopBase<BlockT>*>::const_iterator iterator;
101  iterator begin() const { return SubLoops.begin(); }
102  iterator end() const { return SubLoops.end(); }
103  bool empty() const { return SubLoops.empty(); }
104
105  /// getBlocks - Get a list of the basic blocks which make up this loop.
106  ///
107  const std::vector<BlockT*> &getBlocks() const { return Blocks; }
108  typedef typename std::vector<BlockT*>::const_iterator block_iterator;
109  block_iterator block_begin() const { return Blocks.begin(); }
110  block_iterator block_end() const { return Blocks.end(); }
111
112  /// isLoopExit - True if terminator in the block can branch to another block
113  /// that is outside of the current loop.
114  ///
115  bool isLoopExit(const BlockT *BB) const {
116    typedef GraphTraits<BlockT*> BlockTraits;
117    for (typename BlockTraits::ChildIteratorType SI =
118         BlockTraits::child_begin(const_cast<BlockT*>(BB)),
119         SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
120      if (!contains(*SI))
121        return true;
122    }
123    return false;
124  }
125
126  /// getNumBackEdges - Calculate the number of back edges to the loop header
127  ///
128  unsigned getNumBackEdges() const {
129    unsigned NumBackEdges = 0;
130    BlockT *H = getHeader();
131
132    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
133    for (typename InvBlockTraits::ChildIteratorType I =
134         InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
135         E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
136      if (contains(*I))
137        ++NumBackEdges;
138
139    return NumBackEdges;
140  }
141
142  /// isLoopInvariant - Return true if the specified value is loop invariant
143  ///
144  inline bool isLoopInvariant(Value *V) const {
145    if (Instruction *I = dyn_cast<Instruction>(V))
146      return !contains(I->getParent());
147    return true;  // All non-instructions are loop invariant
148  }
149
150  //===--------------------------------------------------------------------===//
151  // APIs for simple analysis of the loop.
152  //
153  // Note that all of these methods can fail on general loops (ie, there may not
154  // be a preheader, etc).  For best success, the loop simplification and
155  // induction variable canonicalization pass should be used to normalize loops
156  // for easy analysis.  These methods assume canonical loops.
157
158  /// getExitingBlocks - Return all blocks inside the loop that have successors
159  /// outside of the loop.  These are the blocks _inside of the current loop_
160  /// which branch out.  The returned list is always unique.
161  ///
162  void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
163    // Sort the blocks vector so that we can use binary search to do quick
164    // lookups.
165    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
166    std::sort(LoopBBs.begin(), LoopBBs.end());
167
168    typedef GraphTraits<BlockT*> BlockTraits;
169    for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
170         BE = Blocks.end(); BI != BE; ++BI)
171      for (typename BlockTraits::ChildIteratorType I =
172          BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
173          I != E; ++I)
174        if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
175          // Not in current loop? It must be an exit block.
176          ExitingBlocks.push_back(*BI);
177          break;
178        }
179  }
180
181  /// getExitBlocks - Return all of the successor blocks of this loop.  These
182  /// are the blocks _outside of the current loop_ which are branched to.
183  ///
184  void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
185    // Sort the blocks vector so that we can use binary search to do quick
186    // lookups.
187    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
188    std::sort(LoopBBs.begin(), LoopBBs.end());
189
190    typedef GraphTraits<BlockT*> BlockTraits;
191    for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
192         BE = Blocks.end(); BI != BE; ++BI)
193      for (typename BlockTraits::ChildIteratorType I =
194           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
195           I != E; ++I)
196        if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
197          // Not in current loop? It must be an exit block.
198          ExitBlocks.push_back(*I);
199  }
200
201  /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
202  /// These are the blocks _outside of the current loop_ which are branched to.
203  /// This assumes that loop is in canonical form.
204  ///
205  void getUniqueExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
206    // Sort the blocks vector so that we can use binary search to do quick
207    // lookups.
208    SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
209    std::sort(LoopBBs.begin(), LoopBBs.end());
210
211    std::vector<BlockT*> switchExitBlocks;
212
213    for (typename std::vector<BlockT*>::const_iterator BI = Blocks.begin(),
214         BE = Blocks.end(); BI != BE; ++BI) {
215
216      BlockT *current = *BI;
217      switchExitBlocks.clear();
218
219      typedef GraphTraits<BlockT*> BlockTraits;
220      typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
221      for (typename BlockTraits::ChildIteratorType I =
222           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
223           I != E; ++I) {
224        if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
225      // If block is inside the loop then it is not a exit block.
226          continue;
227
228        typename InvBlockTraits::ChildIteratorType PI =
229                                                InvBlockTraits::child_begin(*I);
230        BlockT *firstPred = *PI;
231
232        // If current basic block is this exit block's first predecessor
233        // then only insert exit block in to the output ExitBlocks vector.
234        // This ensures that same exit block is not inserted twice into
235        // ExitBlocks vector.
236        if (current != firstPred)
237          continue;
238
239        // If a terminator has more then two successors, for example SwitchInst,
240        // then it is possible that there are multiple edges from current block
241        // to one exit block.
242        if (std::distance(BlockTraits::child_begin(current),
243                          BlockTraits::child_end(current)) <= 2) {
244          ExitBlocks.push_back(*I);
245          continue;
246        }
247
248        // In case of multiple edges from current block to exit block, collect
249        // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
250        // duplicate edges.
251        if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I)
252            == switchExitBlocks.end()) {
253          switchExitBlocks.push_back(*I);
254          ExitBlocks.push_back(*I);
255        }
256      }
257    }
258  }
259
260  /// getLoopPreheader - If there is a preheader for this loop, return it.  A
261  /// loop has a preheader if there is only one edge to the header of the loop
262  /// from outside of the loop.  If this is the case, the block branching to the
263  /// header of the loop is the preheader node.
264  ///
265  /// This method returns null if there is no preheader for the loop.
266  ///
267  BlockT *getLoopPreheader() const {
268    // Keep track of nodes outside the loop branching to the header...
269    BlockT *Out = 0;
270
271    // Loop over the predecessors of the header node...
272    BlockT *Header = getHeader();
273    typedef GraphTraits<BlockT*> BlockTraits;
274    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
275    for (typename InvBlockTraits::ChildIteratorType PI =
276         InvBlockTraits::child_begin(Header),
277         PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
278      if (!contains(*PI)) {     // If the block is not in the loop...
279        if (Out && Out != *PI)
280          return 0;             // Multiple predecessors outside the loop
281        Out = *PI;
282      }
283
284    // Make sure there is only one exit out of the preheader.
285    assert(Out && "Header of loop has no predecessors from outside loop?");
286    typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
287    ++SI;
288    if (SI != BlockTraits::child_end(Out))
289      return 0;  // Multiple exits from the block, must not be a preheader.
290
291    // If there is exactly one preheader, return it.  If there was zero, then Out
292    // is still null.
293    return Out;
294  }
295
296  /// getLoopLatch - If there is a latch block for this loop, return it.  A
297  /// latch block is the canonical backedge for a loop.  A loop header in normal
298  /// form has two edges into it: one from a preheader and one from a latch
299  /// block.
300  BlockT *getLoopLatch() const {
301    BlockT *Header = getHeader();
302    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
303    typename InvBlockTraits::ChildIteratorType PI =
304                                            InvBlockTraits::child_begin(Header);
305    typename InvBlockTraits::ChildIteratorType PE =
306                                              InvBlockTraits::child_end(Header);
307    if (PI == PE) return 0;  // no preds?
308
309    BlockT *Latch = 0;
310    if (contains(*PI))
311      Latch = *PI;
312    ++PI;
313    if (PI == PE) return 0;  // only one pred?
314
315    if (contains(*PI)) {
316      if (Latch) return 0;  // multiple backedges
317      Latch = *PI;
318    }
319    ++PI;
320    if (PI != PE) return 0;  // more than two preds
321
322    return Latch;
323  }
324
325  /// getCanonicalInductionVariable - Check to see if the loop has a canonical
326  /// induction variable: an integer recurrence that starts at 0 and increments
327  /// by one each time through the loop.  If so, return the phi node that
328  /// corresponds to it.
329  ///
330  inline PHINode *getCanonicalInductionVariable() const {
331    BlockT *H = getHeader();
332
333    BlockT *Incoming = 0, *Backedge = 0;
334    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
335    typename InvBlockTraits::ChildIteratorType PI =
336                                                 InvBlockTraits::child_begin(H);
337    assert(PI != InvBlockTraits::child_end(H) &&
338           "Loop must have at least one backedge!");
339    Backedge = *PI++;
340    if (PI == InvBlockTraits::child_end(H)) return 0;  // dead loop
341    Incoming = *PI++;
342    if (PI != InvBlockTraits::child_end(H)) return 0;  // multiple backedges?
343
344    if (contains(Incoming)) {
345      if (contains(Backedge))
346        return 0;
347      std::swap(Incoming, Backedge);
348    } else if (!contains(Backedge))
349      return 0;
350
351    // Loop over all of the PHI nodes, looking for a canonical indvar.
352    for (typename BlockT::iterator I = H->begin(); isa<PHINode>(I); ++I) {
353      PHINode *PN = cast<PHINode>(I);
354      if (Instruction *Inc =
355          dyn_cast<Instruction>(PN->getIncomingValueForBlock(Backedge)))
356        if (Inc->getOpcode() == Instruction::Add && Inc->getOperand(0) == PN)
357          if (ConstantInt *CI = dyn_cast<ConstantInt>(Inc->getOperand(1)))
358            if (CI->equalsInt(1))
359              return PN;
360    }
361    return 0;
362  }
363
364  /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
365  /// the canonical induction variable value for the "next" iteration of the
366  /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
367  ///
368  inline Instruction *getCanonicalInductionVariableIncrement() const {
369    if (PHINode *PN = getCanonicalInductionVariable()) {
370      bool P1InLoop = contains(PN->getIncomingBlock(1));
371      return cast<Instruction>(PN->getIncomingValue(P1InLoop));
372    }
373    return 0;
374  }
375
376  /// getTripCount - Return a loop-invariant LLVM value indicating the number of
377  /// times the loop will be executed.  Note that this means that the backedge
378  /// of the loop executes N-1 times.  If the trip-count cannot be determined,
379  /// this returns null.
380  ///
381  inline Value *getTripCount() const {
382    // Canonical loops will end with a 'cmp ne I, V', where I is the incremented
383    // canonical induction variable and V is the trip count of the loop.
384    Instruction *Inc = getCanonicalInductionVariableIncrement();
385    if (Inc == 0) return 0;
386    PHINode *IV = cast<PHINode>(Inc->getOperand(0));
387
388    BlockT *BackedgeBlock =
389            IV->getIncomingBlock(contains(IV->getIncomingBlock(1)));
390
391    if (BranchInst *BI = dyn_cast<BranchInst>(BackedgeBlock->getTerminator()))
392      if (BI->isConditional()) {
393        if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
394          if (ICI->getOperand(0) == Inc)
395            if (BI->getSuccessor(0) == getHeader()) {
396              if (ICI->getPredicate() == ICmpInst::ICMP_NE)
397                return ICI->getOperand(1);
398            } else if (ICI->getPredicate() == ICmpInst::ICMP_EQ) {
399              return ICI->getOperand(1);
400            }
401        }
402      }
403
404    return 0;
405  }
406
407  /// isLCSSAForm - Return true if the Loop is in LCSSA form
408  inline bool isLCSSAForm() const {
409    // Sort the blocks vector so that we can use binary search to do quick
410    // lookups.
411    SmallPtrSet<BlockT*, 16> LoopBBs(block_begin(), block_end());
412
413    for (block_iterator BI = block_begin(), E = block_end(); BI != E; ++BI) {
414      BlockT *BB = *BI;
415      for (typename BlockT::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
416        for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
417             ++UI) {
418          BlockT *UserBB = cast<Instruction>(*UI)->getParent();
419          if (PHINode *P = dyn_cast<PHINode>(*UI)) {
420            unsigned OperandNo = UI.getOperandNo();
421            UserBB = P->getIncomingBlock(OperandNo/2);
422          }
423
424          // Check the current block, as a fast-path.  Most values are used in the
425          // same block they are defined in.
426          if (UserBB != BB && !LoopBBs.count(UserBB))
427            return false;
428        }
429    }
430
431    return true;
432  }
433
434  //===--------------------------------------------------------------------===//
435  // APIs for updating loop information after changing the CFG
436  //
437
438  /// addBasicBlockToLoop - This method is used by other analyses to update loop
439  /// information.  NewBB is set to be a new member of the current loop.
440  /// Because of this, it is added as a member of all parent loops, and is added
441  /// to the specified LoopInfo object as being in the current basic block.  It
442  /// is not valid to replace the loop header with this method.
443  ///
444  void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT> &LI);
445
446  /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
447  /// the OldChild entry in our children list with NewChild, and updates the
448  /// parent pointer of OldChild to be null and the NewChild to be this loop.
449  /// This updates the loop depth of the new child.
450  void replaceChildLoopWith(LoopBase<BlockT> *OldChild,
451                            LoopBase<BlockT> *NewChild) {
452    assert(OldChild->ParentLoop == this && "This loop is already broken!");
453    assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
454    typename std::vector<LoopBase<BlockT>*>::iterator I =
455                          std::find(SubLoops.begin(), SubLoops.end(), OldChild);
456    assert(I != SubLoops.end() && "OldChild not in loop!");
457    *I = NewChild;
458    OldChild->ParentLoop = 0;
459    NewChild->ParentLoop = this;
460  }
461
462  /// addChildLoop - Add the specified loop to be a child of this loop.  This
463  /// updates the loop depth of the new child.
464  ///
465  void addChildLoop(LoopBase<BlockT> *NewChild) {
466    assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
467    NewChild->ParentLoop = this;
468    SubLoops.push_back(NewChild);
469  }
470
471  /// removeChildLoop - This removes the specified child from being a subloop of
472  /// this loop.  The loop is not deleted, as it will presumably be inserted
473  /// into another loop.
474  LoopBase<BlockT> *removeChildLoop(iterator I) {
475    assert(I != SubLoops.end() && "Cannot remove end iterator!");
476    LoopBase<BlockT> *Child = *I;
477    assert(Child->ParentLoop == this && "Child is not a child of this loop!");
478    SubLoops.erase(SubLoops.begin()+(I-begin()));
479    Child->ParentLoop = 0;
480    return Child;
481  }
482
483  /// addBlockEntry - This adds a basic block directly to the basic block list.
484  /// This should only be used by transformations that create new loops.  Other
485  /// transformations should use addBasicBlockToLoop.
486  void addBlockEntry(BlockT *BB) {
487    Blocks.push_back(BB);
488  }
489
490  /// moveToHeader - This method is used to move BB (which must be part of this
491  /// loop) to be the loop header of the loop (the block that dominates all
492  /// others).
493  void moveToHeader(BlockT *BB) {
494    if (Blocks[0] == BB) return;
495    for (unsigned i = 0; ; ++i) {
496      assert(i != Blocks.size() && "Loop does not contain BB!");
497      if (Blocks[i] == BB) {
498        Blocks[i] = Blocks[0];
499        Blocks[0] = BB;
500        return;
501      }
502    }
503  }
504
505  /// removeBlockFromLoop - This removes the specified basic block from the
506  /// current loop, updating the Blocks as appropriate.  This does not update
507  /// the mapping in the LoopInfo class.
508  void removeBlockFromLoop(BlockT *BB) {
509    RemoveFromVector(Blocks, BB);
510  }
511
512  /// verifyLoop - Verify loop structure
513  void verifyLoop() const {
514#ifndef NDEBUG
515    assert (getHeader() && "Loop header is missing");
516    assert (getLoopPreheader() && "Loop preheader is missing");
517    assert (getLoopLatch() && "Loop latch is missing");
518    for (typename std::vector<LoopBase<BlockT>*>::const_iterator I =
519         SubLoops.begin(), E = SubLoops.end(); I != E; ++I)
520      (*I)->verifyLoop();
521#endif
522  }
523
524  void print(std::ostream &OS, unsigned Depth = 0) const {
525    OS << std::string(Depth*2, ' ') << "Loop Containing: ";
526
527    for (unsigned i = 0; i < getBlocks().size(); ++i) {
528      if (i) OS << ",";
529      WriteAsOperand(OS, getBlocks()[i], false);
530    }
531    OS << "\n";
532
533    for (iterator I = begin(), E = end(); I != E; ++I)
534      (*I)->print(OS, Depth+2);
535  }
536
537  void print(std::ostream *O, unsigned Depth = 0) const {
538    if (O) print(*O, Depth);
539  }
540
541  void dump() const {
542    print(cerr);
543  }
544
545private:
546  friend class LoopInfoBase<BlockT>;
547  LoopBase(BlockT *BB) : ParentLoop(0) {
548    Blocks.push_back(BB);
549  }
550};
551
552typedef LoopBase<BasicBlock> Loop;
553
554
555//===----------------------------------------------------------------------===//
556/// LoopInfo - This class builds and contains all of the top level loop
557/// structures in the specified function.
558///
559
560template<class BlockT>
561class LoopInfoBase {
562  // BBMap - Mapping of basic blocks to the inner most loop they occur in
563  std::map<BlockT*, LoopBase<BlockT>*> BBMap;
564  std::vector<LoopBase<BlockT>*> TopLevelLoops;
565  friend class LoopBase<BlockT>;
566
567public:
568  LoopInfoBase() { }
569  ~LoopInfoBase() { releaseMemory(); }
570
571  void releaseMemory() {
572    for (typename std::vector<LoopBase<BlockT>* >::iterator I =
573         TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
574      delete *I;   // Delete all of the loops...
575
576    BBMap.clear();                             // Reset internal state of analysis
577    TopLevelLoops.clear();
578  }
579
580  /// iterator/begin/end - The interface to the top-level loops in the current
581  /// function.
582  ///
583  typedef typename std::vector<LoopBase<BlockT>*>::const_iterator iterator;
584  iterator begin() const { return TopLevelLoops.begin(); }
585  iterator end() const { return TopLevelLoops.end(); }
586
587  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
588  /// block is in no loop (for example the entry node), null is returned.
589  ///
590  LoopBase<BlockT> *getLoopFor(const BlockT *BB) const {
591    typename std::map<BlockT *, LoopBase<BlockT>*>::const_iterator I=
592      BBMap.find(const_cast<BlockT*>(BB));
593    return I != BBMap.end() ? I->second : 0;
594  }
595
596  /// operator[] - same as getLoopFor...
597  ///
598  const LoopBase<BlockT> *operator[](const BlockT *BB) const {
599    return getLoopFor(BB);
600  }
601
602  /// getLoopDepth - Return the loop nesting level of the specified block...
603  ///
604  unsigned getLoopDepth(const BlockT *BB) const {
605    const LoopBase<BlockT> *L = getLoopFor(BB);
606    return L ? L->getLoopDepth() : 0;
607  }
608
609  // isLoopHeader - True if the block is a loop header node
610  bool isLoopHeader(BlockT *BB) const {
611    const LoopBase<BlockT> *L = getLoopFor(BB);
612    return L && L->getHeader() == BB;
613  }
614
615  /// removeLoop - This removes the specified top-level loop from this loop info
616  /// object.  The loop is not deleted, as it will presumably be inserted into
617  /// another loop.
618  LoopBase<BlockT> *removeLoop(iterator I) {
619    assert(I != end() && "Cannot remove end iterator!");
620    LoopBase<BlockT> *L = *I;
621    assert(L->getParentLoop() == 0 && "Not a top-level loop!");
622    TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
623    return L;
624  }
625
626  /// changeLoopFor - Change the top-level loop that contains BB to the
627  /// specified loop.  This should be used by transformations that restructure
628  /// the loop hierarchy tree.
629  void changeLoopFor(BlockT *BB, LoopBase<BlockT> *L) {
630    LoopBase<BlockT> *&OldLoop = BBMap[BB];
631    assert(OldLoop && "Block not in a loop yet!");
632    OldLoop = L;
633  }
634
635  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
636  /// list with the indicated loop.
637  void changeTopLevelLoop(LoopBase<BlockT> *OldLoop,
638                          LoopBase<BlockT> *NewLoop) {
639    typename std::vector<LoopBase<BlockT>*>::iterator I =
640                 std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
641    assert(I != TopLevelLoops.end() && "Old loop not at top level!");
642    *I = NewLoop;
643    assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
644           "Loops already embedded into a subloop!");
645  }
646
647  /// addTopLevelLoop - This adds the specified loop to the collection of
648  /// top-level loops.
649  void addTopLevelLoop(LoopBase<BlockT> *New) {
650    assert(New->getParentLoop() == 0 && "Loop already in subloop!");
651    TopLevelLoops.push_back(New);
652  }
653
654  /// removeBlock - This method completely removes BB from all data structures,
655  /// including all of the Loop objects it is nested in and our mapping from
656  /// BasicBlocks to loops.
657  void removeBlock(BlockT *BB) {
658    typename std::map<BlockT *, LoopBase<BlockT>*>::iterator I = BBMap.find(BB);
659    if (I != BBMap.end()) {
660      for (LoopBase<BlockT> *L = I->second; L; L = L->getParentLoop())
661        L->removeBlockFromLoop(BB);
662
663      BBMap.erase(I);
664    }
665  }
666
667  // Internals
668
669  static bool isNotAlreadyContainedIn(LoopBase<BlockT> *SubLoop,
670                                      LoopBase<BlockT> *ParentLoop) {
671    if (SubLoop == 0) return true;
672    if (SubLoop == ParentLoop) return false;
673    return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
674  }
675
676  void Calculate(DominatorTreeBase<BlockT> &DT) {
677    BlockT *RootNode = DT.getRootNode()->getBlock();
678
679    for (df_iterator<BlockT*> NI = df_begin(RootNode),
680           NE = df_end(RootNode); NI != NE; ++NI)
681      if (LoopBase<BlockT> *L = ConsiderForLoop(*NI, DT))
682        TopLevelLoops.push_back(L);
683  }
684
685  LoopBase<BlockT> *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
686    if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
687
688    std::vector<BlockT *> TodoStack;
689
690    // Scan the predecessors of BB, checking to see if BB dominates any of
691    // them.  This identifies backedges which target this node...
692    typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
693    for (typename InvBlockTraits::ChildIteratorType I =
694         InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
695         I != E; ++I)
696      if (DT.dominates(BB, *I))   // If BB dominates it's predecessor...
697        TodoStack.push_back(*I);
698
699    if (TodoStack.empty()) return 0;  // No backedges to this block...
700
701    // Create a new loop to represent this basic block...
702    LoopBase<BlockT> *L = new LoopBase<BlockT>(BB);
703    BBMap[BB] = L;
704
705    BlockT *EntryBlock = BB->getParent()->begin();
706
707    while (!TodoStack.empty()) {  // Process all the nodes in the loop
708      BlockT *X = TodoStack.back();
709      TodoStack.pop_back();
710
711      if (!L->contains(X) &&         // As of yet unprocessed??
712          DT.dominates(EntryBlock, X)) {   // X is reachable from entry block?
713        // Check to see if this block already belongs to a loop.  If this occurs
714        // then we have a case where a loop that is supposed to be a child of the
715        // current loop was processed before the current loop.  When this occurs,
716        // this child loop gets added to a part of the current loop, making it a
717        // sibling to the current loop.  We have to reparent this loop.
718        if (LoopBase<BlockT> *SubLoop =
719            const_cast<LoopBase<BlockT>*>(getLoopFor(X)))
720          if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)) {
721            // Remove the subloop from it's current parent...
722            assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
723            LoopBase<BlockT> *SLP = SubLoop->ParentLoop;  // SubLoopParent
724            typename std::vector<LoopBase<BlockT>*>::iterator I =
725              std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
726            assert(I != SLP->SubLoops.end() && "SubLoop not a child of parent?");
727            SLP->SubLoops.erase(I);   // Remove from parent...
728
729            // Add the subloop to THIS loop...
730            SubLoop->ParentLoop = L;
731            L->SubLoops.push_back(SubLoop);
732          }
733
734        // Normal case, add the block to our loop...
735        L->Blocks.push_back(X);
736
737        typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
738
739        // Add all of the predecessors of X to the end of the work stack...
740        TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
741                         InvBlockTraits::child_end(X));
742      }
743    }
744
745    // If there are any loops nested within this loop, create them now!
746    for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
747         E = L->Blocks.end(); I != E; ++I)
748      if (LoopBase<BlockT> *NewLoop = ConsiderForLoop(*I, DT)) {
749        L->SubLoops.push_back(NewLoop);
750        NewLoop->ParentLoop = L;
751      }
752
753    // Add the basic blocks that comprise this loop to the BBMap so that this
754    // loop can be found for them.
755    //
756    for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
757           E = L->Blocks.end(); I != E; ++I) {
758      typename std::map<BlockT*, LoopBase<BlockT>*>::iterator BBMI =
759                                                          BBMap.lower_bound(*I);
760      if (BBMI == BBMap.end() || BBMI->first != *I)  // Not in map yet...
761        BBMap.insert(BBMI, std::make_pair(*I, L));   // Must be at this level
762    }
763
764    // Now that we have a list of all of the child loops of this loop, check to
765    // see if any of them should actually be nested inside of each other.  We can
766    // accidentally pull loops our of their parents, so we must make sure to
767    // organize the loop nests correctly now.
768    {
769      std::map<BlockT*, LoopBase<BlockT>*> ContainingLoops;
770      for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
771        LoopBase<BlockT> *Child = L->SubLoops[i];
772        assert(Child->getParentLoop() == L && "Not proper child loop?");
773
774        if (LoopBase<BlockT> *ContainingLoop =
775                                          ContainingLoops[Child->getHeader()]) {
776          // If there is already a loop which contains this loop, move this loop
777          // into the containing loop.
778          MoveSiblingLoopInto(Child, ContainingLoop);
779          --i;  // The loop got removed from the SubLoops list.
780        } else {
781          // This is currently considered to be a top-level loop.  Check to see if
782          // any of the contained blocks are loop headers for subloops we have
783          // already processed.
784          for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
785            LoopBase<BlockT> *&BlockLoop = ContainingLoops[Child->Blocks[b]];
786            if (BlockLoop == 0) {   // Child block not processed yet...
787              BlockLoop = Child;
788            } else if (BlockLoop != Child) {
789              LoopBase<BlockT> *SubLoop = BlockLoop;
790              // Reparent all of the blocks which used to belong to BlockLoops
791              for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
792                ContainingLoops[SubLoop->Blocks[j]] = Child;
793
794              // There is already a loop which contains this block, that means
795              // that we should reparent the loop which the block is currently
796              // considered to belong to to be a child of this loop.
797              MoveSiblingLoopInto(SubLoop, Child);
798              --i;  // We just shrunk the SubLoops list.
799            }
800          }
801        }
802      }
803    }
804
805    return L;
806  }
807
808  /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside of
809  /// the NewParent Loop, instead of being a sibling of it.
810  void MoveSiblingLoopInto(LoopBase<BlockT> *NewChild,
811                           LoopBase<BlockT> *NewParent) {
812    LoopBase<BlockT> *OldParent = NewChild->getParentLoop();
813    assert(OldParent && OldParent == NewParent->getParentLoop() &&
814           NewChild != NewParent && "Not sibling loops!");
815
816    // Remove NewChild from being a child of OldParent
817    typename std::vector<LoopBase<BlockT>*>::iterator I =
818      std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(), NewChild);
819    assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
820    OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
821    NewChild->ParentLoop = 0;
822
823    InsertLoopInto(NewChild, NewParent);
824  }
825
826  /// InsertLoopInto - This inserts loop L into the specified parent loop.  If the
827  /// parent loop contains a loop which should contain L, the loop gets inserted
828  /// into L instead.
829  void InsertLoopInto(LoopBase<BlockT> *L, LoopBase<BlockT> *Parent) {
830    BlockT *LHeader = L->getHeader();
831    assert(Parent->contains(LHeader) && "This loop should not be inserted here!");
832
833    // Check to see if it belongs in a child loop...
834    for (unsigned i = 0, e = Parent->SubLoops.size(); i != e; ++i)
835      if (Parent->SubLoops[i]->contains(LHeader)) {
836        InsertLoopInto(L, Parent->SubLoops[i]);
837        return;
838      }
839
840    // If not, insert it here!
841    Parent->SubLoops.push_back(L);
842    L->ParentLoop = Parent;
843  }
844
845  // Debugging
846
847  void print(std::ostream &OS, const Module* ) const {
848    for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
849      TopLevelLoops[i]->print(OS);
850  #if 0
851    for (std::map<BasicBlock*, Loop*>::const_iterator I = BBMap.begin(),
852           E = BBMap.end(); I != E; ++I)
853      OS << "BB '" << I->first->getName() << "' level = "
854         << I->second->getLoopDepth() << "\n";
855  #endif
856  }
857};
858
859class LoopInfo : public FunctionPass {
860  LoopInfoBase<BasicBlock>* LI;
861  friend class LoopBase<BasicBlock>;
862
863public:
864  static char ID; // Pass identification, replacement for typeid
865
866  LoopInfo() : FunctionPass(intptr_t(&ID)) {
867    LI = new LoopInfoBase<BasicBlock>();
868  }
869
870  ~LoopInfo() { delete LI; }
871
872  LoopInfoBase<BasicBlock>& getBase() { return *LI; }
873
874  /// iterator/begin/end - The interface to the top-level loops in the current
875  /// function.
876  ///
877  typedef std::vector<Loop*>::const_iterator iterator;
878  inline iterator begin() const { return LI->begin(); }
879  inline iterator end() const { return LI->end(); }
880
881  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
882  /// block is in no loop (for example the entry node), null is returned.
883  ///
884  inline Loop *getLoopFor(const BasicBlock *BB) const {
885    return LI->getLoopFor(BB);
886  }
887
888  /// operator[] - same as getLoopFor...
889  ///
890  inline const Loop *operator[](const BasicBlock *BB) const {
891    return LI->getLoopFor(BB);
892  }
893
894  /// getLoopDepth - Return the loop nesting level of the specified block...
895  ///
896  inline unsigned getLoopDepth(const BasicBlock *BB) const {
897    return LI->getLoopDepth(BB);
898  }
899
900  // isLoopHeader - True if the block is a loop header node
901  inline bool isLoopHeader(BasicBlock *BB) const {
902    return LI->isLoopHeader(BB);
903  }
904
905  /// runOnFunction - Calculate the natural loop information.
906  ///
907  virtual bool runOnFunction(Function &F);
908
909  virtual void releaseMemory() { LI->releaseMemory(); }
910
911  virtual void print(std::ostream &O, const Module* M = 0) const {
912    if (O) LI->print(O, M);
913  }
914
915  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
916
917  /// removeLoop - This removes the specified top-level loop from this loop info
918  /// object.  The loop is not deleted, as it will presumably be inserted into
919  /// another loop.
920  inline Loop *removeLoop(iterator I) { return LI->removeLoop(I); }
921
922  /// changeLoopFor - Change the top-level loop that contains BB to the
923  /// specified loop.  This should be used by transformations that restructure
924  /// the loop hierarchy tree.
925  inline void changeLoopFor(BasicBlock *BB, Loop *L) {
926    LI->changeLoopFor(BB, L);
927  }
928
929  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
930  /// list with the indicated loop.
931  inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
932    LI->changeTopLevelLoop(OldLoop, NewLoop);
933  }
934
935  /// addTopLevelLoop - This adds the specified loop to the collection of
936  /// top-level loops.
937  inline void addTopLevelLoop(Loop *New) {
938    LI->addTopLevelLoop(New);
939  }
940
941  /// removeBlock - This method completely removes BB from all data structures,
942  /// including all of the Loop objects it is nested in and our mapping from
943  /// BasicBlocks to loops.
944  void removeBlock(BasicBlock *BB) {
945    LI->removeBlock(BB);
946  }
947};
948
949
950// Allow clients to walk the list of nested loops...
951template <> struct GraphTraits<const Loop*> {
952  typedef const Loop NodeType;
953  typedef std::vector<Loop*>::const_iterator ChildIteratorType;
954
955  static NodeType *getEntryNode(const Loop *L) { return L; }
956  static inline ChildIteratorType child_begin(NodeType *N) {
957    return N->begin();
958  }
959  static inline ChildIteratorType child_end(NodeType *N) {
960    return N->end();
961  }
962};
963
964template <> struct GraphTraits<Loop*> {
965  typedef Loop NodeType;
966  typedef std::vector<Loop*>::const_iterator ChildIteratorType;
967
968  static NodeType *getEntryNode(Loop *L) { return L; }
969  static inline ChildIteratorType child_begin(NodeType *N) {
970    return N->begin();
971  }
972  static inline ChildIteratorType child_end(NodeType *N) {
973    return N->end();
974  }
975};
976
977template<class BlockT>
978void LoopBase<BlockT>::addBasicBlockToLoop(BlockT *NewBB,
979                                           LoopInfoBase<BlockT> &LIB) {
980  assert((Blocks.empty() || LIB[getHeader()] == this) &&
981         "Incorrect LI specified for this loop!");
982  assert(NewBB && "Cannot add a null basic block to the loop!");
983  assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
984
985  // Add the loop mapping to the LoopInfo object...
986  LIB.BBMap[NewBB] = this;
987
988  // Add the basic block to this loop and all parent loops...
989  LoopBase<BlockT> *L = this;
990  while (L) {
991    L->Blocks.push_back(NewBB);
992    L = L->getParentLoop();
993  }
994}
995
996} // End llvm namespace
997
998// Make sure that any clients of this file link in LoopInfo.cpp
999FORCE_DEFINING_FILE_TO_BE_LINKED(LoopInfo)
1000
1001#endif
1002