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