1 //===- llvm/BasicBlock.h - Represent a basic block in the VM ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the declaration of the BasicBlock class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_IR_BASICBLOCK_H
15 #define LLVM_IR_BASICBLOCK_H
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"
41 class ValueSymbolTable;
43 /// LLVM Basic Block Representation
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.
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
58 class BasicBlock final : public Value, // Basic blocks are data objects also
59 public ilist_node_with_parent<BasicBlock, Function> {
61 using InstListType = SymbolTableList<Instruction>;
64 friend class BlockAddress;
65 friend class SymbolTableListTraits<BasicBlock>;
67 InstListType InstList;
70 void setParent(Function *parent);
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);
82 BasicBlock(const BasicBlock &) = delete;
83 BasicBlock &operator=(const BasicBlock &) = delete;
86 /// Get the context in which this basic block lives.
87 LLVMContext &getContext() const;
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;
95 /// Creates a new BasicBlock.
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);
106 /// Return the enclosing method, or null if none.
107 const Function *getParent() const { return Parent; }
108 Function *getParent() { return Parent; }
110 /// Return the module owning the function this basic block belongs to, or
111 /// nullptr if the function does not have a module.
113 /// Note: this is undefined behavior if the block does not have a parent.
114 const Module *getModule() const;
115 Module *getModule() {
116 return const_cast<Module *>(
117 static_cast<const BasicBlock *>(this)->getModule());
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;
123 Instruction *getTerminator() {
124 return const_cast<Instruction *>(
125 static_cast<const BasicBlock *>(this)->getTerminator());
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;
132 CallInst *getTerminatingDeoptimizeCall() {
133 return const_cast<CallInst *>(
134 static_cast<const BasicBlock *>(this)->getTerminatingDeoptimizeCall());
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;
141 CallInst *getTerminatingMustTailCall() {
142 return const_cast<CallInst *>(
143 static_cast<const BasicBlock *>(this)->getTerminatingMustTailCall());
146 /// Returns a pointer to the first instruction in this block that is not a
147 /// PHINode instruction.
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;
153 Instruction* getFirstNonPHI() {
154 return const_cast<Instruction *>(
155 static_cast<const BasicBlock *>(this)->getFirstNonPHI());
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;
161 Instruction* getFirstNonPHIOrDbg() {
162 return const_cast<Instruction *>(
163 static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbg());
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;
169 Instruction* getFirstNonPHIOrDbgOrLifetime() {
170 return const_cast<Instruction *>(
171 static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbgOrLifetime());
174 /// Returns an iterator to the first instruction in this block that is
175 /// suitable for inserting a non-PHI instruction.
177 /// In particular, it skips all PHIs and LandingPad instructions.
178 const_iterator getFirstInsertionPt() const;
179 iterator getFirstInsertionPt() {
180 return static_cast<const BasicBlock *>(this)
181 ->getFirstInsertionPt().getNonConst();
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;
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();
196 /// Unlink 'this' from the containing function, but do not delete it.
197 void removeFromParent();
199 /// Unlink 'this' from the containing function and delete it.
201 // \returns an iterator pointing to the element after the erased one.
202 SymbolTableList<BasicBlock>::iterator eraseFromParent();
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);
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);
212 /// Insert unlinked basic block into a function.
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.
217 /// \pre \a getParent() is \c nullptr.
218 void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
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;
223 BasicBlock *getSinglePredecessor() {
224 return const_cast<BasicBlock *>(
225 static_cast<const BasicBlock *>(this)->getSinglePredecessor());
228 /// Return the predecessor of this block if it has a unique predecessor
229 /// block. Otherwise return a null pointer.
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;
235 BasicBlock *getUniquePredecessor() {
236 return const_cast<BasicBlock *>(
237 static_cast<const BasicBlock *>(this)->getUniquePredecessor());
240 /// Return true if this block has exactly N predecessors.
241 bool hasNPredecessors(unsigned N) const;
243 /// Return true if this block has N predecessors or more.
244 bool hasNPredecessorsOrMore(unsigned N) const;
246 /// Return the successor of this block if it has a single successor.
247 /// Otherwise return a null pointer.
249 /// This method is analogous to getSinglePredecessor above.
250 const BasicBlock *getSingleSuccessor() const;
251 BasicBlock *getSingleSuccessor() {
252 return const_cast<BasicBlock *>(
253 static_cast<const BasicBlock *>(this)->getSingleSuccessor());
256 /// Return the successor of this block if it has a unique successor.
257 /// Otherwise return a null pointer.
259 /// This method is analogous to getUniquePredecessor above.
260 const BasicBlock *getUniqueSuccessor() const;
261 BasicBlock *getUniqueSuccessor() {
262 return const_cast<BasicBlock *>(
263 static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
266 //===--------------------------------------------------------------------===//
267 /// Instruction iterator methods
269 inline iterator begin() { return InstList.begin(); }
270 inline const_iterator begin() const { return InstList.begin(); }
271 inline iterator end () { return InstList.end(); }
272 inline const_iterator end () const { return InstList.end(); }
274 inline reverse_iterator rbegin() { return InstList.rbegin(); }
275 inline const_reverse_iterator rbegin() const { return InstList.rbegin(); }
276 inline reverse_iterator rend () { return InstList.rend(); }
277 inline const_reverse_iterator rend () const { return InstList.rend(); }
279 inline size_t size() const { return InstList.size(); }
280 inline bool empty() const { return InstList.empty(); }
281 inline const Instruction &front() const { return InstList.front(); }
282 inline Instruction &front() { return InstList.front(); }
283 inline const Instruction &back() const { return InstList.back(); }
284 inline Instruction &back() { return InstList.back(); }
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> {
295 phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
298 // Allow default construction to build variables, but this doesn't build
299 // a useful iterator.
300 phi_iterator_impl() = default;
302 // Allow conversion between instantiations where valid.
303 template <typename PHINodeU, typename BBIteratorU>
304 phi_iterator_impl(const phi_iterator_impl<PHINodeU, BBIteratorU> &Arg)
307 bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
309 PHINodeT &operator*() const { return *PN; }
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)));
318 using phi_iterator = phi_iterator_impl<>;
319 using const_phi_iterator =
320 phi_iterator_impl<const PHINode, BasicBlock::const_iterator>;
322 /// Returns a range that iterates over the phis in the basic block.
324 /// Note that this cannot be used with basic blocks that have no terminator.
325 iterator_range<const_phi_iterator> phis() const {
326 return const_cast<BasicBlock *>(this)->phis();
328 iterator_range<phi_iterator> phis();
330 /// Return the underlying instruction list container.
332 /// Currently you need to access the underlying instruction list container
333 /// directly if you want to modify it.
334 const InstListType &getInstList() const { return InstList; }
335 InstListType &getInstList() { return InstList; }
337 /// Returns a pointer to a member of the instruction list.
338 static InstListType BasicBlock::*getSublistAccess(Instruction*) {
339 return &BasicBlock::InstList;
342 /// Returns a pointer to the symbol table if one exists.
343 ValueSymbolTable *getValueSymbolTable();
345 /// Methods for support type inquiry through isa, cast, and dyn_cast.
346 static bool classof(const Value *V) {
347 return V->getValueID() == Value::BasicBlockVal;
350 /// Cause all subinstructions to "let go" of all the references that said
351 /// subinstructions are maintaining.
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();
360 /// Notify the BasicBlock that the predecessor \p Pred is no longer able to
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);
368 bool canSplitPredecessors() const;
370 /// Split the basic block into two basic blocks at the specified instruction.
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.
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).
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);
390 /// Returns true if there are any uses of this basic block other than
391 /// direct branches, switches, etc. to it.
392 bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
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);
398 /// Return true if this basic block is an exception handling block.
399 bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
401 /// Return true if this basic block is a landing pad.
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;
407 /// Return the landingpad instruction associated with the landing pad.
408 const LandingPadInst *getLandingPadInst() const;
409 LandingPadInst *getLandingPadInst() {
410 return const_cast<LandingPadInst *>(
411 static_cast<const BasicBlock *>(this)->getLandingPadInst());
414 /// Return true if it is legal to hoist instructions into this block.
415 bool isLegalToHoistInto() const;
417 Optional<uint64_t> getIrrLoopHeaderWeight() const;
420 /// Increment the internal refcount of the number of BlockAddresses
421 /// referencing this BasicBlock by \p Amt.
423 /// This is almost always 0, sometimes one possibly, but almost never 2, and
424 /// inconceivably 3 or more.
425 void AdjustBlockAddressRefCount(int Amt) {
426 setValueSubclassData(getSubclassDataFromValue()+Amt);
427 assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
428 "Refcount wrap-around");
431 /// Shadow Value::setValueSubclassData with a private forwarding method so
432 /// that any future subclasses cannot accidentally use it.
433 void setValueSubclassData(unsigned short D) {
434 Value::setValueSubclassData(D);
438 // Create wrappers for C Binding types (see CBindingWrapping.h).
439 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
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);
445 } // end namespace llvm
447 #endif // LLVM_IR_BASICBLOCK_H