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"
35 #include "llvm/ADT/SmallVector.h"
44 //===----------------------------------------------------------------------===//
45 /// Loop class - Instances of this class are used to represent loops that are
46 /// detected in the flow graph
50 std::vector<Loop*> SubLoops; // Loops contained entirely within this one
51 std::vector<BasicBlock*> Blocks; // First entry is the header node
53 Loop(const Loop &); // DO NOT IMPLEMENT
54 const Loop &operator=(const Loop &); // DO NOT IMPLEMENT
56 /// Loop ctor - This creates an empty loop.
57 Loop() : ParentLoop(0) {}
59 for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
63 unsigned getLoopDepth() const {
65 for (const Loop *CurLoop = this; CurLoop; CurLoop = CurLoop->ParentLoop)
69 BasicBlock *getHeader() const { return Blocks.front(); }
70 Loop *getParentLoop() const { return ParentLoop; }
72 /// contains - Return true of the specified basic block is in this loop
74 bool contains(const BasicBlock *BB) const;
76 /// iterator/begin/end - Return the loops contained entirely within this loop.
78 const std::vector<Loop*> &getSubLoops() const { return SubLoops; }
79 typedef std::vector<Loop*>::const_iterator iterator;
80 iterator begin() const { return SubLoops.begin(); }
81 iterator end() const { return SubLoops.end(); }
83 /// getBlocks - Get a list of the basic blocks which make up this loop.
85 const std::vector<BasicBlock*> &getBlocks() const { return Blocks; }
86 typedef std::vector<BasicBlock*>::const_iterator block_iterator;
87 block_iterator block_begin() const { return Blocks.begin(); }
88 block_iterator block_end() const { return Blocks.end(); }
90 /// isLoopExit - True if terminator in the block can branch to another block
91 /// that is outside of the current loop.
93 bool isLoopExit(const BasicBlock *BB) const;
95 /// getNumBackEdges - Calculate the number of back edges to the loop header
97 unsigned getNumBackEdges() const;
99 /// isLoopInvariant - Return true if the specified value is loop invariant
101 bool isLoopInvariant(Value *V) const;
103 //===--------------------------------------------------------------------===//
104 // APIs for simple analysis of the loop.
106 // Note that all of these methods can fail on general loops (ie, there may not
107 // be a preheader, etc). For best success, the loop simplification and
108 // induction variable canonicalization pass should be used to normalize loops
109 // for easy analysis. These methods assume canonical loops.
111 /// getExitingBlocks - Return all blocks inside the loop that have successors
112 /// outside of the loop. These are the blocks _inside of the current loop_
113 /// which branch out. The returned list is always unique.
115 void getExitingBlocks(SmallVectorImpl<BasicBlock *> &Blocks) const;
117 /// getExitBlocks - Return all of the successor blocks of this loop. These
118 /// are the blocks _outside of the current loop_ which are branched to.
120 void getExitBlocks(SmallVectorImpl<BasicBlock* > &Blocks) const;
122 /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
123 /// These are the blocks _outside of the current loop_ which are branched to.
124 /// This assumes that loop is in canonical form.
126 void getUniqueExitBlocks(SmallVectorImpl<BasicBlock*> &ExitBlocks) const;
128 /// getLoopPreheader - If there is a preheader for this loop, return it. A
129 /// loop has a preheader if there is only one edge to the header of the loop
130 /// from outside of the loop. If this is the case, the block branching to the
131 /// header of the loop is the preheader node.
133 /// This method returns null if there is no preheader for the loop.
135 BasicBlock *getLoopPreheader() const;
137 /// getLoopLatch - If there is a latch block for this loop, return it. A
138 /// latch block is the canonical backedge for a loop. A loop header in normal
139 /// form has two edges into it: one from a preheader and one from a latch
141 BasicBlock *getLoopLatch() const;
143 /// getCanonicalInductionVariable - Check to see if the loop has a canonical
144 /// induction variable: an integer recurrence that starts at 0 and increments
145 /// by one each time through the loop. If so, return the phi node that
146 /// corresponds to it.
148 PHINode *getCanonicalInductionVariable() const;
150 /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
151 /// the canonical induction variable value for the "next" iteration of the
152 /// loop. This always succeeds if getCanonicalInductionVariable succeeds.
154 Instruction *getCanonicalInductionVariableIncrement() const;
156 /// getTripCount - Return a loop-invariant LLVM value indicating the number of
157 /// times the loop will be executed. Note that this means that the backedge
158 /// of the loop executes N-1 times. If the trip-count cannot be determined,
159 /// this returns null.
161 Value *getTripCount() const;
163 /// isLCSSAForm - Return true if the Loop is in LCSSA form
164 bool isLCSSAForm() const;
166 //===--------------------------------------------------------------------===//
167 // APIs for updating loop information after changing the CFG
170 /// addBasicBlockToLoop - This method is used by other analyses to update loop
171 /// information. NewBB is set to be a new member of the current loop.
172 /// Because of this, it is added as a member of all parent loops, and is added
173 /// to the specified LoopInfo object as being in the current basic block. It
174 /// is not valid to replace the loop header with this method.
176 void addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI);
178 /// replaceChildLoopWith - This is used when splitting loops up. It replaces
179 /// the OldChild entry in our children list with NewChild, and updates the
180 /// parent pointer of OldChild to be null and the NewChild to be this loop.
181 /// This updates the loop depth of the new child.
182 void replaceChildLoopWith(Loop *OldChild, Loop *NewChild);
184 /// addChildLoop - Add the specified loop to be a child of this loop. This
185 /// updates the loop depth of the new child.
187 void addChildLoop(Loop *NewChild);
189 /// removeChildLoop - This removes the specified child from being a subloop of
190 /// this loop. The loop is not deleted, as it will presumably be inserted
191 /// into another loop.
192 Loop *removeChildLoop(iterator OldChild);
194 /// addBlockEntry - This adds a basic block directly to the basic block list.
195 /// This should only be used by transformations that create new loops. Other
196 /// transformations should use addBasicBlockToLoop.
197 void addBlockEntry(BasicBlock *BB) {
198 Blocks.push_back(BB);
201 /// moveToHeader - This method is used to move BB (which must be part of this
202 /// loop) to be the loop header of the loop (the block that dominates all
204 void moveToHeader(BasicBlock *BB) {
205 if (Blocks[0] == BB) return;
206 for (unsigned i = 0; ; ++i) {
207 assert(i != Blocks.size() && "Loop does not contain BB!");
208 if (Blocks[i] == BB) {
209 Blocks[i] = Blocks[0];
216 /// removeBlockFromLoop - This removes the specified basic block from the
217 /// current loop, updating the Blocks as appropriate. This does not update
218 /// the mapping in the LoopInfo class.
219 void removeBlockFromLoop(BasicBlock *BB);
221 /// verifyLoop - Verify loop structure
222 void verifyLoop() const;
224 void print(std::ostream &O, unsigned Depth = 0) const;
225 void print(std::ostream *O, unsigned Depth = 0) const {
226 if (O) print(*O, Depth);
230 friend class LoopInfo;
231 Loop(BasicBlock *BB) : ParentLoop(0) {
232 Blocks.push_back(BB);
238 //===----------------------------------------------------------------------===//
239 /// LoopInfo - This class builds and contains all of the top level loop
240 /// structures in the specified function.
242 class LoopInfo : public FunctionPass {
243 // BBMap - Mapping of basic blocks to the inner most loop they occur in
244 std::map<BasicBlock*, Loop*> BBMap;
245 std::vector<Loop*> TopLevelLoops;
248 static char ID; // Pass identification, replacement for typeid
250 LoopInfo() : FunctionPass(intptr_t(&ID)) {}
251 ~LoopInfo() { releaseMemory(); }
253 /// iterator/begin/end - The interface to the top-level loops in the current
256 typedef std::vector<Loop*>::const_iterator iterator;
257 iterator begin() const { return TopLevelLoops.begin(); }
258 iterator end() const { return TopLevelLoops.end(); }
260 /// getLoopFor - Return the inner most loop that BB lives in. If a basic
261 /// block is in no loop (for example the entry node), null is returned.
263 Loop *getLoopFor(const BasicBlock *BB) const {
264 std::map<BasicBlock *, Loop*>::const_iterator I=
265 BBMap.find(const_cast<BasicBlock*>(BB));
266 return I != BBMap.end() ? I->second : 0;
269 /// operator[] - same as getLoopFor...
271 const Loop *operator[](const BasicBlock *BB) const {
272 return getLoopFor(BB);
275 /// getLoopDepth - Return the loop nesting level of the specified block...
277 unsigned getLoopDepth(const BasicBlock *BB) const {
278 const Loop *L = getLoopFor(BB);
279 return L ? L->getLoopDepth() : 0;
282 // isLoopHeader - True if the block is a loop header node
283 bool isLoopHeader(BasicBlock *BB) const {
284 const Loop *L = getLoopFor(BB);
285 return L && L->getHeader() == BB;
288 /// runOnFunction - Calculate the natural loop information.
290 virtual bool runOnFunction(Function &F);
292 virtual void releaseMemory();
294 void print(std::ostream &O, const Module* = 0) const;
295 void print(std::ostream *O, const Module* M = 0) const {
299 virtual void getAnalysisUsage(AnalysisUsage &AU) const;
301 /// removeLoop - This removes the specified top-level loop from this loop info
302 /// object. The loop is not deleted, as it will presumably be inserted into
304 Loop *removeLoop(iterator I);
306 /// changeLoopFor - Change the top-level loop that contains BB to the
307 /// specified loop. This should be used by transformations that restructure
308 /// the loop hierarchy tree.
309 void changeLoopFor(BasicBlock *BB, Loop *L);
311 /// changeTopLevelLoop - Replace the specified loop in the top-level loops
312 /// list with the indicated loop.
313 void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop);
315 /// addTopLevelLoop - This adds the specified loop to the collection of
317 void addTopLevelLoop(Loop *New) {
318 assert(New->getParentLoop() == 0 && "Loop already in subloop!");
319 TopLevelLoops.push_back(New);
322 /// removeBlock - This method completely removes BB from all data structures,
323 /// including all of the Loop objects it is nested in and our mapping from
324 /// BasicBlocks to loops.
325 void removeBlock(BasicBlock *BB);
328 void Calculate(DominatorTree &DT);
329 Loop *ConsiderForLoop(BasicBlock *BB, DominatorTree &DT);
330 void MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent);
331 void InsertLoopInto(Loop *L, Loop *Parent);
335 // Allow clients to walk the list of nested loops...
336 template <> struct GraphTraits<const Loop*> {
337 typedef const Loop NodeType;
338 typedef std::vector<Loop*>::const_iterator ChildIteratorType;
340 static NodeType *getEntryNode(const Loop *L) { return L; }
341 static inline ChildIteratorType child_begin(NodeType *N) {
344 static inline ChildIteratorType child_end(NodeType *N) {
349 template <> struct GraphTraits<Loop*> {
350 typedef Loop NodeType;
351 typedef std::vector<Loop*>::const_iterator ChildIteratorType;
353 static NodeType *getEntryNode(Loop *L) { return L; }
354 static inline ChildIteratorType child_begin(NodeType *N) {
357 static inline ChildIteratorType child_end(NodeType *N) {
362 } // End llvm namespace
364 // Make sure that any clients of this file link in LoopInfo.cpp
365 FORCE_DEFINING_FILE_TO_BE_LINKED(LoopInfo)