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