LLVM API Documentation

LoopInfo.h

Go to the documentation of this file.
00001 //===- llvm/Analysis/LoopInfo.h - Natural Loop Calculator -------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the LoopInfo class that is used to identify natural loops
00011 // and determine the loop depth of various nodes of the CFG.  Note that natural
00012 // loops may actually be several loops that share the same header node.
00013 //
00014 // This analysis calculates the nesting structure of loops in a function.  For
00015 // each natural loop identified, this analysis identifies natural loops
00016 // contained entirely within the loop and the basic blocks the make up the loop.
00017 //
00018 // It can calculate on the fly various bits of information, for example:
00019 //
00020 //  * whether there is a preheader for the loop
00021 //  * the number of back edges to the header
00022 //  * whether or not a particular block branches out of the loop
00023 //  * the successor blocks of the loop
00024 //  * the loop depth
00025 //  * the trip count
00026 //  * etc...
00027 //
00028 //===----------------------------------------------------------------------===//
00029 
00030 #ifndef LLVM_ANALYSIS_LOOP_INFO_H
00031 #define LLVM_ANALYSIS_LOOP_INFO_H
00032 
00033 #include "llvm/Pass.h"
00034 #include "llvm/ADT/DepthFirstIterator.h"
00035 #include "llvm/ADT/GraphTraits.h"
00036 #include "llvm/ADT/SmallVector.h"
00037 #include "llvm/Analysis/Dominators.h"
00038 #include "llvm/Support/CFG.h"
00039 #include "llvm/Support/Streams.h"
00040 #include <algorithm>
00041 #include <ostream>
00042 
00043 namespace llvm {
00044 
00045 template<typename T>
00046 static void RemoveFromVector(std::vector<T*> &V, T *N) {
00047   typename std::vector<T*>::iterator I = std::find(V.begin(), V.end(), N);
00048   assert(I != V.end() && "N is not in this list!");
00049   V.erase(I);
00050 }
00051 
00052 class DominatorTree;
00053 class LoopInfo;
00054 class Loop;
00055 template<class N, class M> class LoopInfoBase;
00056 template<class N, class M> class LoopBase;
00057 
00058 //===----------------------------------------------------------------------===//
00059 /// LoopBase class - Instances of this class are used to represent loops that
00060 /// are detected in the flow graph
00061 ///
00062 template<class BlockT, class LoopT>
00063 class LoopBase {
00064   LoopT *ParentLoop;
00065   // SubLoops - Loops contained entirely within this one.
00066   std::vector<LoopT *> SubLoops;
00067 
00068   // Blocks - The list of blocks in this loop.  First entry is the header node.
00069   std::vector<BlockT*> Blocks;
00070 
00071   // DO NOT IMPLEMENT
00072   LoopBase(const LoopBase<BlockT, LoopT> &);
00073   // DO NOT IMPLEMENT
00074   const LoopBase<BlockT, LoopT>&operator=(const LoopBase<BlockT, LoopT> &);
00075 public:
00076   /// Loop ctor - This creates an empty loop.
00077   LoopBase() : ParentLoop(0) {}
00078   ~LoopBase() {
00079     for (size_t i = 0, e = SubLoops.size(); i != e; ++i)
00080       delete SubLoops[i];
00081   }
00082 
00083   /// getLoopDepth - Return the nesting level of this loop.  An outer-most
00084   /// loop has depth 1, for consistency with loop depth values used for basic
00085   /// blocks, where depth 0 is used for blocks not inside any loops.
00086   unsigned getLoopDepth() const {
00087     unsigned D = 1;
00088     for (const LoopT *CurLoop = ParentLoop; CurLoop;
00089          CurLoop = CurLoop->ParentLoop)
00090       ++D;
00091     return D;
00092   }
00093   BlockT *getHeader() const { return Blocks.front(); }
00094   LoopT *getParentLoop() const { return ParentLoop; }
00095 
00096   /// contains - Return true if the specified basic block is in this loop
00097   ///
00098   bool contains(const BlockT *BB) const {
00099     return std::find(block_begin(), block_end(), BB) != block_end();
00100   }
00101 
00102   /// iterator/begin/end - Return the loops contained entirely within this loop.
00103   ///
00104   const std::vector<LoopT *> &getSubLoops() const { return SubLoops; }
00105   typedef typename std::vector<LoopT *>::const_iterator iterator;
00106   iterator begin() const { return SubLoops.begin(); }
00107   iterator end() const { return SubLoops.end(); }
00108   bool empty() const { return SubLoops.empty(); }
00109 
00110   /// getBlocks - Get a list of the basic blocks which make up this loop.
00111   ///
00112   const std::vector<BlockT*> &getBlocks() const { return Blocks; }
00113   typedef typename std::vector<BlockT*>::const_iterator block_iterator;
00114   block_iterator block_begin() const { return Blocks.begin(); }
00115   block_iterator block_end() const { return Blocks.end(); }
00116 
00117   /// isLoopExit - True if terminator in the block can branch to another block
00118   /// that is outside of the current loop.
00119   ///
00120   bool isLoopExit(const BlockT *BB) const {
00121     typedef GraphTraits<BlockT*> BlockTraits;
00122     for (typename BlockTraits::ChildIteratorType SI =
00123          BlockTraits::child_begin(const_cast<BlockT*>(BB)),
00124          SE = BlockTraits::child_end(const_cast<BlockT*>(BB)); SI != SE; ++SI) {
00125       if (!contains(*SI))
00126         return true;
00127     }
00128     return false;
00129   }
00130 
00131   /// getNumBackEdges - Calculate the number of back edges to the loop header
00132   ///
00133   unsigned getNumBackEdges() const {
00134     unsigned NumBackEdges = 0;
00135     BlockT *H = getHeader();
00136 
00137     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00138     for (typename InvBlockTraits::ChildIteratorType I =
00139          InvBlockTraits::child_begin(const_cast<BlockT*>(H)),
00140          E = InvBlockTraits::child_end(const_cast<BlockT*>(H)); I != E; ++I)
00141       if (contains(*I))
00142         ++NumBackEdges;
00143 
00144     return NumBackEdges;
00145   }
00146 
00147   //===--------------------------------------------------------------------===//
00148   // APIs for simple analysis of the loop.
00149   //
00150   // Note that all of these methods can fail on general loops (ie, there may not
00151   // be a preheader, etc).  For best success, the loop simplification and
00152   // induction variable canonicalization pass should be used to normalize loops
00153   // for easy analysis.  These methods assume canonical loops.
00154 
00155   /// getExitingBlocks - Return all blocks inside the loop that have successors
00156   /// outside of the loop.  These are the blocks _inside of the current loop_
00157   /// which branch out.  The returned list is always unique.
00158   ///
00159   void getExitingBlocks(SmallVectorImpl<BlockT *> &ExitingBlocks) const {
00160     // Sort the blocks vector so that we can use binary search to do quick
00161     // lookups.
00162     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
00163     std::sort(LoopBBs.begin(), LoopBBs.end());
00164 
00165     typedef GraphTraits<BlockT*> BlockTraits;
00166     for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
00167       for (typename BlockTraits::ChildIteratorType I =
00168           BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
00169           I != E; ++I)
00170         if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I)) {
00171           // Not in current loop? It must be an exit block.
00172           ExitingBlocks.push_back(*BI);
00173           break;
00174         }
00175   }
00176 
00177   /// getExitingBlock - If getExitingBlocks would return exactly one block,
00178   /// return that block. Otherwise return null.
00179   BlockT *getExitingBlock() const {
00180     SmallVector<BlockT*, 8> ExitingBlocks;
00181     getExitingBlocks(ExitingBlocks);
00182     if (ExitingBlocks.size() == 1)
00183       return ExitingBlocks[0];
00184     return 0;
00185   }
00186 
00187   /// getExitBlocks - Return all of the successor blocks of this loop.  These
00188   /// are the blocks _outside of the current loop_ which are branched to.
00189   ///
00190   void getExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
00191     // Sort the blocks vector so that we can use binary search to do quick
00192     // lookups.
00193     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
00194     std::sort(LoopBBs.begin(), LoopBBs.end());
00195 
00196     typedef GraphTraits<BlockT*> BlockTraits;
00197     for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
00198       for (typename BlockTraits::ChildIteratorType I =
00199            BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
00200            I != E; ++I)
00201         if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
00202           // Not in current loop? It must be an exit block.
00203           ExitBlocks.push_back(*I);
00204   }
00205 
00206   /// getExitBlock - If getExitBlocks would return exactly one block,
00207   /// return that block. Otherwise return null.
00208   BlockT *getExitBlock() const {
00209     SmallVector<BlockT*, 8> ExitBlocks;
00210     getExitBlocks(ExitBlocks);
00211     if (ExitBlocks.size() == 1)
00212       return ExitBlocks[0];
00213     return 0;
00214   }
00215 
00216   /// getExitEdges - Return all pairs of (_inside_block_,_outside_block_).
00217   /// (Modelled after getExitingBlocks().)
00218   typedef std::pair<const BlockT*,const BlockT*> Edge;
00219   void getExitEdges(SmallVectorImpl<Edge> &ExitEdges) const {
00220     // Sort the blocks vector so that we can use binary search to do quick
00221     // lookups.
00222     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
00223     std::sort(LoopBBs.begin(), LoopBBs.end());
00224 
00225     typedef GraphTraits<BlockT*> BlockTraits;
00226     for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI)
00227       for (typename BlockTraits::ChildIteratorType I =
00228            BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
00229            I != E; ++I)
00230         if (!std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
00231           // Not in current loop? It must be an exit block.
00232           ExitEdges.push_back(std::make_pair(*BI, *I));
00233   }
00234 
00235   /// getUniqueExitBlocks - Return all unique successor blocks of this loop. 
00236   /// These are the blocks _outside of the current loop_ which are branched to.
00237   /// This assumes that loop is in canonical form.
00238   ///
00239   void getUniqueExitBlocks(SmallVectorImpl<BlockT*> &ExitBlocks) const {
00240     // Sort the blocks vector so that we can use binary search to do quick
00241     // lookups.
00242     SmallVector<BlockT*, 128> LoopBBs(block_begin(), block_end());
00243     std::sort(LoopBBs.begin(), LoopBBs.end());
00244 
00245     std::vector<BlockT*> switchExitBlocks;  
00246 
00247     for (block_iterator BI = block_begin(), BE = block_end(); BI != BE; ++BI) {
00248 
00249       BlockT *current = *BI;
00250       switchExitBlocks.clear();
00251 
00252       typedef GraphTraits<BlockT*> BlockTraits;
00253       typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00254       for (typename BlockTraits::ChildIteratorType I =
00255            BlockTraits::child_begin(*BI), E = BlockTraits::child_end(*BI);
00256            I != E; ++I) {
00257         if (std::binary_search(LoopBBs.begin(), LoopBBs.end(), *I))
00258       // If block is inside the loop then it is not a exit block.
00259           continue;
00260       
00261         typename InvBlockTraits::ChildIteratorType PI =
00262                                                 InvBlockTraits::child_begin(*I);
00263         BlockT *firstPred = *PI;
00264 
00265         // If current basic block is this exit block's first predecessor
00266         // then only insert exit block in to the output ExitBlocks vector.
00267         // This ensures that same exit block is not inserted twice into
00268         // ExitBlocks vector.
00269         if (current != firstPred) 
00270           continue;
00271 
00272         // If a terminator has more then two successors, for example SwitchInst,
00273         // then it is possible that there are multiple edges from current block 
00274         // to one exit block. 
00275         if (std::distance(BlockTraits::child_begin(current),
00276                           BlockTraits::child_end(current)) <= 2) {
00277           ExitBlocks.push_back(*I);
00278           continue;
00279         }
00280 
00281         // In case of multiple edges from current block to exit block, collect
00282         // only one edge in ExitBlocks. Use switchExitBlocks to keep track of
00283         // duplicate edges.
00284         if (std::find(switchExitBlocks.begin(), switchExitBlocks.end(), *I) 
00285             == switchExitBlocks.end()) {
00286           switchExitBlocks.push_back(*I);
00287           ExitBlocks.push_back(*I);
00288         }
00289       }
00290     }
00291   }
00292 
00293   /// getUniqueExitBlock - If getUniqueExitBlocks would return exactly one
00294   /// block, return that block. Otherwise return null.
00295   BlockT *getUniqueExitBlock() const {
00296     SmallVector<BlockT*, 8> UniqueExitBlocks;
00297     getUniqueExitBlocks(UniqueExitBlocks);
00298     if (UniqueExitBlocks.size() == 1)
00299       return UniqueExitBlocks[0];
00300     return 0;
00301   }
00302 
00303   /// getLoopPreheader - If there is a preheader for this loop, return it.  A
00304   /// loop has a preheader if there is only one edge to the header of the loop
00305   /// from outside of the loop.  If this is the case, the block branching to the
00306   /// header of the loop is the preheader node.
00307   ///
00308   /// This method returns null if there is no preheader for the loop.
00309   ///
00310   BlockT *getLoopPreheader() const {
00311     // Keep track of nodes outside the loop branching to the header...
00312     BlockT *Out = 0;
00313 
00314     // Loop over the predecessors of the header node...
00315     BlockT *Header = getHeader();
00316     typedef GraphTraits<BlockT*> BlockTraits;
00317     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00318     for (typename InvBlockTraits::ChildIteratorType PI =
00319          InvBlockTraits::child_begin(Header),
00320          PE = InvBlockTraits::child_end(Header); PI != PE; ++PI)
00321       if (!contains(*PI)) {     // If the block is not in the loop...
00322         if (Out && Out != *PI)
00323           return 0;             // Multiple predecessors outside the loop
00324         Out = *PI;
00325       }
00326 
00327     // Make sure there is only one exit out of the preheader.
00328     assert(Out && "Header of loop has no predecessors from outside loop?");
00329     typename BlockTraits::ChildIteratorType SI = BlockTraits::child_begin(Out);
00330     ++SI;
00331     if (SI != BlockTraits::child_end(Out))
00332       return 0;  // Multiple exits from the block, must not be a preheader.
00333 
00334     // If there is exactly one preheader, return it.  If there was zero, then
00335     // Out is still null.
00336     return Out;
00337   }
00338 
00339   /// getLoopLatch - If there is a single latch block for this loop, return it.
00340   /// A latch block is a block that contains a branch back to the header.
00341   /// A loop header in normal form has two edges into it: one from a preheader
00342   /// and one from a latch block.
00343   BlockT *getLoopLatch() const {
00344     BlockT *Header = getHeader();
00345     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00346     typename InvBlockTraits::ChildIteratorType PI =
00347                                             InvBlockTraits::child_begin(Header);
00348     typename InvBlockTraits::ChildIteratorType PE =
00349                                               InvBlockTraits::child_end(Header);
00350     if (PI == PE) return 0;  // no preds?
00351 
00352     BlockT *Latch = 0;
00353     if (contains(*PI))
00354       Latch = *PI;
00355     ++PI;
00356     if (PI == PE) return 0;  // only one pred?
00357 
00358     if (contains(*PI)) {
00359       if (Latch) return 0;  // multiple backedges
00360       Latch = *PI;
00361     }
00362     ++PI;
00363     if (PI != PE) return 0;  // more than two preds
00364 
00365     return Latch;
00366   }
00367 
00368   //===--------------------------------------------------------------------===//
00369   // APIs for updating loop information after changing the CFG
00370   //
00371 
00372   /// addBasicBlockToLoop - This method is used by other analyses to update loop
00373   /// information.  NewBB is set to be a new member of the current loop.
00374   /// Because of this, it is added as a member of all parent loops, and is added
00375   /// to the specified LoopInfo object as being in the current basic block.  It
00376   /// is not valid to replace the loop header with this method.
00377   ///
00378   void addBasicBlockToLoop(BlockT *NewBB, LoopInfoBase<BlockT, LoopT> &LI);
00379 
00380   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
00381   /// the OldChild entry in our children list with NewChild, and updates the
00382   /// parent pointer of OldChild to be null and the NewChild to be this loop.
00383   /// This updates the loop depth of the new child.
00384   void replaceChildLoopWith(LoopT *OldChild,
00385                             LoopT *NewChild) {
00386     assert(OldChild->ParentLoop == this && "This loop is already broken!");
00387     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
00388     typename std::vector<LoopT *>::iterator I =
00389                           std::find(SubLoops.begin(), SubLoops.end(), OldChild);
00390     assert(I != SubLoops.end() && "OldChild not in loop!");
00391     *I = NewChild;
00392     OldChild->ParentLoop = 0;
00393     NewChild->ParentLoop = static_cast<LoopT *>(this);
00394   }
00395 
00396   /// addChildLoop - Add the specified loop to be a child of this loop.  This
00397   /// updates the loop depth of the new child.
00398   ///
00399   void addChildLoop(LoopT *NewChild) {
00400     assert(NewChild->ParentLoop == 0 && "NewChild already has a parent!");
00401     NewChild->ParentLoop = static_cast<LoopT *>(this);
00402     SubLoops.push_back(NewChild);
00403   }
00404 
00405   /// removeChildLoop - This removes the specified child from being a subloop of
00406   /// this loop.  The loop is not deleted, as it will presumably be inserted
00407   /// into another loop.
00408   LoopT *removeChildLoop(iterator I) {
00409     assert(I != SubLoops.end() && "Cannot remove end iterator!");
00410     LoopT *Child = *I;
00411     assert(Child->ParentLoop == this && "Child is not a child of this loop!");
00412     SubLoops.erase(SubLoops.begin()+(I-begin()));
00413     Child->ParentLoop = 0;
00414     return Child;
00415   }
00416 
00417   /// addBlockEntry - This adds a basic block directly to the basic block list.
00418   /// This should only be used by transformations that create new loops.  Other
00419   /// transformations should use addBasicBlockToLoop.
00420   void addBlockEntry(BlockT *BB) {
00421     Blocks.push_back(BB);
00422   }
00423 
00424   /// moveToHeader - This method is used to move BB (which must be part of this
00425   /// loop) to be the loop header of the loop (the block that dominates all
00426   /// others).
00427   void moveToHeader(BlockT *BB) {
00428     if (Blocks[0] == BB) return;
00429     for (unsigned i = 0; ; ++i) {
00430       assert(i != Blocks.size() && "Loop does not contain BB!");
00431       if (Blocks[i] == BB) {
00432         Blocks[i] = Blocks[0];
00433         Blocks[0] = BB;
00434         return;
00435       }
00436     }
00437   }
00438 
00439   /// removeBlockFromLoop - This removes the specified basic block from the
00440   /// current loop, updating the Blocks as appropriate.  This does not update
00441   /// the mapping in the LoopInfo class.
00442   void removeBlockFromLoop(BlockT *BB) {
00443     RemoveFromVector(Blocks, BB);
00444   }
00445 
00446   /// verifyLoop - Verify loop structure
00447   void verifyLoop() const {
00448 #ifndef NDEBUG
00449     assert (getHeader() && "Loop header is missing");
00450     assert (getLoopPreheader() && "Loop preheader is missing");
00451     assert (getLoopLatch() && "Loop latch is missing");
00452     for (iterator I = SubLoops.begin(), E = SubLoops.end(); I != E; ++I)
00453       (*I)->verifyLoop();
00454 #endif
00455   }
00456 
00457   void print(std::ostream &OS, unsigned Depth = 0) const {
00458     OS << std::string(Depth*2, ' ') << "Loop at depth " << getLoopDepth()
00459        << " containing: ";
00460 
00461     for (unsigned i = 0; i < getBlocks().size(); ++i) {
00462       if (i) OS << ",";
00463       BlockT *BB = getBlocks()[i];
00464       WriteAsOperand(OS, BB, false);
00465       if (BB == getHeader())    OS << "<header>";
00466       if (BB == getLoopLatch()) OS << "<latch>";
00467       if (isLoopExit(BB))       OS << "<exit>";
00468     }
00469     OS << "\n";
00470 
00471     for (iterator I = begin(), E = end(); I != E; ++I)
00472       (*I)->print(OS, Depth+2);
00473   }
00474   
00475   void print(std::ostream *O, unsigned Depth = 0) const {
00476     if (O) print(*O, Depth);
00477   }
00478   
00479   void dump() const {
00480     print(cerr);
00481   }
00482   
00483 protected:
00484   friend class LoopInfoBase<BlockT, LoopT>;
00485   explicit LoopBase(BlockT *BB) : ParentLoop(0) {
00486     Blocks.push_back(BB);
00487   }
00488 };
00489 
00490 class Loop : public LoopBase<BasicBlock, Loop> {
00491 public:
00492   Loop() {}
00493 
00494   /// isLoopInvariant - Return true if the specified value is loop invariant
00495   ///
00496   bool isLoopInvariant(Value *V) const;
00497 
00498   /// isLoopInvariant - Return true if the specified instruction is
00499   /// loop-invariant.
00500   ///
00501   bool isLoopInvariant(Instruction *I) const;
00502 
00503   /// makeLoopInvariant - If the given value is an instruction inside of the
00504   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
00505   /// Return true if the value after any hoisting is loop invariant. This
00506   /// function can be used as a slightly more aggressive replacement for
00507   /// isLoopInvariant.
00508   ///
00509   /// If InsertPt is specified, it is the point to hoist instructions to.
00510   /// If null, the terminator of the loop preheader is used.
00511   ///
00512   bool makeLoopInvariant(Value *V, bool &Changed,
00513                          Instruction *InsertPt = 0) const;
00514 
00515   /// makeLoopInvariant - If the given instruction is inside of the
00516   /// loop and it can be hoisted, do so to make it trivially loop-invariant.
00517   /// Return true if the instruction after any hoisting is loop invariant. This
00518   /// function can be used as a slightly more aggressive replacement for
00519   /// isLoopInvariant.
00520   ///
00521   /// If InsertPt is specified, it is the point to hoist instructions to.
00522   /// If null, the terminator of the loop preheader is used.
00523   ///
00524   bool makeLoopInvariant(Instruction *I, bool &Changed,
00525                          Instruction *InsertPt = 0) const;
00526 
00527   /// getCanonicalInductionVariable - Check to see if the loop has a canonical
00528   /// induction variable: an integer recurrence that starts at 0 and increments
00529   /// by one each time through the loop.  If so, return the phi node that
00530   /// corresponds to it.
00531   ///
00532   /// The IndVarSimplify pass transforms loops to have a canonical induction
00533   /// variable.
00534   ///
00535   PHINode *getCanonicalInductionVariable() const;
00536 
00537   /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
00538   /// the canonical induction variable value for the "next" iteration of the
00539   /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
00540   ///
00541   Instruction *getCanonicalInductionVariableIncrement() const;
00542 
00543   /// getTripCount - Return a loop-invariant LLVM value indicating the number of
00544   /// times the loop will be executed.  Note that this means that the backedge
00545   /// of the loop executes N-1 times.  If the trip-count cannot be determined,
00546   /// this returns null.
00547   ///
00548   /// The IndVarSimplify pass transforms loops to have a form that this
00549   /// function easily understands.
00550   ///
00551   Value *getTripCount() const;
00552 
00553   /// getSmallConstantTripCount - Returns the trip count of this loop as a
00554   /// normal unsigned value, if possible. Returns 0 if the trip count is unknown
00555   /// of not constant. Will also return 0 if the trip count is very large
00556   /// (>= 2^32)
00557   unsigned getSmallConstantTripCount() const;
00558 
00559   /// getSmallConstantTripMultiple - Returns the largest constant divisor of the
00560   /// trip count of this loop as a normal unsigned value, if possible. This
00561   /// means that the actual trip count is always a multiple of the returned
00562   /// value (don't forget the trip count could very well be zero as well!).
00563   ///
00564   /// Returns 1 if the trip count is unknown or not guaranteed to be the
00565   /// multiple of a constant (which is also the case if the trip count is simply
00566   /// constant, use getSmallConstantTripCount for that case), Will also return 1
00567   /// if the trip count is very large (>= 2^32).
00568   unsigned getSmallConstantTripMultiple() const;
00569 
00570   /// isLCSSAForm - Return true if the Loop is in LCSSA form
00571   bool isLCSSAForm() const;
00572 
00573   /// isLoopSimplifyForm - Return true if the Loop is in the form that
00574   /// the LoopSimplify form transforms loops to, which is sometimes called
00575   /// normal form.
00576   bool isLoopSimplifyForm() const;
00577 
00578 private:
00579   friend class LoopInfoBase<BasicBlock, Loop>;
00580   explicit Loop(BasicBlock *BB) : LoopBase<BasicBlock, Loop>(BB) {}
00581 };
00582 
00583 //===----------------------------------------------------------------------===//
00584 /// LoopInfo - This class builds and contains all of the top level loop
00585 /// structures in the specified function.
00586 ///
00587 
00588 template<class BlockT, class LoopT>
00589 class LoopInfoBase {
00590   // BBMap - Mapping of basic blocks to the inner most loop they occur in
00591   std::map<BlockT *, LoopT *> BBMap;
00592   std::vector<LoopT *> TopLevelLoops;
00593   friend class LoopBase<BlockT, LoopT>;
00594 
00595   void operator=(const LoopInfoBase &); // do not implement
00596   LoopInfoBase(const LoopInfo &);       // do not implement
00597 public:
00598   LoopInfoBase() { }
00599   ~LoopInfoBase() { releaseMemory(); }
00600   
00601   void releaseMemory() {
00602     for (typename std::vector<LoopT *>::iterator I =
00603          TopLevelLoops.begin(), E = TopLevelLoops.end(); I != E; ++I)
00604       delete *I;   // Delete all of the loops...
00605 
00606     BBMap.clear();                           // Reset internal state of analysis
00607     TopLevelLoops.clear();
00608   }
00609   
00610   /// iterator/begin/end - The interface to the top-level loops in the current
00611   /// function.
00612   ///
00613   typedef typename std::vector<LoopT *>::const_iterator iterator;
00614   iterator begin() const { return TopLevelLoops.begin(); }
00615   iterator end() const { return TopLevelLoops.end(); }
00616   bool empty() const { return TopLevelLoops.empty(); }
00617   
00618   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
00619   /// block is in no loop (for example the entry node), null is returned.
00620   ///
00621   LoopT *getLoopFor(const BlockT *BB) const {
00622     typename std::map<BlockT *, LoopT *>::const_iterator I=
00623       BBMap.find(const_cast<BlockT*>(BB));
00624     return I != BBMap.end() ? I->second : 0;
00625   }
00626   
00627   /// operator[] - same as getLoopFor...
00628   ///
00629   const LoopT *operator[](const BlockT *BB) const {
00630     return getLoopFor(BB);
00631   }
00632   
00633   /// getLoopDepth - Return the loop nesting level of the specified block.  A
00634   /// depth of 0 means the block is not inside any loop.
00635   ///
00636   unsigned getLoopDepth(const BlockT *BB) const {
00637     const LoopT *L = getLoopFor(BB);
00638     return L ? L->getLoopDepth() : 0;
00639   }
00640 
00641   // isLoopHeader - True if the block is a loop header node
00642   bool isLoopHeader(BlockT *BB) const {
00643     const LoopT *L = getLoopFor(BB);
00644     return L && L->getHeader() == BB;
00645   }
00646   
00647   /// removeLoop - This removes the specified top-level loop from this loop info
00648   /// object.  The loop is not deleted, as it will presumably be inserted into
00649   /// another loop.
00650   LoopT *removeLoop(iterator I) {
00651     assert(I != end() && "Cannot remove end iterator!");
00652     LoopT *L = *I;
00653     assert(L->getParentLoop() == 0 && "Not a top-level loop!");
00654     TopLevelLoops.erase(TopLevelLoops.begin() + (I-begin()));
00655     return L;
00656   }
00657   
00658   /// changeLoopFor - Change the top-level loop that contains BB to the
00659   /// specified loop.  This should be used by transformations that restructure
00660   /// the loop hierarchy tree.
00661   void changeLoopFor(BlockT *BB, LoopT *L) {
00662     LoopT *&OldLoop = BBMap[BB];
00663     assert(OldLoop && "Block not in a loop yet!");
00664     OldLoop = L;
00665   }
00666   
00667   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
00668   /// list with the indicated loop.
00669   void changeTopLevelLoop(LoopT *OldLoop,
00670                           LoopT *NewLoop) {
00671     typename std::vector<LoopT *>::iterator I =
00672                  std::find(TopLevelLoops.begin(), TopLevelLoops.end(), OldLoop);
00673     assert(I != TopLevelLoops.end() && "Old loop not at top level!");
00674     *I = NewLoop;
00675     assert(NewLoop->ParentLoop == 0 && OldLoop->ParentLoop == 0 &&
00676            "Loops already embedded into a subloop!");
00677   }
00678   
00679   /// addTopLevelLoop - This adds the specified loop to the collection of
00680   /// top-level loops.
00681   void addTopLevelLoop(LoopT *New) {
00682     assert(New->getParentLoop() == 0 && "Loop already in subloop!");
00683     TopLevelLoops.push_back(New);
00684   }
00685   
00686   /// removeBlock - This method completely removes BB from all data structures,
00687   /// including all of the Loop objects it is nested in and our mapping from
00688   /// BasicBlocks to loops.
00689   void removeBlock(BlockT *BB) {
00690     typename std::map<BlockT *, LoopT *>::iterator I = BBMap.find(BB);
00691     if (I != BBMap.end()) {
00692       for (LoopT *L = I->second; L; L = L->getParentLoop())
00693         L->removeBlockFromLoop(BB);
00694 
00695       BBMap.erase(I);
00696     }
00697   }
00698   
00699   // Internals
00700   
00701   static bool isNotAlreadyContainedIn(const LoopT *SubLoop,
00702                                       const LoopT *ParentLoop) {
00703     if (SubLoop == 0) return true;
00704     if (SubLoop == ParentLoop) return false;
00705     return isNotAlreadyContainedIn(SubLoop->getParentLoop(), ParentLoop);
00706   }
00707   
00708   void Calculate(DominatorTreeBase<BlockT> &DT) {
00709     BlockT *RootNode = DT.getRootNode()->getBlock();
00710 
00711     for (df_iterator<BlockT*> NI = df_begin(RootNode),
00712            NE = df_end(RootNode); NI != NE; ++NI)
00713       if (LoopT *L = ConsiderForLoop(*NI, DT))
00714         TopLevelLoops.push_back(L);
00715   }
00716   
00717   LoopT *ConsiderForLoop(BlockT *BB, DominatorTreeBase<BlockT> &DT) {
00718     if (BBMap.find(BB) != BBMap.end()) return 0;// Haven't processed this node?
00719 
00720     std::vector<BlockT *> TodoStack;
00721 
00722     // Scan the predecessors of BB, checking to see if BB dominates any of
00723     // them.  This identifies backedges which target this node...
00724     typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00725     for (typename InvBlockTraits::ChildIteratorType I =
00726          InvBlockTraits::child_begin(BB), E = InvBlockTraits::child_end(BB);
00727          I != E; ++I)
00728       if (DT.dominates(BB, *I))   // If BB dominates it's predecessor...
00729         TodoStack.push_back(*I);
00730 
00731     if (TodoStack.empty()) return 0;  // No backedges to this block...
00732 
00733     // Create a new loop to represent this basic block...
00734     LoopT *L = new LoopT(BB);
00735     BBMap[BB] = L;
00736 
00737     BlockT *EntryBlock = BB->getParent()->begin();
00738 
00739     while (!TodoStack.empty()) {  // Process all the nodes in the loop
00740       BlockT *X = TodoStack.back();
00741       TodoStack.pop_back();
00742 
00743       if (!L->contains(X) &&         // As of yet unprocessed??
00744           DT.dominates(EntryBlock, X)) {   // X is reachable from entry block?
00745         // Check to see if this block already belongs to a loop.  If this occurs
00746         // then we have a case where a loop that is supposed to be a child of
00747         // the current loop was processed before the current loop.  When this
00748         // occurs, this child loop gets added to a part of the current loop,
00749         // making it a sibling to the current loop.  We have to reparent this
00750         // loop.
00751         if (LoopT *SubLoop =
00752             const_cast<LoopT *>(getLoopFor(X)))
00753           if (SubLoop->getHeader() == X && isNotAlreadyContainedIn(SubLoop, L)){
00754             // Remove the subloop from it's current parent...
00755             assert(SubLoop->ParentLoop && SubLoop->ParentLoop != L);
00756             LoopT *SLP = SubLoop->ParentLoop;  // SubLoopParent
00757             typename std::vector<LoopT *>::iterator I =
00758               std::find(SLP->SubLoops.begin(), SLP->SubLoops.end(), SubLoop);
00759             assert(I != SLP->SubLoops.end() &&"SubLoop not a child of parent?");
00760             SLP->SubLoops.erase(I);   // Remove from parent...
00761 
00762             // Add the subloop to THIS loop...
00763             SubLoop->ParentLoop = L;
00764             L->SubLoops.push_back(SubLoop);
00765           }
00766 
00767         // Normal case, add the block to our loop...
00768         L->Blocks.push_back(X);
00769         
00770         typedef GraphTraits<Inverse<BlockT*> > InvBlockTraits;
00771         
00772         // Add all of the predecessors of X to the end of the work stack...
00773         TodoStack.insert(TodoStack.end(), InvBlockTraits::child_begin(X),
00774                          InvBlockTraits::child_end(X));
00775       }
00776     }
00777 
00778     // If there are any loops nested within this loop, create them now!
00779     for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
00780          E = L->Blocks.end(); I != E; ++I)
00781       if (LoopT *NewLoop = ConsiderForLoop(*I, DT)) {
00782         L->SubLoops.push_back(NewLoop);
00783         NewLoop->ParentLoop = L;
00784       }
00785 
00786     // Add the basic blocks that comprise this loop to the BBMap so that this
00787     // loop can be found for them.
00788     //
00789     for (typename std::vector<BlockT*>::iterator I = L->Blocks.begin(),
00790            E = L->Blocks.end(); I != E; ++I) {
00791       typename std::map<BlockT*, LoopT *>::iterator BBMI = BBMap.find(*I);
00792       if (BBMI == BBMap.end())                       // Not in map yet...
00793         BBMap.insert(BBMI, std::make_pair(*I, L));   // Must be at this level
00794     }
00795 
00796     // Now that we have a list of all of the child loops of this loop, check to
00797     // see if any of them should actually be nested inside of each other.  We
00798     // can accidentally pull loops our of their parents, so we must make sure to
00799     // organize the loop nests correctly now.
00800     {
00801       std::map<BlockT *, LoopT *> ContainingLoops;
00802       for (unsigned i = 0; i != L->SubLoops.size(); ++i) {
00803         LoopT *Child = L->SubLoops[i];
00804         assert(Child->getParentLoop() == L && "Not proper child loop?");
00805 
00806         if (LoopT *ContainingLoop = ContainingLoops[Child->getHeader()]) {
00807           // If there is already a loop which contains this loop, move this loop
00808           // into the containing loop.
00809           MoveSiblingLoopInto(Child, ContainingLoop);
00810           --i;  // The loop got removed from the SubLoops list.
00811         } else {
00812           // This is currently considered to be a top-level loop.  Check to see
00813           // if any of the contained blocks are loop headers for subloops we
00814           // have already processed.
00815           for (unsigned b = 0, e = Child->Blocks.size(); b != e; ++b) {
00816             LoopT *&BlockLoop = ContainingLoops[Child->Blocks[b]];
00817             if (BlockLoop == 0) {   // Child block not processed yet...
00818               BlockLoop = Child;
00819             } else if (BlockLoop != Child) {
00820               LoopT *SubLoop = BlockLoop;
00821               // Reparent all of the blocks which used to belong to BlockLoops
00822               for (unsigned j = 0, e = SubLoop->Blocks.size(); j != e; ++j)
00823                 ContainingLoops[SubLoop->Blocks[j]] = Child;
00824 
00825               // There is already a loop which contains this block, that means
00826               // that we should reparent the loop which the block is currently
00827               // considered to belong to to be a child of this loop.
00828               MoveSiblingLoopInto(SubLoop, Child);
00829               --i;  // We just shrunk the SubLoops list.
00830             }
00831           }
00832         }
00833       }
00834     }
00835 
00836     return L;
00837   }
00838   
00839   /// MoveSiblingLoopInto - This method moves the NewChild loop to live inside
00840   /// of the NewParent Loop, instead of being a sibling of it.
00841   void MoveSiblingLoopInto(LoopT *NewChild,
00842                            LoopT *NewParent) {
00843     LoopT *OldParent = NewChild->getParentLoop();
00844     assert(OldParent && OldParent == NewParent->getParentLoop() &&
00845            NewChild != NewParent && "Not sibling loops!");
00846 
00847     // Remove NewChild from being a child of OldParent
00848     typename std::vector<LoopT *>::iterator I =
00849       std::find(OldParent->SubLoops.begin(), OldParent->SubLoops.end(),
00850                 NewChild);
00851     assert(I != OldParent->SubLoops.end() && "Parent fields incorrect??");
00852     OldParent->SubLoops.erase(I);   // Remove from parent's subloops list
00853     NewChild->ParentLoop = 0;
00854 
00855     InsertLoopInto(NewChild, NewParent);
00856   }
00857   
00858   /// InsertLoopInto - This inserts loop L into the specified parent loop.  If
00859   /// the parent loop contains a loop which should contain L, the loop gets
00860   /// inserted into L instead.
00861   void InsertLoopInto(LoopT *L, LoopT *Parent) {
00862     BlockT *LHeader = L->getHeader();
00863     assert(Parent->contains(LHeader) &&
00864            "This loop should not be inserted here!");
00865 
00866     // Check to see if it belongs in a child loop...
00867     for (unsigned i = 0, e = static_cast<unsigned>(Parent->SubLoops.size());
00868          i != e; ++i)
00869       if (Parent->SubLoops[i]->contains(LHeader)) {
00870         InsertLoopInto(L, Parent->SubLoops[i]);
00871         return;
00872       }
00873 
00874     // If not, insert it here!
00875     Parent->SubLoops.push_back(L);
00876     L->ParentLoop = Parent;
00877   }
00878   
00879   // Debugging
00880   
00881   void print(std::ostream &OS, const Module* ) const {
00882     for (unsigned i = 0; i < TopLevelLoops.size(); ++i)
00883       TopLevelLoops[i]->print(OS);
00884   #if 0
00885     for (std::map<BasicBlock*, LoopT*>::const_iterator I = BBMap.begin(),
00886            E = BBMap.end(); I != E; ++I)
00887       OS << "BB '" << I->first->getName() << "' level = "
00888          << I->second->getLoopDepth() << "\n";
00889   #endif
00890   }
00891 };
00892 
00893 class LoopInfo : public FunctionPass {
00894   LoopInfoBase<BasicBlock, Loop> LI;
00895   friend class LoopBase<BasicBlock, Loop>;
00896 
00897   void operator=(const LoopInfo &); // do not implement
00898   LoopInfo(const LoopInfo &);       // do not implement
00899 public:
00900   static char ID; // Pass identification, replacement for typeid
00901 
00902   LoopInfo() : FunctionPass(&ID) {}
00903 
00904   LoopInfoBase<BasicBlock, Loop>& getBase() { return LI; }
00905 
00906   /// iterator/begin/end - The interface to the top-level loops in the current
00907   /// function.
00908   ///
00909   typedef LoopInfoBase<BasicBlock, Loop>::iterator iterator;
00910   inline iterator begin() const { return LI.begin(); }
00911   inline iterator end() const { return LI.end(); }
00912   bool empty() const { return LI.empty(); }
00913 
00914   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
00915   /// block is in no loop (for example the entry node), null is returned.
00916   ///
00917   inline Loop *getLoopFor(const BasicBlock *BB) const {
00918     return LI.getLoopFor(BB);
00919   }
00920 
00921   /// operator[] - same as getLoopFor...
00922   ///
00923   inline const Loop *operator[](const BasicBlock *BB) const {
00924     return LI.getLoopFor(BB);
00925   }
00926 
00927   /// getLoopDepth - Return the loop nesting level of the specified block.  A
00928   /// depth of 0 means the block is not inside any loop.
00929   ///
00930   inline unsigned getLoopDepth(const BasicBlock *BB) const {
00931     return LI.getLoopDepth(BB);
00932   }
00933 
00934   // isLoopHeader - True if the block is a loop header node
00935   inline bool isLoopHeader(BasicBlock *BB) const {
00936     return LI.isLoopHeader(BB);
00937   }
00938 
00939   /// runOnFunction - Calculate the natural loop information.
00940   ///
00941   virtual bool runOnFunction(Function &F);
00942 
00943   virtual void releaseMemory() { LI.releaseMemory(); }
00944 
00945   virtual void print(std::ostream &O, const Module* M = 0) const {
00946     LI.print(O, M);
00947   }
00948 
00949   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
00950 
00951   /// removeLoop - This removes the specified top-level loop from this loop info
00952   /// object.  The loop is not deleted, as it will presumably be inserted into
00953   /// another loop.
00954   inline Loop *removeLoop(iterator I) { return LI.removeLoop(I); }
00955 
00956   /// changeLoopFor - Change the top-level loop that contains BB to the
00957   /// specified loop.  This should be used by transformations that restructure
00958   /// the loop hierarchy tree.
00959   inline void changeLoopFor(BasicBlock *BB, Loop *L) {
00960     LI.changeLoopFor(BB, L);
00961   }
00962 
00963   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
00964   /// list with the indicated loop.
00965   inline void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop) {
00966     LI.changeTopLevelLoop(OldLoop, NewLoop);
00967   }
00968 
00969   /// addTopLevelLoop - This adds the specified loop to the collection of
00970   /// top-level loops.
00971   inline void addTopLevelLoop(Loop *New) {
00972     LI.addTopLevelLoop(New);
00973   }
00974 
00975   /// removeBlock - This method completely removes BB from all data structures,
00976   /// including all of the Loop objects it is nested in and our mapping from
00977   /// BasicBlocks to loops.
00978   void removeBlock(BasicBlock *BB) {
00979     LI.removeBlock(BB);
00980   }
00981 
00982   static bool isNotAlreadyContainedIn(const Loop *SubLoop,
00983                                       const Loop *ParentLoop) {
00984     return
00985       LoopInfoBase<BasicBlock, Loop>::isNotAlreadyContainedIn(SubLoop,
00986                                                               ParentLoop);
00987   }
00988 };
00989 
00990 
00991 // Allow clients to walk the list of nested loops...
00992 template <> struct GraphTraits<const Loop*> {
00993   typedef const Loop NodeType;
00994   typedef LoopInfo::iterator ChildIteratorType;
00995 
00996   static NodeType *getEntryNode(const Loop *L) { return L; }
00997   static inline ChildIteratorType child_begin(NodeType *N) {
00998     return N->begin();
00999   }
01000   static inline ChildIteratorType child_end(NodeType *N) {
01001     return N->end();
01002   }
01003 };
01004 
01005 template <> struct GraphTraits<Loop*> {
01006   typedef Loop NodeType;
01007   typedef LoopInfo::iterator ChildIteratorType;
01008 
01009   static NodeType *getEntryNode(Loop *L) { return L; }
01010   static inline ChildIteratorType child_begin(NodeType *N) {
01011     return N->begin();
01012   }
01013   static inline ChildIteratorType child_end(NodeType *N) {
01014     return N->end();
01015   }
01016 };
01017 
01018 template<class BlockT, class LoopT>
01019 void
01020 LoopBase<BlockT, LoopT>::addBasicBlockToLoop(BlockT *NewBB,
01021                                              LoopInfoBase<BlockT, LoopT> &LIB) {
01022   assert((Blocks.empty() || LIB[getHeader()] == this) &&
01023          "Incorrect LI specified for this loop!");
01024   assert(NewBB && "Cannot add a null basic block to the loop!");
01025   assert(LIB[NewBB] == 0 && "BasicBlock already in the loop!");
01026 
01027   LoopT *L = static_cast<LoopT *>(this);
01028 
01029   // Add the loop mapping to the LoopInfo object...
01030   LIB.BBMap[NewBB] = L;
01031 
01032   // Add the basic block to this loop and all parent loops...
01033   while (L) {
01034     L->Blocks.push_back(NewBB);
01035     L = L->getParentLoop();
01036   }
01037 }
01038 
01039 } // End llvm namespace
01040 
01041 #endif