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   /// isLCSSAForm - Return true if the Loop is in LCSSA form
00151   bool isLCSSAForm() const;
00152 
00153   //===--------------------------------------------------------------------===//
00154   // APIs for updating loop information after changing the CFG
00155   //
00156 
00157   /// addBasicBlockToLoop - This method is used by other analyses to update loop
00158   /// information.  NewBB is set to be a new member of the current loop.
00159   /// Because of this, it is added as a member of all parent loops, and is added
00160   /// to the specified LoopInfo object as being in the current basic block.  It
00161   /// is not valid to replace the loop header with this method.
00162   ///
00163   void addBasicBlockToLoop(BasicBlock *NewBB, LoopInfo &LI);
00164 
00165   /// replaceChildLoopWith - This is used when splitting loops up.  It replaces
00166   /// the OldChild entry in our children list with NewChild, and updates the
00167   /// parent pointer of OldChild to be null and the NewChild to be this loop.
00168   /// This updates the loop depth of the new child.
00169   void replaceChildLoopWith(Loop *OldChild, Loop *NewChild);
00170 
00171   /// addChildLoop - Add the specified loop to be a child of this loop.  This
00172   /// updates the loop depth of the new child.
00173   ///
00174   void addChildLoop(Loop *NewChild);
00175 
00176   /// removeChildLoop - This removes the specified child from being a subloop of
00177   /// this loop.  The loop is not deleted, as it will presumably be inserted
00178   /// into another loop.
00179   Loop *removeChildLoop(iterator OldChild);
00180 
00181   /// addBlockEntry - This adds a basic block directly to the basic block list.
00182   /// This should only be used by transformations that create new loops.  Other
00183   /// transformations should use addBasicBlockToLoop.
00184   void addBlockEntry(BasicBlock *BB) {
00185     Blocks.push_back(BB);
00186   }
00187 
00188   /// moveToHeader - This method is used to move BB (which must be part of this
00189   /// loop) to be the loop header of the loop (the block that dominates all
00190   /// others).
00191   void moveToHeader(BasicBlock *BB) {
00192     if (Blocks[0] == BB) return;
00193     for (unsigned i = 0; ; ++i) {
00194       assert(i != Blocks.size() && "Loop does not contain BB!");
00195       if (Blocks[i] == BB) {
00196         Blocks[i] = Blocks[0];
00197         Blocks[0] = BB;
00198         return;
00199       }
00200     }
00201   }
00202 
00203   /// removeBlockFromLoop - This removes the specified basic block from the
00204   /// current loop, updating the Blocks as appropriate.  This does not update
00205   /// the mapping in the LoopInfo class.
00206   void removeBlockFromLoop(BasicBlock *BB);
00207 
00208   void print(std::ostream &O, unsigned Depth = 0) const;
00209   void dump() const;
00210 private:
00211   friend class LoopInfo;
00212   Loop(BasicBlock *BB) : ParentLoop(0) {
00213     Blocks.push_back(BB);
00214   }
00215 };
00216 
00217 
00218 
00219 //===----------------------------------------------------------------------===//
00220 /// LoopInfo - This class builds and contains all of the top level loop
00221 /// structures in the specified function.
00222 ///
00223 class LoopInfo : public FunctionPass {
00224   // BBMap - Mapping of basic blocks to the inner most loop they occur in
00225   std::map<BasicBlock*, Loop*> BBMap;
00226   std::vector<Loop*> TopLevelLoops;
00227   friend class Loop;
00228 public:
00229   ~LoopInfo() { releaseMemory(); }
00230 
00231   /// iterator/begin/end - The interface to the top-level loops in the current
00232   /// function.
00233   ///
00234   typedef std::vector<Loop*>::const_iterator iterator;
00235   iterator begin() const { return TopLevelLoops.begin(); }
00236   iterator end() const { return TopLevelLoops.end(); }
00237 
00238   /// getLoopFor - Return the inner most loop that BB lives in.  If a basic
00239   /// block is in no loop (for example the entry node), null is returned.
00240   ///
00241   Loop *getLoopFor(const BasicBlock *BB) const {
00242     std::map<BasicBlock *, Loop*>::const_iterator I=
00243       BBMap.find(const_cast<BasicBlock*>(BB));
00244     return I != BBMap.end() ? I->second : 0;
00245   }
00246 
00247   /// operator[] - same as getLoopFor...
00248   ///
00249   const Loop *operator[](const BasicBlock *BB) const {
00250     return getLoopFor(BB);
00251   }
00252 
00253   /// getLoopDepth - Return the loop nesting level of the specified block...
00254   ///
00255   unsigned getLoopDepth(const BasicBlock *BB) const {
00256     const Loop *L = getLoopFor(BB);
00257     return L ? L->getLoopDepth() : 0;
00258   }
00259 
00260   // isLoopHeader - True if the block is a loop header node
00261   bool isLoopHeader(BasicBlock *BB) const {
00262     const Loop *L = getLoopFor(BB);
00263     return L && L->getHeader() == BB;
00264   }
00265 
00266   /// runOnFunction - Calculate the natural loop information.
00267   ///
00268   virtual bool runOnFunction(Function &F);
00269 
00270   virtual void releaseMemory();
00271   void print(std::ostream &O, const Module* = 0) const;
00272 
00273   virtual void getAnalysisUsage(AnalysisUsage &AU) const;
00274 
00275   /// removeLoop - This removes the specified top-level loop from this loop info
00276   /// object.  The loop is not deleted, as it will presumably be inserted into
00277   /// another loop.
00278   Loop *removeLoop(iterator I);
00279 
00280   /// changeLoopFor - Change the top-level loop that contains BB to the
00281   /// specified loop.  This should be used by transformations that restructure
00282   /// the loop hierarchy tree.
00283   void changeLoopFor(BasicBlock *BB, Loop *L);
00284 
00285   /// changeTopLevelLoop - Replace the specified loop in the top-level loops
00286   /// list with the indicated loop.
00287   void changeTopLevelLoop(Loop *OldLoop, Loop *NewLoop);
00288 
00289   /// addTopLevelLoop - This adds the specified loop to the collection of
00290   /// top-level loops.
00291   void addTopLevelLoop(Loop *New) {
00292     assert(New->getParentLoop() == 0 && "Loop already in subloop!");
00293     TopLevelLoops.push_back(New);
00294   }
00295 
00296   /// removeBlock - This method completely removes BB from all data structures,
00297   /// including all of the Loop objects it is nested in and our mapping from
00298   /// BasicBlocks to loops.
00299   void removeBlock(BasicBlock *BB);
00300 
00301 private:
00302   void Calculate(ETForest &EF);
00303   Loop *ConsiderForLoop(BasicBlock *BB, ETForest &EF);
00304   void MoveSiblingLoopInto(Loop *NewChild, Loop *NewParent);
00305   void InsertLoopInto(Loop *L, Loop *Parent);
00306 };
00307 
00308 
00309 // Allow clients to walk the list of nested loops...
00310 template <> struct GraphTraits<const Loop*> {
00311   typedef const Loop NodeType;
00312   typedef std::vector<Loop*>::const_iterator ChildIteratorType;
00313 
00314   static NodeType *getEntryNode(const Loop *L) { return L; }
00315   static inline ChildIteratorType child_begin(NodeType *N) {
00316     return N->begin();
00317   }
00318   static inline ChildIteratorType child_end(NodeType *N) {
00319     return N->end();
00320   }
00321 };
00322 
00323 template <> struct GraphTraits<Loop*> {
00324   typedef Loop NodeType;
00325   typedef std::vector<Loop*>::const_iterator ChildIteratorType;
00326 
00327   static NodeType *getEntryNode(Loop *L) { return L; }
00328   static inline ChildIteratorType child_begin(NodeType *N) {
00329     return N->begin();
00330   }
00331   static inline ChildIteratorType child_end(NodeType *N) {
00332     return N->end();
00333   }
00334 };
00335 
00336 } // End llvm namespace
00337 
00338 // Make sure that any clients of this file link in LoopInfo.cpp
00339 FORCE_DEFINING_FILE_TO_BE_LINKED(LoopInfo)
00340 
00341 #endif