LLVM 19.0.0git
BasicBlock.h
Go to the documentation of this file.
1//===- llvm/BasicBlock.h - Represent a basic block in the VM ----*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains the declaration of the BasicBlock class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_IR_BASICBLOCK_H
14#define LLVM_IR_BASICBLOCK_H
15
16#include "llvm-c/Types.h"
17#include "llvm/ADT/Twine.h"
18#include "llvm/ADT/ilist.h"
19#include "llvm/ADT/ilist_node.h"
20#include "llvm/ADT/iterator.h"
23#include "llvm/IR/Instruction.h"
26#include "llvm/IR/Value.h"
27#include <cassert>
28#include <cstddef>
29#include <iterator>
30
31namespace llvm {
32
33class AssemblyAnnotationWriter;
34class CallInst;
35class Function;
36class LandingPadInst;
37class LLVMContext;
38class Module;
39class PHINode;
40class ValueSymbolTable;
41class DPValue;
42class DPMarker;
43
44/// LLVM Basic Block Representation
45///
46/// This represents a single basic block in LLVM. A basic block is simply a
47/// container of instructions that execute sequentially. Basic blocks are Values
48/// because they are referenced by instructions such as branches and switch
49/// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
50/// represents a label to which a branch can jump.
51///
52/// A well formed basic block is formed of a list of non-terminating
53/// instructions followed by a single terminator instruction. Terminator
54/// instructions may not occur in the middle of basic blocks, and must terminate
55/// the blocks. The BasicBlock class allows malformed basic blocks to occur
56/// because it may be useful in the intermediate stage of constructing or
57/// modifying a program. However, the verifier will ensure that basic blocks are
58/// "well formed".
59class BasicBlock final : public Value, // Basic blocks are data objects also
60 public ilist_node_with_parent<BasicBlock, Function> {
61public:
63 /// Flag recording whether or not this block stores debug-info in the form
64 /// of intrinsic instructions (false) or non-instruction records (true).
66
67private:
68 friend class BlockAddress;
70
71 InstListType InstList;
72 Function *Parent;
73
74public:
75 /// Attach a DPMarker to the given instruction. Enables the storage of any
76 /// debug-info at this position in the program.
79
80 /// Convert variable location debugging information stored in dbg.value
81 /// intrinsics into DPMarker / DPValue records. Deletes all dbg.values in
82 /// the process and sets IsNewDbgInfoFormat = true. Only takes effect if
83 /// the UseNewDbgInfoFormat LLVM command line option is given.
85
86 /// Convert variable location debugging information stored in DPMarkers and
87 /// DPValues into the dbg.value intrinsic representation. Sets
88 /// IsNewDbgInfoFormat = false.
90
91 /// Ensure the block is in "old" dbg.value format (\p NewFlag == false) or
92 /// in the new format (\p NewFlag == true), converting to the desired format
93 /// if necessary.
94 void setIsNewDbgInfoFormat(bool NewFlag);
95
96 /// Record that the collection of DPValues in \p M "trails" after the last
97 /// instruction of this block. These are equivalent to dbg.value intrinsics
98 /// that exist at the end of a basic block with no terminator (a transient
99 /// state that occurs regularly).
101
102 /// Fetch the collection of DPValues that "trail" after the last instruction
103 /// of this block, see \ref setTrailingDPValues. If there are none, returns
104 /// nullptr.
106
107 /// Delete any trailing DPValues at the end of this block, see
108 /// \ref setTrailingDPValues.
110
111 void dumpDbgValues() const;
112
113 /// Return the DPMarker for the position given by \p It, so that DPValues can
114 /// be inserted there. This will either be nullptr if not present, a DPMarker,
115 /// or TrailingDPValues if It is end().
117
118 /// Return the DPMarker for the position that comes after \p I. \see
119 /// BasicBlock::getMarker, this can be nullptr, a DPMarker, or
120 /// TrailingDPValues if there is no next instruction.
122
123 /// Insert a DPValue into a block at the position given by \p I.
125
126 /// Insert a DPValue into a block at the position given by \p Here.
128
129 /// Eject any debug-info trailing at the end of a block. DPValues can
130 /// transiently be located "off the end" of a block if the blocks terminator
131 /// is temporarily removed. Once a terminator is re-inserted this method will
132 /// move such DPValues back to the right place (ahead of the terminator).
134
135 /// In rare circumstances instructions can be speculatively removed from
136 /// blocks, and then be re-inserted back into that position later. When this
137 /// happens in RemoveDIs debug-info mode, some special patching-up needs to
138 /// occur: inserting into the middle of a sequence of dbg.value intrinsics
139 /// does not have an equivalent with DPValues.
141 std::optional<DbgRecord::self_iterator> Pos);
142
143private:
144 void setParent(Function *parent);
145
146 /// Constructor.
147 ///
148 /// If the function parameter is specified, the basic block is automatically
149 /// inserted at either the end of the function (if InsertBefore is null), or
150 /// before the specified basic block.
151 explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
152 Function *Parent = nullptr,
153 BasicBlock *InsertBefore = nullptr);
154
155public:
156 BasicBlock(const BasicBlock &) = delete;
157 BasicBlock &operator=(const BasicBlock &) = delete;
158 ~BasicBlock();
159
160 /// Get the context in which this basic block lives.
161 LLVMContext &getContext() const;
162
163 /// Instruction iterators...
168
169 // These functions and classes need access to the instruction list.
175 ilist_iterator_bits<true>>;
176 friend class llvm::ilist_node_with_parent<llvm::Instruction, llvm::BasicBlock,
177 ilist_iterator_bits<true>>;
178
179 // Friendly methods that need to access us for the maintenence of
180 // debug-info attachments.
181 friend void Instruction::insertBefore(BasicBlock::iterator InsertPos);
182 friend void Instruction::insertAfter(Instruction *InsertPos);
183 friend void Instruction::insertBefore(BasicBlock &BB,
184 InstListType::iterator InsertPos);
185 friend void Instruction::moveBeforeImpl(BasicBlock &BB,
186 InstListType::iterator I,
187 bool Preserve);
188 friend iterator_range<DbgRecord::self_iterator>
190 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
191 bool InsertAtHead);
192
193 /// Creates a new BasicBlock.
194 ///
195 /// If the Parent parameter is specified, the basic block is automatically
196 /// inserted at either the end of the function (if InsertBefore is 0), or
197 /// before the specified basic block.
198 static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
199 Function *Parent = nullptr,
200 BasicBlock *InsertBefore = nullptr) {
201 return new BasicBlock(Context, Name, Parent, InsertBefore);
202 }
203
204 /// Return the enclosing method, or null if none.
205 const Function *getParent() const { return Parent; }
206 Function *getParent() { return Parent; }
207
208 /// Return the module owning the function this basic block belongs to, or
209 /// nullptr if the function does not have a module.
210 ///
211 /// Note: this is undefined behavior if the block does not have a parent.
212 const Module *getModule() const;
214 return const_cast<Module *>(
215 static_cast<const BasicBlock *>(this)->getModule());
216 }
217
218 /// Returns the terminator instruction if the block is well formed or null
219 /// if the block is not well formed.
221 if (InstList.empty() || !InstList.back().isTerminator())
222 return nullptr;
223 return &InstList.back();
224 }
226 return const_cast<Instruction *>(
227 static_cast<const BasicBlock *>(this)->getTerminator());
228 }
229
230 /// Returns the call instruction calling \@llvm.experimental.deoptimize
231 /// prior to the terminating return instruction of this basic block, if such
232 /// a call is present. Otherwise, returns null.
235 return const_cast<CallInst *>(
236 static_cast<const BasicBlock *>(this)->getTerminatingDeoptimizeCall());
237 }
238
239 /// Returns the call instruction calling \@llvm.experimental.deoptimize
240 /// that is present either in current basic block or in block that is a unique
241 /// successor to current block, if such call is present. Otherwise, returns null.
244 return const_cast<CallInst *>(
245 static_cast<const BasicBlock *>(this)->getPostdominatingDeoptimizeCall());
246 }
247
248 /// Returns the call instruction marked 'musttail' prior to the terminating
249 /// return instruction of this basic block, if such a call is present.
250 /// Otherwise, returns null.
253 return const_cast<CallInst *>(
254 static_cast<const BasicBlock *>(this)->getTerminatingMustTailCall());
255 }
256
257 /// Returns a pointer to the first instruction in this block that is not a
258 /// PHINode instruction.
259 ///
260 /// When adding instructions to the beginning of the basic block, they should
261 /// be added before the returned value, not before the first instruction,
262 /// which might be PHI. Returns 0 is there's no non-PHI instruction.
263 const Instruction* getFirstNonPHI() const;
265 return const_cast<Instruction *>(
266 static_cast<const BasicBlock *>(this)->getFirstNonPHI());
267 }
268
269 /// Iterator returning form of getFirstNonPHI. Installed as a placeholder for
270 /// the RemoveDIs project that will eventually remove debug intrinsics.
274 static_cast<const BasicBlock *>(this)->getFirstNonPHIIt().getNonConst();
275 It.setHeadBit(true);
276 return It;
277 }
278
279 /// Returns a pointer to the first instruction in this block that is not a
280 /// PHINode or a debug intrinsic, or any pseudo operation if \c SkipPseudoOp
281 /// is true.
282 const Instruction *getFirstNonPHIOrDbg(bool SkipPseudoOp = true) const;
283 Instruction *getFirstNonPHIOrDbg(bool SkipPseudoOp = true) {
284 return const_cast<Instruction *>(
285 static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbg(
286 SkipPseudoOp));
287 }
288
289 /// Returns a pointer to the first instruction in this block that is not a
290 /// PHINode, a debug intrinsic, or a lifetime intrinsic, or any pseudo
291 /// operation if \c SkipPseudoOp is true.
292 const Instruction *
293 getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp = true) const;
294 Instruction *getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp = true) {
295 return const_cast<Instruction *>(
296 static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbgOrLifetime(
297 SkipPseudoOp));
298 }
299
300 /// Returns an iterator to the first instruction in this block that is
301 /// suitable for inserting a non-PHI instruction.
302 ///
303 /// In particular, it skips all PHIs and LandingPad instructions.
306 return static_cast<const BasicBlock *>(this)
307 ->getFirstInsertionPt().getNonConst();
308 }
309
310 /// Returns an iterator to the first instruction in this block that is
311 /// not a PHINode, a debug intrinsic, a static alloca or any pseudo operation.
314 return static_cast<const BasicBlock *>(this)
316 .getNonConst();
317 }
318
319 /// Returns the first potential AsynchEH faulty instruction
320 /// currently it checks for loads/stores (which may dereference a null
321 /// pointer) and calls/invokes (which may propagate exceptions)
322 const Instruction* getFirstMayFaultInst() const;
324 return const_cast<Instruction*>(
325 static_cast<const BasicBlock*>(this)->getFirstMayFaultInst());
326 }
327
328 /// Return a const iterator range over the instructions in the block, skipping
329 /// any debug instructions. Skip any pseudo operations as well if \c
330 /// SkipPseudoOp is true.
332 std::function<bool(const Instruction &)>>>
333 instructionsWithoutDebug(bool SkipPseudoOp = true) const;
334
335 /// Return an iterator range over the instructions in the block, skipping any
336 /// debug instructions. Skip and any pseudo operations as well if \c
337 /// SkipPseudoOp is true.
340 instructionsWithoutDebug(bool SkipPseudoOp = true);
341
342 /// Return the size of the basic block ignoring debug instructions
344 std::function<bool(const Instruction &)>>::difference_type
345 sizeWithoutDebug() const;
346
347 /// Unlink 'this' from the containing function, but do not delete it.
348 void removeFromParent();
349
350 /// Unlink 'this' from the containing function and delete it.
351 ///
352 // \returns an iterator pointing to the element after the erased one.
354
355 /// Unlink this basic block from its current function and insert it into
356 /// the function that \p MovePos lives in, right before \p MovePos.
357 inline void moveBefore(BasicBlock *MovePos) {
358 moveBefore(MovePos->getIterator());
359 }
361
362 /// Unlink this basic block from its current function and insert it
363 /// right after \p MovePos in the function \p MovePos lives in.
364 void moveAfter(BasicBlock *MovePos);
365
366 /// Insert unlinked basic block into a function.
367 ///
368 /// Inserts an unlinked basic block into \c Parent. If \c InsertBefore is
369 /// provided, inserts before that basic block, otherwise inserts at the end.
370 ///
371 /// \pre \a getParent() is \c nullptr.
372 void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
373
374 /// Return the predecessor of this block if it has a single predecessor
375 /// block. Otherwise return a null pointer.
376 const BasicBlock *getSinglePredecessor() const;
378 return const_cast<BasicBlock *>(
379 static_cast<const BasicBlock *>(this)->getSinglePredecessor());
380 }
381
382 /// Return the predecessor of this block if it has a unique predecessor
383 /// block. Otherwise return a null pointer.
384 ///
385 /// Note that unique predecessor doesn't mean single edge, there can be
386 /// multiple edges from the unique predecessor to this block (for example a
387 /// switch statement with multiple cases having the same destination).
388 const BasicBlock *getUniquePredecessor() const;
390 return const_cast<BasicBlock *>(
391 static_cast<const BasicBlock *>(this)->getUniquePredecessor());
392 }
393
394 /// Return true if this block has exactly N predecessors.
395 bool hasNPredecessors(unsigned N) const;
396
397 /// Return true if this block has N predecessors or more.
398 bool hasNPredecessorsOrMore(unsigned N) const;
399
400 /// Return the successor of this block if it has a single successor.
401 /// Otherwise return a null pointer.
402 ///
403 /// This method is analogous to getSinglePredecessor above.
404 const BasicBlock *getSingleSuccessor() const;
406 return const_cast<BasicBlock *>(
407 static_cast<const BasicBlock *>(this)->getSingleSuccessor());
408 }
409
410 /// Return the successor of this block if it has a unique successor.
411 /// Otherwise return a null pointer.
412 ///
413 /// This method is analogous to getUniquePredecessor above.
414 const BasicBlock *getUniqueSuccessor() const;
416 return const_cast<BasicBlock *>(
417 static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
418 }
419
420 /// Print the basic block to an output stream with an optional
421 /// AssemblyAnnotationWriter.
422 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
423 bool ShouldPreserveUseListOrder = false,
424 bool IsForDebug = false) const;
425
426 //===--------------------------------------------------------------------===//
427 /// Instruction iterator methods
428 ///
429 inline iterator begin() {
430 iterator It = InstList.begin();
431 // Set the head-inclusive bit to indicate that this iterator includes
432 // any debug-info at the start of the block. This is a no-op unless the
433 // appropriate CMake flag is set.
434 It.setHeadBit(true);
435 return It;
436 }
437 inline const_iterator begin() const {
438 const_iterator It = InstList.begin();
439 It.setHeadBit(true);
440 return It;
441 }
442 inline iterator end () { return InstList.end(); }
443 inline const_iterator end () const { return InstList.end(); }
444
445 inline reverse_iterator rbegin() { return InstList.rbegin(); }
446 inline const_reverse_iterator rbegin() const { return InstList.rbegin(); }
447 inline reverse_iterator rend () { return InstList.rend(); }
448 inline const_reverse_iterator rend () const { return InstList.rend(); }
449
450 inline size_t size() const { return InstList.size(); }
451 inline bool empty() const { return InstList.empty(); }
452 inline const Instruction &front() const { return InstList.front(); }
453 inline Instruction &front() { return InstList.front(); }
454 inline const Instruction &back() const { return InstList.back(); }
455 inline Instruction &back() { return InstList.back(); }
456
457 /// Iterator to walk just the phi nodes in the basic block.
458 template <typename PHINodeT = PHINode, typename BBIteratorT = iterator>
460 : public iterator_facade_base<phi_iterator_impl<PHINodeT, BBIteratorT>,
461 std::forward_iterator_tag, PHINodeT> {
462 friend BasicBlock;
463
464 PHINodeT *PN;
465
466 phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
467
468 public:
469 // Allow default construction to build variables, but this doesn't build
470 // a useful iterator.
471 phi_iterator_impl() = default;
472
473 // Allow conversion between instantiations where valid.
474 template <typename PHINodeU, typename BBIteratorU,
475 typename = std::enable_if_t<
476 std::is_convertible<PHINodeU *, PHINodeT *>::value>>
478 : PN(Arg.PN) {}
479
480 bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
481
482 PHINodeT &operator*() const { return *PN; }
483
484 using phi_iterator_impl::iterator_facade_base::operator++;
486 assert(PN && "Cannot increment the end iterator!");
487 PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
488 return *this;
489 }
490 };
494
495 /// Returns a range that iterates over the phis in the basic block.
496 ///
497 /// Note that this cannot be used with basic blocks that have no terminator.
499 return const_cast<BasicBlock *>(this)->phis();
500 }
502
503private:
504 /// Return the underlying instruction list container.
505 /// This is deliberately private because we have implemented an adequate set
506 /// of functions to modify the list, including BasicBlock::splice(),
507 /// BasicBlock::erase(), Instruction::insertInto() etc.
508 const InstListType &getInstList() const { return InstList; }
509 InstListType &getInstList() { return InstList; }
510
511 /// Returns a pointer to a member of the instruction list.
512 /// This is private on purpose, just like `getInstList()`.
513 static InstListType BasicBlock::*getSublistAccess(Instruction *) {
514 return &BasicBlock::InstList;
515 }
516
517 /// Dedicated function for splicing debug-info: when we have an empty
518 /// splice (i.e. zero instructions), the caller may still intend any
519 /// debug-info in between the two "positions" to be spliced.
520 void spliceDebugInfoEmptyBlock(BasicBlock::iterator ToIt, BasicBlock *FromBB,
521 BasicBlock::iterator FromBeginIt,
522 BasicBlock::iterator FromEndIt);
523
524 /// Perform any debug-info specific maintenence for the given splice
525 /// activity. In the DPValue debug-info representation, debug-info is not
526 /// in instructions, and so it does not automatically move from one block
527 /// to another.
528 void spliceDebugInfo(BasicBlock::iterator ToIt, BasicBlock *FromBB,
529 BasicBlock::iterator FromBeginIt,
530 BasicBlock::iterator FromEndIt);
531 void spliceDebugInfoImpl(BasicBlock::iterator ToIt, BasicBlock *FromBB,
532 BasicBlock::iterator FromBeginIt,
533 BasicBlock::iterator FromEndIt);
534
535public:
536 /// Returns a pointer to the symbol table if one exists.
537 ValueSymbolTable *getValueSymbolTable();
538
539 /// Methods for support type inquiry through isa, cast, and dyn_cast.
540 static bool classof(const Value *V) {
541 return V->getValueID() == Value::BasicBlockVal;
542 }
543
544 /// Cause all subinstructions to "let go" of all the references that said
545 /// subinstructions are maintaining.
546 ///
547 /// This allows one to 'delete' a whole class at a time, even though there may
548 /// be circular references... first all references are dropped, and all use
549 /// counts go to zero. Then everything is delete'd for real. Note that no
550 /// operations are valid on an object that has "dropped all references",
551 /// except operator delete.
552 void dropAllReferences();
553
554 /// Update PHI nodes in this BasicBlock before removal of predecessor \p Pred.
555 /// Note that this function does not actually remove the predecessor.
556 ///
557 /// If \p KeepOneInputPHIs is true then don't remove PHIs that are left with
558 /// zero or one incoming values, and don't simplify PHIs with all incoming
559 /// values the same.
560 void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs = false);
561
562 bool canSplitPredecessors() const;
563
564 /// Split the basic block into two basic blocks at the specified instruction.
565 ///
566 /// If \p Before is true, splitBasicBlockBefore handles the
567 /// block splitting. Otherwise, execution proceeds as described below.
568 ///
569 /// Note that all instructions BEFORE the specified iterator
570 /// stay as part of the original basic block, an unconditional branch is added
571 /// to the original BB, and the rest of the instructions in the BB are moved
572 /// to the new BB, including the old terminator. The newly formed basic block
573 /// is returned. This function invalidates the specified iterator.
574 ///
575 /// Note that this only works on well formed basic blocks (must have a
576 /// terminator), and \p 'I' must not be the end of instruction list (which
577 /// would cause a degenerate basic block to be formed, having a terminator
578 /// inside of the basic block).
579 ///
580 /// Also note that this doesn't preserve any passes. To split blocks while
581 /// keeping loop information consistent, use the SplitBlock utility function.
582 BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "",
583 bool Before = false);
585 bool Before = false) {
586 return splitBasicBlock(I->getIterator(), BBName, Before);
587 }
588
589 /// Split the basic block into two basic blocks at the specified instruction
590 /// and insert the new basic blocks as the predecessor of the current block.
591 ///
592 /// This function ensures all instructions AFTER and including the specified
593 /// iterator \p I are part of the original basic block. All Instructions
594 /// BEFORE the iterator \p I are moved to the new BB and an unconditional
595 /// branch is added to the new BB. The new basic block is returned.
596 ///
597 /// Note that this only works on well formed basic blocks (must have a
598 /// terminator), and \p 'I' must not be the end of instruction list (which
599 /// would cause a degenerate basic block to be formed, having a terminator
600 /// inside of the basic block). \p 'I' cannot be a iterator for a PHINode
601 /// with multiple incoming blocks.
602 ///
603 /// Also note that this doesn't preserve any passes. To split blocks while
604 /// keeping loop information consistent, use the SplitBlockBefore utility
605 /// function.
606 BasicBlock *splitBasicBlockBefore(iterator I, const Twine &BBName = "");
608 return splitBasicBlockBefore(I->getIterator(), BBName);
609 }
610
611 /// Transfer all instructions from \p FromBB to this basic block at \p ToIt.
613 splice(ToIt, FromBB, FromBB->begin(), FromBB->end());
614 }
615
616 /// Transfer one instruction from \p FromBB at \p FromIt to this basic block
617 /// at \p ToIt.
619 BasicBlock::iterator FromIt) {
620 auto FromItNext = std::next(FromIt);
621 // Single-element splice is a noop if destination == source.
622 if (ToIt == FromIt || ToIt == FromItNext)
623 return;
624 splice(ToIt, FromBB, FromIt, FromItNext);
625 }
626
627 /// Transfer a range of instructions that belong to \p FromBB from \p
628 /// FromBeginIt to \p FromEndIt, to this basic block at \p ToIt.
629 void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB,
630 BasicBlock::iterator FromBeginIt,
631 BasicBlock::iterator FromEndIt);
632
633 /// Erases a range of instructions from \p FromIt to (not including) \p ToIt.
634 /// \Returns \p ToIt.
636
637 /// Returns true if there are any uses of this basic block other than
638 /// direct branches, switches, etc. to it.
639 bool hasAddressTaken() const {
640 return getBasicBlockBits().BlockAddressRefCount != 0;
641 }
642
643 /// Update all phi nodes in this basic block to refer to basic block \p New
644 /// instead of basic block \p Old.
646
647 /// Update all phi nodes in this basic block's successors to refer to basic
648 /// block \p New instead of basic block \p Old.
650
651 /// Update all phi nodes in this basic block's successors to refer to basic
652 /// block \p New instead of to it.
654
655 /// Return true if this basic block is an exception handling block.
656 bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
657
658 /// Return true if this basic block is a landing pad.
659 ///
660 /// Being a ``landing pad'' means that the basic block is the destination of
661 /// the 'unwind' edge of an invoke instruction.
662 bool isLandingPad() const;
663
664 /// Return the landingpad instruction associated with the landing pad.
665 const LandingPadInst *getLandingPadInst() const;
667 return const_cast<LandingPadInst *>(
668 static_cast<const BasicBlock *>(this)->getLandingPadInst());
669 }
670
671 /// Return true if it is legal to hoist instructions into this block.
672 bool isLegalToHoistInto() const;
673
674 /// Return true if this is the entry block of the containing function.
675 /// This method can only be used on blocks that have a parent function.
676 bool isEntryBlock() const;
677
678 std::optional<uint64_t> getIrrLoopHeaderWeight() const;
679
680 /// Returns true if the Order field of child Instructions is valid.
681 bool isInstrOrderValid() const {
682 return getBasicBlockBits().InstrOrderValid;
683 }
684
685 /// Mark instruction ordering invalid. Done on every instruction insert.
688 BasicBlockBits Bits = getBasicBlockBits();
689 Bits.InstrOrderValid = false;
690 setBasicBlockBits(Bits);
691 }
692
693 /// Renumber instructions and mark the ordering as valid.
695
696 /// Asserts that instruction order numbers are marked invalid, or that they
697 /// are in ascending order. This is constant time if the ordering is invalid,
698 /// and linear in the number of instructions if the ordering is valid. Callers
699 /// should be careful not to call this in ways that make common operations
700 /// O(n^2). For example, it takes O(n) time to assign order numbers to
701 /// instructions, so the order should be validated no more than once after
702 /// each ordering to ensure that transforms have the same algorithmic
703 /// complexity when asserts are enabled as when they are disabled.
704 void validateInstrOrdering() const;
705
706private:
707#if defined(_AIX) && (!defined(__GNUC__) || defined(__clang__))
708// Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
709// and give the `pack` pragma push semantics.
710#define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")
711#define END_TWO_BYTE_PACK() _Pragma("pack(pop)")
712#else
713#define BEGIN_TWO_BYTE_PACK()
714#define END_TWO_BYTE_PACK()
715#endif
716
718 /// Bitfield to help interpret the bits in Value::SubclassData.
719 struct BasicBlockBits {
720 unsigned short BlockAddressRefCount : 15;
721 unsigned short InstrOrderValid : 1;
722 };
724
725#undef BEGIN_TWO_BYTE_PACK
726#undef END_TWO_BYTE_PACK
727
728 /// Safely reinterpret the subclass data bits to a more useful form.
729 BasicBlockBits getBasicBlockBits() const {
730 static_assert(sizeof(BasicBlockBits) == sizeof(unsigned short),
731 "too many bits for Value::SubclassData");
732 unsigned short ValueData = getSubclassDataFromValue();
733 BasicBlockBits AsBits;
734 memcpy(&AsBits, &ValueData, sizeof(AsBits));
735 return AsBits;
736 }
737
738 /// Reinterpret our subclass bits and store them back into Value.
739 void setBasicBlockBits(BasicBlockBits AsBits) {
740 unsigned short D;
741 memcpy(&D, &AsBits, sizeof(D));
743 }
744
745 /// Increment the internal refcount of the number of BlockAddresses
746 /// referencing this BasicBlock by \p Amt.
747 ///
748 /// This is almost always 0, sometimes one possibly, but almost never 2, and
749 /// inconceivably 3 or more.
750 void AdjustBlockAddressRefCount(int Amt) {
751 BasicBlockBits Bits = getBasicBlockBits();
752 Bits.BlockAddressRefCount += Amt;
753 setBasicBlockBits(Bits);
754 assert(Bits.BlockAddressRefCount < 255 && "Refcount wrap-around");
755 }
756
757 /// Shadow Value::setValueSubclassData with a private forwarding method so
758 /// that any future subclasses cannot accidentally use it.
759 void setValueSubclassData(unsigned short D) {
761 }
762};
763
764// Create wrappers for C Binding types (see CBindingWrapping.h).
766
767/// Advance \p It while it points to a debug instruction and return the result.
768/// This assumes that \p It is not at the end of a block.
770
771#ifdef NDEBUG
772/// In release builds, this is a no-op. For !NDEBUG builds, the checks are
773/// implemented in the .cpp file to avoid circular header deps.
774inline void BasicBlock::validateInstrOrdering() const {}
775#endif
776
777} // end namespace llvm
778
779#endif // LLVM_IR_BASICBLOCK_H
aarch64 promote const
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref)
#define LLVM_READONLY
Definition: Compiler.h:227
std::string Name
#define I(x, y, z)
Definition: MD5.cpp:58
Machine Check Debug Module
LLVMContext & Context
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
#define END_TWO_BYTE_PACK()
#define BEGIN_TWO_BYTE_PACK()
Iterator to walk just the phi nodes in the basic block.
Definition: BasicBlock.h:461
bool operator==(const phi_iterator_impl &Arg) const
Definition: BasicBlock.h:480
phi_iterator_impl(const phi_iterator_impl< PHINodeU, BBIteratorU > &Arg)
Definition: BasicBlock.h:477
phi_iterator_impl & operator++()
Definition: BasicBlock.h:485
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
BasicBlock::iterator erase(BasicBlock::iterator FromIt, BasicBlock::iterator ToIt)
Erases a range of instructions from FromIt to (not including) ToIt.
Definition: BasicBlock.cpp:619
void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block's successors to refer to basic block New instead of basic bl...
Definition: BasicBlock.cpp:637
BasicBlock(const BasicBlock &)=delete
iterator end()
Definition: BasicBlock.h:442
DPMarker * getMarker(InstListType::iterator It)
Return the DPMarker for the position given by It, so that DPValues can be inserted there.
Instruction * getFirstMayFaultInst()
Definition: BasicBlock.h:323
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:429
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:498
const_iterator begin() const
Definition: BasicBlock.h:437
const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
Definition: BasicBlock.cpp:656
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:389
reverse_iterator rbegin()
Definition: BasicBlock.h:445
static bool classof(const Value *V)
Methods for support type inquiry through isa, cast, and dyn_cast.
Definition: BasicBlock.h:540
void renumberInstructions()
Renumber instructions and mark the ordering as valid.
Definition: BasicBlock.cpp:679
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug(bool SkipPseudoOp=true) const
Return a const iterator range over the instructions in the block, skipping any debug instructions.
Definition: BasicBlock.cpp:229
InstListType::iterator getFirstNonPHIIt()
Definition: BasicBlock.h:272
bool empty() const
Definition: BasicBlock.h:451
BasicBlock * splitBasicBlock(Instruction *I, const Twine &BBName="", bool Before=false)
Definition: BasicBlock.h:584
BasicBlock * splitBasicBlockBefore(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction and insert the new basic blo...
Definition: BasicBlock.cpp:581
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition: BasicBlock.h:639
InstListType::const_iterator getFirstNonPHIIt() const
Iterator returning form of getFirstNonPHI.
Definition: BasicBlock.cpp:349
BasicBlock * splitBasicBlockBefore(Instruction *I, const Twine &BBName="")
Definition: BasicBlock.h:607
void invalidateOrders()
Mark instruction ordering invalid. Done on every instruction insert.
Definition: BasicBlock.h:686
friend void Instruction::removeFromParent()
void convertToNewDbgValues()
Convert variable location debugging information stored in dbg.value intrinsics into DPMarker / DPValu...
Definition: BasicBlock.cpp:63
void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW=nullptr, bool ShouldPreserveUseListOrder=false, bool IsForDebug=false) const
Print the basic block to an output stream with an optional AssemblyAnnotationWriter.
Definition: AsmWriter.cpp:4809
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:165
void setIsNewDbgInfoFormat(bool NewFlag)
Ensure the block is in "old" dbg.value format (NewFlag == false) or in the new format (NewFlag == tru...
Definition: BasicBlock.cpp:137
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:342
BasicBlock * getUniqueSuccessor()
Definition: BasicBlock.h:415
const Instruction & front() const
Definition: BasicBlock.h:452
Module * getModule()
Definition: BasicBlock.h:213
Instruction & front()
Definition: BasicBlock.h:453
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:198
BasicBlock * getSingleSuccessor()
Definition: BasicBlock.h:405
friend BasicBlock::iterator Instruction::eraseFromParent()
bool isEntryBlock() const
Return true if this is the entry block of the containing function.
Definition: BasicBlock.cpp:544
ValueSymbolTable * getValueSymbolTable()
Returns a pointer to the symbol table if one exists.
Definition: BasicBlock.cpp:144
BasicBlock * getUniquePredecessor()
Definition: BasicBlock.h:389
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
Definition: BasicBlock.cpp:266
bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
Definition: BasicBlock.cpp:454
BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="", bool Before=false)
Split the basic block into two basic blocks at the specified instruction.
Definition: BasicBlock.cpp:550
DPMarker * getTrailingDPValues()
Fetch the collection of DPValues that "trail" after the last instruction of this block,...
BasicBlock * getSinglePredecessor()
Definition: BasicBlock.h:377
void convertFromNewDbgValues()
Convert variable location debugging information stored in DPMarkers and DPValues into the dbg....
Definition: BasicBlock.cpp:100
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
Definition: BasicBlock.cpp:470
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:432
DPMarker * createMarker(Instruction *I)
Attach a DPMarker to the given instruction.
Definition: BasicBlock.cpp:39
std::optional< uint64_t > getIrrLoopHeaderWeight() const
Definition: BasicBlock.cpp:660
Instruction * getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp=true)
Definition: BasicBlock.h:294
void dumpDbgValues() const
Definition: BasicBlock.cpp:126
const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
Definition: BasicBlock.cpp:306
Instruction & back()
Definition: BasicBlock.h:455
InstListType::reverse_iterator reverse_iterator
Definition: BasicBlock.h:166
friend void Instruction::moveBeforeImpl(BasicBlock &BB, InstListType::iterator I, bool Preserve)
void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New)
Update all phi nodes in this basic block to refer to basic block New instead of basic block Old.
Definition: BasicBlock.cpp:626
const Instruction * getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode, a debug intrinsic,...
Definition: BasicBlock.cpp:373
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:440
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:462
void insertDPValueAfter(DbgRecord *DPV, Instruction *I)
Insert a DPValue into a block at the position given by I.
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB, BasicBlock::iterator FromIt)
Transfer one instruction from FromBB at FromIt to this basic block at ToIt.
Definition: BasicBlock.h:618
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:205
void setTrailingDPValues(DPMarker *M)
Record that the collection of DPValues in M "trails" after the last instruction of this block.
Function * getParent()
Definition: BasicBlock.h:206
const_reverse_iterator rend() const
Definition: BasicBlock.h:448
reverse_iterator rend()
Definition: BasicBlock.h:447
void validateInstrOrdering() const
Asserts that instruction order numbers are marked invalid, or that they are in ascending order.
const Instruction * getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
Definition: BasicBlock.cpp:359
filter_iterator< BasicBlock::const_iterator, std::function< bool(constInstruction &)> >::difference_type sizeWithoutDebug() const
Return the size of the basic block ignoring debug instructions.
Definition: BasicBlock.cpp:249
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:164
Instruction * getFirstNonPHI()
Definition: BasicBlock.h:264
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:150
CallInst * getPostdominatingDeoptimizeCall()
Definition: BasicBlock.h:243
const_iterator getFirstNonPHIOrDbgOrAlloca() const
Returns an iterator to the first instruction in this block that is not a PHINode, a debug intrinsic,...
Definition: BasicBlock.cpp:403
Instruction * getTerminator()
Definition: BasicBlock.h:225
BasicBlock & operator=(const BasicBlock &)=delete
iterator getFirstNonPHIOrDbgOrAlloca()
Definition: BasicBlock.h:313
bool IsNewDbgInfoFormat
Flag recording whether or not this block stores debug-info in the form of intrinsic instructions (fal...
Definition: BasicBlock.h:65
CallInst * getTerminatingDeoptimizeCall()
Definition: BasicBlock.h:234
void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
Definition: BasicBlock.cpp:427
size_t size() const
Definition: BasicBlock.h:450
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition: BasicBlock.h:357
bool isLandingPad() const
Return true if this basic block is a landing pad.
Definition: BasicBlock.cpp:652
InstListType::const_reverse_iterator const_reverse_iterator
Definition: BasicBlock.h:167
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition: BasicBlock.h:656
CallInst * getTerminatingMustTailCall()
Definition: BasicBlock.h:252
void reinsertInstInDPValues(Instruction *I, std::optional< DbgRecord::self_iterator > Pos)
In rare circumstances instructions can be speculatively removed from blocks, and then be re-inserted ...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:220
bool canSplitPredecessors() const
Definition: BasicBlock.cpp:518
const_iterator end() const
Definition: BasicBlock.h:443
void deleteTrailingDPValues()
Delete any trailing DPValues at the end of this block, see setTrailingDPValues.
const CallInst * getTerminatingMustTailCall() const
Returns the call instruction marked 'musttail' prior to the terminating return instruction of this ba...
Definition: BasicBlock.cpp:275
friend BasicBlock::iterator Instruction::insertInto(BasicBlock *BB, BasicBlock::iterator It)
bool isLegalToHoistInto() const
Return true if it is legal to hoist instructions into this block.
Definition: BasicBlock.cpp:530
Instruction * getFirstNonPHIOrDbg(bool SkipPseudoOp=true)
Definition: BasicBlock.h:283
DPMarker * getNextMarker(Instruction *I)
Return the DPMarker for the position that comes after I.
bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
Definition: BasicBlock.cpp:458
bool isInstrOrderValid() const
Returns true if the Order field of child Instructions is valid.
Definition: BasicBlock.h:681
const CallInst * getPostdominatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize that is present either in current ...
Definition: BasicBlock.cpp:321
void insertDPValueBefore(DbgRecord *DPV, InstListType::iterator Here)
Insert a DPValue into a block at the position given by Here.
SymbolTableList< Instruction, ilist_iterator_bits< true > > InstListType
Definition: BasicBlock.h:62
const Instruction * getFirstMayFaultInst() const
Returns the first potential AsynchEH faulty instruction currently it checks for loads/stores (which m...
Definition: BasicBlock.cpp:333
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition: BasicBlock.h:612
void flushTerminatorDbgValues()
Eject any debug-info trailing at the end of a block.
Definition: BasicBlock.cpp:692
const_reverse_iterator rbegin() const
Definition: BasicBlock.h:446
LandingPadInst * getLandingPadInst()
Definition: BasicBlock.h:666
const Instruction & back() const
Definition: BasicBlock.h:454
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:271
iterator getFirstInsertionPt()
Definition: BasicBlock.h:305
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition: BasicBlock.cpp:489
The address of a basic block.
Definition: Constants.h:888
This class represents a function call, abstracting a target machine's calling convention.
Per-instruction record of debug-info.
Base class for non-instruction debug metadata records that have positions within IR.
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
Definition: Instruction.cpp:88
iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction.
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Definition: Instruction.h:800
InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void insertAfter(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately after the specified instruction.
InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
The landingpad instruction holds all of the information necessary to generate correct exception handl...
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
LLVM Value Representation.
Definition: Value.h:74
unsigned short getSubclassDataFromValue() const
Definition: Value.h:866
void setValueSubclassData(unsigned short D)
Definition: Value.h:867
Specialization of filter_iterator_base for forward iteration only.
Definition: STLExtras.h:506
self_iterator getIterator()
Definition: ilist_node.h:109
An ilist node that can access its parent list.
Definition: ilist_node.h:284
base_list_type::const_reverse_iterator const_reverse_iterator
Definition: ilist.h:125
base_list_type::reverse_iterator reverse_iterator
Definition: ilist.h:123
base_list_type::const_iterator const_iterator
Definition: ilist.h:122
base_list_type::iterator iterator
Definition: ilist.h:121
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Definition: iterator.h:80
A range adaptor for a pair of iterators.
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition: raw_ostream.h:52
struct LLVMOpaqueBasicBlock * LLVMBasicBlockRef
Represents a basic block of instructions in LLVM IR.
Definition: Types.h:82
This file defines classes to implement an intrusive doubly linked list class (i.e.
This file defines the ilist_node class template, which is a convenient base class for creating classe...
This provides a very simple, boring adaptor for a begin and end iterator into a range type.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It)
Advance It while it points to a debug instruction and return the result.
Definition: BasicBlock.cpp:673
#define N
Option to add extra bits to the ilist_iterator.