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