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