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/DenseMap.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"
24#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 DbgVariableRecord;
42class DbgMarker;
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 DbgMarker 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 DbgMarkers / DbgRecords. 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 DbgMarkers and
87 /// DbgRecords 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 void setNewDbgInfoFormatFlag(bool NewFlag);
96
97 /// Record that the collection of DbgRecords in \p M "trails" after the last
98 /// instruction of this block. These are equivalent to dbg.value intrinsics
99 /// that exist at the end of a basic block with no terminator (a transient
100 /// state that occurs regularly).
102
103 /// Fetch the collection of DbgRecords that "trail" after the last instruction
104 /// of this block, see \ref setTrailingDbgRecords. If there are none, returns
105 /// nullptr.
107
108 /// Delete any trailing DbgRecords at the end of this block, see
109 /// \ref setTrailingDbgRecords.
111
112 void dumpDbgValues() const;
113
114 /// Return the DbgMarker for the position given by \p It, so that DbgRecords
115 /// can be inserted there. This will either be nullptr if not present, a
116 /// DbgMarker, or TrailingDbgRecords if It is end().
118
119 /// Return the DbgMarker for the position that comes after \p I. \see
120 /// BasicBlock::getMarker, this can be nullptr, a DbgMarker, or
121 /// TrailingDbgRecords if there is no next instruction.
123
124 /// Insert a DbgRecord into a block at the position given by \p I.
126
127 /// Insert a DbgRecord into a block at the position given by \p Here.
129
130 /// Eject any debug-info trailing at the end of a block. DbgRecords can
131 /// transiently be located "off the end" of a block if the blocks terminator
132 /// is temporarily removed. Once a terminator is re-inserted this method will
133 /// move such DbgRecords back to the right place (ahead of the terminator).
135
136 /// In rare circumstances instructions can be speculatively removed from
137 /// blocks, and then be re-inserted back into that position later. When this
138 /// happens in RemoveDIs debug-info mode, some special patching-up needs to
139 /// occur: inserting into the middle of a sequence of dbg.value intrinsics
140 /// does not have an equivalent with DbgRecords.
142 std::optional<DbgRecord::self_iterator> Pos);
143
144private:
145 void setParent(Function *parent);
146
147 /// Constructor.
148 ///
149 /// If the function parameter is specified, the basic block is automatically
150 /// inserted at either the end of the function (if InsertBefore is null), or
151 /// before the specified basic block.
152 explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
153 Function *Parent = nullptr,
154 BasicBlock *InsertBefore = nullptr);
155
156public:
157 BasicBlock(const BasicBlock &) = delete;
158 BasicBlock &operator=(const BasicBlock &) = delete;
159 ~BasicBlock();
160
161 /// Get the context in which this basic block lives.
162 LLVMContext &getContext() const;
163
164 /// Instruction iterators...
169
170 // These functions and classes need access to the instruction list.
176 ilist_iterator_bits<true>>;
177 friend class llvm::ilist_node_with_parent<llvm::Instruction, llvm::BasicBlock,
178 ilist_iterator_bits<true>>;
179
180 // Friendly methods that need to access us for the maintenence of
181 // debug-info attachments.
182 friend void Instruction::insertBefore(BasicBlock::iterator InsertPos);
183 friend void Instruction::insertAfter(Instruction *InsertPos);
184 friend void Instruction::insertBefore(BasicBlock &BB,
185 InstListType::iterator InsertPos);
186 friend void Instruction::moveBeforeImpl(BasicBlock &BB,
187 InstListType::iterator I,
188 bool Preserve);
189 friend iterator_range<DbgRecord::self_iterator>
191 const Instruction *From, std::optional<DbgRecord::self_iterator> FromHere,
192 bool InsertAtHead);
193
194 /// Creates a new BasicBlock.
195 ///
196 /// If the Parent parameter is specified, the basic block is automatically
197 /// inserted at either the end of the function (if InsertBefore is 0), or
198 /// before the specified basic block.
199 static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
200 Function *Parent = nullptr,
201 BasicBlock *InsertBefore = nullptr) {
202 return new BasicBlock(Context, Name, Parent, InsertBefore);
203 }
204
205 /// Return the enclosing method, or null if none.
206 const Function *getParent() const { return Parent; }
207 Function *getParent() { return Parent; }
208
209 /// Return the module owning the function this basic block belongs to, or
210 /// nullptr if the function does not have a module.
211 ///
212 /// Note: this is undefined behavior if the block does not have a parent.
213 const Module *getModule() const;
215 return const_cast<Module *>(
216 static_cast<const BasicBlock *>(this)->getModule());
217 }
218
219 /// Returns the terminator instruction if the block is well formed or null
220 /// if the block is not well formed.
222 if (InstList.empty() || !InstList.back().isTerminator())
223 return nullptr;
224 return &InstList.back();
225 }
227 return const_cast<Instruction *>(
228 static_cast<const BasicBlock *>(this)->getTerminator());
229 }
230
231 /// Returns the call instruction calling \@llvm.experimental.deoptimize
232 /// prior to the terminating return instruction of this basic block, if such
233 /// a call is present. Otherwise, returns null.
236 return const_cast<CallInst *>(
237 static_cast<const BasicBlock *>(this)->getTerminatingDeoptimizeCall());
238 }
239
240 /// Returns the call instruction calling \@llvm.experimental.deoptimize
241 /// that is present either in current basic block or in block that is a unique
242 /// successor to current block, if such call is present. Otherwise, returns null.
245 return const_cast<CallInst *>(
246 static_cast<const BasicBlock *>(this)->getPostdominatingDeoptimizeCall());
247 }
248
249 /// Returns the call instruction marked 'musttail' prior to the terminating
250 /// return instruction of this basic block, if such a call is present.
251 /// Otherwise, returns null.
254 return const_cast<CallInst *>(
255 static_cast<const BasicBlock *>(this)->getTerminatingMustTailCall());
256 }
257
258 /// Returns a pointer to the first instruction in this block that is not a
259 /// PHINode instruction.
260 ///
261 /// When adding instructions to the beginning of the basic block, they should
262 /// be added before the returned value, not before the first instruction,
263 /// which might be PHI. Returns 0 is there's no non-PHI instruction.
264 const Instruction* getFirstNonPHI() const;
266 return const_cast<Instruction *>(
267 static_cast<const BasicBlock *>(this)->getFirstNonPHI());
268 }
269
270 /// Iterator returning form of getFirstNonPHI. Installed as a placeholder for
271 /// the RemoveDIs project that will eventually remove debug intrinsics.
275 static_cast<const BasicBlock *>(this)->getFirstNonPHIIt().getNonConst();
276 It.setHeadBit(true);
277 return It;
278 }
279
280 /// Returns a pointer to the first instruction in this block that is not a
281 /// PHINode or a debug intrinsic, or any pseudo operation if \c SkipPseudoOp
282 /// is true.
283 const Instruction *getFirstNonPHIOrDbg(bool SkipPseudoOp = true) const;
284 Instruction *getFirstNonPHIOrDbg(bool SkipPseudoOp = true) {
285 return const_cast<Instruction *>(
286 static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbg(
287 SkipPseudoOp));
288 }
289
290 /// Returns a pointer to the first instruction in this block that is not a
291 /// PHINode, a debug intrinsic, or a lifetime intrinsic, or any pseudo
292 /// operation if \c SkipPseudoOp is true.
293 const Instruction *
294 getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp = true) const;
295 Instruction *getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp = true) {
296 return const_cast<Instruction *>(
297 static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbgOrLifetime(
298 SkipPseudoOp));
299 }
300
301 /// Returns an iterator to the first instruction in this block that is
302 /// suitable for inserting a non-PHI instruction.
303 ///
304 /// In particular, it skips all PHIs and LandingPad instructions.
307 return static_cast<const BasicBlock *>(this)
308 ->getFirstInsertionPt().getNonConst();
309 }
310
311 /// Returns an iterator to the first instruction in this block that is
312 /// not a PHINode, a debug intrinsic, a static alloca or any pseudo operation.
315 return static_cast<const BasicBlock *>(this)
317 .getNonConst();
318 }
319
320 /// Returns the first potential AsynchEH faulty instruction
321 /// currently it checks for loads/stores (which may dereference a null
322 /// pointer) and calls/invokes (which may propagate exceptions)
323 const Instruction* getFirstMayFaultInst() const;
325 return const_cast<Instruction*>(
326 static_cast<const BasicBlock*>(this)->getFirstMayFaultInst());
327 }
328
329 /// Return a const iterator range over the instructions in the block, skipping
330 /// any debug instructions. Skip any pseudo operations as well if \c
331 /// SkipPseudoOp is true.
333 std::function<bool(const Instruction &)>>>
334 instructionsWithoutDebug(bool SkipPseudoOp = true) const;
335
336 /// Return an iterator range over the instructions in the block, skipping any
337 /// debug instructions. Skip and any pseudo operations as well if \c
338 /// SkipPseudoOp is true.
341 instructionsWithoutDebug(bool SkipPseudoOp = true);
342
343 /// Return the size of the basic block ignoring debug instructions
345 std::function<bool(const Instruction &)>>::difference_type
346 sizeWithoutDebug() const;
347
348 /// Unlink 'this' from the containing function, but do not delete it.
349 void removeFromParent();
350
351 /// Unlink 'this' from the containing function and delete it.
352 ///
353 // \returns an iterator pointing to the element after the erased one.
355
356 /// Unlink this basic block from its current function and insert it into
357 /// the function that \p MovePos lives in, right before \p MovePos.
358 inline void moveBefore(BasicBlock *MovePos) {
359 moveBefore(MovePos->getIterator());
360 }
362
363 /// Unlink this basic block from its current function and insert it
364 /// right after \p MovePos in the function \p MovePos lives in.
365 void moveAfter(BasicBlock *MovePos);
366
367 /// Insert unlinked basic block into a function.
368 ///
369 /// Inserts an unlinked basic block into \c Parent. If \c InsertBefore is
370 /// provided, inserts before that basic block, otherwise inserts at the end.
371 ///
372 /// \pre \a getParent() is \c nullptr.
373 void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
374
375 /// Return the predecessor of this block if it has a single predecessor
376 /// block. Otherwise return a null pointer.
377 const BasicBlock *getSinglePredecessor() const;
379 return const_cast<BasicBlock *>(
380 static_cast<const BasicBlock *>(this)->getSinglePredecessor());
381 }
382
383 /// Return the predecessor of this block if it has a unique predecessor
384 /// block. Otherwise return a null pointer.
385 ///
386 /// Note that unique predecessor doesn't mean single edge, there can be
387 /// multiple edges from the unique predecessor to this block (for example a
388 /// switch statement with multiple cases having the same destination).
389 const BasicBlock *getUniquePredecessor() const;
391 return const_cast<BasicBlock *>(
392 static_cast<const BasicBlock *>(this)->getUniquePredecessor());
393 }
394
395 /// Return true if this block has exactly N predecessors.
396 bool hasNPredecessors(unsigned N) const;
397
398 /// Return true if this block has N predecessors or more.
399 bool hasNPredecessorsOrMore(unsigned N) const;
400
401 /// Return the successor of this block if it has a single successor.
402 /// Otherwise return a null pointer.
403 ///
404 /// This method is analogous to getSinglePredecessor above.
405 const BasicBlock *getSingleSuccessor() const;
407 return const_cast<BasicBlock *>(
408 static_cast<const BasicBlock *>(this)->getSingleSuccessor());
409 }
410
411 /// Return the successor of this block if it has a unique successor.
412 /// Otherwise return a null pointer.
413 ///
414 /// This method is analogous to getUniquePredecessor above.
415 const BasicBlock *getUniqueSuccessor() const;
417 return const_cast<BasicBlock *>(
418 static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
419 }
420
421 /// Print the basic block to an output stream with an optional
422 /// AssemblyAnnotationWriter.
423 void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
424 bool ShouldPreserveUseListOrder = false,
425 bool IsForDebug = false) const;
426
427 //===--------------------------------------------------------------------===//
428 /// Instruction iterator methods
429 ///
430 inline iterator begin() {
431 iterator It = InstList.begin();
432 // Set the head-inclusive bit to indicate that this iterator includes
433 // any debug-info at the start of the block. This is a no-op unless the
434 // appropriate CMake flag is set.
435 It.setHeadBit(true);
436 return It;
437 }
438 inline const_iterator begin() const {
439 const_iterator It = InstList.begin();
440 It.setHeadBit(true);
441 return It;
442 }
443 inline iterator end () { return InstList.end(); }
444 inline const_iterator end () const { return InstList.end(); }
445
446 inline reverse_iterator rbegin() { return InstList.rbegin(); }
447 inline const_reverse_iterator rbegin() const { return InstList.rbegin(); }
448 inline reverse_iterator rend () { return InstList.rend(); }
449 inline const_reverse_iterator rend () const { return InstList.rend(); }
450
451 inline size_t size() const { return InstList.size(); }
452 inline bool empty() const { return InstList.empty(); }
453 inline const Instruction &front() const { return InstList.front(); }
454 inline Instruction &front() { return InstList.front(); }
455 inline const Instruction &back() const { return InstList.back(); }
456 inline Instruction &back() { return InstList.back(); }
457
458 /// Iterator to walk just the phi nodes in the basic block.
459 template <typename PHINodeT = PHINode, typename BBIteratorT = iterator>
461 : public iterator_facade_base<phi_iterator_impl<PHINodeT, BBIteratorT>,
462 std::forward_iterator_tag, PHINodeT> {
463 friend BasicBlock;
464
465 PHINodeT *PN;
466
467 phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
468
469 public:
470 // Allow default construction to build variables, but this doesn't build
471 // a useful iterator.
472 phi_iterator_impl() = default;
473
474 // Allow conversion between instantiations where valid.
475 template <typename PHINodeU, typename BBIteratorU,
476 typename = std::enable_if_t<
477 std::is_convertible<PHINodeU *, PHINodeT *>::value>>
479 : PN(Arg.PN) {}
480
481 bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
482
483 PHINodeT &operator*() const { return *PN; }
484
485 using phi_iterator_impl::iterator_facade_base::operator++;
487 assert(PN && "Cannot increment the end iterator!");
488 PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
489 return *this;
490 }
491 };
495
496 /// Returns a range that iterates over the phis in the basic block.
497 ///
498 /// Note that this cannot be used with basic blocks that have no terminator.
500 return const_cast<BasicBlock *>(this)->phis();
501 }
503
504private:
505 /// Return the underlying instruction list container.
506 /// This is deliberately private because we have implemented an adequate set
507 /// of functions to modify the list, including BasicBlock::splice(),
508 /// BasicBlock::erase(), Instruction::insertInto() etc.
509 const InstListType &getInstList() const { return InstList; }
510 InstListType &getInstList() { return InstList; }
511
512 /// Returns a pointer to a member of the instruction list.
513 /// This is private on purpose, just like `getInstList()`.
514 static InstListType BasicBlock::*getSublistAccess(Instruction *) {
515 return &BasicBlock::InstList;
516 }
517
518 /// Dedicated function for splicing debug-info: when we have an empty
519 /// splice (i.e. zero instructions), the caller may still intend any
520 /// debug-info in between the two "positions" to be spliced.
521 void spliceDebugInfoEmptyBlock(BasicBlock::iterator ToIt, BasicBlock *FromBB,
522 BasicBlock::iterator FromBeginIt,
523 BasicBlock::iterator FromEndIt);
524
525 /// Perform any debug-info specific maintenence for the given splice
526 /// activity. In the DbgRecord debug-info representation, debug-info is not
527 /// in instructions, and so it does not automatically move from one block
528 /// to another.
529 void spliceDebugInfo(BasicBlock::iterator ToIt, BasicBlock *FromBB,
530 BasicBlock::iterator FromBeginIt,
531 BasicBlock::iterator FromEndIt);
532 void spliceDebugInfoImpl(BasicBlock::iterator ToIt, BasicBlock *FromBB,
533 BasicBlock::iterator FromBeginIt,
534 BasicBlock::iterator FromEndIt);
535
536public:
537 /// Returns a pointer to the symbol table if one exists.
538 ValueSymbolTable *getValueSymbolTable();
539
540 /// Methods for support type inquiry through isa, cast, and dyn_cast.
541 static bool classof(const Value *V) {
542 return V->getValueID() == Value::BasicBlockVal;
543 }
544
545 /// Cause all subinstructions to "let go" of all the references that said
546 /// subinstructions are maintaining.
547 ///
548 /// This allows one to 'delete' a whole class at a time, even though there may
549 /// be circular references... first all references are dropped, and all use
550 /// counts go to zero. Then everything is delete'd for real. Note that no
551 /// operations are valid on an object that has "dropped all references",
552 /// except operator delete.
553 void dropAllReferences();
554
555 /// Update PHI nodes in this BasicBlock before removal of predecessor \p Pred.
556 /// Note that this function does not actually remove the predecessor.
557 ///
558 /// If \p KeepOneInputPHIs is true then don't remove PHIs that are left with
559 /// zero or one incoming values, and don't simplify PHIs with all incoming
560 /// values the same.
561 void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs = false);
562
563 bool canSplitPredecessors() const;
564
565 /// Split the basic block into two basic blocks at the specified instruction.
566 ///
567 /// If \p Before is true, splitBasicBlockBefore handles the
568 /// block splitting. Otherwise, execution proceeds as described below.
569 ///
570 /// Note that all instructions BEFORE the specified iterator
571 /// stay as part of the original basic block, an unconditional branch is added
572 /// to the original BB, and the rest of the instructions in the BB are moved
573 /// to the new BB, including the old terminator. The newly formed basic block
574 /// is returned. This function invalidates the specified iterator.
575 ///
576 /// Note that this only works on well formed basic blocks (must have a
577 /// terminator), and \p 'I' must not be the end of instruction list (which
578 /// would cause a degenerate basic block to be formed, having a terminator
579 /// inside of the basic block).
580 ///
581 /// Also note that this doesn't preserve any passes. To split blocks while
582 /// keeping loop information consistent, use the SplitBlock utility function.
583 BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "",
584 bool Before = false);
586 bool Before = false) {
587 return splitBasicBlock(I->getIterator(), BBName, Before);
588 }
589
590 /// Split the basic block into two basic blocks at the specified instruction
591 /// and insert the new basic blocks as the predecessor of the current block.
592 ///
593 /// This function ensures all instructions AFTER and including the specified
594 /// iterator \p I are part of the original basic block. All Instructions
595 /// BEFORE the iterator \p I are moved to the new BB and an unconditional
596 /// branch is added to the new BB. The new basic block is returned.
597 ///
598 /// Note that this only works on well formed basic blocks (must have a
599 /// terminator), and \p 'I' must not be the end of instruction list (which
600 /// would cause a degenerate basic block to be formed, having a terminator
601 /// inside of the basic block). \p 'I' cannot be a iterator for a PHINode
602 /// with multiple incoming blocks.
603 ///
604 /// Also note that this doesn't preserve any passes. To split blocks while
605 /// keeping loop information consistent, use the SplitBlockBefore utility
606 /// function.
607 BasicBlock *splitBasicBlockBefore(iterator I, const Twine &BBName = "");
609 return splitBasicBlockBefore(I->getIterator(), BBName);
610 }
611
612 /// Transfer all instructions from \p FromBB to this basic block at \p ToIt.
614 splice(ToIt, FromBB, FromBB->begin(), FromBB->end());
615 }
616
617 /// Transfer one instruction from \p FromBB at \p FromIt to this basic block
618 /// at \p ToIt.
620 BasicBlock::iterator FromIt) {
621 auto FromItNext = std::next(FromIt);
622 // Single-element splice is a noop if destination == source.
623 if (ToIt == FromIt || ToIt == FromItNext)
624 return;
625 splice(ToIt, FromBB, FromIt, FromItNext);
626 }
627
628 /// Transfer a range of instructions that belong to \p FromBB from \p
629 /// FromBeginIt to \p FromEndIt, to this basic block at \p ToIt.
630 void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB,
631 BasicBlock::iterator FromBeginIt,
632 BasicBlock::iterator FromEndIt);
633
634 /// Erases a range of instructions from \p FromIt to (not including) \p ToIt.
635 /// \Returns \p ToIt.
637
638 /// Returns true if there are any uses of this basic block other than
639 /// direct branches, switches, etc. to it.
640 bool hasAddressTaken() const {
641 return getBasicBlockBits().BlockAddressRefCount != 0;
642 }
643
644 /// Update all phi nodes in this basic block to refer to basic block \p New
645 /// instead of basic block \p Old.
647
648 /// Update all phi nodes in this basic block's successors to refer to basic
649 /// block \p New instead of basic block \p Old.
651
652 /// Update all phi nodes in this basic block's successors to refer to basic
653 /// block \p New instead of to it.
655
656 /// Return true if this basic block is an exception handling block.
657 bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
658
659 /// Return true if this basic block is a landing pad.
660 ///
661 /// Being a ``landing pad'' means that the basic block is the destination of
662 /// the 'unwind' edge of an invoke instruction.
663 bool isLandingPad() const;
664
665 /// Return the landingpad instruction associated with the landing pad.
666 const LandingPadInst *getLandingPadInst() const;
668 return const_cast<LandingPadInst *>(
669 static_cast<const BasicBlock *>(this)->getLandingPadInst());
670 }
671
672 /// Return true if it is legal to hoist instructions into this block.
673 bool isLegalToHoistInto() const;
674
675 /// Return true if this is the entry block of the containing function.
676 /// This method can only be used on blocks that have a parent function.
677 bool isEntryBlock() const;
678
679 std::optional<uint64_t> getIrrLoopHeaderWeight() const;
680
681 /// Returns true if the Order field of child Instructions is valid.
682 bool isInstrOrderValid() const {
683 return getBasicBlockBits().InstrOrderValid;
684 }
685
686 /// Mark instruction ordering invalid. Done on every instruction insert.
689 BasicBlockBits Bits = getBasicBlockBits();
690 Bits.InstrOrderValid = false;
691 setBasicBlockBits(Bits);
692 }
693
694 /// Renumber instructions and mark the ordering as valid.
696
697 /// Asserts that instruction order numbers are marked invalid, or that they
698 /// are in ascending order. This is constant time if the ordering is invalid,
699 /// and linear in the number of instructions if the ordering is valid. Callers
700 /// should be careful not to call this in ways that make common operations
701 /// O(n^2). For example, it takes O(n) time to assign order numbers to
702 /// instructions, so the order should be validated no more than once after
703 /// each ordering to ensure that transforms have the same algorithmic
704 /// complexity when asserts are enabled as when they are disabled.
705 void validateInstrOrdering() const;
706
707private:
708#if defined(_AIX) && (!defined(__GNUC__) || defined(__clang__))
709// Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
710// and give the `pack` pragma push semantics.
711#define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")
712#define END_TWO_BYTE_PACK() _Pragma("pack(pop)")
713#else
714#define BEGIN_TWO_BYTE_PACK()
715#define END_TWO_BYTE_PACK()
716#endif
717
719 /// Bitfield to help interpret the bits in Value::SubclassData.
720 struct BasicBlockBits {
721 unsigned short BlockAddressRefCount : 15;
722 unsigned short InstrOrderValid : 1;
723 };
725
726#undef BEGIN_TWO_BYTE_PACK
727#undef END_TWO_BYTE_PACK
728
729 /// Safely reinterpret the subclass data bits to a more useful form.
730 BasicBlockBits getBasicBlockBits() const {
731 static_assert(sizeof(BasicBlockBits) == sizeof(unsigned short),
732 "too many bits for Value::SubclassData");
733 unsigned short ValueData = getSubclassDataFromValue();
734 BasicBlockBits AsBits;
735 memcpy(&AsBits, &ValueData, sizeof(AsBits));
736 return AsBits;
737 }
738
739 /// Reinterpret our subclass bits and store them back into Value.
740 void setBasicBlockBits(BasicBlockBits AsBits) {
741 unsigned short D;
742 memcpy(&D, &AsBits, sizeof(D));
744 }
745
746 /// Increment the internal refcount of the number of BlockAddresses
747 /// referencing this BasicBlock by \p Amt.
748 ///
749 /// This is almost always 0, sometimes one possibly, but almost never 2, and
750 /// inconceivably 3 or more.
751 void AdjustBlockAddressRefCount(int Amt) {
752 BasicBlockBits Bits = getBasicBlockBits();
753 Bits.BlockAddressRefCount += Amt;
754 setBasicBlockBits(Bits);
755 assert(Bits.BlockAddressRefCount < 255 && "Refcount wrap-around");
756 }
757
758 /// Shadow Value::setValueSubclassData with a private forwarding method so
759 /// that any future subclasses cannot accidentally use it.
760 void setValueSubclassData(unsigned short D) {
762 }
763};
764
765// Create wrappers for C Binding types (see CBindingWrapping.h).
767
768/// Advance \p It while it points to a debug instruction and return the result.
769/// This assumes that \p It is not at the end of a block.
771
772#ifdef NDEBUG
773/// In release builds, this is a no-op. For !NDEBUG builds, the checks are
774/// implemented in the .cpp file to avoid circular header deps.
775inline void BasicBlock::validateInstrOrdering() const {}
776#endif
777
778// Specialize DenseMapInfo for iterators, so that ththey can be installed into
779// maps and sets. The iterator is made up of its node pointer, and the
780// debug-info "head" bit.
781template <> struct DenseMapInfo<BasicBlock::iterator> {
783 return BasicBlock::iterator(nullptr);
784 }
785
787 BasicBlock::iterator It(nullptr);
788 It.setHeadBit(true);
789 return It;
790 }
791
792 static unsigned getHashValue(const BasicBlock::iterator &It) {
794 reinterpret_cast<void *>(It.getNodePtr())) ^
795 (unsigned)It.getHeadBit();
796 }
797
798 static bool isEqual(const BasicBlock::iterator &LHS,
799 const BasicBlock::iterator &RHS) {
800 return LHS == RHS && LHS.getHeadBit() == RHS.getHeadBit();
801 }
802};
803
804} // end namespace llvm
805
806#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
This file defines the DenseMap class.
std::string Name
#define I(x, y, z)
Definition: MD5.cpp:58
Machine Check Debug Module
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
#define END_TWO_BYTE_PACK()
#define BEGIN_TWO_BYTE_PACK()
Value * RHS
Value * LHS
Iterator to walk just the phi nodes in the basic block.
Definition: BasicBlock.h:462
bool operator==(const phi_iterator_impl &Arg) const
Definition: BasicBlock.h:481
phi_iterator_impl(const phi_iterator_impl< PHINodeU, BBIteratorU > &Arg)
Definition: BasicBlock.h:478
phi_iterator_impl & operator++()
Definition: BasicBlock.h:486
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:639
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:657
BasicBlock(const BasicBlock &)=delete
iterator end()
Definition: BasicBlock.h:443
Instruction * getFirstMayFaultInst()
Definition: BasicBlock.h:324
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:430
void deleteTrailingDbgRecords()
Delete any trailing DbgRecords at the end of this block, see setTrailingDbgRecords.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:499
const_iterator begin() const
Definition: BasicBlock.h:438
const LandingPadInst * getLandingPadInst() const
Return the landingpad instruction associated with the landing pad.
Definition: BasicBlock.cpp:676
void setTrailingDbgRecords(DbgMarker *M)
Record that the collection of DbgRecords in M "trails" after the last instruction of this block.
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:409
reverse_iterator rbegin()
Definition: BasicBlock.h:446
static bool classof(const Value *V)
Methods for support type inquiry through isa, cast, and dyn_cast.
Definition: BasicBlock.h:541
void renumberInstructions()
Renumber instructions and mark the ordering as valid.
Definition: BasicBlock.cpp:699
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:247
InstListType::iterator getFirstNonPHIIt()
Definition: BasicBlock.h:273
bool empty() const
Definition: BasicBlock.h:452
DbgMarker * createMarker(Instruction *I)
Attach a DbgMarker to the given instruction.
Definition: BasicBlock.cpp:52
BasicBlock * splitBasicBlock(Instruction *I, const Twine &BBName="", bool Before=false)
Definition: BasicBlock.h:585
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:601
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition: BasicBlock.h:640
InstListType::const_iterator getFirstNonPHIIt() const
Iterator returning form of getFirstNonPHI.
Definition: BasicBlock.cpp:367
void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
BasicBlock * splitBasicBlockBefore(Instruction *I, const Twine &BBName="")
Definition: BasicBlock.h:608
void invalidateOrders()
Mark instruction ordering invalid. Done on every instruction insert.
Definition: BasicBlock.h:687
friend void Instruction::removeFromParent()
void convertToNewDbgValues()
Convert variable location debugging information stored in dbg.value intrinsics into DbgMarkers / DbgR...
Definition: BasicBlock.cpp:76
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:4862
InstListType::const_iterator const_iterator
Definition: BasicBlock.h:166
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:152
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:360
BasicBlock * getUniqueSuccessor()
Definition: BasicBlock.h:416
const Instruction & front() const
Definition: BasicBlock.h:453
Module * getModule()
Definition: BasicBlock.h:214
Instruction & front()
Definition: BasicBlock.h:454
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition: BasicBlock.h:199
BasicBlock * getSingleSuccessor()
Definition: BasicBlock.h:406
friend BasicBlock::iterator Instruction::eraseFromParent()
void setNewDbgInfoFormatFlag(bool NewFlag)
Definition: BasicBlock.cpp:158
bool isEntryBlock() const
Return true if this is the entry block of the containing function.
Definition: BasicBlock.cpp:564
ValueSymbolTable * getValueSymbolTable()
Returns a pointer to the symbol table if one exists.
Definition: BasicBlock.cpp:162
BasicBlock * getUniquePredecessor()
Definition: BasicBlock.h:390
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:284
bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
Definition: BasicBlock.cpp:474
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:570
BasicBlock * getSinglePredecessor()
Definition: BasicBlock.h:378
void convertFromNewDbgValues()
Convert variable location debugging information stored in DbgMarkers and DbgRecords into the dbg....
Definition: BasicBlock.cpp:115
const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
Definition: BasicBlock.cpp:490
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:452
std::optional< uint64_t > getIrrLoopHeaderWeight() const
Definition: BasicBlock.cpp:680
Instruction * getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp=true)
Definition: BasicBlock.h:295
void dumpDbgValues() const
Definition: BasicBlock.cpp:141
const CallInst * getTerminatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize prior to the terminating return in...
Definition: BasicBlock.cpp:324
Instruction & back()
Definition: BasicBlock.h:456
InstListType::reverse_iterator reverse_iterator
Definition: BasicBlock.h:167
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:646
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:393
const BasicBlock * getUniquePredecessor() const
Return the predecessor of this block if it has a unique predecessor block.
Definition: BasicBlock.cpp:460
const BasicBlock * getSingleSuccessor() const
Return the successor of this block if it has a single successor.
Definition: BasicBlock.cpp:482
void flushTerminatorDbgRecords()
Eject any debug-info trailing at the end of a block.
Definition: BasicBlock.cpp:712
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:619
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:206
Function * getParent()
Definition: BasicBlock.h:207
const_reverse_iterator rend() const
Definition: BasicBlock.h:449
reverse_iterator rend()
Definition: BasicBlock.h:448
void insertDbgRecordAfter(DbgRecord *DR, Instruction *I)
Insert a DbgRecord into a block at the position given by I.
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:379
DbgMarker * getMarker(InstListType::iterator It)
Return the DbgMarker for the position given by It, so that DbgRecords can be inserted there.
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:267
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
Instruction * getFirstNonPHI()
Definition: BasicBlock.h:265
LLVMContext & getContext() const
Get the context in which this basic block lives.
Definition: BasicBlock.cpp:168
CallInst * getPostdominatingDeoptimizeCall()
Definition: BasicBlock.h:244
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:423
Instruction * getTerminator()
Definition: BasicBlock.h:226
BasicBlock & operator=(const BasicBlock &)=delete
iterator getFirstNonPHIOrDbgOrAlloca()
Definition: BasicBlock.h:314
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:235
void dropAllReferences()
Cause all subinstructions to "let go" of all the references that said subinstructions are maintaining...
Definition: BasicBlock.cpp:447
size_t size() const
Definition: BasicBlock.h:451
void reinsertInstInDbgRecords(Instruction *I, std::optional< DbgRecord::self_iterator > Pos)
In rare circumstances instructions can be speculatively removed from blocks, and then be re-inserted ...
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
Definition: BasicBlock.h:358
bool isLandingPad() const
Return true if this basic block is a landing pad.
Definition: BasicBlock.cpp:672
InstListType::const_reverse_iterator const_reverse_iterator
Definition: BasicBlock.h:168
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition: BasicBlock.h:657
DbgMarker * getTrailingDbgRecords()
Fetch the collection of DbgRecords that "trail" after the last instruction of this block,...
CallInst * getTerminatingMustTailCall()
Definition: BasicBlock.h:253
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:221
bool canSplitPredecessors() const
Definition: BasicBlock.cpp:538
const_iterator end() const
Definition: BasicBlock.h:444
const CallInst * getTerminatingMustTailCall() const
Returns the call instruction marked 'musttail' prior to the terminating return instruction of this ba...
Definition: BasicBlock.cpp:293
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:550
Instruction * getFirstNonPHIOrDbg(bool SkipPseudoOp=true)
Definition: BasicBlock.h:284
bool hasNPredecessorsOrMore(unsigned N) const
Return true if this block has N predecessors or more.
Definition: BasicBlock.cpp:478
bool isInstrOrderValid() const
Returns true if the Order field of child Instructions is valid.
Definition: BasicBlock.h:682
const CallInst * getPostdominatingDeoptimizeCall() const
Returns the call instruction calling @llvm.experimental.deoptimize that is present either in current ...
Definition: BasicBlock.cpp:339
SymbolTableList< Instruction, ilist_iterator_bits< true > > InstListType
Definition: BasicBlock.h:62
DbgMarker * getNextMarker(Instruction *I)
Return the DbgMarker for the position that comes after I.
const Instruction * getFirstMayFaultInst() const
Returns the first potential AsynchEH faulty instruction currently it checks for loads/stores (which m...
Definition: BasicBlock.cpp:351
void splice(BasicBlock::iterator ToIt, BasicBlock *FromBB)
Transfer all instructions from FromBB to this basic block at ToIt.
Definition: BasicBlock.h:613
const_reverse_iterator rbegin() const
Definition: BasicBlock.h:447
LandingPadInst * getLandingPadInst()
Definition: BasicBlock.h:667
const Instruction & back() const
Definition: BasicBlock.h:455
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:289
iterator getFirstInsertionPt()
Definition: BasicBlock.h:306
void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Definition: BasicBlock.cpp:509
The address of a basic block.
Definition: Constants.h:890
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:91
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:812
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:497
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:693
#define N
static BasicBlock::iterator getEmptyKey()
Definition: BasicBlock.h:782
static unsigned getHashValue(const BasicBlock::iterator &It)
Definition: BasicBlock.h:792
static bool isEqual(const BasicBlock::iterator &LHS, const BasicBlock::iterator &RHS)
Definition: BasicBlock.h:798
static BasicBlock::iterator getTombstoneKey()
Definition: BasicBlock.h:786
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:50
Option to add extra bits to the ilist_iterator.