LoopInfo.h revision 06ac2bef15f8a41f2e3439899b5aa1d95f4bd1f5
1//===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the LoopInfo class that is used to identify natural loops
11// and determine the loop depth of various nodes of the CFG.  Note that natural
12// loops may actually be several loops that share the same header node.
13//
14// This analysis calculates the nesting structure of loops in a function.  For
15// each natural loop identified, this analysis identifies natural loops
16// contained entirely within the loop and the basic blocks the make up the loop.
17//
18// It can calculate on the fly various bits of information, for example:
19//
20//  * whether there is a preheader for the loop
21//  * the number of back edges to the header
22//  * whether or not a particular block branches out of the loop
23//  * the successor blocks of the loop
24//  * the loop depth
25//  * the trip count
26//  * etc...
27//
28//===----------------------------------------------------------------------===//
29
30#ifndef LLVM_ANALYSIS_LOOP_INFO_H
31#define LLVM_ANALYSIS_LOOP_INFO_H
32
33#include "llvm/Pass.h"
34#include "Support/GraphTraits.h"
35
36namespace llvm {
37
38class DominatorSet;
39class LoopInfo;
40class PHINode;
41class Instruction;
42
43//===----------------------------------------------------------------------===//
44/// Loop class - Instances of this class are used to represent loops that are
45/// detected in the flow graph
46///
47class Loop {
48  Loop *ParentLoop;
49  std::vector<Loop*> SubLoops;       // Loops contained entirely within this one
50  std::vector<BasicBlock*> Blocks;   // First entry is the header node
51
52  Loop(const Loop &);                  // DO NOT IMPLEMENT
53  const Loop &operator=(const Loop &); // DO NOT IMPLEMENT
54public:
55  /// Loop ctor - This creates an empty loop.
56  Loop() : ParentLoop(0) {}
57  ~Loop() {
58    for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
59      delete SubLoops[i];
60  }
61
62  unsigned getLoopDepth() const {
63    unsigned D = 0;
64    for (const Loop *CurLoop = this; CurLoop; CurLoop = CurLoop->ParentLoop)
65      ++D;
66    return D;
67  }
68  BasicBlock *getHeader() const { return Blocks.front(); }
69  Loop *getParentLoop() const { return ParentLoop; }
70
71  /// contains - Return true of the specified basic block is in this loop
72  ///
73  bool contains(const BasicBlock *BB) const;
74
75  /// iterator/begin/end - Return the loops contained entirely within this loop.
76  ///
77  typedef std::vector<Loop*>::const_iterator iterator;
78  iterator begin() const { return SubLoops.begin(); }
79  iterator end() const { return SubLoops.end(); }
80
81  /// getBlocks - Get a list of the basic blocks which make up this loop.
82  ///
83  const std::vector<BasicBlock*> &getBlocks() const { return Blocks; }
84  typedef std::vector<BasicBlock*>::const_iterator block_iterator;
85  block_iterator block_begin() const { return Blocks.begin(); }
86  block_iterator block_end() const { return Blocks.end(); }
87
88  /// isLoopExit - True if terminator in the block can branch to another block
89  /// that is outside of the current loop.
90  ///
91  bool isLoopExit(const BasicBlock *BB) const;
92
93  /// getNumBackEdges - Calculate the number of back edges to the loop header
94  ///
95  unsigned getNumBackEdges() const;
96
97  /// isLoopInvariant - Return true if the specified value is loop invariant
98  ///
99  bool isLoopInvariant(Value *V) const;
100
101  //===--------------------------------------------------------------------===//
102  // APIs for simple analysis of the loop.
103  //
104  // Note that all of these methods can fail on general loops (ie, there may not
105  // be a preheader, etc).  For best success, the loop simplification and
106  // induction variable canonicalization pass should be used to normalize loops
107  // for easy analysis.  These methods assume canonical loops.
108
109  /// getExitBlocks - Return all of the successor blocks of this loop.  These
110  /// are the blocks _outside of the current loop_ which are branched to.
111  ///
112  void getExitBlocks(std::vector<BasicBlock*> &Blocks) const;
113
114  /// getLoopPreheader - If there is a preheader for this loop, return it.  A
115  /// loop has a preheader if there is only one edge to the header of the loop
116  /// from outside of the loop.  If this is the case, the block branching to the
117  /// header of the loop is the preheader node.
118  ///
119  /// This method returns null if there is no preheader for the loop.
120  ///
121  BasicBlock *getLoopPreheader() const;
122
123  /// getCanonicalInductionVariable - Check to see if the loop has a canonical
124  /// induction variable: an integer recurrence that starts at 0 and increments
125  /// by one each time through the loop.  If so, return the phi node that
126  /// corresponds to it.
127  ///
128  PHINode *getCanonicalInductionVariable() const;
129
130  /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
131  /// the canonical induction variable value for the "next" iteration of the
132  /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
133  ///
134  Instruction *getCanonicalInductionVariableIncrement() const;
135
136  /// getTripCount - Return a loop-invariant LLVM value indicating the number of
137  /// times the loop will be executed.  Note that this means that the backedge
138  /// of the loop executes N-1 times.  If the trip-count cannot be determined,
139  /// this returns null.
140  ///
141  Value *getTripCount() const;
142
143  //===--------------------------------------------------------------------===//
144  // APIs for updating loop information after changing the CFG
145  //
146
147  /// addBasicBlockToLoop - This method is used by other analyses to update loop
148  /// information.  NewBB is set to be a new member of the current loop.
149  /// Because of this, it is added as a member of all parent loops, and is added
150  /// to the specified LoopInfo object as being in the current basic block.  It
151  /// is not valid to replace the loop header with this method.
152  ///
153  void addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI);
154
155  /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
156  /// the OldChild entry in our children list with NewChild, and updates the
157  /// parent pointer of OldChild to be null and the NewChild to be this loop.
158  /// This updates the loop depth of the new child.
159  void replaceChildLoopWith(Loop *OldChild, Loop *NewChild);
160
161  /// addChildLoop - Add the specified loop to be a child of this loop.  This
162  /// updates the loop depth of the new child.
163  ///
164  void addChildLoop(Loop *NewChild);
165
166  /// removeChildLoop - This removes the specified child from being a subloop of
167  /// this loop.  The loop is not deleted, as it will presumably be inserted
168  /// into another loop.
169  Loop *removeChildLoop(iterator OldChild);
170
171  /// addBlockEntry - This adds a basic block directly to the basic block list.
172  /// This should only be used by transformations that create new loops.  Other
173  /// transformations should use addBasicBlockToLoop.
174  void addBlockEntry(BasicBlock *BB) {
175    Blocks.push_back(BB);
176  }
177
178  /// removeBlockFromLoop - This removes the specified basic block from the
179  /// current loop, updating the Blocks as appropriate.  This does not update
180  /// the mapping in the LoopInfo class.
181  void removeBlockFromLoop(BasicBlock *BB);
182
183  void print(std::ostream &O, unsigned Depth = 0) const;
184  void dump() const;
185private:
186  friend class LoopInfo;
187  Loop(BasicBlock *BB) : ParentLoop(0) {
188    Blocks.push_back(BB);
189  }
190};
191
192
193
194//===----------------------------------------------------------------------===//
195/// LoopInfo - This class builds and contains all of the top level loop
196/// structures in the specified function.
197///
198class LoopInfo : public FunctionPass {
199  // BBMap - Mapping of basic blocks to the inner most loop they occur in
200  std::map<BasicBlock*, Loop*> BBMap;
201  std::vector<Loop*> TopLevelLoops;
202  friend class Loop;
203public:
204  ~LoopInfo() { releaseMemory(); }
205
206  /// iterator/begin/end - The interface to the top-level loops in the current
207  /// function.
208  ///
209  typedef std::vector<Loop*>::const_iterator iterator;
210  iterator begin() const { return TopLevelLoops.begin(); }
211  iterator end() const { return TopLevelLoops.end(); }
212
213  /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
214  /// block is in no loop (for example the entry node), null is returned.
215  ///
216  Loop *getLoopFor(const BasicBlock *BB) const {
217    std::map<BasicBlock *, Loop*>::const_iterator I=BBMap.find((BasicBlock*)BB);
218    return I != BBMap.end() ? I->second : 0;
219  }
220
221  /// operator[] - same as getLoopFor...
222  ///
223  const Loop *operator[](const BasicBlock *BB) const {
224    return getLoopFor(BB);
225  }
226
227  /// getLoopDepth - Return the loop nesting level of the specified block...
228  ///
229  unsigned getLoopDepth(const BasicBlock *BB) const {
230    const Loop *L = getLoopFor(BB);
231    return L ? L->getLoopDepth() : 0;
232  }
233
234  // isLoopHeader - True if the block is a loop header node
235  bool isLoopHeader(BasicBlock *BB) const {
236    return getLoopFor(BB)->getHeader() == BB;
237  }
238
239  /// runOnFunction - Calculate the natural loop information.
240  ///
241  virtual bool runOnFunction(Function &F);
242
243  virtual void releaseMemory();
244  void print(std::ostream &O) const;
245
246  /// getAnalysisUsage - Requires dominator sets
247  ///
248  virtual void getAnalysisUsage(AnalysisUsage &AU) const;
249
250  /// removeLoop - This removes the specified top-level loop from this loop info
251  /// object.  The loop is not deleted, as it will presumably be inserted into
252  /// another loop.
253  Loop *removeLoop(iterator I);
254
255  /// changeLoopFor - Change the top-level loop that contains BB to the
256  /// specified loop.  This should be used by transformations that restructure
257  /// the loop hierarchy tree.
258  void changeLoopFor(BasicBlock *BB, Loop *L);
259
260  /// changeTopLevelLoop - Replace the specified loop in the top-level loops
261  /// list with the indicated loop.
262  void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop);
263
264  /// addTopLevelLoop - This adds the specified loop to the collection of
265  /// top-level loops.
266  void addTopLevelLoop(Loop *New) {
267    assert(New->getParentLoop() == 0 && "Loop already in subloop!");
268    TopLevelLoops.push_back(New);
269  }
270
271  /// removeBlock - This method completely removes BB from all data structures,
272  /// including all of the Loop objects it is nested in and our mapping from
273  /// BasicBlocks to loops.
274  void removeBlock(BasicBlock *BB);
275
276  static void stub();  // Noop
277private:
278  void Calculate(const DominatorSet &DS);
279  Loop *ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS);
280  void MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent);
281  void InsertLoopInto(Loop *L, Loop *Parent);
282};
283
284
285// Make sure that any clients of this file link in LoopInfo.cpp
286static IncludeFile
287LOOP_INFO_INCLUDE_FILE((void*)&LoopInfo::stub);
288
289// Allow clients to walk the list of nested loops...
290template <> struct GraphTraits<const Loop*> {
291  typedef const Loop NodeType;
292  typedef std::vector<Loop*>::const_iterator ChildIteratorType;
293
294  static NodeType *getEntryNode(const Loop *L) { return L; }
295  static inline ChildIteratorType child_begin(NodeType *N) {
296    return N->begin();
297  }
298  static inline ChildIteratorType child_end(NodeType *N) {
299    return N->end();
300  }
301};
302
303template <> struct GraphTraits<Loop*> {
304  typedef Loop NodeType;
305  typedef std::vector<Loop*>::const_iterator ChildIteratorType;
306
307  static NodeType *getEntryNode(Loop *L) { return L; }
308  static inline ChildIteratorType child_begin(NodeType *N) {
309    return N->begin();
310  }
311  static inline ChildIteratorType child_end(NodeType *N) {
312    return N->end();
313  }
314};
315
316} // End llvm namespace
317
318#endif
319