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