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