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