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