LLVM API Documentation

BasicBlock.h
Go to the documentation of this file.
00001 //===-- llvm/BasicBlock.h - Represent a basic block in the VM ---*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains the declaration of the BasicBlock class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_IR_BASICBLOCK_H
00015 #define LLVM_IR_BASICBLOCK_H
00016 
00017 #include "llvm/ADT/Twine.h"
00018 #include "llvm/ADT/ilist.h"
00019 #include "llvm/IR/Instruction.h"
00020 #include "llvm/IR/SymbolTableListTraits.h"
00021 #include "llvm/Support/CBindingWrapping.h"
00022 #include "llvm/Support/DataTypes.h"
00023 
00024 namespace llvm {
00025 
00026 class LandingPadInst;
00027 class TerminatorInst;
00028 class LLVMContext;
00029 class BlockAddress;
00030 
00031 template<> struct ilist_traits<Instruction>
00032   : public SymbolTableListTraits<Instruction, BasicBlock> {
00033 
00034   /// \brief Return a node that marks the end of a list.
00035   ///
00036   /// The sentinel is relative to this instance, so we use a non-static
00037   /// method.
00038   Instruction *createSentinel() const {
00039     // Since i(p)lists always publicly derive from their corresponding traits,
00040     // placing a data member in this class will augment the i(p)list.  But since
00041     // the NodeTy is expected to be publicly derive from ilist_node<NodeTy>,
00042     // there is a legal viable downcast from it to NodeTy. We use this trick to
00043     // superimpose an i(p)list with a "ghostly" NodeTy, which becomes the
00044     // sentinel. Dereferencing the sentinel is forbidden (save the
00045     // ilist_node<NodeTy>), so no one will ever notice the superposition.
00046     return static_cast<Instruction*>(&Sentinel);
00047   }
00048   static void destroySentinel(Instruction*) {}
00049 
00050   Instruction *provideInitialHead() const { return createSentinel(); }
00051   Instruction *ensureHead(Instruction*) const { return createSentinel(); }
00052   static void noteHead(Instruction*, Instruction*) {}
00053 private:
00054   mutable ilist_half_node<Instruction> Sentinel;
00055 };
00056 
00057 /// \brief LLVM Basic Block Representation
00058 ///
00059 /// This represents a single basic block in LLVM. A basic block is simply a
00060 /// container of instructions that execute sequentially. Basic blocks are Values
00061 /// because they are referenced by instructions such as branches and switch
00062 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
00063 /// represents a label to which a branch can jump.
00064 ///
00065 /// A well formed basic block is formed of a list of non-terminating
00066 /// instructions followed by a single TerminatorInst instruction.
00067 /// TerminatorInst's may not occur in the middle of basic blocks, and must
00068 /// terminate the blocks. The BasicBlock class allows malformed basic blocks to
00069 /// occur because it may be useful in the intermediate stage of constructing or
00070 /// modifying a program. However, the verifier will ensure that basic blocks
00071 /// are "well formed".
00072 class BasicBlock : public Value, // Basic blocks are data objects also
00073                    public ilist_node<BasicBlock> {
00074   friend class BlockAddress;
00075 public:
00076   typedef iplist<Instruction> InstListType;
00077 private:
00078   InstListType InstList;
00079   Function *Parent;
00080 
00081   void setParent(Function *parent);
00082   friend class SymbolTableListTraits<BasicBlock, Function>;
00083 
00084   BasicBlock(const BasicBlock &) LLVM_DELETED_FUNCTION;
00085   void operator=(const BasicBlock &) LLVM_DELETED_FUNCTION;
00086 
00087   /// \brief Constructor.
00088   ///
00089   /// If the function parameter is specified, the basic block is automatically
00090   /// inserted at either the end of the function (if InsertBefore is null), or
00091   /// before the specified basic block.
00092   explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
00093                       Function *Parent = nullptr,
00094                       BasicBlock *InsertBefore = nullptr);
00095 public:
00096   /// \brief Get the context in which this basic block lives.
00097   LLVMContext &getContext() const;
00098 
00099   /// Instruction iterators...
00100   typedef InstListType::iterator iterator;
00101   typedef InstListType::const_iterator const_iterator;
00102   typedef InstListType::reverse_iterator reverse_iterator;
00103   typedef InstListType::const_reverse_iterator const_reverse_iterator;
00104 
00105   /// \brief Creates a new BasicBlock.
00106   ///
00107   /// If the Parent parameter is specified, the basic block is automatically
00108   /// inserted at either the end of the function (if InsertBefore is 0), or
00109   /// before the specified basic block.
00110   static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
00111                             Function *Parent = nullptr,
00112                             BasicBlock *InsertBefore = nullptr) {
00113     return new BasicBlock(Context, Name, Parent, InsertBefore);
00114   }
00115   ~BasicBlock();
00116 
00117   /// \brief Return the enclosing method, or null if none.
00118   const Function *getParent() const { return Parent; }
00119         Function *getParent()       { return Parent; }
00120 
00121   const DataLayout *getDataLayout() const;
00122 
00123   /// \brief Returns the terminator instruction if the block is well formed or
00124   /// null if the block is not well formed.
00125   TerminatorInst *getTerminator();
00126   const TerminatorInst *getTerminator() const;
00127 
00128   /// \brief Returns a pointer to the first instruction in this block that is
00129   /// not a PHINode instruction.
00130   ///
00131   /// When adding instructions to the beginning of the basic block, they should
00132   /// be added before the returned value, not before the first instruction,
00133   /// which might be PHI. Returns 0 is there's no non-PHI instruction.
00134   Instruction* getFirstNonPHI();
00135   const Instruction* getFirstNonPHI() const {
00136     return const_cast<BasicBlock*>(this)->getFirstNonPHI();
00137   }
00138 
00139   /// \brief Returns a pointer to the first instruction in this block that is not
00140   /// a PHINode or a debug intrinsic.
00141   Instruction* getFirstNonPHIOrDbg();
00142   const Instruction* getFirstNonPHIOrDbg() const {
00143     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbg();
00144   }
00145 
00146   /// \brief Returns a pointer to the first instruction in this block that is not
00147   /// a PHINode, a debug intrinsic, or a lifetime intrinsic.
00148   Instruction* getFirstNonPHIOrDbgOrLifetime();
00149   const Instruction* getFirstNonPHIOrDbgOrLifetime() const {
00150     return const_cast<BasicBlock*>(this)->getFirstNonPHIOrDbgOrLifetime();
00151   }
00152 
00153   /// \brief Returns an iterator to the first instruction in this block that is
00154   /// suitable for inserting a non-PHI instruction.
00155   ///
00156   /// In particular, it skips all PHIs and LandingPad instructions.
00157   iterator getFirstInsertionPt();
00158   const_iterator getFirstInsertionPt() const {
00159     return const_cast<BasicBlock*>(this)->getFirstInsertionPt();
00160   }
00161 
00162   /// \brief Unlink 'this' from the containing function, but do not delete it.
00163   void removeFromParent();
00164 
00165   /// \brief Unlink 'this' from the containing function and delete it.
00166   void eraseFromParent();
00167 
00168   /// \brief Unlink this basic block from its current function and insert it
00169   /// into the function that \p MovePos lives in, right before \p MovePos.
00170   void moveBefore(BasicBlock *MovePos);
00171 
00172   /// \brief Unlink this basic block from its current function and insert it
00173   /// right after \p MovePos in the function \p MovePos lives in.
00174   void moveAfter(BasicBlock *MovePos);
00175 
00176 
00177   /// \brief Return the predecessor of this block if it has a single predecessor
00178   /// block. Otherwise return a null pointer.
00179   BasicBlock *getSinglePredecessor();
00180   const BasicBlock *getSinglePredecessor() const {
00181     return const_cast<BasicBlock*>(this)->getSinglePredecessor();
00182   }
00183 
00184   /// \brief Return the predecessor of this block if it has a unique predecessor
00185   /// block. Otherwise return a null pointer.
00186   ///
00187   /// Note that unique predecessor doesn't mean single edge, there can be
00188   /// multiple edges from the unique predecessor to this block (for example a
00189   /// switch statement with multiple cases having the same destination).
00190   BasicBlock *getUniquePredecessor();
00191   const BasicBlock *getUniquePredecessor() const {
00192     return const_cast<BasicBlock*>(this)->getUniquePredecessor();
00193   }
00194 
00195   //===--------------------------------------------------------------------===//
00196   /// Instruction iterator methods
00197   ///
00198   inline iterator                begin()       { return InstList.begin(); }
00199   inline const_iterator          begin() const { return InstList.begin(); }
00200   inline iterator                end  ()       { return InstList.end();   }
00201   inline const_iterator          end  () const { return InstList.end();   }
00202 
00203   inline reverse_iterator        rbegin()       { return InstList.rbegin(); }
00204   inline const_reverse_iterator  rbegin() const { return InstList.rbegin(); }
00205   inline reverse_iterator        rend  ()       { return InstList.rend();   }
00206   inline const_reverse_iterator  rend  () const { return InstList.rend();   }
00207 
00208   inline size_t                   size() const { return InstList.size();  }
00209   inline bool                    empty() const { return InstList.empty(); }
00210   inline const Instruction      &front() const { return InstList.front(); }
00211   inline       Instruction      &front()       { return InstList.front(); }
00212   inline const Instruction       &back() const { return InstList.back();  }
00213   inline       Instruction       &back()       { return InstList.back();  }
00214 
00215   /// \brief Return the underlying instruction list container.
00216   ///
00217   /// Currently you need to access the underlying instruction list container
00218   /// directly if you want to modify it.
00219   const InstListType &getInstList() const { return InstList; }
00220         InstListType &getInstList()       { return InstList; }
00221 
00222   /// \brief Returns a pointer to a member of the instruction list.
00223   static iplist<Instruction> BasicBlock::*getSublistAccess(Instruction*) {
00224     return &BasicBlock::InstList;
00225   }
00226 
00227   /// \brief Returns a pointer to the symbol table if one exists.
00228   ValueSymbolTable *getValueSymbolTable();
00229 
00230   /// \brief Methods for support type inquiry through isa, cast, and dyn_cast.
00231   static inline bool classof(const Value *V) {
00232     return V->getValueID() == Value::BasicBlockVal;
00233   }
00234 
00235   /// \brief Cause all subinstructions to "let go" of all the references that
00236   /// said subinstructions are maintaining.
00237   ///
00238   /// This allows one to 'delete' a whole class at a time, even though there may
00239   /// be circular references... first all references are dropped, and all use
00240   /// counts go to zero.  Then everything is delete'd for real.  Note that no
00241   /// operations are valid on an object that has "dropped all references",
00242   /// except operator delete.
00243   void dropAllReferences();
00244 
00245   /// \brief Notify the BasicBlock that the predecessor \p Pred is no longer
00246   /// able to reach it.
00247   ///
00248   /// This is actually not used to update the Predecessor list, but is actually
00249   /// used to update the PHI nodes that reside in the block.  Note that this
00250   /// should be called while the predecessor still refers to this block.
00251   void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
00252 
00253   /// \brief Split the basic block into two basic blocks at the specified
00254   /// instruction.
00255   ///
00256   /// Note that all instructions BEFORE the specified iterator stay as part of
00257   /// the original basic block, an unconditional branch is added to the original
00258   /// BB, and the rest of the instructions in the BB are moved to the new BB,
00259   /// including the old terminator.  The newly formed BasicBlock is returned.
00260   /// This function invalidates the specified iterator.
00261   ///
00262   /// Note that this only works on well formed basic blocks (must have a
00263   /// terminator), and 'I' must not be the end of instruction list (which would
00264   /// cause a degenerate basic block to be formed, having a terminator inside of
00265   /// the basic block).
00266   ///
00267   /// Also note that this doesn't preserve any passes. To split blocks while
00268   /// keeping loop information consistent, use the SplitBlock utility function.
00269   BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
00270 
00271   /// \brief Returns true if there are any uses of this basic block other than
00272   /// direct branches, switches, etc. to it.
00273   bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
00274 
00275   /// \brief Update all phi nodes in this basic block's successors to refer to
00276   /// basic block \p New instead of to it.
00277   void replaceSuccessorsPhiUsesWith(BasicBlock *New);
00278 
00279   /// \brief Return true if this basic block is a landing pad.
00280   ///
00281   /// Being a ``landing pad'' means that the basic block is the destination of
00282   /// the 'unwind' edge of an invoke instruction.
00283   bool isLandingPad() const;
00284 
00285   /// \brief Return the landingpad instruction associated with the landing pad.
00286   LandingPadInst *getLandingPadInst();
00287   const LandingPadInst *getLandingPadInst() const;
00288 
00289 private:
00290   /// \brief Increment the internal refcount of the number of BlockAddresses
00291   /// referencing this BasicBlock by \p Amt.
00292   ///
00293   /// This is almost always 0, sometimes one possibly, but almost never 2, and
00294   /// inconceivably 3 or more.
00295   void AdjustBlockAddressRefCount(int Amt) {
00296     setValueSubclassData(getSubclassDataFromValue()+Amt);
00297     assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
00298            "Refcount wrap-around");
00299   }
00300   /// \brief Shadow Value::setValueSubclassData with a private forwarding method
00301   /// so that any future subclasses cannot accidentally use it.
00302   void setValueSubclassData(unsigned short D) {
00303     Value::setValueSubclassData(D);
00304   }
00305 };
00306 
00307 // Create wrappers for C Binding types (see CBindingWrapping.h).
00308 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
00309 
00310 } // End llvm namespace
00311 
00312 #endif