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 was developed by the LLVM research group and is distributed under
00006 // the University of Illinois Open Source 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/GraphTraits.h"
00035 
00036 namespace llvm {
00037 
00038 struct ETForest;
00039 class LoopInfo;
00040 class PHINode;
00041 class Instruction;
00042 
00043 //===----------------------------------------------------------------------===//
00044 /// Loop class - Instances of this class are used to represent loops that are
00045 /// detected in the flow graph
00046 ///
00047 class Loop {
00048   Loop *ParentLoop;
00049   std::vector<Loop*> SubLoops;       // Loops contained entirely within this one
00050   std::vector<BasicBlock*> Blocks;   // First entry is the header node
00051 
00052   Loop(const Loop &);                  // DO NOT IMPLEMENT
00053   const Loop &operator=(const Loop &); // DO NOT IMPLEMENT
00054 public:
00055   /// Loop ctor - This creates an empty loop.
00056   Loop() : ParentLoop(0) {}
00057   ~Loop() {
00058     for (unsigned i = 0, e = SubLoops.size(); i != e; ++i)
00059       delete SubLoops[i];
00060   }
00061 
00062   unsigned getLoopDepth() const {
00063     unsigned D = 0;
00064     for (const Loop *CurLoop = this; CurLoop; CurLoop = CurLoop->ParentLoop)
00065       ++D;
00066     return D;
00067   }
00068   BasicBlock *getHeader() const { return Blocks.front(); }
00069   Loop *getParentLoop() const { return ParentLoop; }
00070 
00071   /// contains - Return true of the specified basic block is in this loop
00072   ///
00073   bool contains(const BasicBlock *BB) const;
00074 
00075   /// iterator/begin/end - Return the loops contained entirely within this loop.
00076   ///
00077   const std::vector<Loop*> &getSubLoops() const { return SubLoops; }
00078   typedef std::vector<Loop*>::const_iterator iterator;
00079   iterator begin() const { return SubLoops.begin(); }
00080   iterator end() const { return SubLoops.end(); }
00081 
00082   /// getBlocks - Get a list of the basic blocks which make up this loop.
00083   ///
00084   const std::vector<BasicBlock*> &getBlocks() const { return Blocks; }
00085   typedef std::vector<BasicBlock*>::const_iterator block_iterator;
00086   block_iterator block_begin() const { return Blocks.begin(); }
00087   block_iterator block_end() const { return Blocks.end(); }
00088 
00089   /// isLoopExit - True if terminator in the block can branch to another block
00090   /// that is outside of the current loop.
00091   ///
00092   bool isLoopExit(const BasicBlock *BB) const;
00093 
00094   /// getNumBackEdges - Calculate the number of back edges to the loop header
00095   ///
00096   unsigned getNumBackEdges() const;
00097 
00098   /// isLoopInvariant - Return true if the specified value is loop invariant
00099   ///
00100   bool isLoopInvariant(Value *V) const;
00101 
00102   //===--------------------------------------------------------------------===//
00103   // APIs for simple analysis of the loop.
00104   //
00105   // Note that all of these methods can fail on general loops (ie, there may not
00106   // be a preheader, etc).  For best success, the loop simplification and
00107   // induction variable canonicalization pass should be used to normalize loops
00108   // for easy analysis.  These methods assume canonical loops.
00109 
00110   /// getExitBlocks - Return all of the successor blocks of this loop.  These
00111   /// are the blocks _outside of the current loop_ which are branched to.
00112   ///
00113   void getExitBlocks(std::vector<BasicBlock*> &Blocks) const;
00114 
00115   /// getLoopPreheader - If there is a preheader for this loop, return it.  A
00116   /// loop has a preheader if there is only one edge to the header of the loop
00117   /// from outside of the loop.  If this is the case, the block branching to the
00118   /// header of the loop is the preheader node.
00119   ///
00120   /// This method returns null if there is no preheader for the loop.
00121   ///
00122   BasicBlock *getLoopPreheader() const;
00123 
00124   /// getLoopLatch - If there is a latch block for this loop, return it.  A
00125   /// latch block is the canonical backedge for a loop.  A loop header in normal
00126   /// form has two edges into it: one from a preheader and one from a latch
00127   /// block.
00128   BasicBlock *getLoopLatch() const;
00129   
00130   /// getCanonicalInductionVariable - Check to see if the loop has a canonical
00131   /// induction variable: an integer recurrence that starts at 0 and increments
00132   /// by one each time through the loop.  If so, return the phi node that
00133   /// corresponds to it.
00134   ///
00135   PHINode *getCanonicalInductionVariable() const;
00136 
00137   /// getCanonicalInductionVariableIncrement - Return the LLVM value that holds
00138   /// the canonical induction variable value for the "next" iteration of the
00139   /// loop.  This always succeeds if getCanonicalInductionVariable succeeds.
00140   ///
00141   Instruction *getCanonicalInductionVariableIncrement() const;
00142 
00143   /// getTripCount - Return a loop-invariant LLVM value indicating the number of
00144   /// times the loop will be executed.  Note that this means that the backedge
00145   /// of the loop executes N-1 times.  If the trip-count cannot be determined,
00146   /// this returns null.
00147   ///
00148   Value *getTripCount() const;
00149 
00150   //===--------------------------------------------------------------------===//
00151   // APIs for updating loop information after changing the CFG
00152   //
00153 
00154   /// addBasicBlockToLoop - This method is used by other analyses to update loop
00155   /// information.  NewBB is set to be a new member of the current loop.
00156   /// Because of this, it is added as a member of all parent loops, and is added
00157   /// to the specified LoopInfo object as being in the current basic block.  It
00158   /// is not valid to replace the loop header with this method.
00159   ///
00160   void addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI);
00161 
00162   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
00163   /// the OldChild entry in our children list with NewChild, and updates the
00164   /// parent pointer of OldChild to be null and the NewChild to be this loop.
00165   /// This updates the loop depth of the new child.
00166   void replaceChildLoopWith(Loop *OldChild, Loop *NewChild);
00167 
00168   /// addChildLoop - Add the specified loop to be a child of this loop.  This
00169   /// updates the loop depth of the new child.
00170   ///
00171   void addChildLoop(Loop *NewChild);
00172 
00173   /// removeChildLoop - This removes the specified child from being a subloop of
00174   /// this loop.  The loop is not deleted, as it will presumably be inserted
00175   /// into another loop.
00176   Loop *removeChildLoop(iterator OldChild);
00177 
00178   /// addBlockEntry - This adds a basic block directly to the basic block list.
00179   /// This should only be used by transformations that create new loops.  Other
00180   /// transformations should use addBasicBlockToLoop.
00181   void addBlockEntry(BasicBlock *BB) {
00182     Blocks.push_back(BB);
00183   }
00184 
00185   /// moveToHeader - This method is used to move BB (which must be part of this
00186   /// loop) to be the loop header of the loop (the block that dominates all
00187   /// others).
00188   void moveToHeader(BasicBlock *BB) {
00189     if (Blocks[0] == BB) return;
00190     for (unsigned i = 0; ; ++i) {
00191       assert(i != Blocks.size() && "Loop does not contain BB!");
00192       if (Blocks[i] == BB) {
00193         Blocks[i] = Blocks[0];
00194         Blocks[0] = BB;
00195         return;
00196       }
00197     }
00198   }
00199 
00200   /// removeBlockFromLoop - This removes the specified basic block from the
00201   /// current loop, updating the Blocks as appropriate.  This does not update
00202   /// the mapping in the LoopInfo class.
00203   void removeBlockFromLoop(BasicBlock *BB);
00204 
00205   void print(std::ostream &O, unsigned Depth = 0) const;
00206   void dump() const;
00207 private:
00208   friend class LoopInfo;
00209   Loop(BasicBlock *BB) : ParentLoop(0) {
00210     Blocks.push_back(BB);
00211   }
00212 };
00213 
00214 
00215 
00216 //===----------------------------------------------------------------------===//
00217 /// LoopInfo - This class builds and contains all of the top level loop
00218 /// structures in the specified function.
00219 ///
00220 class LoopInfo : public FunctionPass {
00221   // BBMap - Mapping of basic blocks to the inner most loop they occur in
00222   std::map<BasicBlock*, Loop*> BBMap;
00223   std::vector<Loop*> TopLevelLoops;
00224   friend class Loop;
00225 public:
00226   ~LoopInfo() { releaseMemory(); }
00227 
00228   /// iterator/begin/end - The interface to the top-level loops in the current
00229   /// function.
00230   ///
00231   typedef std::vector<Loop*>::const_iterator iterator;
00232   iterator begin() const { return TopLevelLoops.begin(); }
00233   iterator end() const { return TopLevelLoops.end(); }
00234 
00235   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
00236   /// block is in no loop (for example the entry node), null is returned.
00237   ///
00238   Loop *getLoopFor(const BasicBlock *BB) const {
00239     std::map<BasicBlock *, Loop*>::const_iterator I=
00240       BBMap.find(const_cast<BasicBlock*>(BB));
00241     return I != BBMap.end() ? I->second : 0;
00242   }
00243 
00244   /// operator[] - same as getLoopFor...
00245   ///
00246   const Loop *operator[](const BasicBlock *BB) const {
00247     return getLoopFor(BB);
00248   }
00249 
00250   /// getLoopDepth - Return the loop nesting level of the specified block...
00251   ///
00252   unsigned getLoopDepth(const BasicBlock *BB) const {
00253     const Loop *L = getLoopFor(BB);
00254     return L ? L->getLoopDepth() : 0;
00255   }
00256 
00257   // isLoopHeader - True if the block is a loop header node
00258   bool isLoopHeader(BasicBlock *BB) const {
00259     const Loop *L = getLoopFor(BB);
00260     return L && L->getHeader() == BB;
00261   }
00262 
00263   /// runOnFunction - Calculate the natural loop information.
00264   ///
00265   virtual bool runOnFunction(Function &F);
00266 
00267   virtual void releaseMemory();
00268   void print(std::ostream &O, const Module* = 0) const;
00269 
00270   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
00271 
00272   /// removeLoop - This removes the specified top-level loop from this loop info
00273   /// object.  The loop is not deleted, as it will presumably be inserted into
00274   /// another loop.
00275   Loop *removeLoop(iterator I);
00276 
00277   /// changeLoopFor - Change the top-level loop that contains BB to the
00278   /// specified loop.  This should be used by transformations that restructure
00279   /// the loop hierarchy tree.
00280   void changeLoopFor(BasicBlock *BB, Loop *L);
00281 
00282   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
00283   /// list with the indicated loop.
00284   void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop);
00285 
00286   /// addTopLevelLoop - This adds the specified loop to the collection of
00287   /// top-level loops.
00288   void addTopLevelLoop(Loop *New) {
00289     assert(New->getParentLoop() == 0 && "Loop already in subloop!");
00290     TopLevelLoops.push_back(New);
00291   }
00292 
00293   /// removeBlock - This method completely removes BB from all data structures,
00294   /// including all of the Loop objects it is nested in and our mapping from
00295   /// BasicBlocks to loops.
00296   void removeBlock(BasicBlock *BB);
00297 
00298   static void stub();  // Noop
00299 private:
00300   void Calculate(ETForest &EF);
00301   Loop *ConsiderForLoop(BasicBlock *BB, ETForest &EF);
00302   void MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent);
00303   void InsertLoopInto(Loop *L, Loop *Parent);
00304 };
00305 
00306 
00307 // Make sure that any clients of this file link in LoopInfo.cpp
00308 static IncludeFile
00309 LOOP_INFO_INCLUDE_FILE((void*)(&LoopInfo::stub));
00310 
00311 // Allow clients to walk the list of nested loops...
00312 template <> struct GraphTraits<const Loop*> {
00313   typedef const Loop NodeType;
00314   typedef std::vector<Loop*>::const_iterator ChildIteratorType;
00315 
00316   static NodeType *getEntryNode(const Loop *L) { return L; }
00317   static inline ChildIteratorType child_begin(NodeType *N) {
00318     return N->begin();
00319   }
00320   static inline ChildIteratorType child_end(NodeType *N) {
00321     return N->end();
00322   }
00323 };
00324 
00325 template <> struct GraphTraits<Loop*> {
00326   typedef Loop NodeType;
00327   typedef std::vector<Loop*>::const_iterator ChildIteratorType;
00328 
00329   static NodeType *getEntryNode(Loop *L) { return L; }
00330   static inline ChildIteratorType child_begin(NodeType *N) {
00331     return N->begin();
00332   }
00333   static inline ChildIteratorType child_end(NodeType *N) {
00334     return N->end();
00335   }
00336 };
00337 
00338 } // End llvm namespace
00339 
00340 #endif