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-c/Types.h"
18 #include "llvm/ADT/Twine.h"
19 #include "llvm/ADT/ilist.h"
20 #include "llvm/ADT/ilist_node.h"
21 #include "llvm/ADT/iterator.h"
22 #include "llvm/ADT/iterator_range.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/SymbolTableListTraits.h"
25 #include "llvm/IR/Value.h"
26 #include "llvm/Support/CBindingWrapping.h"
27 #include "llvm/Support/Casting.h"
28 #include "llvm/Support/Compiler.h"
29 #include <cassert>
30 #include <cstddef>
31 #include <iterator>
32 
33 namespace llvm {
34 
35 class CallInst;
36 class Function;
37 class LandingPadInst;
38 class LLVMContext;
39 class Module;
40 class PHINode;
41 class ValueSymbolTable;
42 
43 /// LLVM Basic Block Representation
44 ///
45 /// This represents a single basic block in LLVM. A basic block is simply a
46 /// container of instructions that execute sequentially. Basic blocks are Values
47 /// because they are referenced by instructions such as branches and switch
48 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
49 /// represents a label to which a branch can jump.
50 ///
51 /// A well formed basic block is formed of a list of non-terminating
52 /// instructions followed by a single terminator instruction. Terminator
53 /// instructions may not occur in the middle of basic blocks, and must terminate
54 /// the blocks. The BasicBlock class allows malformed basic blocks to occur
55 /// because it may be useful in the intermediate stage of constructing or
56 /// modifying a program. However, the verifier will ensure that basic blocks are
57 /// "well formed".
58 class BasicBlock final : public Value, // Basic blocks are data objects also
59                          public ilist_node_with_parent<BasicBlock, Function> {
60 public:
61   using InstListType = SymbolTableList<Instruction>;
62 
63 private:
64   friend class BlockAddress;
65   friend class SymbolTableListTraits<BasicBlock>;
66 
67   InstListType InstList;
68   Function *Parent;
69 
70   void setParent(Function *parent);
71 
72   /// Constructor.
73   ///
74   /// If the function parameter is specified, the basic block is automatically
75   /// inserted at either the end of the function (if InsertBefore is null), or
76   /// before the specified basic block.
77   explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
78                       Function *Parent = nullptr,
79                       BasicBlock *InsertBefore = nullptr);
80 
81 public:
82   BasicBlock(const BasicBlock &) = delete;
83   BasicBlock &operator=(const BasicBlock &) = delete;
84   ~BasicBlock();
85 
86   /// Get the context in which this basic block lives.
87   LLVMContext &getContext() const;
88 
89   /// Instruction iterators...
90   using iterator = InstListType::iterator;
91   using const_iterator = InstListType::const_iterator;
92   using reverse_iterator = InstListType::reverse_iterator;
93   using const_reverse_iterator = InstListType::const_reverse_iterator;
94 
95   /// Creates a new BasicBlock.
96   ///
97   /// If the Parent parameter is specified, the basic block is automatically
98   /// inserted at either the end of the function (if InsertBefore is 0), or
99   /// before the specified basic block.
100   static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
101                             Function *Parent = nullptr,
102                             BasicBlock *InsertBefore = nullptr) {
103     return new BasicBlock(Context, Name, Parent, InsertBefore);
104   }
105 
106   /// Return the enclosing method, or null if none.
getParent()107   const Function *getParent() const { return Parent; }
getParent()108         Function *getParent()       { return Parent; }
109 
110   /// Return the module owning the function this basic block belongs to, or
111   /// nullptr if the function does not have a module.
112   ///
113   /// Note: this is undefined behavior if the block does not have a parent.
114   const Module *getModule() const;
getModule()115   Module *getModule() {
116     return const_cast<Module *>(
117                             static_cast<const BasicBlock *>(this)->getModule());
118   }
119 
120   /// Returns the terminator instruction if the block is well formed or null
121   /// if the block is not well formed.
122   const Instruction *getTerminator() const LLVM_READONLY;
getTerminator()123   Instruction *getTerminator() {
124     return const_cast<Instruction *>(
125         static_cast<const BasicBlock *>(this)->getTerminator());
126   }
127 
128   /// Returns the call instruction calling \@llvm.experimental.deoptimize
129   /// prior to the terminating return instruction of this basic block, if such
130   /// a call is present.  Otherwise, returns null.
131   const CallInst *getTerminatingDeoptimizeCall() const;
getTerminatingDeoptimizeCall()132   CallInst *getTerminatingDeoptimizeCall() {
133     return const_cast<CallInst *>(
134          static_cast<const BasicBlock *>(this)->getTerminatingDeoptimizeCall());
135   }
136 
137   /// Returns the call instruction marked 'musttail' prior to the terminating
138   /// return instruction of this basic block, if such a call is present.
139   /// Otherwise, returns null.
140   const CallInst *getTerminatingMustTailCall() const;
getTerminatingMustTailCall()141   CallInst *getTerminatingMustTailCall() {
142     return const_cast<CallInst *>(
143            static_cast<const BasicBlock *>(this)->getTerminatingMustTailCall());
144   }
145 
146   /// Returns a pointer to the first instruction in this block that is not a
147   /// PHINode instruction.
148   ///
149   /// When adding instructions to the beginning of the basic block, they should
150   /// be added before the returned value, not before the first instruction,
151   /// which might be PHI. Returns 0 is there's no non-PHI instruction.
152   const Instruction* getFirstNonPHI() const;
getFirstNonPHI()153   Instruction* getFirstNonPHI() {
154     return const_cast<Instruction *>(
155                        static_cast<const BasicBlock *>(this)->getFirstNonPHI());
156   }
157 
158   /// Returns a pointer to the first instruction in this block that is not a
159   /// PHINode or a debug intrinsic.
160   const Instruction* getFirstNonPHIOrDbg() const;
getFirstNonPHIOrDbg()161   Instruction* getFirstNonPHIOrDbg() {
162     return const_cast<Instruction *>(
163                   static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbg());
164   }
165 
166   /// Returns a pointer to the first instruction in this block that is not a
167   /// PHINode, a debug intrinsic, or a lifetime intrinsic.
168   const Instruction* getFirstNonPHIOrDbgOrLifetime() const;
getFirstNonPHIOrDbgOrLifetime()169   Instruction* getFirstNonPHIOrDbgOrLifetime() {
170     return const_cast<Instruction *>(
171         static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbgOrLifetime());
172   }
173 
174   /// Returns an iterator to the first instruction in this block that is
175   /// suitable for inserting a non-PHI instruction.
176   ///
177   /// In particular, it skips all PHIs and LandingPad instructions.
178   const_iterator getFirstInsertionPt() const;
getFirstInsertionPt()179   iterator getFirstInsertionPt() {
180     return static_cast<const BasicBlock *>(this)
181                                           ->getFirstInsertionPt().getNonConst();
182   }
183 
184   /// Return a const iterator range over the instructions in the block, skipping
185   /// any debug instructions.
186   iterator_range<filter_iterator<BasicBlock::const_iterator,
187                                  std::function<bool(const Instruction &)>>>
188   instructionsWithoutDebug() const;
189 
190   /// Return an iterator range over the instructions in the block, skipping any
191   /// debug instructions.
192   iterator_range<filter_iterator<BasicBlock::iterator,
193                                  std::function<bool(Instruction &)>>>
194   instructionsWithoutDebug();
195 
196   /// Unlink 'this' from the containing function, but do not delete it.
197   void removeFromParent();
198 
199   /// Unlink 'this' from the containing function and delete it.
200   ///
201   // \returns an iterator pointing to the element after the erased one.
202   SymbolTableList<BasicBlock>::iterator eraseFromParent();
203 
204   /// Unlink this basic block from its current function and insert it into
205   /// the function that \p MovePos lives in, right before \p MovePos.
206   void moveBefore(BasicBlock *MovePos);
207 
208   /// Unlink this basic block from its current function and insert it
209   /// right after \p MovePos in the function \p MovePos lives in.
210   void moveAfter(BasicBlock *MovePos);
211 
212   /// Insert unlinked basic block into a function.
213   ///
214   /// Inserts an unlinked basic block into \c Parent.  If \c InsertBefore is
215   /// provided, inserts before that basic block, otherwise inserts at the end.
216   ///
217   /// \pre \a getParent() is \c nullptr.
218   void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
219 
220   /// Return the predecessor of this block if it has a single predecessor
221   /// block. Otherwise return a null pointer.
222   const BasicBlock *getSinglePredecessor() const;
getSinglePredecessor()223   BasicBlock *getSinglePredecessor() {
224     return const_cast<BasicBlock *>(
225                  static_cast<const BasicBlock *>(this)->getSinglePredecessor());
226   }
227 
228   /// Return the predecessor of this block if it has a unique predecessor
229   /// block. Otherwise return a null pointer.
230   ///
231   /// Note that unique predecessor doesn't mean single edge, there can be
232   /// multiple edges from the unique predecessor to this block (for example a
233   /// switch statement with multiple cases having the same destination).
234   const BasicBlock *getUniquePredecessor() const;
getUniquePredecessor()235   BasicBlock *getUniquePredecessor() {
236     return const_cast<BasicBlock *>(
237                  static_cast<const BasicBlock *>(this)->getUniquePredecessor());
238   }
239 
240   /// Return true if this block has exactly N predecessors.
241   bool hasNPredecessors(unsigned N) const;
242 
243   /// Return true if this block has N predecessors or more.
244   bool hasNPredecessorsOrMore(unsigned N) const;
245 
246   /// Return the successor of this block if it has a single successor.
247   /// Otherwise return a null pointer.
248   ///
249   /// This method is analogous to getSinglePredecessor above.
250   const BasicBlock *getSingleSuccessor() const;
getSingleSuccessor()251   BasicBlock *getSingleSuccessor() {
252     return const_cast<BasicBlock *>(
253                    static_cast<const BasicBlock *>(this)->getSingleSuccessor());
254   }
255 
256   /// Return the successor of this block if it has a unique successor.
257   /// Otherwise return a null pointer.
258   ///
259   /// This method is analogous to getUniquePredecessor above.
260   const BasicBlock *getUniqueSuccessor() const;
getUniqueSuccessor()261   BasicBlock *getUniqueSuccessor() {
262     return const_cast<BasicBlock *>(
263                    static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
264   }
265 
266   //===--------------------------------------------------------------------===//
267   /// Instruction iterator methods
268   ///
begin()269   inline iterator                begin()       { return InstList.begin(); }
begin()270   inline const_iterator          begin() const { return InstList.begin(); }
end()271   inline iterator                end  ()       { return InstList.end();   }
end()272   inline const_iterator          end  () const { return InstList.end();   }
273 
rbegin()274   inline reverse_iterator        rbegin()       { return InstList.rbegin(); }
rbegin()275   inline const_reverse_iterator  rbegin() const { return InstList.rbegin(); }
rend()276   inline reverse_iterator        rend  ()       { return InstList.rend();   }
rend()277   inline const_reverse_iterator  rend  () const { return InstList.rend();   }
278 
size()279   inline size_t                   size() const { return InstList.size();  }
empty()280   inline bool                    empty() const { return InstList.empty(); }
front()281   inline const Instruction      &front() const { return InstList.front(); }
front()282   inline       Instruction      &front()       { return InstList.front(); }
back()283   inline const Instruction       &back() const { return InstList.back();  }
back()284   inline       Instruction       &back()       { return InstList.back();  }
285 
286   /// Iterator to walk just the phi nodes in the basic block.
287   template <typename PHINodeT = PHINode, typename BBIteratorT = iterator>
288   class phi_iterator_impl
289       : public iterator_facade_base<phi_iterator_impl<PHINodeT, BBIteratorT>,
290                                     std::forward_iterator_tag, PHINodeT> {
291     friend BasicBlock;
292 
293     PHINodeT *PN;
294 
phi_iterator_impl(PHINodeT * PN)295     phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
296 
297   public:
298     // Allow default construction to build variables, but this doesn't build
299     // a useful iterator.
300     phi_iterator_impl() = default;
301 
302     // Allow conversion between instantiations where valid.
303     template <typename PHINodeU, typename BBIteratorU>
phi_iterator_impl(const phi_iterator_impl<PHINodeU,BBIteratorU> & Arg)304     phi_iterator_impl(const phi_iterator_impl<PHINodeU, BBIteratorU> &Arg)
305         : PN(Arg.PN) {}
306 
307     bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
308 
309     PHINodeT &operator*() const { return *PN; }
310 
311     using phi_iterator_impl::iterator_facade_base::operator++;
312     phi_iterator_impl &operator++() {
313       assert(PN && "Cannot increment the end iterator!");
314       PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
315       return *this;
316     }
317   };
318   using phi_iterator = phi_iterator_impl<>;
319   using const_phi_iterator =
320       phi_iterator_impl<const PHINode, BasicBlock::const_iterator>;
321 
322   /// Returns a range that iterates over the phis in the basic block.
323   ///
324   /// Note that this cannot be used with basic blocks that have no terminator.
phis()325   iterator_range<const_phi_iterator> phis() const {
326     return const_cast<BasicBlock *>(this)->phis();
327   }
328   iterator_range<phi_iterator> phis();
329 
330   /// Return the underlying instruction list container.
331   ///
332   /// Currently you need to access the underlying instruction list container
333   /// directly if you want to modify it.
getInstList()334   const InstListType &getInstList() const { return InstList; }
getInstList()335         InstListType &getInstList()       { return InstList; }
336 
337   /// Returns a pointer to a member of the instruction list.
getSublistAccess(Instruction *)338   static InstListType BasicBlock::*getSublistAccess(Instruction*) {
339     return &BasicBlock::InstList;
340   }
341 
342   /// Returns a pointer to the symbol table if one exists.
343   ValueSymbolTable *getValueSymbolTable();
344 
345   /// Methods for support type inquiry through isa, cast, and dyn_cast.
classof(const Value * V)346   static bool classof(const Value *V) {
347     return V->getValueID() == Value::BasicBlockVal;
348   }
349 
350   /// Cause all subinstructions to "let go" of all the references that said
351   /// subinstructions are maintaining.
352   ///
353   /// This allows one to 'delete' a whole class at a time, even though there may
354   /// be circular references... first all references are dropped, and all use
355   /// counts go to zero.  Then everything is delete'd for real.  Note that no
356   /// operations are valid on an object that has "dropped all references",
357   /// except operator delete.
358   void dropAllReferences();
359 
360   /// Notify the BasicBlock that the predecessor \p Pred is no longer able to
361   /// reach it.
362   ///
363   /// This is actually not used to update the Predecessor list, but is actually
364   /// used to update the PHI nodes that reside in the block.  Note that this
365   /// should be called while the predecessor still refers to this block.
366   void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
367 
368   bool canSplitPredecessors() const;
369 
370   /// Split the basic block into two basic blocks at the specified instruction.
371   ///
372   /// Note that all instructions BEFORE the specified iterator stay as part of
373   /// the original basic block, an unconditional branch is added to the original
374   /// BB, and the rest of the instructions in the BB are moved to the new BB,
375   /// including the old terminator.  The newly formed BasicBlock is returned.
376   /// This function invalidates the specified iterator.
377   ///
378   /// Note that this only works on well formed basic blocks (must have a
379   /// terminator), and 'I' must not be the end of instruction list (which would
380   /// cause a degenerate basic block to be formed, having a terminator inside of
381   /// the basic block).
382   ///
383   /// Also note that this doesn't preserve any passes. To split blocks while
384   /// keeping loop information consistent, use the SplitBlock utility function.
385   BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
386   BasicBlock *splitBasicBlock(Instruction *I, const Twine &BBName = "") {
387     return splitBasicBlock(I->getIterator(), BBName);
388   }
389 
390   /// Returns true if there are any uses of this basic block other than
391   /// direct branches, switches, etc. to it.
hasAddressTaken()392   bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
393 
394   /// Update all phi nodes in this basic block's successors to refer to basic
395   /// block \p New instead of to it.
396   void replaceSuccessorsPhiUsesWith(BasicBlock *New);
397 
398   /// Return true if this basic block is an exception handling block.
isEHPad()399   bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
400 
401   /// Return true if this basic block is a landing pad.
402   ///
403   /// Being a ``landing pad'' means that the basic block is the destination of
404   /// the 'unwind' edge of an invoke instruction.
405   bool isLandingPad() const;
406 
407   /// Return the landingpad instruction associated with the landing pad.
408   const LandingPadInst *getLandingPadInst() const;
getLandingPadInst()409   LandingPadInst *getLandingPadInst() {
410     return const_cast<LandingPadInst *>(
411                     static_cast<const BasicBlock *>(this)->getLandingPadInst());
412   }
413 
414   /// Return true if it is legal to hoist instructions into this block.
415   bool isLegalToHoistInto() const;
416 
417   Optional<uint64_t> getIrrLoopHeaderWeight() const;
418 
419 private:
420   /// Increment the internal refcount of the number of BlockAddresses
421   /// referencing this BasicBlock by \p Amt.
422   ///
423   /// This is almost always 0, sometimes one possibly, but almost never 2, and
424   /// inconceivably 3 or more.
AdjustBlockAddressRefCount(int Amt)425   void AdjustBlockAddressRefCount(int Amt) {
426     setValueSubclassData(getSubclassDataFromValue()+Amt);
427     assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
428            "Refcount wrap-around");
429   }
430 
431   /// Shadow Value::setValueSubclassData with a private forwarding method so
432   /// that any future subclasses cannot accidentally use it.
setValueSubclassData(unsigned short D)433   void setValueSubclassData(unsigned short D) {
434     Value::setValueSubclassData(D);
435   }
436 };
437 
438 // Create wrappers for C Binding types (see CBindingWrapping.h).
439 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
440 
441 /// Advance \p It while it points to a debug instruction and return the result.
442 /// This assumes that \p It is not at the end of a block.
443 BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It);
444 
445 } // end namespace llvm
446 
447 #endif // LLVM_IR_BASICBLOCK_H
448