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