Home | History | Annotate | Download | only in llvm
      1 //===-- llvm/BasicBlock.h - Represent a basic block in the VM ---*- 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 contains the declaration of the BasicBlock class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_BASICBLOCK_H
     15 #define LLVM_BASICBLOCK_H
     16 
     17 #include "llvm/Instruction.h"
     18 #include "llvm/SymbolTableListTraits.h"
     19 #include "llvm/ADT/ilist.h"
     20 #include "llvm/ADT/Twine.h"
     21 #include "llvm/Support/DataTypes.h"
     22 
     23 namespace llvm {
     24 
     25 class LandingPadInst;
     26 class TerminatorInst;
     27 class LLVMContext;
     28 class BlockAddress;
     29 
     30 template<> struct ilist_traits<Instruction>
     31   : public SymbolTableListTraits<Instruction, BasicBlock> {
     32   // createSentinel is used to get hold of a node that marks the end of
     33   // the list...
     34   // The sentinel is relative to this instance, so we use a non-static
     35   // method.
     36   Instruction *createSentinel() const {
     37     // since i(p)lists always publicly derive from the corresponding
     38     // traits, placing a data member in this class will augment i(p)list.
     39     // But since the NodeTy is expected to publicly derive from
     40     // ilist_node<NodeTy>, there is a legal viable downcast from it
     41     // to NodeTy. We use this trick to superpose i(p)list with a "ghostly"
     42     // NodeTy, which becomes the sentinel. Dereferencing the sentinel is
     43     // forbidden (save the ilist_node<NodeTy>) so no one will ever notice
     44     // the superposition.
     45     return static_cast<Instruction*>(&Sentinel);
     46   }
     47   static void destroySentinel(Instruction*) {}
     48 
     49   Instruction *provideInitialHead() const { return createSentinel(); }
     50   Instruction *ensureHead(Instruction*) const { return createSentinel(); }
     51   static void noteHead(Instruction*, Instruction*) {}
     52 private:
     53   mutable ilist_half_node<Instruction> Sentinel;
     54 };
     55 
     56 /// This represents a single basic block in LLVM. A basic block is simply a
     57 /// container of instructions that execute sequentially. Basic blocks are Values
     58 /// because they are referenced by instructions such as branches and switch
     59 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
     60 /// represents a label to which a branch can jump.
     61 ///
     62 /// A well formed basic block is formed of a list of non-terminating
     63 /// instructions followed by a single TerminatorInst instruction.
     64 /// TerminatorInst's may not occur in the middle of basic blocks, and must
     65 /// terminate the blocks. The BasicBlock class allows malformed basic blocks to
     66 /// occur because it may be useful in the intermediate stage of constructing or
     67 /// modifying a program. However, the verifier will ensure that basic blocks
     68 /// are "well formed".
     69 /// @brief LLVM Basic Block Representation
     70 class BasicBlock : public Value, // Basic blocks are data objects also
     71                    public ilist_node<BasicBlock> {
     72   friend class BlockAddress;
     73 public:
     74   typedef iplist<Instruction> InstListType;
     75 private:
     76   InstListType InstList;
     77   Function *Parent;
     78 
     79   void setParent(Function *parent);
     80   friend class SymbolTableListTraits<BasicBlock, Function>;
     81 
     82   BasicBlock(const BasicBlock &);     // Do not implement
     83   void operator=(const BasicBlock &); // Do not implement
     84 
     85   /// BasicBlock ctor - If the function parameter is specified, the basic block
     86   /// is automatically inserted at either the end of the function (if
     87   /// InsertBefore is null), or before the specified basic block.
     88   ///
     89   explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
     90                       Function *Parent = 0, BasicBlock *InsertBefore = 0);
     91 public:
     92   /// getContext - Get the context in which this basic block lives.
     93   LLVMContext &getContext() const;
     94 
     95   /// Instruction iterators...
     96   typedef InstListType::iterator                              iterator;
     97   typedef InstListType::const_iterator                  const_iterator;
     98 
     99   /// Create - Creates a new BasicBlock. If the Parent parameter is specified,
    100   /// the basic block is automatically inserted at either the end of the
    101   /// function (if InsertBefore is 0), or before the specified basic block.
    102   static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
    103                             Function *Parent = 0,BasicBlock *InsertBefore = 0) {
    104     return new BasicBlock(Context, Name, Parent, InsertBefore);
    105   }
    106   ~BasicBlock();
    107 
    108   /// getParent - Return the enclosing method, or null if none
    109   ///
    110   const Function *getParent() const { return Parent; }
    111         Function *getParent()       { return Parent; }
    112 
    113   /// getTerminator() - If this is a well formed basic block, then this returns
    114   /// a pointer to the terminator instruction.  If it is not, then you get a
    115   /// null pointer back.
    116   ///
    117   TerminatorInst *getTerminator();
    118   const TerminatorInst *getTerminator() const;
    119 
    120   /// Returns a pointer to the first instructon in this block that is not a
    121   /// PHINode instruction. When adding instruction to the beginning of the
    122   /// basic block, they should be added before the returned value, not before
    123   /// the first instruction, which might be PHI.
    124   /// Returns 0 is there's no non-PHI instruction.
    125   Instruction* getFirstNonPHI();
    126   const Instruction* getFirstNonPHI() const {
    127     return const_cast<BasicBlock*>(this)->getFirstNonPHI();
    128   }
    129 
    130   // Same as above, but also skip debug intrinsics.
    131   Instruction* getFirstNonPHIOrDbg();
    132   const Instruction* getFirstNonPHIOrDbg() const {
    133     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbg();
    134   }
    135 
    136   // Same as above, but also skip lifetime intrinsics.
    137   Instruction* getFirstNonPHIOrDbgOrLifetime();
    138   const Instruction* getFirstNonPHIOrDbgOrLifetime() const {
    139     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbgOrLifetime();
    140   }
    141 
    142   /// getFirstInsertionPt - Returns an iterator to the first instruction in this
    143   /// block that is suitable for inserting a non-PHI instruction. In particular,
    144   /// it skips all PHIs and LandingPad instructions.
    145   iterator getFirstInsertionPt();
    146   const_iterator getFirstInsertionPt() const {
    147     return const_cast<BasicBlock*>(this)->getFirstInsertionPt();
    148   }
    149 
    150   /// removeFromParent - This method unlinks 'this' from the containing
    151   /// function, but does not delete it.
    152   ///
    153   void removeFromParent();
    154 
    155   /// eraseFromParent - This method unlinks 'this' from the containing function
    156   /// and deletes it.
    157   ///
    158   void eraseFromParent();
    159 
    160   /// moveBefore - Unlink this basic block from its current function and
    161   /// insert it into the function that MovePos lives in, right before MovePos.
    162   void moveBefore(BasicBlock *MovePos);
    163 
    164   /// moveAfter - Unlink this basic block from its current function and
    165   /// insert it into the function that MovePos lives in, right after MovePos.
    166   void moveAfter(BasicBlock *MovePos);
    167 
    168 
    169   /// getSinglePredecessor - If this basic block has a single predecessor block,
    170   /// return the block, otherwise return a null pointer.
    171   BasicBlock *getSinglePredecessor();
    172   const BasicBlock *getSinglePredecessor() const {
    173     return const_cast<BasicBlock*>(this)->getSinglePredecessor();
    174   }
    175 
    176   /// getUniquePredecessor - If this basic block has a unique predecessor block,
    177   /// return the block, otherwise return a null pointer.
    178   /// Note that unique predecessor doesn't mean single edge, there can be
    179   /// multiple edges from the unique predecessor to this block (for example
    180   /// a switch statement with multiple cases having the same destination).
    181   BasicBlock *getUniquePredecessor();
    182   const BasicBlock *getUniquePredecessor() const {
    183     return const_cast<BasicBlock*>(this)->getUniquePredecessor();
    184   }
    185 
    186   //===--------------------------------------------------------------------===//
    187   /// Instruction iterator methods
    188   ///
    189   inline iterator                begin()       { return InstList.begin(); }
    190   inline const_iterator          begin() const { return InstList.begin(); }
    191   inline iterator                end  ()       { return InstList.end();   }
    192   inline const_iterator          end  () const { return InstList.end();   }
    193 
    194   inline size_t                   size() const { return InstList.size();  }
    195   inline bool                    empty() const { return InstList.empty(); }
    196   inline const Instruction      &front() const { return InstList.front(); }
    197   inline       Instruction      &front()       { return InstList.front(); }
    198   inline const Instruction       &back() const { return InstList.back();  }
    199   inline       Instruction       &back()       { return InstList.back();  }
    200 
    201   /// getInstList() - Return the underlying instruction list container.  You
    202   /// need to access it directly if you want to modify it currently.
    203   ///
    204   const InstListType &getInstList() const { return InstList; }
    205         InstListType &getInstList()       { return InstList; }
    206 
    207   /// getSublistAccess() - returns pointer to member of instruction list
    208   static iplist<Instruction> BasicBlock::*getSublistAccess(Instruction*) {
    209     return &BasicBlock::InstList;
    210   }
    211 
    212   /// getValueSymbolTable() - returns pointer to symbol table (if any)
    213   ValueSymbolTable *getValueSymbolTable();
    214 
    215   /// Methods for support type inquiry through isa, cast, and dyn_cast:
    216   static inline bool classof(const BasicBlock *) { return true; }
    217   static inline bool classof(const Value *V) {
    218     return V->getValueID() == Value::BasicBlockVal;
    219   }
    220 
    221   /// dropAllReferences() - This function causes all the subinstructions to "let
    222   /// go" of all references that they are maintaining.  This allows one to
    223   /// 'delete' a whole class at a time, even though there may be circular
    224   /// references... first all references are dropped, and all use counts go to
    225   /// zero.  Then everything is delete'd for real.  Note that no operations are
    226   /// valid on an object that has "dropped all references", except operator
    227   /// delete.
    228   ///
    229   void dropAllReferences();
    230 
    231   /// removePredecessor - This method is used to notify a BasicBlock that the
    232   /// specified Predecessor of the block is no longer able to reach it.  This is
    233   /// actually not used to update the Predecessor list, but is actually used to
    234   /// update the PHI nodes that reside in the block.  Note that this should be
    235   /// called while the predecessor still refers to this block.
    236   ///
    237   void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
    238 
    239   /// splitBasicBlock - This splits a basic block into two at the specified
    240   /// instruction.  Note that all instructions BEFORE the specified iterator
    241   /// stay as part of the original basic block, an unconditional branch is added
    242   /// to the original BB, and the rest of the instructions in the BB are moved
    243   /// to the new BB, including the old terminator.  The newly formed BasicBlock
    244   /// is returned.  This function invalidates the specified iterator.
    245   ///
    246   /// Note that this only works on well formed basic blocks (must have a
    247   /// terminator), and 'I' must not be the end of instruction list (which would
    248   /// cause a degenerate basic block to be formed, having a terminator inside of
    249   /// the basic block).
    250   ///
    251   /// Also note that this doesn't preserve any passes. To split blocks while
    252   /// keeping loop information consistent, use the SplitBlock utility function.
    253   ///
    254   BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
    255 
    256   /// hasAddressTaken - returns true if there are any uses of this basic block
    257   /// other than direct branches, switches, etc. to it.
    258   bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
    259 
    260   /// replaceSuccessorsPhiUsesWith - Update all phi nodes in all our successors
    261   /// to refer to basic block New instead of to us.
    262   void replaceSuccessorsPhiUsesWith(BasicBlock *New);
    263 
    264   /// isLandingPad - Return true if this basic block is a landing pad. I.e.,
    265   /// it's the destination of the 'unwind' edge of an invoke instruction.
    266   bool isLandingPad() const;
    267 
    268   /// getLandingPadInst() - Return the landingpad instruction associated with
    269   /// the landing pad.
    270   LandingPadInst *getLandingPadInst();
    271   const LandingPadInst *getLandingPadInst() const;
    272 
    273 private:
    274   /// AdjustBlockAddressRefCount - BasicBlock stores the number of BlockAddress
    275   /// objects using it.  This is almost always 0, sometimes one, possibly but
    276   /// almost never 2, and inconceivably 3 or more.
    277   void AdjustBlockAddressRefCount(int Amt) {
    278     setValueSubclassData(getSubclassDataFromValue()+Amt);
    279     assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
    280            "Refcount wrap-around");
    281   }
    282   // Shadow Value::setValueSubclassData with a private forwarding method so that
    283   // any future subclasses cannot accidentally use it.
    284   void setValueSubclassData(unsigned short D) {
    285     Value::setValueSubclassData(D);
    286   }
    287 };
    288 
    289 } // End llvm namespace
    290 
    291 #endif
    292