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