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