Make Loop::getLoopLatch() work on loops which don't have preheaders, as
[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
118   /// block 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   BlockT *getLoopLatch() const {
273     BlockT *Header = getHeader();
274     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
275     typename InvBlockTraits::ChildIteratorType PI =
276                                             InvBlockTraits::child_begin(Header);
277     typename InvBlockTraits::ChildIteratorType PE =
278                                               InvBlockTraits::child_end(Header);
279     BlockT *Latch = 0;
280     for (; PI != PE; ++PI)
281       if (contains(*PI)) {
282         if (Latch) return 0;
283         Latch = *PI;
284       }
285
286     return Latch;
287   }
288
289   //===--------------------------------------------------------------------===//
290   // APIs for updating loop information after changing the CFG
291   //
292
293   /// addBasicBlockToLoop - This method is used by other analyses to update loop
294   /// information.  NewBB is set to be a new member of the current loop.
295   /// Because of this, it is added as a member of all parent loops, and is added
296   /// to the specified LoopInfo object as being in the current basic block.  It
297   /// is not valid to replace the loop header with this method.
298   ///
299   void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
300
301   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
302   /// the OldChild entry in our children list with NewChild, and updates the
303   /// parent pointer of OldChild to be null and the NewChild to be this loop.
304   /// This updates the loop depth of the new child.
305   void replaceChildLoopWith(LoopT *OldChild,
306                             LoopT *NewChild) {
307     assert(OldChild->ParentLoop == this && "This loop is already broken!");
308     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
309     typename std::vector<LoopT *>::iterator I =
310                           std::find(SubLoops.begin(), SubLoops.end(), OldChild);
311     assert(I != SubLoops.end() && "OldChild not in loop!");
312     *I = NewChild;
313     OldChild->ParentLoop = 0;
314     NewChild->ParentLoop = static_cast<LoopT *>(this);
315   }
316
317   /// addChildLoop - Add the specified loop to be a child of this loop.  This
318   /// updates the loop depth of the new child.
319   ///
320   void addChildLoop(LoopT *NewChild) {
321     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
322     NewChild->ParentLoop = static_cast<LoopT *>(this);
323     SubLoops.push_back(NewChild);
324   }
325
326   /// removeChildLoop - This removes the specified child from being a subloop of
327   /// this loop.  The loop is not deleted, as it will presumably be inserted
328   /// into another loop.
329   LoopT *removeChildLoop(iterator I) {
330     assert(I != SubLoops.end() && "Cannot remove end iterator!");
331     LoopT *Child = *I;
332     assert(Child->ParentLoop == this && "Child is not a child of this loop!");
333     SubLoops.erase(SubLoops.begin()+(I-begin()));
334     Child->ParentLoop = 0;
335     return Child;
336   }
337
338   /// addBlockEntry - This adds a basic block directly to the basic block list.
339   /// This should only be used by transformations that create new loops.  Other
340   /// transformations should use addBasicBlockToLoop.
341   void addBlockEntry(BlockT *BB) {
342     Blocks.push_back(BB);
343   }
344
345   /// moveToHeader - This method is used to move BB (which must be part of this
346   /// loop) to be the loop header of the loop (the block that dominates all
347   /// others).
348   void moveToHeader(BlockT *BB) {
349     if (Blocks[0] == BB) return;
350     for (unsigned i = 0; ; ++i) {
351       assert(i != Blocks.size() && "Loop does not contain BB!");
352       if (Blocks[i] == BB) {
353         Blocks[i] = Blocks[0];
354         Blocks[0] = BB;
355         return;
356       }
357     }
358   }
359
360   /// removeBlockFromLoop - This removes the specified basic block from the
361   /// current loop, updating the Blocks as appropriate.  This does not update
362   /// the mapping in the LoopInfo class.
363   void removeBlockFromLoop(BlockT *BB) {
364     RemoveFromVector(Blocks, BB);
365   }
366
367   /// verifyLoop - Verify loop structure
368   void verifyLoop() const {
369 #ifndef NDEBUG
370     assert(!Blocks.empty() && "Loop header is missing");
371
372     // Sort the blocks vector so that we can use binary search to do quick
373     // lookups.
374     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
375     std::sort(LoopBBs.begin(), LoopBBs.end());
376
377     // Check the individual blocks.
378     for (block_iterator I = block_begin(), E = block_end(); I != E; ++I) {
379       BlockT *BB = *I;
380       bool HasInsideLoopSuccs = false;
381       bool HasInsideLoopPreds = false;
382       SmallVector<BlockT *, 2> OutsideLoopPreds;
383
384       typedef GraphTraits<BlockT*> BlockTraits;
385       for (typename BlockTraits::ChildIteratorType SI =
386            BlockTraits::child_begin(BB), SE = BlockTraits::child_end(BB);
387            SI != SE; ++SI)
388         if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *SI)) {
389           HasInsideLoopSuccs = true;
390           break;
391         }
392       typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
393       for (typename InvBlockTraits::ChildIteratorType PI =
394            InvBlockTraits::child_begin(BB), PE = InvBlockTraits::child_end(BB);
395            PI != PE; ++PI) {
396         if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *PI))
397           HasInsideLoopPreds = true;
398         else
399           OutsideLoopPreds.push_back(*PI);
400       }
401
402       if (BB == getHeader()) {
403         assert(!OutsideLoopPreds.empty() && "Loop is unreachable!");
404       } else if (!OutsideLoopPreds.empty()) {
405         // A non-header loop shouldn't be reachable from outside the loop,
406         // though it is permitted if the predecessor is not itself actually
407         // reachable.
408         BlockT *EntryBB = BB->getParent()->begin();
409         for (df_iterator<BlockT *> NI = df_begin(EntryBB),
410              NE = df_end(EntryBB); NI != NE; ++NI)
411           for (unsigned i = 0, e = OutsideLoopPreds.size(); i != e; ++i)
412             assert(*NI != OutsideLoopPreds[i] &&
413                    "Loop has multiple entry points!");
414       }
415       assert(HasInsideLoopPreds && "Loop block has no in-loop predecessors!");
416       assert(HasInsideLoopSuccs && "Loop block has no in-loop successors!");
417       assert(BB != getHeader()->getParent()->begin() &&
418              "Loop contains function entry block!");
419     }
420
421     // Check the subloops.
422     for (iterator I = begin(), E = end(); I != E; ++I)
423       // Each block in each subloop should be contained within this loop.
424       for (block_iterator BI = (*I)->block_begin(), BE = (*I)->block_end();
425            BI != BE; ++BI) {
426         assert(std::binary_search(LoopBBs.begin(), LoopBBs.end(), *BI) &&
427                "Loop does not contain all the blocks of a subloop!");
428       }
429
430     // Check the parent loop pointer.
431     if (ParentLoop) {
432       assert(std::find(ParentLoop->begin(), ParentLoop->end(), this) !=
433                ParentLoop->end() &&
434              "Loop is not a subloop of its parent!");
435     }
436 #endif
437   }
438
439   /// verifyLoop - Verify loop structure of this loop and all nested loops.
440   void verifyLoopNest() const {
441     // Verify this loop.
442     verifyLoop();
443     // Verify the subloops.
444     for (iterator I = begin(), E = end(); I != E; ++I)
445       (*I)->verifyLoopNest();
446   }
447
448   void print(raw_ostream &OS, unsigned Depth = 0) const {
449     OS.indent(Depth*2) << "Loop at depth " << getLoopDepth()
450        << " containing: ";
451
452     for (unsigned i = 0; i < getBlocks().size(); ++i) {
453       if (i) OS << ",";
454       BlockT *BB = getBlocks()[i];
455       WriteAsOperand(OS, BB, false);
456       if (BB == getHeader())    OS << "<header>";
457       if (BB == getLoopLatch()) OS << "<latch>";
458       if (isLoopExiting(BB))    OS << "<exiting>";
459     }
460     OS << "\n";
461
462     for (iterator I = begin(), E = end(); I != E; ++I)
463       (*I)->print(OS, Depth+2);
464   }
465   
466   void dump() const {
467     print(errs());
468   }
469   
470 protected:
471   friend class LoopInfoBase<BlockT, LoopT>;
472   explicit LoopBase(BlockT *BB) : ParentLoop(0) {
473     Blocks.push_back(BB);
474   }
475 };
476
477 class Loop : public LoopBase<BasicBlock, Loop> {
478 public:
479   Loop() {}
480
481   /// isLoopInvariant - Return true if the specified value is loop invariant
482   ///
483   bool isLoopInvariant(Value *V) const;
484
485   /// isLoopInvariant - Return true if the specified instruction is
486   /// loop-invariant.
487   ///
488   bool isLoopInvariant(Instruction *I) const;
489
490   /// makeLoopInvariant - If the given value is an instruction inside of the
491   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
492   /// Return true if the value after any hoisting is loop invariant. This
493   /// function can be used as a slightly more aggressive replacement for
494   /// isLoopInvariant.
495   ///
496   /// If InsertPt is specified, it is the point to hoist instructions to.
497   /// If null, the terminator of the loop preheader is used.
498   ///
499   bool makeLoopInvariant(Value *V, bool &Changed,
500                          Instruction *InsertPt = 0) const;
501
502   /// makeLoopInvariant - If the given instruction is inside of the
503   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
504   /// Return true if the instruction after any hoisting is loop invariant. This
505   /// function can be used as a slightly more aggressive replacement for
506   /// isLoopInvariant.
507   ///
508   /// If InsertPt is specified, it is the point to hoist instructions to.
509   /// If null, the terminator of the loop preheader is used.
510   ///
511   bool makeLoopInvariant(Instruction *I, bool &Changed,
512                          Instruction *InsertPt = 0) const;
513
514   /// getCanonicalInductionVariable - Check to see if the loop has a canonical
515   /// induction variable: an integer recurrence that starts at 0 and increments
516   /// by one each time through the loop.  If so, return the phi node that
517   /// corresponds to it.
518   ///
519   /// The IndVarSimplify pass transforms loops to have a canonical induction
520   /// variable.
521   ///
522   PHINode *getCanonicalInductionVariable() const;
523
524   /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
525   /// the canonical induction variable value for the "next" iteration of the
526   /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
527   ///
528   Instruction *getCanonicalInductionVariableIncrement() const;
529
530   /// getTripCount - Return a loop-invariant LLVM value indicating the number of
531   /// times the loop will be executed.  Note that this means that the backedge
532   /// of the loop executes N-1 times.  If the trip-count cannot be determined,
533   /// this returns null.
534   ///
535   /// The IndVarSimplify pass transforms loops to have a form that this
536   /// function easily understands.
537   ///
538   Value *getTripCount() const;
539
540   /// getSmallConstantTripCount - Returns the trip count of this loop as a
541   /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
542   /// of not constant. Will also return 0 if the trip count is very large
543   /// (>= 2^32)
544   unsigned getSmallConstantTripCount() const;
545
546   /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
547   /// trip count of this loop as a normal unsigned value, if possible. This
548   /// means that the actual trip count is always a multiple of the returned
549   /// value (don't forget the trip count could very well be zero as well!).
550   ///
551   /// Returns 1 if the trip count is unknown or not guaranteed to be the
552   /// multiple of a constant (which is also the case if the trip count is simply
553   /// constant, use getSmallConstantTripCount for that case), Will also return 1
554   /// if the trip count is very large (>= 2^32).
555   unsigned getSmallConstantTripMultiple() const;
556
557   /// isLCSSAForm - Return true if the Loop is in LCSSA form
558   bool isLCSSAForm() const;
559
560   /// isLoopSimplifyForm - Return true if the Loop is in the form that
561   /// the LoopSimplify form transforms loops to, which is sometimes called
562   /// normal form.
563   bool isLoopSimplifyForm() const;
564
565   /// hasDedicatedExits - Return true if no exit block for the loop
566   /// has a predecessor that is outside the loop.
567   bool hasDedicatedExits() const;
568
569   /// getUniqueExitBlocks - Return all unique successor blocks of this loop. 
570   /// These are the blocks _outside of the current loop_ which are branched to.
571   /// This assumes that loop is in canonical form.
572   ///
573   void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
574
575   /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
576   /// block, return that block. Otherwise return null.
577   BasicBlock *getUniqueExitBlock() const;
578
579 private:
580   friend class LoopInfoBase<BasicBlock, Loop>;
581   explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
582 };
583
584 //===----------------------------------------------------------------------===//
585 /// LoopInfo - This class builds and contains all of the top level loop
586 /// structures in the specified function.
587 ///
588
589 template<class BlockT, class LoopT>
590 class LoopInfoBase {
591   // BBMap - Mapping of basic blocks to the inner most loop they occur in
592   std::map<BlockT *, LoopT *> BBMap;
593   std::vector<LoopT *> TopLevelLoops;
594   friend class LoopBase<BlockT, LoopT>;
595
596   void operator=(const LoopInfoBase &); // do not implement
597   LoopInfoBase(const LoopInfo &);       // do not implement
598 public:
599   LoopInfoBase() { }
600   ~LoopInfoBase() { releaseMemory(); }
601   
602   void releaseMemory() {
603     for (typename std::vector<LoopT *>::iterator I =
604          TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
605       delete *I;   // Delete all of the loops...
606
607     BBMap.clear();                           // Reset internal state of analysis
608     TopLevelLoops.clear();
609   }
610   
611   /// iterator/begin/end - The interface to the top-level loops in the current
612   /// function.
613   ///
614   typedef typename std::vector<LoopT *>::const_iterator iterator;
615   iterator begin() const { return TopLevelLoops.begin(); }
616   iterator end() const { return TopLevelLoops.end(); }
617   bool empty() const { return TopLevelLoops.empty(); }
618   
619   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
620   /// block is in no loop (for example the entry node), null is returned.
621   ///
622   LoopT *getLoopFor(const BlockT *BB) const {
623     typename std::map<BlockT *, LoopT *>::const_iterator I=
624       BBMap.find(const_cast<BlockT*>(BB));
625     return I != BBMap.end() ? I->second : 0;
626   }
627   
628   /// operator[] - same as getLoopFor...
629   ///
630   const LoopT *operator[](const BlockT *BB) const {
631     return getLoopFor(BB);
632   }
633   
634   /// getLoopDepth - Return the loop nesting level of the specified block.  A
635   /// depth of 0 means the block is not inside any loop.
636   ///
637   unsigned getLoopDepth(const BlockT *BB) const {
638     const LoopT *L = getLoopFor(BB);
639     return L ? L->getLoopDepth() : 0;
640   }
641
642   // isLoopHeader - True if the block is a loop header node
643   bool isLoopHeader(BlockT *BB) const {
644     const LoopT *L = getLoopFor(BB);
645     return L && L->getHeader() == BB;
646   }
647   
648   /// removeLoop - This removes the specified top-level loop from this loop info
649   /// object.  The loop is not deleted, as it will presumably be inserted into
650   /// another loop.
651   LoopT *removeLoop(iterator I) {
652     assert(I != end() && "Cannot remove end iterator!");
653     LoopT *L = *I;
654     assert(L->getParentLoop() == 0 && "Not a top-level loop!");
655     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
656     return L;
657   }
658   
659   /// changeLoopFor - Change the top-level loop that contains BB to the
660   /// specified loop.  This should be used by transformations that restructure
661   /// the loop hierarchy tree.
662   void changeLoopFor(BlockT *BB, LoopT *L) {
663     LoopT *&OldLoop = BBMap[BB];
664     assert(OldLoop && "Block not in a loop yet!");
665     OldLoop = L;
666   }
667   
668   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
669   /// list with the indicated loop.
670   void changeTopLevelLoop(LoopT *OldLoop,
671                           LoopT *NewLoop) {
672     typename std::vector<LoopT *>::iterator I =
673                  std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
674     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
675     *I = NewLoop;
676     assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
677            "Loops already embedded into a subloop!");
678   }
679   
680   /// addTopLevelLoop - This adds the specified loop to the collection of
681   /// top-level loops.
682   void addTopLevelLoop(LoopT *New) {
683     assert(New->getParentLoop() == 0 && "Loop already in subloop!");
684     TopLevelLoops.push_back(New);
685   }
686   
687   /// removeBlock - This method completely removes BB from all data structures,
688   /// including all of the Loop objects it is nested in and our mapping from
689   /// BasicBlocks to loops.
690   void removeBlock(BlockT *BB) {
691     typename std::map<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
692     if (I != BBMap.end()) {
693       for (LoopT *L = I->second; L; L = L->getParentLoop())
694         L->removeBlockFromLoop(BB);
695
696       BBMap.erase(I);
697     }
698   }
699   
700   // Internals
701   
702   static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
703                                       const LoopT *ParentLoop) {
704     if (SubLoop == 0) return true;
705     if (SubLoop == ParentLoop) return false;
706     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
707   }
708   
709   void Calculate(DominatorTreeBase<BlockT> &DT) {
710     BlockT *RootNode = DT.getRootNode()->getBlock();
711
712     for (df_iterator<BlockT*> NI = df_begin(RootNode),
713            NE = df_end(RootNode); NI != NE; ++NI)
714       if (LoopT *L = ConsiderForLoop(*NI, DT))
715         TopLevelLoops.push_back(L);
716   }
717   
718   LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
719     if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
720
721     std::vector<BlockT *> TodoStack;
722
723     // Scan the predecessors of BB, checking to see if BB dominates any of
724     // them.  This identifies backedges which target this node...
725     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
726     for (typename InvBlockTraits::ChildIteratorType I =
727          InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
728          I != E; ++I)
729       if (DT.dominates(BB, *I))   // If BB dominates its predecessor...
730         TodoStack.push_back(*I);
731
732     if (TodoStack.empty()) return 0;  // No backedges to this block...
733
734     // Create a new loop to represent this basic block...
735     LoopT *L = new LoopT(BB);
736     BBMap[BB] = L;
737
738     BlockT *EntryBlock = BB->getParent()->begin();
739
740     while (!TodoStack.empty()) {  // Process all the nodes in the loop
741       BlockT *X = TodoStack.back();
742       TodoStack.pop_back();
743
744       if (!L->contains(X) &&         // As of yet unprocessed??
745           DT.dominates(EntryBlock, X)) {   // X is reachable from entry block?
746         // Check to see if this block already belongs to a loop.  If this occurs
747         // then we have a case where a loop that is supposed to be a child of
748         // the current loop was processed before the current loop.  When this
749         // occurs, this child loop gets added to a part of the current loop,
750         // making it a sibling to the current loop.  We have to reparent this
751         // loop.
752         if (LoopT *SubLoop =
753             const_cast<LoopT *>(getLoopFor(X)))
754           if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
755             // Remove the subloop from its current parent...
756             assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
757             LoopT *SLP = SubLoop->ParentLoop;  // SubLoopParent
758             typename std::vector<LoopT *>::iterator I =
759               std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
760             assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
761             SLP->SubLoops.erase(I);   // Remove from parent...
762
763             // Add the subloop to THIS loop...
764             SubLoop->ParentLoop = L;
765             L->SubLoops.push_back(SubLoop);
766           }
767
768         // Normal case, add the block to our loop...
769         L->Blocks.push_back(X);
770         
771         typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
772         
773         // Add all of the predecessors of X to the end of the work stack...
774         TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
775                          InvBlockTraits::child_end(X));
776       }
777     }
778
779     // If there are any loops nested within this loop, create them now!
780     for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
781          E = L->Blocks.end(); I != E; ++I)
782       if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
783         L->SubLoops.push_back(NewLoop);
784         NewLoop->ParentLoop = L;
785       }
786
787     // Add the basic blocks that comprise this loop to the BBMap so that this
788     // loop can be found for them.
789     //
790     for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
791            E = L->Blocks.end(); I != E; ++I)
792       BBMap.insert(std::make_pair(*I, L));
793
794     // Now that we have a list of all of the child loops of this loop, check to
795     // see if any of them should actually be nested inside of each other.  We
796     // can accidentally pull loops our of their parents, so we must make sure to
797     // organize the loop nests correctly now.
798     {
799       std::map<BlockT *, LoopT *> ContainingLoops;
800       for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
801         LoopT *Child = L->SubLoops[i];
802         assert(Child->getParentLoop() == L && "Not proper child loop?");
803
804         if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
805           // If there is already a loop which contains this loop, move this loop
806           // into the containing loop.
807           MoveSiblingLoopInto(Child, ContainingLoop);
808           --i;  // The loop got removed from the SubLoops list.
809         } else {
810           // This is currently considered to be a top-level loop.  Check to see
811           // if any of the contained blocks are loop headers for subloops we
812           // have already processed.
813           for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
814             LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
815             if (BlockLoop == 0) {   // Child block not processed yet...
816               BlockLoop = Child;
817             } else if (BlockLoop != Child) {
818               LoopT *SubLoop = BlockLoop;
819               // Reparent all of the blocks which used to belong to BlockLoops
820               for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
821                 ContainingLoops[SubLoop->Blocks[j]] = Child;
822
823               // There is already a loop which contains this block, that means
824               // that we should reparent the loop which the block is currently
825               // considered to belong to to be a child of this loop.
826               MoveSiblingLoopInto(SubLoop, Child);
827               --i;  // We just shrunk the SubLoops list.
828             }
829           }
830         }
831       }
832     }
833
834     return L;
835   }
836   
837   /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
838   /// of the NewParent Loop, instead of being a sibling of it.
839   void MoveSiblingLoopInto(LoopT *NewChild,
840                            LoopT *NewParent) {
841     LoopT *OldParent = NewChild->getParentLoop();
842     assert(OldParent && OldParent == NewParent->getParentLoop() &&
843            NewChild != NewParent && "Not sibling loops!");
844
845     // Remove NewChild from being a child of OldParent
846     typename std::vector<LoopT *>::iterator I =
847       std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
848                 NewChild);
849     assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
850     OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
851     NewChild->ParentLoop = 0;
852
853     InsertLoopInto(NewChild, NewParent);
854   }
855   
856   /// InsertLoopInto - This inserts loop L into the specified parent loop.  If
857   /// the parent loop contains a loop which should contain L, the loop gets
858   /// inserted into L instead.
859   void InsertLoopInto(LoopT *L, LoopT *Parent) {
860     BlockT *LHeader = L->getHeader();
861     assert(Parent->contains(LHeader) &&
862            "This loop should not be inserted here!");
863
864     // Check to see if it belongs in a child loop...
865     for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
866          i != e; ++i)
867       if (Parent->SubLoops[i]->contains(LHeader)) {
868         InsertLoopInto(L, Parent->SubLoops[i]);
869         return;
870       }
871
872     // If not, insert it here!
873     Parent->SubLoops.push_back(L);
874     L->ParentLoop = Parent;
875   }
876   
877   // Debugging
878   
879   void print(raw_ostream &OS) const {
880     for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
881       TopLevelLoops[i]->print(OS);
882   #if 0
883     for (std::map<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
884            E = BBMap.end(); I != E; ++I)
885       OS << "BB '" << I->first->getName() << "' level = "
886          << I->second->getLoopDepth() << "\n";
887   #endif
888   }
889 };
890
891 class LoopInfo : public FunctionPass {
892   LoopInfoBase<BasicBlock, Loop> LI;
893   friend class LoopBase<BasicBlock, Loop>;
894
895   void operator=(const LoopInfo &); // do not implement
896   LoopInfo(const LoopInfo &);       // do not implement
897 public:
898   static char ID; // Pass identification, replacement for typeid
899
900   LoopInfo() : FunctionPass(&ID) {}
901
902   LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
903
904   /// iterator/begin/end - The interface to the top-level loops in the current
905   /// function.
906   ///
907   typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
908   inline iterator begin() const { return LI.begin(); }
909   inline iterator end() const { return LI.end(); }
910   bool empty() const { return LI.empty(); }
911
912   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
913   /// block is in no loop (for example the entry node), null is returned.
914   ///
915   inline Loop *getLoopFor(const BasicBlock *BB) const {
916     return LI.getLoopFor(BB);
917   }
918
919   /// operator[] - same as getLoopFor...
920   ///
921   inline const Loop *operator[](const BasicBlock *BB) const {
922     return LI.getLoopFor(BB);
923   }
924
925   /// getLoopDepth - Return the loop nesting level of the specified block.  A
926   /// depth of 0 means the block is not inside any loop.
927   ///
928   inline unsigned getLoopDepth(const BasicBlock *BB) const {
929     return LI.getLoopDepth(BB);
930   }
931
932   // isLoopHeader - True if the block is a loop header node
933   inline bool isLoopHeader(BasicBlock *BB) const {
934     return LI.isLoopHeader(BB);
935   }
936
937   /// runOnFunction - Calculate the natural loop information.
938   ///
939   virtual bool runOnFunction(Function &F);
940
941   virtual void verifyAnalysis() const;
942
943   virtual void releaseMemory() { LI.releaseMemory(); }
944
945   virtual void print(raw_ostream &O, const Module* M = 0) const;
946   
947   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
948
949   /// removeLoop - This removes the specified top-level loop from this loop info
950   /// object.  The loop is not deleted, as it will presumably be inserted into
951   /// another loop.
952   inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
953
954   /// changeLoopFor - Change the top-level loop that contains BB to the
955   /// specified loop.  This should be used by transformations that restructure
956   /// the loop hierarchy tree.
957   inline void changeLoopFor(BasicBlock *BB, Loop *L) {
958     LI.changeLoopFor(BB, L);
959   }
960
961   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
962   /// list with the indicated loop.
963   inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
964     LI.changeTopLevelLoop(OldLoop, NewLoop);
965   }
966
967   /// addTopLevelLoop - This adds the specified loop to the collection of
968   /// top-level loops.
969   inline void addTopLevelLoop(Loop *New) {
970     LI.addTopLevelLoop(New);
971   }
972
973   /// removeBlock - This method completely removes BB from all data structures,
974   /// including all of the Loop objects it is nested in and our mapping from
975   /// BasicBlocks to loops.
976   void removeBlock(BasicBlock *BB) {
977     LI.removeBlock(BB);
978   }
979
980   static bool isNotAlreadyContainedIn(const Loop *SubLoop,
981                                       const Loop *ParentLoop) {
982     return
983       LoopInfoBase<BasicBlock, Loop>::isNotAlreadyContainedIn(SubLoop,
984                                                               ParentLoop);
985   }
986 };
987
988
989 // Allow clients to walk the list of nested loops...
990 template <> struct GraphTraits<const Loop*> {
991   typedef const Loop NodeType;
992   typedef LoopInfo::iterator ChildIteratorType;
993
994   static NodeType *getEntryNode(const Loop *L) { return L; }
995   static inline ChildIteratorType child_begin(NodeType *N) {
996     return N->begin();
997   }
998   static inline ChildIteratorType child_end(NodeType *N) {
999     return N->end();
1000   }
1001 };
1002
1003 template <> struct GraphTraits<Loop*> {
1004   typedef Loop NodeType;
1005   typedef LoopInfo::iterator ChildIteratorType;
1006
1007   static NodeType *getEntryNode(Loop *L) { return L; }
1008   static inline ChildIteratorType child_begin(NodeType *N) {
1009     return N->begin();
1010   }
1011   static inline ChildIteratorType child_end(NodeType *N) {
1012     return N->end();
1013   }
1014 };
1015
1016 template<class BlockT, class LoopT>
1017 void
1018 LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
1019                                              LoopInfoBase<BlockT, LoopT> &LIB) {
1020   assert((Blocks.empty() || LIB[getHeader()] == this) &&
1021          "Incorrect LI specified for this loop!");
1022   assert(NewBB && "Cannot add a null basic block to the loop!");
1023   assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
1024
1025   LoopT *L = static_cast<LoopT *>(this);
1026
1027   // Add the loop mapping to the LoopInfo object...
1028   LIB.BBMap[NewBB] = L;
1029
1030   // Add the basic block to this loop and all parent loops...
1031   while (L) {
1032     L->Blocks.push_back(NewBB);
1033     L = L->getParentLoop();
1034   }
1035 }
1036
1037 } // End llvm namespace
1038
1039 #endif