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