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