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