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