[block-freq] Add a method to loop info for returning all loop latches for a specific...
[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 //  * etc...
27 //
28 //===----------------------------------------------------------------------===//
29
30 #ifndef LLVM_ANALYSIS_LOOPINFO_H
31 #define LLVM_ANALYSIS_LOOPINFO_H
32
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/GraphTraits.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/Analysis/Dominators.h"
38 #include "llvm/Pass.h"
39 #include <algorithm>
40
41 namespace llvm {
42
43 template<typename T>
44 inline void RemoveFromVector(std::vector<T*> &V, T *N) {
45   typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
46   assert(I != V.end() && "N is not in this list!");
47   V.erase(I);
48 }
49
50 class DominatorTree;
51 class LoopInfo;
52 class Loop;
53 class MDNode;
54 class PHINode;
55 class raw_ostream;
56 template<class N, class M> class LoopInfoBase;
57 template<class N, class M> class LoopBase;
58
59 //===----------------------------------------------------------------------===//
60 /// LoopBase class - Instances of this class are used to represent loops that
61 /// are detected in the flow graph
62 ///
63 template<class BlockT, class LoopT>
64 class LoopBase {
65   LoopT *ParentLoop;
66   // SubLoops - Loops contained entirely within this one.
67   std::vector<LoopT *> SubLoops;
68
69   // Blocks - The list of blocks in this loop.  First entry is the header node.
70   std::vector<BlockT*> Blocks;
71
72   SmallPtrSet<const BlockT*, 8> DenseBlockSet;
73
74   LoopBase(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
75   const LoopBase<BlockT, LoopT>&
76     operator=(const LoopBase<BlockT, LoopT> &) LLVM_DELETED_FUNCTION;
77 public:
78   /// Loop ctor - This creates an empty loop.
79   LoopBase() : ParentLoop(0) {}
80   ~LoopBase() {
81     for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
82       delete SubLoops[i];
83   }
84
85   /// getLoopDepth - Return the nesting level of this loop.  An outer-most
86   /// loop has depth 1, for consistency with loop depth values used for basic
87   /// blocks, where depth 0 is used for blocks not inside any loops.
88   unsigned getLoopDepth() const {
89     unsigned D = 1;
90     for (const LoopT *CurLoop = ParentLoop; CurLoop;
91          CurLoop = CurLoop->ParentLoop)
92       ++D;
93     return D;
94   }
95   BlockT *getHeader() const { return Blocks.front(); }
96   LoopT *getParentLoop() const { return ParentLoop; }
97
98   /// setParentLoop is a raw interface for bypassing addChildLoop.
99   void setParentLoop(LoopT *L) { ParentLoop = L; }
100
101   /// contains - Return true if the specified loop is contained within in
102   /// this loop.
103   ///
104   bool contains(const LoopT *L) const {
105     if (L == this) return true;
106     if (L == 0)    return false;
107     return contains(L->getParentLoop());
108   }
109
110   /// contains - Return true if the specified basic block is in this loop.
111   ///
112   bool contains(const BlockT *BB) const {
113     return DenseBlockSet.count(BB);
114   }
115
116   /// contains - Return true if the specified instruction is in this loop.
117   ///
118   template<class InstT>
119   bool contains(const InstT *Inst) const {
120     return contains(Inst->getParent());
121   }
122
123   /// iterator/begin/end - Return the loops contained entirely within this loop.
124   ///
125   const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
126   std::vector<LoopT *> &getSubLoopsVector() { return SubLoops; }
127   typedef typename std::vector<LoopT *>::const_iterator iterator;
128   typedef typename std::vector<LoopT *>::const_reverse_iterator
129     reverse_iterator;
130   iterator begin() const { return SubLoops.begin(); }
131   iterator end() const { return SubLoops.end(); }
132   reverse_iterator rbegin() const { return SubLoops.rbegin(); }
133   reverse_iterator rend() const { return SubLoops.rend(); }
134   bool empty() const { return SubLoops.empty(); }
135
136   /// getBlocks - Get a list of the basic blocks which make up this loop.
137   ///
138   const std::vector<BlockT*> &getBlocks() const { return Blocks; }
139   typedef typename std::vector<BlockT*>::const_iterator block_iterator;
140   block_iterator block_begin() const { return Blocks.begin(); }
141   block_iterator block_end() const { return Blocks.end(); }
142
143   /// getNumBlocks - Get the number of blocks in this loop in constant time.
144   unsigned getNumBlocks() const {
145     return Blocks.size();
146   }
147
148   /// isLoopExiting - True if terminator in the block can branch to another
149   /// block that is outside of the current loop.
150   ///
151   bool isLoopExiting(const BlockT *BB) const {
152     typedef GraphTraits<const BlockT*> BlockTraits;
153     for (typename BlockTraits::ChildIteratorType SI =
154          BlockTraits::child_begin(BB),
155          SE = BlockTraits::child_end(BB); SI != SE; ++SI) {
156       if (!contains(*SI))
157         return true;
158     }
159     return false;
160   }
161
162   /// getNumBackEdges - Calculate the number of back edges to the loop header
163   ///
164   unsigned getNumBackEdges() const {
165     unsigned NumBackEdges = 0;
166     BlockT *H = getHeader();
167
168     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
169     for (typename InvBlockTraits::ChildIteratorType I =
170          InvBlockTraits::child_begin(H),
171          E = InvBlockTraits::child_end(H); I != E; ++I)
172       if (contains(*I))
173         ++NumBackEdges;
174
175     return NumBackEdges;
176   }
177
178   //===--------------------------------------------------------------------===//
179   // APIs for simple analysis of the loop.
180   //
181   // Note that all of these methods can fail on general loops (ie, there may not
182   // be a preheader, etc).  For best success, the loop simplification and
183   // induction variable canonicalization pass should be used to normalize loops
184   // for easy analysis.  These methods assume canonical loops.
185
186   /// getExitingBlocks - Return all blocks inside the loop that have successors
187   /// outside of the loop.  These are the blocks _inside of the current loop_
188   /// which branch out.  The returned list is always unique.
189   ///
190   void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const;
191
192   /// getExitingBlock - If getExitingBlocks would return exactly one block,
193   /// return that block. Otherwise return null.
194   BlockT *getExitingBlock() const;
195
196   /// getExitBlocks - Return all of the successor blocks of this loop.  These
197   /// are the blocks _outside of the current loop_ which are branched to.
198   ///
199   void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const;
200
201   /// getExitBlock - If getExitBlocks would return exactly one block,
202   /// return that block. Otherwise return null.
203   BlockT *getExitBlock() const;
204
205   /// Edge type.
206   typedef std::pair<const BlockT*, const BlockT*> Edge;
207
208   /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
209   void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const;
210
211   /// getLoopPreheader - If there is a preheader for this loop, return it.  A
212   /// loop has a preheader if there is only one edge to the header of the loop
213   /// from outside of the loop.  If this is the case, the block branching to the
214   /// header of the loop is the preheader node.
215   ///
216   /// This method returns null if there is no preheader for the loop.
217   ///
218   BlockT *getLoopPreheader() const;
219
220   /// getLoopPredecessor - If the given loop's header has exactly one unique
221   /// predecessor outside the loop, return it. Otherwise return null.
222   /// This is less strict that the loop "preheader" concept, which requires
223   /// the predecessor to have exactly one successor.
224   ///
225   BlockT *getLoopPredecessor() const;
226
227   /// getLoopLatch - If there is a single latch block for this loop, return it.
228   /// A latch block is a block that contains a branch back to the header.
229   BlockT *getLoopLatch() const;
230
231   /// getLoopLatches - Return all loop latch blocks of this loop. A latch block
232   /// is a block that contains a branch back to the header.
233   void getLoopLatches(SmallVectorImpl<BlockT *> &LoopLatches) const {
234     BlockT *H = getHeader();
235     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
236     for (typename InvBlockTraits::ChildIteratorType I =
237          InvBlockTraits::child_begin(H),
238          E = InvBlockTraits::child_end(H); I != E; ++I)
239       if (contains(*I))
240         LoopLatches.push_back(*I);
241   }
242
243   //===--------------------------------------------------------------------===//
244   // APIs for updating loop information after changing the CFG
245   //
246
247   /// addBasicBlockToLoop - This method is used by other analyses to update loop
248   /// information.  NewBB is set to be a new member of the current loop.
249   /// Because of this, it is added as a member of all parent loops, and is added
250   /// to the specified LoopInfo object as being in the current basic block.  It
251   /// is not valid to replace the loop header with this method.
252   ///
253   void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
254
255   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
256   /// the OldChild entry in our children list with NewChild, and updates the
257   /// parent pointer of OldChild to be null and the NewChild to be this loop.
258   /// This updates the loop depth of the new child.
259   void replaceChildLoopWith(LoopT *OldChild, LoopT *NewChild);
260
261   /// addChildLoop - Add the specified loop to be a child of this loop.  This
262   /// updates the loop depth of the new child.
263   ///
264   void addChildLoop(LoopT *NewChild) {
265     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
266     NewChild->ParentLoop = static_cast<LoopT *>(this);
267     SubLoops.push_back(NewChild);
268   }
269
270   /// removeChildLoop - This removes the specified child from being a subloop of
271   /// this loop.  The loop is not deleted, as it will presumably be inserted
272   /// into another loop.
273   LoopT *removeChildLoop(iterator I) {
274     assert(I != SubLoops.end() && "Cannot remove end iterator!");
275     LoopT *Child = *I;
276     assert(Child->ParentLoop == this && "Child is not a child of this loop!");
277     SubLoops.erase(SubLoops.begin()+(I-begin()));
278     Child->ParentLoop = 0;
279     return Child;
280   }
281
282   /// addBlockEntry - This adds a basic block directly to the basic block list.
283   /// This should only be used by transformations that create new loops.  Other
284   /// transformations should use addBasicBlockToLoop.
285   void addBlockEntry(BlockT *BB) {
286     Blocks.push_back(BB);
287     DenseBlockSet.insert(BB);
288   }
289
290   /// reverseBlocks - interface to reverse Blocks[from, end of loop] in this loop
291   void reverseBlock(unsigned from) {
292     std::reverse(Blocks.begin() + from, Blocks.end());
293   }
294
295   /// reserveBlocks- interface to do reserve() for Blocks
296   void reserveBlocks(unsigned size) {
297     Blocks.reserve(size);
298   }
299
300   /// moveToHeader - This method is used to move BB (which must be part of this
301   /// loop) to be the loop header of the loop (the block that dominates all
302   /// others).
303   void moveToHeader(BlockT *BB) {
304     if (Blocks[0] == BB) return;
305     for (unsigned i = 0; ; ++i) {
306       assert(i != Blocks.size() && "Loop does not contain BB!");
307       if (Blocks[i] == BB) {
308         Blocks[i] = Blocks[0];
309         Blocks[0] = BB;
310         return;
311       }
312     }
313   }
314
315   /// removeBlockFromLoop - This removes the specified basic block from the
316   /// current loop, updating the Blocks as appropriate.  This does not update
317   /// the mapping in the LoopInfo class.
318   void removeBlockFromLoop(BlockT *BB) {
319     RemoveFromVector(Blocks, BB);
320     DenseBlockSet.erase(BB);
321   }
322
323   /// verifyLoop - Verify loop structure
324   void verifyLoop() const;
325
326   /// verifyLoop - Verify loop structure of this loop and all nested loops.
327   void verifyLoopNest(DenseSet<const LoopT*> *Loops) const;
328
329   void print(raw_ostream &OS, unsigned Depth = 0) const;
330
331 protected:
332   friend class LoopInfoBase<BlockT, LoopT>;
333   explicit LoopBase(BlockT *BB) : ParentLoop(0) {
334     Blocks.push_back(BB);
335     DenseBlockSet.insert(BB);
336   }
337 };
338
339 template<class BlockT, class LoopT>
340 raw_ostream& operator<<(raw_ostream &OS, const LoopBase<BlockT, LoopT> &Loop) {
341   Loop.print(OS);
342   return OS;
343 }
344
345 // Implementation in LoopInfoImpl.h
346 #ifdef __GNUC__
347 __extension__ extern template class LoopBase<BasicBlock, Loop>;
348 #endif
349
350 class Loop : public LoopBase<BasicBlock, Loop> {
351 public:
352   Loop() {}
353
354   /// isLoopInvariant - Return true if the specified value is loop invariant
355   ///
356   bool isLoopInvariant(Value *V) const;
357
358   /// hasLoopInvariantOperands - Return true if all the operands of the
359   /// specified instruction are loop invariant.
360   bool hasLoopInvariantOperands(Instruction *I) const;
361
362   /// makeLoopInvariant - If the given value is an instruction inside of the
363   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
364   /// Return true if the value after any hoisting is loop invariant. This
365   /// function can be used as a slightly more aggressive replacement for
366   /// isLoopInvariant.
367   ///
368   /// If InsertPt is specified, it is the point to hoist instructions to.
369   /// If null, the terminator of the loop preheader is used.
370   ///
371   bool makeLoopInvariant(Value *V, bool &Changed,
372                          Instruction *InsertPt = 0) const;
373
374   /// makeLoopInvariant - If the given instruction is inside of the
375   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
376   /// Return true if the instruction after any hoisting is loop invariant. This
377   /// function can be used as a slightly more aggressive replacement for
378   /// isLoopInvariant.
379   ///
380   /// If InsertPt is specified, it is the point to hoist instructions to.
381   /// If null, the terminator of the loop preheader is used.
382   ///
383   bool makeLoopInvariant(Instruction *I, bool &Changed,
384                          Instruction *InsertPt = 0) const;
385
386   /// getCanonicalInductionVariable - Check to see if the loop has a canonical
387   /// induction variable: an integer recurrence that starts at 0 and increments
388   /// by one each time through the loop.  If so, return the phi node that
389   /// corresponds to it.
390   ///
391   /// The IndVarSimplify pass transforms loops to have a canonical induction
392   /// variable.
393   ///
394   PHINode *getCanonicalInductionVariable() const;
395
396   /// isLCSSAForm - Return true if the Loop is in LCSSA form
397   bool isLCSSAForm(DominatorTree &DT) const;
398
399   /// isLoopSimplifyForm - Return true if the Loop is in the form that
400   /// the LoopSimplify form transforms loops to, which is sometimes called
401   /// normal form.
402   bool isLoopSimplifyForm() const;
403
404   /// isSafeToClone - Return true if the loop body is safe to clone in practice.
405   bool isSafeToClone() const;
406
407   /// Returns true if the loop is annotated parallel.
408   ///
409   /// A parallel loop can be assumed to not contain any dependencies between
410   /// iterations by the compiler. That is, any loop-carried dependency checking
411   /// can be skipped completely when parallelizing the loop on the target
412   /// machine. Thus, if the parallel loop information originates from the
413   /// programmer, e.g. via the OpenMP parallel for pragma, it is the
414   /// programmer's responsibility to ensure there are no loop-carried
415   /// dependencies. The final execution order of the instructions across
416   /// iterations is not guaranteed, thus, the end result might or might not
417   /// implement actual concurrent execution of instructions across multiple
418   /// iterations.
419   bool isAnnotatedParallel() const;
420
421   /// Return the llvm.loop loop id metadata node for this loop if it is present.
422   ///
423   /// If this loop contains the same llvm.loop metadata on each branch to the
424   /// header then the node is returned. If any latch instruction does not
425   /// contain llvm.loop or or if multiple latches contain different nodes then
426   /// 0 is returned.
427   MDNode *getLoopID() const;
428   /// Set the llvm.loop loop id metadata for this loop.
429   ///
430   /// The LoopID metadata node will be added to each terminator instruction in
431   /// the loop that branches to the loop header.
432   ///
433   /// The LoopID metadata node should have one or more operands and the first
434   /// operand should should be the node itself.
435   void setLoopID(MDNode *LoopID) const;
436
437   /// hasDedicatedExits - Return true if no exit block for the loop
438   /// has a predecessor that is outside the loop.
439   bool hasDedicatedExits() const;
440
441   /// getUniqueExitBlocks - Return all unique successor blocks of this loop.
442   /// These are the blocks _outside of the current loop_ which are branched to.
443   /// This assumes that loop exits are in canonical form.
444   ///
445   void getUniqueExitBlocks(SmallVectorImpl<BasicBlock *> &ExitBlocks) const;
446
447   /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
448   /// block, return that block. Otherwise return null.
449   BasicBlock *getUniqueExitBlock() const;
450
451   void dump() const;
452
453 private:
454   friend class LoopInfoBase<BasicBlock, Loop>;
455   explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
456 };
457
458 //===----------------------------------------------------------------------===//
459 /// LoopInfo - This class builds and contains all of the top level loop
460 /// structures in the specified function.
461 ///
462
463 template<class BlockT, class LoopT>
464 class LoopInfoBase {
465   // BBMap - Mapping of basic blocks to the inner most loop they occur in
466   DenseMap<BlockT *, LoopT *> BBMap;
467   std::vector<LoopT *> TopLevelLoops;
468   friend class LoopBase<BlockT, LoopT>;
469   friend class LoopInfo;
470
471   void operator=(const LoopInfoBase &) LLVM_DELETED_FUNCTION;
472   LoopInfoBase(const LoopInfo &) LLVM_DELETED_FUNCTION;
473 public:
474   LoopInfoBase() { }
475   ~LoopInfoBase() { releaseMemory(); }
476
477   void releaseMemory() {
478     for (typename std::vector<LoopT *>::iterator I =
479          TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
480       delete *I;   // Delete all of the loops...
481
482     BBMap.clear();                           // Reset internal state of analysis
483     TopLevelLoops.clear();
484   }
485
486   /// iterator/begin/end - The interface to the top-level loops in the current
487   /// function.
488   ///
489   typedef typename std::vector<LoopT *>::const_iterator iterator;
490   typedef typename std::vector<LoopT *>::const_reverse_iterator
491     reverse_iterator;
492   iterator begin() const { return TopLevelLoops.begin(); }
493   iterator end() const { return TopLevelLoops.end(); }
494   reverse_iterator rbegin() const { return TopLevelLoops.rbegin(); }
495   reverse_iterator rend() const { return TopLevelLoops.rend(); }
496   bool empty() const { return TopLevelLoops.empty(); }
497
498   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
499   /// block is in no loop (for example the entry node), null is returned.
500   ///
501   LoopT *getLoopFor(const BlockT *BB) const {
502     return BBMap.lookup(const_cast<BlockT*>(BB));
503   }
504
505   /// operator[] - same as getLoopFor...
506   ///
507   const LoopT *operator[](const BlockT *BB) const {
508     return getLoopFor(BB);
509   }
510
511   /// getLoopDepth - Return the loop nesting level of the specified block.  A
512   /// depth of 0 means the block is not inside any loop.
513   ///
514   unsigned getLoopDepth(const BlockT *BB) const {
515     const LoopT *L = getLoopFor(BB);
516     return L ? L->getLoopDepth() : 0;
517   }
518
519   // isLoopHeader - True if the block is a loop header node
520   bool isLoopHeader(BlockT *BB) const {
521     const LoopT *L = getLoopFor(BB);
522     return L && L->getHeader() == BB;
523   }
524
525   /// removeLoop - This removes the specified top-level loop from this loop info
526   /// object.  The loop is not deleted, as it will presumably be inserted into
527   /// another loop.
528   LoopT *removeLoop(iterator I) {
529     assert(I != end() && "Cannot remove end iterator!");
530     LoopT *L = *I;
531     assert(L->getParentLoop() == 0 && "Not a top-level loop!");
532     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
533     return L;
534   }
535
536   /// changeLoopFor - Change the top-level loop that contains BB to the
537   /// specified loop.  This should be used by transformations that restructure
538   /// the loop hierarchy tree.
539   void changeLoopFor(BlockT *BB, LoopT *L) {
540     if (!L) {
541       BBMap.erase(BB);
542       return;
543     }
544     BBMap[BB] = L;
545   }
546
547   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
548   /// list with the indicated loop.
549   void changeTopLevelLoop(LoopT *OldLoop,
550                           LoopT *NewLoop) {
551     typename std::vector<LoopT *>::iterator I =
552                  std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
553     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
554     *I = NewLoop;
555     assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
556            "Loops already embedded into a subloop!");
557   }
558
559   /// addTopLevelLoop - This adds the specified loop to the collection of
560   /// top-level loops.
561   void addTopLevelLoop(LoopT *New) {
562     assert(New->getParentLoop() == 0 && "Loop already in subloop!");
563     TopLevelLoops.push_back(New);
564   }
565
566   /// removeBlock - This method completely removes BB from all data structures,
567   /// including all of the Loop objects it is nested in and our mapping from
568   /// BasicBlocks to loops.
569   void removeBlock(BlockT *BB) {
570     typename DenseMap<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
571     if (I != BBMap.end()) {
572       for (LoopT *L = I->second; L; L = L->getParentLoop())
573         L->removeBlockFromLoop(BB);
574
575       BBMap.erase(I);
576     }
577   }
578
579   // Internals
580
581   static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
582                                       const LoopT *ParentLoop) {
583     if (SubLoop == 0) return true;
584     if (SubLoop == ParentLoop) return false;
585     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
586   }
587
588   /// Create the loop forest using a stable algorithm.
589   void Analyze(DominatorTreeBase<BlockT> &DomTree);
590
591   // Debugging
592
593   void print(raw_ostream &OS) const;
594 };
595
596 // Implementation in LoopInfoImpl.h
597 #ifdef __GNUC__
598 __extension__ extern template class LoopInfoBase<BasicBlock, Loop>;
599 #endif
600
601 class LoopInfo : public FunctionPass {
602   LoopInfoBase<BasicBlock, Loop> LI;
603   friend class LoopBase<BasicBlock, Loop>;
604
605   void operator=(const LoopInfo &) LLVM_DELETED_FUNCTION;
606   LoopInfo(const LoopInfo &) LLVM_DELETED_FUNCTION;
607 public:
608   static char ID; // Pass identification, replacement for typeid
609
610   LoopInfo() : FunctionPass(ID) {
611     initializeLoopInfoPass(*PassRegistry::getPassRegistry());
612   }
613
614   LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
615
616   /// iterator/begin/end - The interface to the top-level loops in the current
617   /// function.
618   ///
619   typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
620   typedef LoopInfoBase<BasicBlock, Loop>::reverse_iterator reverse_iterator;
621   inline iterator begin() const { return LI.begin(); }
622   inline iterator end() const { return LI.end(); }
623   inline reverse_iterator rbegin() const { return LI.rbegin(); }
624   inline reverse_iterator rend() const { return LI.rend(); }
625   bool empty() const { return LI.empty(); }
626
627   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
628   /// block is in no loop (for example the entry node), null is returned.
629   ///
630   inline Loop *getLoopFor(const BasicBlock *BB) const {
631     return LI.getLoopFor(BB);
632   }
633
634   /// operator[] - same as getLoopFor...
635   ///
636   inline const Loop *operator[](const BasicBlock *BB) const {
637     return LI.getLoopFor(BB);
638   }
639
640   /// getLoopDepth - Return the loop nesting level of the specified block.  A
641   /// depth of 0 means the block is not inside any loop.
642   ///
643   inline unsigned getLoopDepth(const BasicBlock *BB) const {
644     return LI.getLoopDepth(BB);
645   }
646
647   // isLoopHeader - True if the block is a loop header node
648   inline bool isLoopHeader(BasicBlock *BB) const {
649     return LI.isLoopHeader(BB);
650   }
651
652   /// runOnFunction - Calculate the natural loop information.
653   ///
654   virtual bool runOnFunction(Function &F);
655
656   virtual void verifyAnalysis() const;
657
658   virtual void releaseMemory() { LI.releaseMemory(); }
659
660   virtual void print(raw_ostream &O, const Module* M = 0) const;
661
662   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
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   inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
668
669   /// changeLoopFor - Change the top-level loop that contains BB to the
670   /// specified loop.  This should be used by transformations that restructure
671   /// the loop hierarchy tree.
672   inline void changeLoopFor(BasicBlock *BB, Loop *L) {
673     LI.changeLoopFor(BB, L);
674   }
675
676   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
677   /// list with the indicated loop.
678   inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
679     LI.changeTopLevelLoop(OldLoop, NewLoop);
680   }
681
682   /// addTopLevelLoop - This adds the specified loop to the collection of
683   /// top-level loops.
684   inline void addTopLevelLoop(Loop *New) {
685     LI.addTopLevelLoop(New);
686   }
687
688   /// removeBlock - This method completely removes BB from all data structures,
689   /// including all of the Loop objects it is nested in and our mapping from
690   /// BasicBlocks to loops.
691   void removeBlock(BasicBlock *BB) {
692     LI.removeBlock(BB);
693   }
694
695   /// updateUnloop - Update LoopInfo after removing the last backedge from a
696   /// loop--now the "unloop". This updates the loop forest and parent loops for
697   /// each block so that Unloop is no longer referenced, but the caller must
698   /// actually delete the Unloop object.
699   void updateUnloop(Loop *Unloop);
700
701   /// replacementPreservesLCSSAForm - Returns true if replacing From with To
702   /// everywhere is guaranteed to preserve LCSSA form.
703   bool replacementPreservesLCSSAForm(Instruction *From, Value *To) {
704     // Preserving LCSSA form is only problematic if the replacing value is an
705     // instruction.
706     Instruction *I = dyn_cast<Instruction>(To);
707     if (!I) return true;
708     // If both instructions are defined in the same basic block then replacement
709     // cannot break LCSSA form.
710     if (I->getParent() == From->getParent())
711       return true;
712     // If the instruction is not defined in a loop then it can safely replace
713     // anything.
714     Loop *ToLoop = getLoopFor(I->getParent());
715     if (!ToLoop) return true;
716     // If the replacing instruction is defined in the same loop as the original
717     // instruction, or in a loop that contains it as an inner loop, then using
718     // it as a replacement will not break LCSSA form.
719     return ToLoop->contains(getLoopFor(From->getParent()));
720   }
721 };
722
723
724 // Allow clients to walk the list of nested loops...
725 template <> struct GraphTraits<const Loop*> {
726   typedef const Loop NodeType;
727   typedef LoopInfo::iterator ChildIteratorType;
728
729   static NodeType *getEntryNode(const Loop *L) { return L; }
730   static inline ChildIteratorType child_begin(NodeType *N) {
731     return N->begin();
732   }
733   static inline ChildIteratorType child_end(NodeType *N) {
734     return N->end();
735   }
736 };
737
738 template <> struct GraphTraits<Loop*> {
739   typedef Loop NodeType;
740   typedef LoopInfo::iterator ChildIteratorType;
741
742   static NodeType *getEntryNode(Loop *L) { return L; }
743   static inline ChildIteratorType child_begin(NodeType *N) {
744     return N->begin();
745   }
746   static inline ChildIteratorType child_end(NodeType *N) {
747     return N->end();
748   }
749 };
750
751 } // End llvm namespace
752
753 #endif