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