1 //===- llvm/BasicBlock.h - Represent a basic block in the VM ----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the declaration of the BasicBlock class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_IR_BASICBLOCK_H
14 #define LLVM_IR_BASICBLOCK_H
15 
16 #include "llvm-c/Types.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/ADT/ilist.h"
19 #include "llvm/ADT/ilist_node.h"
20 #include "llvm/ADT/iterator.h"
21 #include "llvm/ADT/iterator_range.h"
22 #include "llvm/IR/Instruction.h"
23 #include "llvm/IR/SymbolTableListTraits.h"
24 #include "llvm/IR/Value.h"
25 #include "llvm/Support/CBindingWrapping.h"
26 #include "llvm/Support/Casting.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 Function;
37 class LandingPadInst;
38 class LLVMContext;
39 class Module;
40 class PHINode;
41 class ValueSymbolTable;
42 
43 /// LLVM Basic Block Representation
44 ///
45 /// This represents a single basic block in LLVM. A basic block is simply a
46 /// container of instructions that execute sequentially. Basic blocks are Values
47 /// because they are referenced by instructions such as branches and switch
48 /// tables. The type of a BasicBlock is "Type::LabelTy" because the basic block
49 /// represents a label to which a branch can jump.
50 ///
51 /// A well formed basic block is formed of a list of non-terminating
52 /// instructions followed by a single terminator instruction. Terminator
53 /// instructions may not occur in the middle of basic blocks, and must terminate
54 /// the blocks. The BasicBlock class allows malformed basic blocks to occur
55 /// because it may be useful in the intermediate stage of constructing or
56 /// modifying a program. However, the verifier will ensure that basic blocks are
57 /// "well formed".
58 class BasicBlock final : public Value, // Basic blocks are data objects also
59                          public ilist_node_with_parent<BasicBlock, Function> {
60 public:
61   using InstListType = SymbolTableList<Instruction>;
62 
63 private:
64   friend class BlockAddress;
65   friend class SymbolTableListTraits<BasicBlock>;
66 
67   InstListType InstList;
68   Function *Parent;
69 
70   void setParent(Function *parent);
71 
72   /// Constructor.
73   ///
74   /// If the function parameter is specified, the basic block is automatically
75   /// inserted at either the end of the function (if InsertBefore is null), or
76   /// before the specified basic block.
77   explicit BasicBlock(LLVMContext &C, const Twine &Name = "",
78                       Function *Parent = nullptr,
79                       BasicBlock *InsertBefore = nullptr);
80 
81 public:
82   BasicBlock(const BasicBlock &) = delete;
83   BasicBlock &operator=(const BasicBlock &) = delete;
84   ~BasicBlock();
85 
86   /// Get the context in which this basic block lives.
87   LLVMContext &getContext() const;
88 
89   /// Instruction iterators...
90   using iterator = InstListType::iterator;
91   using const_iterator = InstListType::const_iterator;
92   using reverse_iterator = InstListType::reverse_iterator;
93   using const_reverse_iterator = InstListType::const_reverse_iterator;
94 
95   /// Creates a new BasicBlock.
96   ///
97   /// If the Parent parameter is specified, the basic block is automatically
98   /// inserted at either the end of the function (if InsertBefore is 0), or
99   /// before the specified basic block.
100   static BasicBlock *Create(LLVMContext &Context, const Twine &Name = "",
101                             Function *Parent = nullptr,
102                             BasicBlock *InsertBefore = nullptr) {
103     return new BasicBlock(Context, Name, Parent, InsertBefore);
104   }
105 
106   /// Return the enclosing method, or null if none.
107   const Function *getParent() const { return Parent; }
108         Function *getParent()       { return Parent; }
109 
110   /// Return the module owning the function this basic block belongs to, or
111   /// nullptr if the function does not have a module.
112   ///
113   /// Note: this is undefined behavior if the block does not have a parent.
114   const Module *getModule() const;
115   Module *getModule() {
116     return const_cast<Module *>(
117                             static_cast<const BasicBlock *>(this)->getModule());
118   }
119 
120   /// Returns the terminator instruction if the block is well formed or null
121   /// if the block is not well formed.
122   const Instruction *getTerminator() const LLVM_READONLY;
123   Instruction *getTerminator() {
124     return const_cast<Instruction *>(
125         static_cast<const BasicBlock *>(this)->getTerminator());
126   }
127 
128   /// Returns the call instruction calling \@llvm.experimental.deoptimize
129   /// prior to the terminating return instruction of this basic block, if such
130   /// a call is present.  Otherwise, returns null.
131   const CallInst *getTerminatingDeoptimizeCall() const;
132   CallInst *getTerminatingDeoptimizeCall() {
133     return const_cast<CallInst *>(
134          static_cast<const BasicBlock *>(this)->getTerminatingDeoptimizeCall());
135   }
136 
137   /// Returns the call instruction calling \@llvm.experimental.deoptimize
138   /// that is present either in current basic block or in block that is a unique
139   /// successor to current block, if such call is present. Otherwise, returns null.
140   const CallInst *getPostdominatingDeoptimizeCall() const;
141   CallInst *getPostdominatingDeoptimizeCall() {
142     return const_cast<CallInst *>(
143          static_cast<const BasicBlock *>(this)->getPostdominatingDeoptimizeCall());
144   }
145 
146   /// Returns the call instruction marked 'musttail' prior to the terminating
147   /// return instruction of this basic block, if such a call is present.
148   /// Otherwise, returns null.
149   const CallInst *getTerminatingMustTailCall() const;
150   CallInst *getTerminatingMustTailCall() {
151     return const_cast<CallInst *>(
152            static_cast<const BasicBlock *>(this)->getTerminatingMustTailCall());
153   }
154 
155   /// Returns a pointer to the first instruction in this block that is not a
156   /// PHINode instruction.
157   ///
158   /// When adding instructions to the beginning of the basic block, they should
159   /// be added before the returned value, not before the first instruction,
160   /// which might be PHI. Returns 0 is there's no non-PHI instruction.
161   const Instruction* getFirstNonPHI() const;
162   Instruction* getFirstNonPHI() {
163     return const_cast<Instruction *>(
164                        static_cast<const BasicBlock *>(this)->getFirstNonPHI());
165   }
166 
167   /// Returns a pointer to the first instruction in this block that is not a
168   /// PHINode or a debug intrinsic, or any pseudo operation if \c SkipPseudoOp
169   /// is true.
170   const Instruction *getFirstNonPHIOrDbg(bool SkipPseudoOp = false) const;
171   Instruction *getFirstNonPHIOrDbg(bool SkipPseudoOp = false) {
172     return const_cast<Instruction *>(
173         static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbg(
174             SkipPseudoOp));
175   }
176 
177   /// Returns a pointer to the first instruction in this block that is not a
178   /// PHINode, a debug intrinsic, or a lifetime intrinsic, or any pseudo
179   /// operation if \c SkipPseudoOp is true.
180   const Instruction *
181   getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp = false) const;
182   Instruction *getFirstNonPHIOrDbgOrLifetime(bool SkipPseudoOp = false) {
183     return const_cast<Instruction *>(
184         static_cast<const BasicBlock *>(this)->getFirstNonPHIOrDbgOrLifetime(
185             SkipPseudoOp));
186   }
187 
188   /// Returns an iterator to the first instruction in this block that is
189   /// suitable for inserting a non-PHI instruction.
190   ///
191   /// In particular, it skips all PHIs and LandingPad instructions.
192   const_iterator getFirstInsertionPt() const;
193   iterator getFirstInsertionPt() {
194     return static_cast<const BasicBlock *>(this)
195                                           ->getFirstInsertionPt().getNonConst();
196   }
197 
198   /// Return a const iterator range over the instructions in the block, skipping
199   /// any debug instructions. Skip any pseudo operations as well if \c
200   /// SkipPseudoOp is true.
201   iterator_range<filter_iterator<BasicBlock::const_iterator,
202                                  std::function<bool(const Instruction &)>>>
203   instructionsWithoutDebug(bool SkipPseudoOp = false) const;
204 
205   /// Return an iterator range over the instructions in the block, skipping any
206   /// debug instructions. Skip and any pseudo operations as well if \c
207   /// SkipPseudoOp is true.
208   iterator_range<
209       filter_iterator<BasicBlock::iterator, std::function<bool(Instruction &)>>>
210   instructionsWithoutDebug(bool SkipPseudoOp = false);
211 
212   /// Return the size of the basic block ignoring debug instructions
213   filter_iterator<BasicBlock::const_iterator,
214                   std::function<bool(const Instruction &)>>::difference_type
215   sizeWithoutDebug() const;
216 
217   /// Unlink 'this' from the containing function, but do not delete it.
218   void removeFromParent();
219 
220   /// Unlink 'this' from the containing function and delete it.
221   ///
222   // \returns an iterator pointing to the element after the erased one.
223   SymbolTableList<BasicBlock>::iterator eraseFromParent();
224 
225   /// Unlink this basic block from its current function and insert it into
226   /// the function that \p MovePos lives in, right before \p MovePos.
227   void moveBefore(BasicBlock *MovePos);
228 
229   /// Unlink this basic block from its current function and insert it
230   /// right after \p MovePos in the function \p MovePos lives in.
231   void moveAfter(BasicBlock *MovePos);
232 
233   /// Insert unlinked basic block into a function.
234   ///
235   /// Inserts an unlinked basic block into \c Parent.  If \c InsertBefore is
236   /// provided, inserts before that basic block, otherwise inserts at the end.
237   ///
238   /// \pre \a getParent() is \c nullptr.
239   void insertInto(Function *Parent, BasicBlock *InsertBefore = nullptr);
240 
241   /// Return the predecessor of this block if it has a single predecessor
242   /// block. Otherwise return a null pointer.
243   const BasicBlock *getSinglePredecessor() const;
244   BasicBlock *getSinglePredecessor() {
245     return const_cast<BasicBlock *>(
246                  static_cast<const BasicBlock *>(this)->getSinglePredecessor());
247   }
248 
249   /// Return the predecessor of this block if it has a unique predecessor
250   /// block. Otherwise return a null pointer.
251   ///
252   /// Note that unique predecessor doesn't mean single edge, there can be
253   /// multiple edges from the unique predecessor to this block (for example a
254   /// switch statement with multiple cases having the same destination).
255   const BasicBlock *getUniquePredecessor() const;
256   BasicBlock *getUniquePredecessor() {
257     return const_cast<BasicBlock *>(
258                  static_cast<const BasicBlock *>(this)->getUniquePredecessor());
259   }
260 
261   /// Return true if this block has exactly N predecessors.
262   bool hasNPredecessors(unsigned N) const;
263 
264   /// Return true if this block has N predecessors or more.
265   bool hasNPredecessorsOrMore(unsigned N) const;
266 
267   /// Return the successor of this block if it has a single successor.
268   /// Otherwise return a null pointer.
269   ///
270   /// This method is analogous to getSinglePredecessor above.
271   const BasicBlock *getSingleSuccessor() const;
272   BasicBlock *getSingleSuccessor() {
273     return const_cast<BasicBlock *>(
274                    static_cast<const BasicBlock *>(this)->getSingleSuccessor());
275   }
276 
277   /// Return the successor of this block if it has a unique successor.
278   /// Otherwise return a null pointer.
279   ///
280   /// This method is analogous to getUniquePredecessor above.
281   const BasicBlock *getUniqueSuccessor() const;
282   BasicBlock *getUniqueSuccessor() {
283     return const_cast<BasicBlock *>(
284                    static_cast<const BasicBlock *>(this)->getUniqueSuccessor());
285   }
286 
287   /// Print the basic block to an output stream with an optional
288   /// AssemblyAnnotationWriter.
289   void print(raw_ostream &OS, AssemblyAnnotationWriter *AAW = nullptr,
290              bool ShouldPreserveUseListOrder = false,
291              bool IsForDebug = false) const;
292 
293   //===--------------------------------------------------------------------===//
294   /// Instruction iterator methods
295   ///
296   inline iterator                begin()       { return InstList.begin(); }
297   inline const_iterator          begin() const { return InstList.begin(); }
298   inline iterator                end  ()       { return InstList.end();   }
299   inline const_iterator          end  () const { return InstList.end();   }
300 
301   inline reverse_iterator        rbegin()       { return InstList.rbegin(); }
302   inline const_reverse_iterator  rbegin() const { return InstList.rbegin(); }
303   inline reverse_iterator        rend  ()       { return InstList.rend();   }
304   inline const_reverse_iterator  rend  () const { return InstList.rend();   }
305 
306   inline size_t                   size() const { return InstList.size();  }
307   inline bool                    empty() const { return InstList.empty(); }
308   inline const Instruction      &front() const { return InstList.front(); }
309   inline       Instruction      &front()       { return InstList.front(); }
310   inline const Instruction       &back() const { return InstList.back();  }
311   inline       Instruction       &back()       { return InstList.back();  }
312 
313   /// Iterator to walk just the phi nodes in the basic block.
314   template <typename PHINodeT = PHINode, typename BBIteratorT = iterator>
315   class phi_iterator_impl
316       : public iterator_facade_base<phi_iterator_impl<PHINodeT, BBIteratorT>,
317                                     std::forward_iterator_tag, PHINodeT> {
318     friend BasicBlock;
319 
320     PHINodeT *PN;
321 
322     phi_iterator_impl(PHINodeT *PN) : PN(PN) {}
323 
324   public:
325     // Allow default construction to build variables, but this doesn't build
326     // a useful iterator.
327     phi_iterator_impl() = default;
328 
329     // Allow conversion between instantiations where valid.
330     template <typename PHINodeU, typename BBIteratorU>
331     phi_iterator_impl(const phi_iterator_impl<PHINodeU, BBIteratorU> &Arg)
332         : PN(Arg.PN) {}
333 
334     bool operator==(const phi_iterator_impl &Arg) const { return PN == Arg.PN; }
335 
336     PHINodeT &operator*() const { return *PN; }
337 
338     using phi_iterator_impl::iterator_facade_base::operator++;
339     phi_iterator_impl &operator++() {
340       assert(PN && "Cannot increment the end iterator!");
341       PN = dyn_cast<PHINodeT>(std::next(BBIteratorT(PN)));
342       return *this;
343     }
344   };
345   using phi_iterator = phi_iterator_impl<>;
346   using const_phi_iterator =
347       phi_iterator_impl<const PHINode, BasicBlock::const_iterator>;
348 
349   /// Returns a range that iterates over the phis in the basic block.
350   ///
351   /// Note that this cannot be used with basic blocks that have no terminator.
352   iterator_range<const_phi_iterator> phis() const {
353     return const_cast<BasicBlock *>(this)->phis();
354   }
355   iterator_range<phi_iterator> phis();
356 
357   /// Return the underlying instruction list container.
358   ///
359   /// Currently you need to access the underlying instruction list container
360   /// directly if you want to modify it.
361   const InstListType &getInstList() const { return InstList; }
362         InstListType &getInstList()       { return InstList; }
363 
364   /// Returns a pointer to a member of the instruction list.
365   static InstListType BasicBlock::*getSublistAccess(Instruction*) {
366     return &BasicBlock::InstList;
367   }
368 
369   /// Returns a pointer to the symbol table if one exists.
370   ValueSymbolTable *getValueSymbolTable();
371 
372   /// Methods for support type inquiry through isa, cast, and dyn_cast.
373   static bool classof(const Value *V) {
374     return V->getValueID() == Value::BasicBlockVal;
375   }
376 
377   /// Cause all subinstructions to "let go" of all the references that said
378   /// subinstructions are maintaining.
379   ///
380   /// This allows one to 'delete' a whole class at a time, even though there may
381   /// be circular references... first all references are dropped, and all use
382   /// counts go to zero.  Then everything is delete'd for real.  Note that no
383   /// operations are valid on an object that has "dropped all references",
384   /// except operator delete.
385   void dropAllReferences();
386 
387   /// Update PHI nodes in this BasicBlock before removal of predecessor \p Pred.
388   /// Note that this function does not actually remove the predecessor.
389   ///
390   /// If \p KeepOneInputPHIs is true then don't remove PHIs that are left with
391   /// zero or one incoming values, and don't simplify PHIs with all incoming
392   /// values the same.
393   void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs = false);
394 
395   bool canSplitPredecessors() const;
396 
397   /// Split the basic block into two basic blocks at the specified instruction.
398   ///
399   /// Note that all instructions BEFORE the specified iterator stay as part of
400   /// the original basic block, an unconditional branch is added to the original
401   /// BB, and the rest of the instructions in the BB are moved to the new BB,
402   /// including the old terminator.  The newly formed BasicBlock is returned.
403   /// This function invalidates the specified iterator.
404   ///
405   /// Note that this only works on well formed basic blocks (must have a
406   /// terminator), and 'I' must not be the end of instruction list (which would
407   /// cause a degenerate basic block to be formed, having a terminator inside of
408   /// the basic block).
409   ///
410   /// Also note that this doesn't preserve any passes. To split blocks while
411   /// keeping loop information consistent, use the SplitBlock utility function.
412   BasicBlock *splitBasicBlock(iterator I, const Twine &BBName = "");
413   BasicBlock *splitBasicBlock(Instruction *I, const Twine &BBName = "") {
414     return splitBasicBlock(I->getIterator(), BBName);
415   }
416 
417   /// Returns true if there are any uses of this basic block other than
418   /// direct branches, switches, etc. to it.
419   bool hasAddressTaken() const {
420     return getBasicBlockBits().BlockAddressRefCount != 0;
421   }
422 
423   /// Update all phi nodes in this basic block to refer to basic block \p New
424   /// instead of basic block \p Old.
425   void replacePhiUsesWith(BasicBlock *Old, BasicBlock *New);
426 
427   /// Update all phi nodes in this basic block's successors to refer to basic
428   /// block \p New instead of basic block \p Old.
429   void replaceSuccessorsPhiUsesWith(BasicBlock *Old, BasicBlock *New);
430 
431   /// Update all phi nodes in this basic block's successors to refer to basic
432   /// block \p New instead of to it.
433   void replaceSuccessorsPhiUsesWith(BasicBlock *New);
434 
435   /// Return true if this basic block is an exception handling block.
436   bool isEHPad() const { return getFirstNonPHI()->isEHPad(); }
437 
438   /// Return true if this basic block is a landing pad.
439   ///
440   /// Being a ``landing pad'' means that the basic block is the destination of
441   /// the 'unwind' edge of an invoke instruction.
442   bool isLandingPad() const;
443 
444   /// Return the landingpad instruction associated with the landing pad.
445   const LandingPadInst *getLandingPadInst() const;
446   LandingPadInst *getLandingPadInst() {
447     return const_cast<LandingPadInst *>(
448                     static_cast<const BasicBlock *>(this)->getLandingPadInst());
449   }
450 
451   /// Return true if it is legal to hoist instructions into this block.
452   bool isLegalToHoistInto() const;
453 
454   Optional<uint64_t> getIrrLoopHeaderWeight() const;
455 
456   /// Returns true if the Order field of child Instructions is valid.
457   bool isInstrOrderValid() const {
458     return getBasicBlockBits().InstrOrderValid;
459   }
460 
461   /// Mark instruction ordering invalid. Done on every instruction insert.
462   void invalidateOrders() {
463     validateInstrOrdering();
464     BasicBlockBits Bits = getBasicBlockBits();
465     Bits.InstrOrderValid = false;
466     setBasicBlockBits(Bits);
467   }
468 
469   /// Renumber instructions and mark the ordering as valid.
470   void renumberInstructions();
471 
472   /// Asserts that instruction order numbers are marked invalid, or that they
473   /// are in ascending order. This is constant time if the ordering is invalid,
474   /// and linear in the number of instructions if the ordering is valid. Callers
475   /// should be careful not to call this in ways that make common operations
476   /// O(n^2). For example, it takes O(n) time to assign order numbers to
477   /// instructions, so the order should be validated no more than once after
478   /// each ordering to ensure that transforms have the same algorithmic
479   /// complexity when asserts are enabled as when they are disabled.
480   void validateInstrOrdering() const;
481 
482 private:
483 #if defined(_AIX) && (!defined(__GNUC__) || defined(__ibmxl__))
484 // Except for GCC; by default, AIX compilers store bit-fields in 4-byte words
485 // and give the `pack` pragma push semantics.
486 #define BEGIN_TWO_BYTE_PACK() _Pragma("pack(2)")
487 #define END_TWO_BYTE_PACK() _Pragma("pack(pop)")
488 #else
489 #define BEGIN_TWO_BYTE_PACK()
490 #define END_TWO_BYTE_PACK()
491 #endif
492 
493   BEGIN_TWO_BYTE_PACK()
494   /// Bitfield to help interpret the bits in Value::SubclassData.
495   struct BasicBlockBits {
496     unsigned short BlockAddressRefCount : 15;
497     unsigned short InstrOrderValid : 1;
498   };
499   END_TWO_BYTE_PACK()
500 
501 #undef BEGIN_TWO_BYTE_PACK
502 #undef END_TWO_BYTE_PACK
503 
504   /// Safely reinterpret the subclass data bits to a more useful form.
505   BasicBlockBits getBasicBlockBits() const {
506     static_assert(sizeof(BasicBlockBits) == sizeof(unsigned short),
507                   "too many bits for Value::SubclassData");
508     unsigned short ValueData = getSubclassDataFromValue();
509     BasicBlockBits AsBits;
510     memcpy(&AsBits, &ValueData, sizeof(AsBits));
511     return AsBits;
512   }
513 
514   /// Reinterpret our subclass bits and store them back into Value.
515   void setBasicBlockBits(BasicBlockBits AsBits) {
516     unsigned short D;
517     memcpy(&D, &AsBits, sizeof(D));
518     Value::setValueSubclassData(D);
519   }
520 
521   /// Increment the internal refcount of the number of BlockAddresses
522   /// referencing this BasicBlock by \p Amt.
523   ///
524   /// This is almost always 0, sometimes one possibly, but almost never 2, and
525   /// inconceivably 3 or more.
526   void AdjustBlockAddressRefCount(int Amt) {
527     BasicBlockBits Bits = getBasicBlockBits();
528     Bits.BlockAddressRefCount += Amt;
529     setBasicBlockBits(Bits);
530     assert(Bits.BlockAddressRefCount < 255 && "Refcount wrap-around");
531   }
532 
533   /// Shadow Value::setValueSubclassData with a private forwarding method so
534   /// that any future subclasses cannot accidentally use it.
535   void setValueSubclassData(unsigned short D) {
536     Value::setValueSubclassData(D);
537   }
538 };
539 
540 // Create wrappers for C Binding types (see CBindingWrapping.h).
541 DEFINE_SIMPLE_CONVERSION_FUNCTIONS(BasicBlock, LLVMBasicBlockRef)
542 
543 /// Advance \p It while it points to a debug instruction and return the result.
544 /// This assumes that \p It is not at the end of a block.
545 BasicBlock::iterator skipDebugIntrinsics(BasicBlock::iterator It);
546 
547 #ifdef NDEBUG
548 /// In release builds, this is a no-op. For !NDEBUG builds, the checks are
549 /// implemented in the .cpp file to avoid circular header deps.
550 inline void BasicBlock::validateInstrOrdering() const {}
551 #endif
552 
553 } // end namespace llvm
554 
555 #endif // LLVM_IR_BASICBLOCK_H
556