1 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
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.
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.
18 // It can calculate on the fly various bits of information, for example:
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
28 //===----------------------------------------------------------------------===//
30 #ifndef LLVM_ANALYSIS_LOOP_INFO_H
31 #define LLVM_ANALYSIS_LOOP_INFO_H
33 #include "llvm/Pass.h"
34 #include "llvm/ADT/GraphTraits.h"
43 //===----------------------------------------------------------------------===//
44 /// Loop class - Instances of this class are used to represent loops that are
45 /// detected in the flow graph
49 std::vector<Loop*> SubLoops; // Loops contained entirely within this one
50 std::vector<BasicBlock*> Blocks; // First entry is the header node
52 Loop(const Loop &); // DO NOT IMPLEMENT
53 const Loop &operator=(const Loop &); // DO NOT IMPLEMENT
55 /// Loop ctor - This creates an empty loop.
56 Loop() : ParentLoop(0) {}
58 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
62 unsigned getLoopDepth() const {
64 for (const Loop *CurLoop = this; CurLoop; CurLoop = CurLoop->ParentLoop)
68 BasicBlock *getHeader() const { return Blocks.front(); }
69 Loop *getParentLoop() const { return ParentLoop; }
71 /// contains - Return true of the specified basic block is in this loop
73 bool contains(const BasicBlock *BB) const;
75 /// iterator/begin/end - Return the loops contained entirely within this loop.
77 const std::vector<Loop*> &getSubLoops() const { return SubLoops; }
78 typedef std::vector<Loop*>::const_iterator iterator;
79 iterator begin() const { return SubLoops.begin(); }
80 iterator end() const { return SubLoops.end(); }
82 /// getBlocks - Get a list of the basic blocks which make up this loop.
84 const std::vector<BasicBlock*> &getBlocks() const { return Blocks; }
85 typedef std::vector<BasicBlock*>::const_iterator block_iterator;
86 block_iterator block_begin() const { return Blocks.begin(); }
87 block_iterator block_end() const { return Blocks.end(); }
89 /// isLoopExit - True if terminator in the block can branch to another block
90 /// that is outside of the current loop.
92 bool isLoopExit(const BasicBlock *BB) const;
94 /// getNumBackEdges - Calculate the number of back edges to the loop header
96 unsigned getNumBackEdges() const;
98 /// isLoopInvariant - Return true if the specified value is loop invariant
100 bool isLoopInvariant(Value *V) const;
102 //===--------------------------------------------------------------------===//
103 // APIs for simple analysis of the loop.
105 // Note that all of these methods can fail on general loops (ie, there may not
106 // be a preheader, etc). For best success, the loop simplification and
107 // induction variable canonicalization pass should be used to normalize loops
108 // for easy analysis. These methods assume canonical loops.
110 /// getExitBlocks - Return all of the successor blocks of this loop. These
111 /// are the blocks _outside of the current loop_ which are branched to.
113 void getExitBlocks(std::vector<BasicBlock*> &Blocks) const;
115 /// getLoopPreheader - If there is a preheader for this loop, return it. A
116 /// loop has a preheader if there is only one edge to the header of the loop
117 /// from outside of the loop. If this is the case, the block branching to the
118 /// header of the loop is the preheader node.
120 /// This method returns null if there is no preheader for the loop.
122 BasicBlock *getLoopPreheader() const;
124 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
125 /// induction variable: an integer recurrence that starts at 0 and increments
126 /// by one each time through the loop. If so, return the phi node that
127 /// corresponds to it.
129 PHINode *getCanonicalInductionVariable() const;
131 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
132 /// the canonical induction variable value for the "next" iteration of the
133 /// loop. This always succeeds if getCanonicalInductionVariable succeeds.
135 Instruction *getCanonicalInductionVariableIncrement() const;
137 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
138 /// times the loop will be executed. Note that this means that the backedge
139 /// of the loop executes N-1 times. If the trip-count cannot be determined,
140 /// this returns null.
142 Value *getTripCount() const;
144 //===--------------------------------------------------------------------===//
145 // APIs for updating loop information after changing the CFG
148 /// addBasicBlockToLoop - This method is used by other analyses to update loop
149 /// information. NewBB is set to be a new member of the current loop.
150 /// Because of this, it is added as a member of all parent loops, and is added
151 /// to the specified LoopInfo object as being in the current basic block. It
152 /// is not valid to replace the loop header with this method.
154 void addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI);
156 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
157 /// the OldChild entry in our children list with NewChild, and updates the
158 /// parent pointer of OldChild to be null and the NewChild to be this loop.
159 /// This updates the loop depth of the new child.
160 void replaceChildLoopWith(Loop *OldChild, Loop *NewChild);
162 /// addChildLoop - Add the specified loop to be a child of this loop. This
163 /// updates the loop depth of the new child.
165 void addChildLoop(Loop *NewChild);
167 /// removeChildLoop - This removes the specified child from being a subloop of
168 /// this loop. The loop is not deleted, as it will presumably be inserted
169 /// into another loop.
170 Loop *removeChildLoop(iterator OldChild);
172 /// addBlockEntry - This adds a basic block directly to the basic block list.
173 /// This should only be used by transformations that create new loops. Other
174 /// transformations should use addBasicBlockToLoop.
175 void addBlockEntry(BasicBlock *BB) {
176 Blocks.push_back(BB);
179 /// moveToHeader - This method is used to move BB (which must be part of this
180 /// loop) to be the loop header of the loop (the block that dominates all
182 void moveToHeader(BasicBlock *BB) {
183 if (Blocks[0] == BB) return;
184 for (unsigned i = 0; ; ++i) {
185 assert(i != Blocks.size() && "Loop does not contain BB!");
186 if (Blocks[i] == BB) {
187 Blocks[i] = Blocks[0];
194 /// removeBlockFromLoop - This removes the specified basic block from the
195 /// current loop, updating the Blocks as appropriate. This does not update
196 /// the mapping in the LoopInfo class.
197 void removeBlockFromLoop(BasicBlock *BB);
199 void print(std::ostream &O, unsigned Depth = 0) const;
202 friend class LoopInfo;
203 Loop(BasicBlock *BB) : ParentLoop(0) {
204 Blocks.push_back(BB);
210 //===----------------------------------------------------------------------===//
211 /// LoopInfo - This class builds and contains all of the top level loop
212 /// structures in the specified function.
214 class LoopInfo : public FunctionPass {
215 // BBMap - Mapping of basic blocks to the inner most loop they occur in
216 std::map<BasicBlock*, Loop*> BBMap;
217 std::vector<Loop*> TopLevelLoops;
220 ~LoopInfo() { releaseMemory(); }
222 /// iterator/begin/end - The interface to the top-level loops in the current
225 typedef std::vector<Loop*>::const_iterator iterator;
226 iterator begin() const { return TopLevelLoops.begin(); }
227 iterator end() const { return TopLevelLoops.end(); }
229 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
230 /// block is in no loop (for example the entry node), null is returned.
232 Loop *getLoopFor(const BasicBlock *BB) const {
233 std::map<BasicBlock *, Loop*>::const_iterator I=
234 BBMap.find(const_cast<BasicBlock*>(BB));
235 return I != BBMap.end() ? I->second : 0;
238 /// operator[] - same as getLoopFor...
240 const Loop *operator[](const BasicBlock *BB) const {
241 return getLoopFor(BB);
244 /// getLoopDepth - Return the loop nesting level of the specified block...
246 unsigned getLoopDepth(const BasicBlock *BB) const {
247 const Loop *L = getLoopFor(BB);
248 return L ? L->getLoopDepth() : 0;
251 // isLoopHeader - True if the block is a loop header node
252 bool isLoopHeader(BasicBlock *BB) const {
253 const Loop *L = getLoopFor(BB);
254 return L && L->getHeader() == BB;
257 /// runOnFunction - Calculate the natural loop information.
259 virtual bool runOnFunction(Function &F);
261 virtual void releaseMemory();
262 void print(std::ostream &O, const Module* = 0) const;
264 /// getAnalysisUsage - Requires dominator sets
266 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
268 /// removeLoop - This removes the specified top-level loop from this loop info
269 /// object. The loop is not deleted, as it will presumably be inserted into
271 Loop *removeLoop(iterator I);
273 /// changeLoopFor - Change the top-level loop that contains BB to the
274 /// specified loop. This should be used by transformations that restructure
275 /// the loop hierarchy tree.
276 void changeLoopFor(BasicBlock *BB, Loop *L);
278 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
279 /// list with the indicated loop.
280 void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop);
282 /// addTopLevelLoop - This adds the specified loop to the collection of
284 void addTopLevelLoop(Loop *New) {
285 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
286 TopLevelLoops.push_back(New);
289 /// removeBlock - This method completely removes BB from all data structures,
290 /// including all of the Loop objects it is nested in and our mapping from
291 /// BasicBlocks to loops.
292 void removeBlock(BasicBlock *BB);
294 static void stub(); // Noop
296 void Calculate(const DominatorSet &DS);
297 Loop *ConsiderForLoop(BasicBlock *BB, const DominatorSet &DS);
298 void MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent);
299 void InsertLoopInto(Loop *L, Loop *Parent);
303 // Make sure that any clients of this file link in LoopInfo.cpp
305 LOOP_INFO_INCLUDE_FILE((void*)(&LoopInfo::stub));
307 // Allow clients to walk the list of nested loops...
308 template <> struct GraphTraits<const Loop*> {
309 typedef const Loop NodeType;
310 typedef std::vector<Loop*>::const_iterator ChildIteratorType;
312 static NodeType *getEntryNode(const Loop *L) { return L; }
313 static inline ChildIteratorType child_begin(NodeType *N) {
316 static inline ChildIteratorType child_end(NodeType *N) {
321 template <> struct GraphTraits<Loop*> {
322 typedef Loop NodeType;
323 typedef std::vector<Loop*>::const_iterator ChildIteratorType;
325 static NodeType *getEntryNode(Loop *L) { return L; }
326 static inline ChildIteratorType child_begin(NodeType *N) {
329 static inline ChildIteratorType child_end(NodeType *N) {
334 } // End llvm namespace