Line data Source code
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 8071317 : return new BasicBlock(Context, Name, Parent, InsertBefore);
104 : }
105 :
106 : /// Return the enclosing method, or null if none.
107 0 : const Function *getParent() const { return Parent; }
108 0 : 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;
115 : Module *getModule() {
116 : return const_cast<Module *>(
117 16895971 : 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;
123 : Instruction *getTerminator() {
124 : return const_cast<Instruction *>(
125 133004471 : 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;
132 : CallInst *getTerminatingDeoptimizeCall() {
133 : return const_cast<CallInst *>(
134 1445 : 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;
141 : CallInst *getTerminatingMustTailCall() {
142 : return const_cast<CallInst *>(
143 135044 : 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;
153 : Instruction* getFirstNonPHI() {
154 : return const_cast<Instruction *>(
155 393071 : 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;
161 : Instruction* getFirstNonPHIOrDbg() {
162 : return const_cast<Instruction *>(
163 1279299 : 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;
169 : Instruction* getFirstNonPHIOrDbgOrLifetime() {
170 : return const_cast<Instruction *>(
171 109 : 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;
179 : iterator getFirstInsertionPt() {
180 : return static_cast<const BasicBlock *>(this)
181 287725 : ->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;
223 : BasicBlock *getSinglePredecessor() {
224 : return const_cast<BasicBlock *>(
225 11933968 : 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;
235 : BasicBlock *getUniquePredecessor() {
236 : return const_cast<BasicBlock *>(
237 3189316 : static_cast<const BasicBlock *>(this)->getUniquePredecessor());
238 : }
239 :
240 : /// Return the successor of this block if it has a single successor.
241 : /// Otherwise return a null pointer.
242 : ///
243 : /// This method is analogous to getSinglePredecessor above.
244 : const BasicBlock *getSingleSuccessor() const;
245 : BasicBlock *getSingleSuccessor() {
246 : return const_cast<BasicBlock *>(
247 476869 : static_cast<const BasicBlock *>(this)->getSingleSuccessor());
248 : }
249 :
250 : /// Return the successor of this block if it has a unique successor.
251 : /// Otherwise return a null pointer.
252 : ///
253 : /// This method is analogous to getUniquePredecessor above.
254 : const BasicBlock *getUniqueSuccessor() const;
255 : BasicBlock *getUniqueSuccessor() {
256 : return const_cast<BasicBlock *>(
257 887184 : static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
258 : }
259 :
260 : //===--------------------------------------------------------------------===//
261 : /// Instruction iterator methods
262 : ///
263 : inline iterator begin() { return InstList.begin(); }
264 : inline const_iterator begin() const { return InstList.begin(); }
265 : inline iterator end () { return InstList.end(); }
266 : inline const_iterator end () const { return InstList.end(); }
267 :
268 : inline reverse_iterator rbegin() { return InstList.rbegin(); }
269 : inline const_reverse_iterator rbegin() const { return InstList.rbegin(); }
270 : inline reverse_iterator rend () { return InstList.rend(); }
271 : inline const_reverse_iterator rend () const { return InstList.rend(); }
272 :
273 : inline size_t size() const { return InstList.size(); }
274 : inline bool empty() const { return InstList.empty(); }
275 : inline const Instruction &front() const { return InstList.front(); }
276 : inline Instruction &front() { return InstList.front(); }
277 : inline const Instruction &back() const { return InstList.back(); }
278 : inline Instruction &back() { return InstList.back(); }
279 :
280 : /// Iterator to walk just the phi nodes in the basic block.
281 : template <typename PHINodeT = PHINode, typename BBIteratorT = iterator>
282 : class phi_iterator_impl
283 : : public iterator_facade_base<phi_iterator_impl<PHINodeT, BBIteratorT>,
284 : std::forward_iterator_tag, PHINodeT> {
285 : friend BasicBlock;
286 :
287 : PHINodeT *PN;
288 :
289 : phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
290 :
291 : public:
292 : // Allow default construction to build variables, but this doesn't build
293 : // a useful iterator.
294 : phi_iterator_impl() = default;
295 :
296 : // Allow conversion between instantiations where valid.
297 : template <typename PHINodeU, typename BBIteratorU>
298 : phi_iterator_impl(const phi_iterator_impl<PHINodeU, BBIteratorU> &Arg)
299 1 : : PN(Arg.PN) {}
300 :
301 186 : bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
302 :
303 0 : PHINodeT &operator*() const { return *PN; }
304 :
305 : using phi_iterator_impl::iterator_facade_base::operator++;
306 : phi_iterator_impl &operator++() {
307 : assert(PN && "Cannot increment the end iterator!");
308 0 : PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
309 : return *this;
310 : }
311 : };
312 : using phi_iterator = phi_iterator_impl<>;
313 : using const_phi_iterator =
314 : phi_iterator_impl<const PHINode, BasicBlock::const_iterator>;
315 :
316 : /// Returns a range that iterates over the phis in the basic block.
317 : ///
318 : /// Note that this cannot be used with basic blocks that have no terminator.
319 : iterator_range<const_phi_iterator> phis() const {
320 6895039 : return const_cast<BasicBlock *>(this)->phis();
321 : }
322 : iterator_range<phi_iterator> phis();
323 :
324 : /// Return the underlying instruction list container.
325 : ///
326 : /// Currently you need to access the underlying instruction list container
327 : /// directly if you want to modify it.
328 : const InstListType &getInstList() const { return InstList; }
329 4104 : InstListType &getInstList() { return InstList; }
330 :
331 : /// Returns a pointer to a member of the instruction list.
332 0 : static InstListType BasicBlock::*getSublistAccess(Instruction*) {
333 0 : return &BasicBlock::InstList;
334 : }
335 :
336 : /// Returns a pointer to the symbol table if one exists.
337 : ValueSymbolTable *getValueSymbolTable();
338 :
339 : /// Methods for support type inquiry through isa, cast, and dyn_cast.
340 : static bool classof(const Value *V) {
341 : return V->getValueID() == Value::BasicBlockVal;
342 : }
343 :
344 : /// Cause all subinstructions to "let go" of all the references that said
345 : /// subinstructions are maintaining.
346 : ///
347 : /// This allows one to 'delete' a whole class at a time, even though there may
348 : /// be circular references... first all references are dropped, and all use
349 : /// counts go to zero. Then everything is delete'd for real. Note that no
350 : /// operations are valid on an object that has "dropped all references",
351 : /// except operator delete.
352 : void dropAllReferences();
353 :
354 : /// Notify the BasicBlock that the predecessor \p Pred is no longer able to
355 : /// reach it.
356 : ///
357 : /// This is actually not used to update the Predecessor list, but is actually
358 : /// used to update the PHI nodes that reside in the block. Note that this
359 : /// should be called while the predecessor still refers to this block.
360 : void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs = false);
361 :
362 : bool canSplitPredecessors() const;
363 :
364 : /// Split the basic block into two basic blocks at the specified instruction.
365 : ///
366 : /// Note that all instructions BEFORE the specified iterator stay as part of
367 : /// the original basic block, an unconditional branch is added to the original
368 : /// BB, and the rest of the instructions in the BB are moved to the new BB,
369 : /// including the old terminator. The newly formed BasicBlock is returned.
370 : /// This function invalidates the specified iterator.
371 : ///
372 : /// Note that this only works on well formed basic blocks (must have a
373 : /// terminator), and 'I' must not be the end of instruction list (which would
374 : /// cause a degenerate basic block to be formed, having a terminator inside of
375 : /// the basic block).
376 : ///
377 : /// Also note that this doesn't preserve any passes. To split blocks while
378 : /// keeping loop information consistent, use the SplitBlock utility function.
379 : BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
380 : BasicBlock *splitBasicBlock(Instruction *I, const Twine &BBName = "") {
381 4077 : return splitBasicBlock(I->getIterator(), BBName);
382 : }
383 :
384 : /// Returns true if there are any uses of this basic block other than
385 : /// direct branches, switches, etc. to it.
386 22212495 : bool hasAddressTaken() const { return getSubclassDataFromValue() != 0; }
387 :
388 : /// Update all phi nodes in this basic block's successors to refer to basic
389 : /// block \p New instead of to it.
390 : void replaceSuccessorsPhiUsesWith(BasicBlock *New);
391 :
392 : /// Return true if this basic block is an exception handling block.
393 9973174 : bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
394 :
395 : /// Return true if this basic block is a landing pad.
396 : ///
397 : /// Being a ``landing pad'' means that the basic block is the destination of
398 : /// the 'unwind' edge of an invoke instruction.
399 : bool isLandingPad() const;
400 :
401 : /// Return the landingpad instruction associated with the landing pad.
402 : const LandingPadInst *getLandingPadInst() const;
403 : LandingPadInst *getLandingPadInst() {
404 : return const_cast<LandingPadInst *>(
405 3189544 : static_cast<const BasicBlock *>(this)->getLandingPadInst());
406 : }
407 :
408 : /// Return true if it is legal to hoist instructions into this block.
409 : bool isLegalToHoistInto() const;
410 :
411 : Optional<uint64_t> getIrrLoopHeaderWeight() const;
412 :
413 : private:
414 : /// Increment the internal refcount of the number of BlockAddresses
415 : /// referencing this BasicBlock by \p Amt.
416 : ///
417 : /// This is almost always 0, sometimes one possibly, but almost never 2, and
418 : /// inconceivably 3 or more.
419 : void AdjustBlockAddressRefCount(int Amt) {
420 18 : setValueSubclassData(getSubclassDataFromValue()+Amt);
421 : assert((int)(signed char)getSubclassDataFromValue() >= 0 &&
422 : "Refcount wrap-around");
423 : }
424 :
425 : /// Shadow Value::setValueSubclassData with a private forwarding method so
426 : /// that any future subclasses cannot accidentally use it.
427 : void setValueSubclassData(unsigned short D) {
428 : Value::setValueSubclassData(D);
429 : }
430 : };
431 :
432 : // Create wrappers for C Binding types (see CBindingWrapping.h).
433 : DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
434 :
435 : /// Advance \p It while it points to a debug instruction and return the result.
436 : /// This assumes that \p It is not at the end of a block.
437 : BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It);
438 :
439 : } // end namespace llvm
440 :
441 : #endif // LLVM_IR_BASICBLOCK_H
|