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