xref: /llvm-project/llvm/include/llvm/CodeGen/MachineBasicBlock.h (revision f5f32cef617c0796a7d980a464786949cbf21227)
1 //===- llvm/CodeGen/MachineBasicBlock.h -------------------------*- 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 // Collect the sequence of machine instructions for a basic block.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CODEGEN_MACHINEBASICBLOCK_H
14 #define LLVM_CODEGEN_MACHINEBASICBLOCK_H
15 
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/ADT/GraphTraits.h"
18 #include "llvm/ADT/SparseBitVector.h"
19 #include "llvm/ADT/ilist.h"
20 #include "llvm/ADT/iterator_range.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineInstrBundleIterator.h"
23 #include "llvm/IR/DebugLoc.h"
24 #include "llvm/MC/LaneBitmask.h"
25 #include "llvm/Support/BranchProbability.h"
26 #include <cassert>
27 #include <cstdint>
28 #include <iterator>
29 #include <string>
30 #include <vector>
31 
32 namespace llvm {
33 
34 class BasicBlock;
35 class MachineDomTreeUpdater;
36 class MachineFunction;
37 class MCSymbol;
38 class ModuleSlotTracker;
39 class Pass;
40 class Printable;
41 class SlotIndexes;
42 class StringRef;
43 class raw_ostream;
44 class LiveIntervals;
45 class TargetRegisterClass;
46 class TargetRegisterInfo;
47 template <typename IRUnitT, typename... ExtraArgTs> class AnalysisManager;
48 using MachineFunctionAnalysisManager = AnalysisManager<MachineFunction>;
49 
50 // This structure uniquely identifies a basic block section.
51 // Possible values are
52 //  {Type: Default, Number: (unsigned)} (These are regular section IDs)
53 //  {Type: Exception, Number: 0}  (ExceptionSectionID)
54 //  {Type: Cold, Number: 0}  (ColdSectionID)
55 struct MBBSectionID {
56   enum SectionType {
57     Default = 0, // Regular section (these sections are distinguished by the
58                  // Number field).
59     Exception,   // Special section type for exception handling blocks
60     Cold,        // Special section type for cold blocks
61   } Type;
62   unsigned Number;
63 
64   MBBSectionID(unsigned N) : Type(Default), Number(N) {}
65 
66   // Special unique sections for cold and exception blocks.
67   const static MBBSectionID ColdSectionID;
68   const static MBBSectionID ExceptionSectionID;
69 
70   bool operator==(const MBBSectionID &Other) const {
71     return Type == Other.Type && Number == Other.Number;
72   }
73 
74   bool operator!=(const MBBSectionID &Other) const { return !(*this == Other); }
75 
76 private:
77   // This is only used to construct the special cold and exception sections.
78   MBBSectionID(SectionType T) : Type(T), Number(0) {}
79 };
80 
81 template <> struct DenseMapInfo<MBBSectionID> {
82   using TypeInfo = DenseMapInfo<MBBSectionID::SectionType>;
83   using NumberInfo = DenseMapInfo<unsigned>;
84 
85   static inline MBBSectionID getEmptyKey() {
86     return MBBSectionID(NumberInfo::getEmptyKey());
87   }
88   static inline MBBSectionID getTombstoneKey() {
89     return MBBSectionID(NumberInfo::getTombstoneKey());
90   }
91   static unsigned getHashValue(const MBBSectionID &SecID) {
92     return detail::combineHashValue(TypeInfo::getHashValue(SecID.Type),
93                                     NumberInfo::getHashValue(SecID.Number));
94   }
95   static bool isEqual(const MBBSectionID &LHS, const MBBSectionID &RHS) {
96     return LHS == RHS;
97   }
98 };
99 
100 // This structure represents the information for a basic block pertaining to
101 // the basic block sections profile.
102 struct UniqueBBID {
103   unsigned BaseID;
104   unsigned CloneID;
105 };
106 
107 template <> struct ilist_traits<MachineInstr> {
108 private:
109   friend class MachineBasicBlock; // Set by the owning MachineBasicBlock.
110 
111   MachineBasicBlock *Parent;
112 
113   using instr_iterator =
114       simple_ilist<MachineInstr, ilist_sentinel_tracking<true>>::iterator;
115 
116 public:
117   void addNodeToList(MachineInstr *N);
118   void removeNodeFromList(MachineInstr *N);
119   void transferNodesFromList(ilist_traits &FromList, instr_iterator First,
120                              instr_iterator Last);
121   void deleteNode(MachineInstr *MI);
122 };
123 
124 class MachineBasicBlock
125     : public ilist_node_with_parent<MachineBasicBlock, MachineFunction> {
126 public:
127   /// Pair of physical register and lane mask.
128   /// This is not simply a std::pair typedef because the members should be named
129   /// clearly as they both have an integer type.
130   struct RegisterMaskPair {
131   public:
132     MCRegister PhysReg;
133     LaneBitmask LaneMask;
134 
135     RegisterMaskPair(MCPhysReg PhysReg, LaneBitmask LaneMask)
136         : PhysReg(PhysReg), LaneMask(LaneMask) {}
137 
138     bool operator==(const RegisterMaskPair &other) const {
139       return PhysReg == other.PhysReg && LaneMask == other.LaneMask;
140     }
141   };
142 
143 private:
144   using Instructions = ilist<MachineInstr, ilist_sentinel_tracking<true>>;
145 
146   const BasicBlock *BB;
147   int Number;
148 
149   /// The call frame size on entry to this basic block due to call frame setup
150   /// instructions in a predecessor. This is usually zero, unless basic blocks
151   /// are split in the middle of a call sequence.
152   ///
153   /// This information is only maintained until PrologEpilogInserter eliminates
154   /// call frame pseudos.
155   unsigned CallFrameSize = 0;
156 
157   MachineFunction *xParent;
158   Instructions Insts;
159 
160   /// Keep track of the predecessor / successor basic blocks.
161   SmallVector<MachineBasicBlock *, 4> Predecessors;
162   SmallVector<MachineBasicBlock *, 2> Successors;
163 
164   /// Keep track of the probabilities to the successors. This vector has the
165   /// same order as Successors, or it is empty if we don't use it (disable
166   /// optimization).
167   std::vector<BranchProbability> Probs;
168   using probability_iterator = std::vector<BranchProbability>::iterator;
169   using const_probability_iterator =
170       std::vector<BranchProbability>::const_iterator;
171 
172   std::optional<uint64_t> IrrLoopHeaderWeight;
173 
174   /// Keep track of the physical registers that are livein of the basicblock.
175   using LiveInVector = std::vector<RegisterMaskPair>;
176   LiveInVector LiveIns;
177 
178   /// Alignment of the basic block. One if the basic block does not need to be
179   /// aligned.
180   Align Alignment;
181   /// Maximum amount of bytes that can be added to align the basic block. If the
182   /// alignment cannot be reached in this many bytes, no bytes are emitted.
183   /// Zero to represent no maximum.
184   unsigned MaxBytesForAlignment = 0;
185 
186   /// Indicate that this basic block is entered via an exception handler.
187   bool IsEHPad = false;
188 
189   /// Indicate that this MachineBasicBlock is referenced somewhere other than
190   /// as predecessor/successor, a terminator MachineInstr, or a jump table.
191   bool MachineBlockAddressTaken = false;
192 
193   /// If this MachineBasicBlock corresponds to an IR-level "blockaddress"
194   /// constant, this contains a pointer to that block.
195   BasicBlock *AddressTakenIRBlock = nullptr;
196 
197   /// Indicate that this basic block needs its symbol be emitted regardless of
198   /// whether the flow just falls-through to it.
199   bool LabelMustBeEmitted = false;
200 
201   /// Indicate that this basic block is the entry block of an EH scope, i.e.,
202   /// the block that used to have a catchpad or cleanuppad instruction in the
203   /// LLVM IR.
204   bool IsEHScopeEntry = false;
205 
206   /// Indicates if this is a target block of a catchret.
207   bool IsEHCatchretTarget = false;
208 
209   /// Indicate that this basic block is the entry block of an EH funclet.
210   bool IsEHFuncletEntry = false;
211 
212   /// Indicate that this basic block is the entry block of a cleanup funclet.
213   bool IsCleanupFuncletEntry = false;
214 
215   /// Fixed unique ID assigned to this basic block upon creation. Used with
216   /// basic block sections and basic block labels.
217   std::optional<UniqueBBID> BBID;
218 
219   /// With basic block sections, this stores the Section ID of the basic block.
220   MBBSectionID SectionID{0};
221 
222   // Indicate that this basic block begins a section.
223   bool IsBeginSection = false;
224 
225   // Indicate that this basic block ends a section.
226   bool IsEndSection = false;
227 
228   /// Indicate that this basic block is the indirect dest of an INLINEASM_BR.
229   bool IsInlineAsmBrIndirectTarget = false;
230 
231   /// since getSymbol is a relatively heavy-weight operation, the symbol
232   /// is only computed once and is cached.
233   mutable MCSymbol *CachedMCSymbol = nullptr;
234 
235   /// Cached MCSymbol for this block (used if IsEHCatchRetTarget).
236   mutable MCSymbol *CachedEHCatchretMCSymbol = nullptr;
237 
238   /// Marks the end of the basic block. Used during basic block sections to
239   /// calculate the size of the basic block, or the BB section ending with it.
240   mutable MCSymbol *CachedEndMCSymbol = nullptr;
241 
242   // Intrusive list support
243   MachineBasicBlock() = default;
244 
245   explicit MachineBasicBlock(MachineFunction &MF, const BasicBlock *BB);
246 
247   ~MachineBasicBlock();
248 
249   // MachineBasicBlocks are allocated and owned by MachineFunction.
250   friend class MachineFunction;
251 
252 public:
253   /// Return the LLVM basic block that this instance corresponded to originally.
254   /// Note that this may be NULL if this instance does not correspond directly
255   /// to an LLVM basic block.
256   const BasicBlock *getBasicBlock() const { return BB; }
257 
258   /// Remove the reference to the underlying IR BasicBlock. This is for
259   /// reduction tools and should generally not be used.
260   void clearBasicBlock() {
261     BB = nullptr;
262   }
263 
264   /// Check if there is a name of corresponding LLVM basic block.
265   bool hasName() const;
266 
267   /// Return the name of the corresponding LLVM basic block, or an empty string.
268   StringRef getName() const;
269 
270   /// Return a formatted string to identify this block and its parent function.
271   std::string getFullName() const;
272 
273   /// Test whether this block is used as something other than the target
274   /// of a terminator, exception-handling target, or jump table. This is
275   /// either the result of an IR-level "blockaddress", or some form
276   /// of target-specific branch lowering.
277   bool hasAddressTaken() const {
278     return MachineBlockAddressTaken || AddressTakenIRBlock;
279   }
280 
281   /// Test whether this block is used as something other than the target of a
282   /// terminator, exception-handling target, jump table, or IR blockaddress.
283   /// For example, its address might be loaded into a register, or
284   /// stored in some branch table that isn't part of MachineJumpTableInfo.
285   bool isMachineBlockAddressTaken() const { return MachineBlockAddressTaken; }
286 
287   /// Test whether this block is the target of an IR BlockAddress.  (There can
288   /// more than one MBB associated with an IR BB where the address is taken.)
289   bool isIRBlockAddressTaken() const { return AddressTakenIRBlock; }
290 
291   /// Retrieves the BasicBlock which corresponds to this MachineBasicBlock.
292   BasicBlock *getAddressTakenIRBlock() const { return AddressTakenIRBlock; }
293 
294   /// Set this block to indicate that its address is used as something other
295   /// than the target of a terminator, exception-handling target, jump table,
296   /// or IR-level "blockaddress".
297   void setMachineBlockAddressTaken() { MachineBlockAddressTaken = true; }
298 
299   /// Set this block to reflect that it corresponds to an IR-level basic block
300   /// with a BlockAddress.
301   void setAddressTakenIRBlock(BasicBlock *BB) { AddressTakenIRBlock = BB; }
302 
303   /// Test whether this block must have its label emitted.
304   bool hasLabelMustBeEmitted() const { return LabelMustBeEmitted; }
305 
306   /// Set this block to reflect that, regardless how we flow to it, we need
307   /// its label be emitted.
308   void setLabelMustBeEmitted() { LabelMustBeEmitted = true; }
309 
310   /// Return the MachineFunction containing this basic block.
311   const MachineFunction *getParent() const { return xParent; }
312   MachineFunction *getParent() { return xParent; }
313 
314   using instr_iterator = Instructions::iterator;
315   using const_instr_iterator = Instructions::const_iterator;
316   using reverse_instr_iterator = Instructions::reverse_iterator;
317   using const_reverse_instr_iterator = Instructions::const_reverse_iterator;
318 
319   using iterator = MachineInstrBundleIterator<MachineInstr>;
320   using const_iterator = MachineInstrBundleIterator<const MachineInstr>;
321   using reverse_iterator = MachineInstrBundleIterator<MachineInstr, true>;
322   using const_reverse_iterator =
323       MachineInstrBundleIterator<const MachineInstr, true>;
324 
325   unsigned size() const { return (unsigned)Insts.size(); }
326   bool sizeWithoutDebugLargerThan(unsigned Limit) const;
327   bool empty() const { return Insts.empty(); }
328 
329   MachineInstr       &instr_front()       { return Insts.front(); }
330   MachineInstr       &instr_back()        { return Insts.back();  }
331   const MachineInstr &instr_front() const { return Insts.front(); }
332   const MachineInstr &instr_back()  const { return Insts.back();  }
333 
334   MachineInstr       &front()             { return Insts.front(); }
335   MachineInstr       &back()              { return *--end();      }
336   const MachineInstr &front()       const { return Insts.front(); }
337   const MachineInstr &back()        const { return *--end();      }
338 
339   instr_iterator                instr_begin()       { return Insts.begin();  }
340   const_instr_iterator          instr_begin() const { return Insts.begin();  }
341   instr_iterator                  instr_end()       { return Insts.end();    }
342   const_instr_iterator            instr_end() const { return Insts.end();    }
343   reverse_instr_iterator       instr_rbegin()       { return Insts.rbegin(); }
344   const_reverse_instr_iterator instr_rbegin() const { return Insts.rbegin(); }
345   reverse_instr_iterator       instr_rend  ()       { return Insts.rend();   }
346   const_reverse_instr_iterator instr_rend  () const { return Insts.rend();   }
347 
348   using instr_range = iterator_range<instr_iterator>;
349   using const_instr_range = iterator_range<const_instr_iterator>;
350   instr_range instrs() { return instr_range(instr_begin(), instr_end()); }
351   const_instr_range instrs() const {
352     return const_instr_range(instr_begin(), instr_end());
353   }
354 
355   iterator                begin()       { return instr_begin();  }
356   const_iterator          begin() const { return instr_begin();  }
357   iterator                end  ()       { return instr_end();    }
358   const_iterator          end  () const { return instr_end();    }
359   reverse_iterator rbegin() {
360     return reverse_iterator::getAtBundleBegin(instr_rbegin());
361   }
362   const_reverse_iterator rbegin() const {
363     return const_reverse_iterator::getAtBundleBegin(instr_rbegin());
364   }
365   reverse_iterator rend() { return reverse_iterator(instr_rend()); }
366   const_reverse_iterator rend() const {
367     return const_reverse_iterator(instr_rend());
368   }
369 
370   /// Support for MachineInstr::getNextNode().
371   static Instructions MachineBasicBlock::*getSublistAccess(MachineInstr *) {
372     return &MachineBasicBlock::Insts;
373   }
374 
375   inline iterator_range<iterator> terminators() {
376     return make_range(getFirstTerminator(), end());
377   }
378   inline iterator_range<const_iterator> terminators() const {
379     return make_range(getFirstTerminator(), end());
380   }
381 
382   /// Returns a range that iterates over the phis in the basic block.
383   inline iterator_range<iterator> phis() {
384     return make_range(begin(), getFirstNonPHI());
385   }
386   inline iterator_range<const_iterator> phis() const {
387     return const_cast<MachineBasicBlock *>(this)->phis();
388   }
389 
390   // Machine-CFG iterators
391   using pred_iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
392   using const_pred_iterator =
393       SmallVectorImpl<MachineBasicBlock *>::const_iterator;
394   using succ_iterator = SmallVectorImpl<MachineBasicBlock *>::iterator;
395   using const_succ_iterator =
396       SmallVectorImpl<MachineBasicBlock *>::const_iterator;
397   using pred_reverse_iterator =
398       SmallVectorImpl<MachineBasicBlock *>::reverse_iterator;
399   using const_pred_reverse_iterator =
400       SmallVectorImpl<MachineBasicBlock *>::const_reverse_iterator;
401   using succ_reverse_iterator =
402       SmallVectorImpl<MachineBasicBlock *>::reverse_iterator;
403   using const_succ_reverse_iterator =
404       SmallVectorImpl<MachineBasicBlock *>::const_reverse_iterator;
405   pred_iterator        pred_begin()       { return Predecessors.begin(); }
406   const_pred_iterator  pred_begin() const { return Predecessors.begin(); }
407   pred_iterator        pred_end()         { return Predecessors.end();   }
408   const_pred_iterator  pred_end()   const { return Predecessors.end();   }
409   pred_reverse_iterator        pred_rbegin()
410                                           { return Predecessors.rbegin();}
411   const_pred_reverse_iterator  pred_rbegin() const
412                                           { return Predecessors.rbegin();}
413   pred_reverse_iterator        pred_rend()
414                                           { return Predecessors.rend();  }
415   const_pred_reverse_iterator  pred_rend()   const
416                                           { return Predecessors.rend();  }
417   unsigned             pred_size()  const {
418     return (unsigned)Predecessors.size();
419   }
420   bool                 pred_empty() const { return Predecessors.empty(); }
421   succ_iterator        succ_begin()       { return Successors.begin();   }
422   const_succ_iterator  succ_begin() const { return Successors.begin();   }
423   succ_iterator        succ_end()         { return Successors.end();     }
424   const_succ_iterator  succ_end()   const { return Successors.end();     }
425   succ_reverse_iterator        succ_rbegin()
426                                           { return Successors.rbegin();  }
427   const_succ_reverse_iterator  succ_rbegin() const
428                                           { return Successors.rbegin();  }
429   succ_reverse_iterator        succ_rend()
430                                           { return Successors.rend();    }
431   const_succ_reverse_iterator  succ_rend()   const
432                                           { return Successors.rend();    }
433   unsigned             succ_size()  const {
434     return (unsigned)Successors.size();
435   }
436   bool                 succ_empty() const { return Successors.empty();   }
437 
438   inline iterator_range<pred_iterator> predecessors() {
439     return make_range(pred_begin(), pred_end());
440   }
441   inline iterator_range<const_pred_iterator> predecessors() const {
442     return make_range(pred_begin(), pred_end());
443   }
444   inline iterator_range<succ_iterator> successors() {
445     return make_range(succ_begin(), succ_end());
446   }
447   inline iterator_range<const_succ_iterator> successors() const {
448     return make_range(succ_begin(), succ_end());
449   }
450 
451   // LiveIn management methods.
452 
453   /// Adds the specified register as a live in. Note that it is an error to add
454   /// the same register to the same set more than once unless the intention is
455   /// to call sortUniqueLiveIns after all registers are added.
456   void addLiveIn(MCRegister PhysReg,
457                  LaneBitmask LaneMask = LaneBitmask::getAll()) {
458     LiveIns.push_back(RegisterMaskPair(PhysReg, LaneMask));
459   }
460   void addLiveIn(const RegisterMaskPair &RegMaskPair) {
461     LiveIns.push_back(RegMaskPair);
462   }
463 
464   /// Sorts and uniques the LiveIns vector. It can be significantly faster to do
465   /// this than repeatedly calling isLiveIn before calling addLiveIn for every
466   /// LiveIn insertion.
467   void sortUniqueLiveIns();
468 
469   /// Clear live in list.
470   void clearLiveIns();
471 
472   /// Clear the live in list, and return the removed live in's in \p OldLiveIns.
473   /// Requires that the vector \p OldLiveIns is empty.
474   void clearLiveIns(std::vector<RegisterMaskPair> &OldLiveIns);
475 
476   /// Add PhysReg as live in to this block, and ensure that there is a copy of
477   /// PhysReg to a virtual register of class RC. Return the virtual register
478   /// that is a copy of the live in PhysReg.
479   Register addLiveIn(MCRegister PhysReg, const TargetRegisterClass *RC);
480 
481   /// Remove the specified register from the live in set.
482   void removeLiveIn(MCRegister Reg,
483                     LaneBitmask LaneMask = LaneBitmask::getAll());
484 
485   /// Return true if the specified register is in the live in set.
486   bool isLiveIn(MCRegister Reg,
487                 LaneBitmask LaneMask = LaneBitmask::getAll()) const;
488 
489   // Iteration support for live in sets.  These sets are kept in sorted
490   // order by their register number.
491   using livein_iterator = LiveInVector::const_iterator;
492 
493   /// Unlike livein_begin, this method does not check that the liveness
494   /// information is accurate. Still for debug purposes it may be useful
495   /// to have iterators that won't assert if the liveness information
496   /// is not current.
497   livein_iterator livein_begin_dbg() const { return LiveIns.begin(); }
498   iterator_range<livein_iterator> liveins_dbg() const {
499     return make_range(livein_begin_dbg(), livein_end());
500   }
501 
502   livein_iterator livein_begin() const;
503   livein_iterator livein_end()   const { return LiveIns.end(); }
504   bool            livein_empty() const { return LiveIns.empty(); }
505   iterator_range<livein_iterator> liveins() const {
506     return make_range(livein_begin(), livein_end());
507   }
508 
509   /// Remove entry from the livein set and return iterator to the next.
510   livein_iterator removeLiveIn(livein_iterator I);
511 
512   const std::vector<RegisterMaskPair> &getLiveIns() const { return LiveIns; }
513 
514   class liveout_iterator {
515   public:
516     using iterator_category = std::input_iterator_tag;
517     using difference_type = std::ptrdiff_t;
518     using value_type = RegisterMaskPair;
519     using pointer = const RegisterMaskPair *;
520     using reference = const RegisterMaskPair &;
521 
522     liveout_iterator(const MachineBasicBlock &MBB, MCPhysReg ExceptionPointer,
523                      MCPhysReg ExceptionSelector, bool End)
524         : ExceptionPointer(ExceptionPointer),
525           ExceptionSelector(ExceptionSelector), BlockI(MBB.succ_begin()),
526           BlockEnd(MBB.succ_end()) {
527       if (End)
528         BlockI = BlockEnd;
529       else if (BlockI != BlockEnd) {
530         LiveRegI = (*BlockI)->livein_begin();
531         if (!advanceToValidPosition())
532           return;
533         if (LiveRegI->PhysReg == ExceptionPointer ||
534             LiveRegI->PhysReg == ExceptionSelector)
535           ++(*this);
536       }
537     }
538 
539     liveout_iterator &operator++() {
540       do {
541         ++LiveRegI;
542         if (!advanceToValidPosition())
543           return *this;
544       } while ((*BlockI)->isEHPad() &&
545                (LiveRegI->PhysReg == ExceptionPointer ||
546                 LiveRegI->PhysReg == ExceptionSelector));
547       return *this;
548     }
549 
550     liveout_iterator operator++(int) {
551       liveout_iterator Tmp = *this;
552       ++(*this);
553       return Tmp;
554     }
555 
556     reference operator*() const {
557       return *LiveRegI;
558     }
559 
560     pointer operator->() const {
561       return &*LiveRegI;
562     }
563 
564     bool operator==(const liveout_iterator &RHS) const {
565       if (BlockI != BlockEnd)
566         return BlockI == RHS.BlockI && LiveRegI == RHS.LiveRegI;
567       return RHS.BlockI == BlockEnd;
568     }
569 
570     bool operator!=(const liveout_iterator &RHS) const {
571       return !(*this == RHS);
572     }
573   private:
574     bool advanceToValidPosition() {
575       if (LiveRegI != (*BlockI)->livein_end())
576         return true;
577 
578       do {
579         ++BlockI;
580       } while (BlockI != BlockEnd && (*BlockI)->livein_empty());
581       if (BlockI == BlockEnd)
582         return false;
583 
584       LiveRegI = (*BlockI)->livein_begin();
585       return true;
586     }
587 
588     MCPhysReg ExceptionPointer, ExceptionSelector;
589     const_succ_iterator BlockI;
590     const_succ_iterator BlockEnd;
591     livein_iterator LiveRegI;
592   };
593 
594   /// Iterator scanning successor basic blocks' liveins to determine the
595   /// registers potentially live at the end of this block. There may be
596   /// duplicates or overlapping registers in the list returned.
597   liveout_iterator liveout_begin() const;
598   liveout_iterator liveout_end() const {
599     return liveout_iterator(*this, 0, 0, true);
600   }
601   iterator_range<liveout_iterator> liveouts() const {
602     return make_range(liveout_begin(), liveout_end());
603   }
604 
605   /// Get the clobber mask for the start of this basic block. Funclets use this
606   /// to prevent register allocation across funclet transitions.
607   const uint32_t *getBeginClobberMask(const TargetRegisterInfo *TRI) const;
608 
609   /// Get the clobber mask for the end of the basic block.
610   /// \see getBeginClobberMask()
611   const uint32_t *getEndClobberMask(const TargetRegisterInfo *TRI) const;
612 
613   /// Return alignment of the basic block.
614   Align getAlignment() const { return Alignment; }
615 
616   /// Set alignment of the basic block.
617   void setAlignment(Align A) { Alignment = A; }
618 
619   void setAlignment(Align A, unsigned MaxBytes) {
620     setAlignment(A);
621     setMaxBytesForAlignment(MaxBytes);
622   }
623 
624   /// Return the maximum amount of padding allowed for aligning the basic block.
625   unsigned getMaxBytesForAlignment() const { return MaxBytesForAlignment; }
626 
627   /// Set the maximum amount of padding allowed for aligning the basic block
628   void setMaxBytesForAlignment(unsigned MaxBytes) {
629     MaxBytesForAlignment = MaxBytes;
630   }
631 
632   /// Returns true if the block is a landing pad. That is this basic block is
633   /// entered via an exception handler.
634   bool isEHPad() const { return IsEHPad; }
635 
636   /// Indicates the block is a landing pad.  That is this basic block is entered
637   /// via an exception handler.
638   void setIsEHPad(bool V = true) { IsEHPad = V; }
639 
640   bool hasEHPadSuccessor() const;
641 
642   /// Returns true if this is the entry block of the function.
643   bool isEntryBlock() const;
644 
645   /// Returns true if this is the entry block of an EH scope, i.e., the block
646   /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
647   bool isEHScopeEntry() const { return IsEHScopeEntry; }
648 
649   /// Indicates if this is the entry block of an EH scope, i.e., the block that
650   /// that used to have a catchpad or cleanuppad instruction in the LLVM IR.
651   void setIsEHScopeEntry(bool V = true) { IsEHScopeEntry = V; }
652 
653   /// Returns true if this is a target block of a catchret.
654   bool isEHCatchretTarget() const { return IsEHCatchretTarget; }
655 
656   /// Indicates if this is a target block of a catchret.
657   void setIsEHCatchretTarget(bool V = true) { IsEHCatchretTarget = V; }
658 
659   /// Returns true if this is the entry block of an EH funclet.
660   bool isEHFuncletEntry() const { return IsEHFuncletEntry; }
661 
662   /// Indicates if this is the entry block of an EH funclet.
663   void setIsEHFuncletEntry(bool V = true) { IsEHFuncletEntry = V; }
664 
665   /// Returns true if this is the entry block of a cleanup funclet.
666   bool isCleanupFuncletEntry() const { return IsCleanupFuncletEntry; }
667 
668   /// Indicates if this is the entry block of a cleanup funclet.
669   void setIsCleanupFuncletEntry(bool V = true) { IsCleanupFuncletEntry = V; }
670 
671   /// Returns true if this block begins any section.
672   bool isBeginSection() const { return IsBeginSection; }
673 
674   /// Returns true if this block ends any section.
675   bool isEndSection() const { return IsEndSection; }
676 
677   void setIsBeginSection(bool V = true) { IsBeginSection = V; }
678 
679   void setIsEndSection(bool V = true) { IsEndSection = V; }
680 
681   std::optional<UniqueBBID> getBBID() const { return BBID; }
682 
683   /// Returns the section ID of this basic block.
684   MBBSectionID getSectionID() const { return SectionID; }
685 
686   /// Sets the fixed BBID of this basic block.
687   void setBBID(const UniqueBBID &V) {
688     assert(!BBID.has_value() && "Cannot change BBID.");
689     BBID = V;
690   }
691 
692   /// Sets the section ID for this basic block.
693   void setSectionID(MBBSectionID V) { SectionID = V; }
694 
695   /// Returns the MCSymbol marking the end of this basic block.
696   MCSymbol *getEndSymbol() const;
697 
698   /// Returns true if this block may have an INLINEASM_BR (overestimate, by
699   /// checking if any of the successors are indirect targets of any inlineasm_br
700   /// in the function).
701   bool mayHaveInlineAsmBr() const;
702 
703   /// Returns true if this is the indirect dest of an INLINEASM_BR.
704   bool isInlineAsmBrIndirectTarget() const {
705     return IsInlineAsmBrIndirectTarget;
706   }
707 
708   /// Indicates if this is the indirect dest of an INLINEASM_BR.
709   void setIsInlineAsmBrIndirectTarget(bool V = true) {
710     IsInlineAsmBrIndirectTarget = V;
711   }
712 
713   /// Returns true if it is legal to hoist instructions into this block.
714   bool isLegalToHoistInto() const;
715 
716   // Code Layout methods.
717 
718   /// Move 'this' block before or after the specified block.  This only moves
719   /// the block, it does not modify the CFG or adjust potential fall-throughs at
720   /// the end of the block.
721   void moveBefore(MachineBasicBlock *NewAfter);
722   void moveAfter(MachineBasicBlock *NewBefore);
723 
724   /// Returns true if this and MBB belong to the same section.
725   bool sameSection(const MachineBasicBlock *MBB) const {
726     return getSectionID() == MBB->getSectionID();
727   }
728 
729   /// Update the terminator instructions in block to account for changes to
730   /// block layout which may have been made. PreviousLayoutSuccessor should be
731   /// set to the block which may have been used as fallthrough before the block
732   /// layout was modified.  If the block previously fell through to that block,
733   /// it may now need a branch. If it previously branched to another block, it
734   /// may now be able to fallthrough to the current layout successor.
735   void updateTerminator(MachineBasicBlock *PreviousLayoutSuccessor);
736 
737   // Machine-CFG mutators
738 
739   /// Add Succ as a successor of this MachineBasicBlock.  The Predecessors list
740   /// of Succ is automatically updated. PROB parameter is stored in
741   /// Probabilities list. The default probability is set as unknown. Mixing
742   /// known and unknown probabilities in successor list is not allowed. When all
743   /// successors have unknown probabilities, 1 / N is returned as the
744   /// probability for each successor, where N is the number of successors.
745   ///
746   /// Note that duplicate Machine CFG edges are not allowed.
747   void addSuccessor(MachineBasicBlock *Succ,
748                     BranchProbability Prob = BranchProbability::getUnknown());
749 
750   /// Add Succ as a successor of this MachineBasicBlock.  The Predecessors list
751   /// of Succ is automatically updated. The probability is not provided because
752   /// BPI is not available (e.g. -O0 is used), in which case edge probabilities
753   /// won't be used. Using this interface can save some space.
754   void addSuccessorWithoutProb(MachineBasicBlock *Succ);
755 
756   /// Set successor probability of a given iterator.
757   void setSuccProbability(succ_iterator I, BranchProbability Prob);
758 
759   /// Normalize probabilities of all successors so that the sum of them becomes
760   /// one. This is usually done when the current update on this MBB is done, and
761   /// the sum of its successors' probabilities is not guaranteed to be one. The
762   /// user is responsible for the correct use of this function.
763   /// MBB::removeSuccessor() has an option to do this automatically.
764   void normalizeSuccProbs() {
765     BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end());
766   }
767 
768   /// Validate successors' probabilities and check if the sum of them is
769   /// approximate one. This only works in DEBUG mode.
770   void validateSuccProbs() const;
771 
772   /// Remove successor from the successors list of this MachineBasicBlock. The
773   /// Predecessors list of Succ is automatically updated.
774   /// If NormalizeSuccProbs is true, then normalize successors' probabilities
775   /// after the successor is removed.
776   void removeSuccessor(MachineBasicBlock *Succ,
777                        bool NormalizeSuccProbs = false);
778 
779   /// Remove specified successor from the successors list of this
780   /// MachineBasicBlock. The Predecessors list of Succ is automatically updated.
781   /// If NormalizeSuccProbs is true, then normalize successors' probabilities
782   /// after the successor is removed.
783   /// Return the iterator to the element after the one removed.
784   succ_iterator removeSuccessor(succ_iterator I,
785                                 bool NormalizeSuccProbs = false);
786 
787   /// Replace successor OLD with NEW and update probability info.
788   void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New);
789 
790   /// Copy a successor (and any probability info) from original block to this
791   /// block's. Uses an iterator into the original blocks successors.
792   ///
793   /// This is useful when doing a partial clone of successors. Afterward, the
794   /// probabilities may need to be normalized.
795   void copySuccessor(const MachineBasicBlock *Orig, succ_iterator I);
796 
797   /// Split the old successor into old plus new and updates the probability
798   /// info.
799   void splitSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New,
800                       bool NormalizeSuccProbs = false);
801 
802   /// Transfers all the successors from MBB to this machine basic block (i.e.,
803   /// copies all the successors FromMBB and remove all the successors from
804   /// FromMBB).
805   void transferSuccessors(MachineBasicBlock *FromMBB);
806 
807   /// Transfers all the successors, as in transferSuccessors, and update PHI
808   /// operands in the successor blocks which refer to FromMBB to refer to this.
809   void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB);
810 
811   /// Return true if any of the successors have probabilities attached to them.
812   bool hasSuccessorProbabilities() const { return !Probs.empty(); }
813 
814   /// Return true if the specified MBB is a predecessor of this block.
815   bool isPredecessor(const MachineBasicBlock *MBB) const;
816 
817   /// Return true if the specified MBB is a successor of this block.
818   bool isSuccessor(const MachineBasicBlock *MBB) const;
819 
820   /// Return true if the specified MBB will be emitted immediately after this
821   /// block, such that if this block exits by falling through, control will
822   /// transfer to the specified MBB. Note that MBB need not be a successor at
823   /// all, for example if this block ends with an unconditional branch to some
824   /// other block.
825   bool isLayoutSuccessor(const MachineBasicBlock *MBB) const;
826 
827   /// Return the successor of this block if it has a single successor.
828   /// Otherwise return a null pointer.
829   ///
830   const MachineBasicBlock *getSingleSuccessor() const;
831   MachineBasicBlock *getSingleSuccessor() {
832     return const_cast<MachineBasicBlock *>(
833         static_cast<const MachineBasicBlock *>(this)->getSingleSuccessor());
834   }
835 
836   /// Return the predecessor of this block if it has a single predecessor.
837   /// Otherwise return a null pointer.
838   ///
839   const MachineBasicBlock *getSinglePredecessor() const;
840   MachineBasicBlock *getSinglePredecessor() {
841     return const_cast<MachineBasicBlock *>(
842         static_cast<const MachineBasicBlock *>(this)->getSinglePredecessor());
843   }
844 
845   /// Return the fallthrough block if the block can implicitly
846   /// transfer control to the block after it by falling off the end of
847   /// it. If an explicit branch to the fallthrough block is not allowed,
848   /// set JumpToFallThrough to be false. Non-null return is a conservative
849   /// answer.
850   MachineBasicBlock *getFallThrough(bool JumpToFallThrough = true);
851 
852   /// Return the fallthrough block if the block can implicitly
853   /// transfer control to it's successor, whether by a branch or
854   /// a fallthrough. Non-null return is a conservative answer.
855   MachineBasicBlock *getLogicalFallThrough() { return getFallThrough(false); }
856 
857   /// Return true if the block can implicitly transfer control to the
858   /// block after it by falling off the end of it.  This should return
859   /// false if it can reach the block after it, but it uses an
860   /// explicit branch to do so (e.g., a table jump).  True is a
861   /// conservative answer.
862   bool canFallThrough();
863 
864   /// Returns a pointer to the first instruction in this block that is not a
865   /// PHINode instruction. When adding instructions to the beginning of the
866   /// basic block, they should be added before the returned value, not before
867   /// the first instruction, which might be PHI.
868   /// Returns end() is there's no non-PHI instruction.
869   iterator getFirstNonPHI();
870   const_iterator getFirstNonPHI() const {
871     return const_cast<MachineBasicBlock *>(this)->getFirstNonPHI();
872   }
873 
874   /// Return the first instruction in MBB after I that is not a PHI or a label.
875   /// This is the correct point to insert lowered copies at the beginning of a
876   /// basic block that must be before any debugging information.
877   iterator SkipPHIsAndLabels(iterator I);
878 
879   /// Return the first instruction in MBB after I that is not a PHI, label or
880   /// debug.  This is the correct point to insert copies at the beginning of a
881   /// basic block. \p Reg is the register being used by a spill or defined for a
882   /// restore/split during register allocation.
883   iterator SkipPHIsLabelsAndDebug(iterator I, Register Reg = Register(),
884                                   bool SkipPseudoOp = true);
885 
886   /// Returns an iterator to the first terminator instruction of this basic
887   /// block. If a terminator does not exist, it returns end().
888   iterator getFirstTerminator();
889   const_iterator getFirstTerminator() const {
890     return const_cast<MachineBasicBlock *>(this)->getFirstTerminator();
891   }
892 
893   /// Same getFirstTerminator but it ignores bundles and return an
894   /// instr_iterator instead.
895   instr_iterator getFirstInstrTerminator();
896 
897   /// Finds the first terminator in a block by scanning forward. This can handle
898   /// cases in GlobalISel where there may be non-terminator instructions between
899   /// terminators, for which getFirstTerminator() will not work correctly.
900   iterator getFirstTerminatorForward();
901 
902   /// Returns an iterator to the first non-debug instruction in the basic block,
903   /// or end(). Skip any pseudo probe operation if \c SkipPseudoOp is true.
904   /// Pseudo probes are like debug instructions which do not turn into real
905   /// machine code. We try to use the function to skip both debug instructions
906   /// and pseudo probe operations to avoid API proliferation. This should work
907   /// most of the time when considering optimizing the rest of code in the
908   /// block, except for certain cases where pseudo probes are designed to block
909   /// the optimizations. For example, code merge like optimizations are supposed
910   /// to be blocked by pseudo probes for better AutoFDO profile quality.
911   /// Therefore, they should be considered as a valid instruction when this
912   /// function is called in a context of such optimizations. On the other hand,
913   /// \c SkipPseudoOp should be true when it's used in optimizations that
914   /// unlikely hurt profile quality, e.g., without block merging. The default
915   /// value of \c SkipPseudoOp is set to true to maximize code quality in
916   /// general, with an explict false value passed in in a few places like branch
917   /// folding and if-conversion to favor profile quality.
918   iterator getFirstNonDebugInstr(bool SkipPseudoOp = true);
919   const_iterator getFirstNonDebugInstr(bool SkipPseudoOp = true) const {
920     return const_cast<MachineBasicBlock *>(this)->getFirstNonDebugInstr(
921         SkipPseudoOp);
922   }
923 
924   /// Returns an iterator to the last non-debug instruction in the basic block,
925   /// or end(). Skip any pseudo operation if \c SkipPseudoOp is true.
926   /// Pseudo probes are like debug instructions which do not turn into real
927   /// machine code. We try to use the function to skip both debug instructions
928   /// and pseudo probe operations to avoid API proliferation. This should work
929   /// most of the time when considering optimizing the rest of code in the
930   /// block, except for certain cases where pseudo probes are designed to block
931   /// the optimizations. For example, code merge like optimizations are supposed
932   /// to be blocked by pseudo probes for better AutoFDO profile quality.
933   /// Therefore, they should be considered as a valid instruction when this
934   /// function is called in a context of such optimizations. On the other hand,
935   /// \c SkipPseudoOp should be true when it's used in optimizations that
936   /// unlikely hurt profile quality, e.g., without block merging. The default
937   /// value of \c SkipPseudoOp is set to true to maximize code quality in
938   /// general, with an explict false value passed in in a few places like branch
939   /// folding and if-conversion to favor profile quality.
940   iterator getLastNonDebugInstr(bool SkipPseudoOp = true);
941   const_iterator getLastNonDebugInstr(bool SkipPseudoOp = true) const {
942     return const_cast<MachineBasicBlock *>(this)->getLastNonDebugInstr(
943         SkipPseudoOp);
944   }
945 
946   /// Convenience function that returns true if the block ends in a return
947   /// instruction.
948   bool isReturnBlock() const {
949     return !empty() && back().isReturn();
950   }
951 
952   /// Convenience function that returns true if the bock ends in a EH scope
953   /// return instruction.
954   bool isEHScopeReturnBlock() const {
955     return !empty() && back().isEHScopeReturn();
956   }
957 
958   /// Split a basic block into 2 pieces at \p SplitPoint. A new block will be
959   /// inserted after this block, and all instructions after \p SplitInst moved
960   /// to it (\p SplitInst will be in the original block). If \p LIS is provided,
961   /// LiveIntervals will be appropriately updated. \return the newly inserted
962   /// block.
963   ///
964   /// If \p UpdateLiveIns is true, this will ensure the live ins list is
965   /// accurate, including for physreg uses/defs in the original block.
966   MachineBasicBlock *splitAt(MachineInstr &SplitInst, bool UpdateLiveIns = true,
967                              LiveIntervals *LIS = nullptr);
968 
969   /// Split the critical edge from this block to the given successor block, and
970   /// return the newly created block, or null if splitting is not possible.
971   ///
972   /// This function updates LiveVariables, MachineDominatorTree, and
973   /// MachineLoopInfo, as applicable.
974   MachineBasicBlock *
975   SplitCriticalEdge(MachineBasicBlock *Succ, Pass &P,
976                     std::vector<SparseBitVector<>> *LiveInSets = nullptr,
977                     MachineDomTreeUpdater *MDTU = nullptr) {
978     return SplitCriticalEdge(Succ, &P, nullptr, LiveInSets, MDTU);
979   }
980 
981   MachineBasicBlock *
982   SplitCriticalEdge(MachineBasicBlock *Succ,
983                     MachineFunctionAnalysisManager &MFAM,
984                     std::vector<SparseBitVector<>> *LiveInSets = nullptr,
985                     MachineDomTreeUpdater *MDTU = nullptr) {
986     return SplitCriticalEdge(Succ, nullptr, &MFAM, LiveInSets, MDTU);
987   }
988 
989   // Helper method for new pass manager migration.
990   MachineBasicBlock *SplitCriticalEdge(
991       MachineBasicBlock *Succ, Pass *P, MachineFunctionAnalysisManager *MFAM,
992       std::vector<SparseBitVector<>> *LiveInSets, MachineDomTreeUpdater *MDTU);
993 
994   /// Check if the edge between this block and the given successor \p
995   /// Succ, can be split. If this returns true a subsequent call to
996   /// SplitCriticalEdge is guaranteed to return a valid basic block if
997   /// no changes occurred in the meantime.
998   bool canSplitCriticalEdge(const MachineBasicBlock *Succ) const;
999 
1000   void pop_front() { Insts.pop_front(); }
1001   void pop_back() { Insts.pop_back(); }
1002   void push_back(MachineInstr *MI) { Insts.push_back(MI); }
1003 
1004   /// Insert MI into the instruction list before I, possibly inside a bundle.
1005   ///
1006   /// If the insertion point is inside a bundle, MI will be added to the bundle,
1007   /// otherwise MI will not be added to any bundle. That means this function
1008   /// alone can't be used to prepend or append instructions to bundles. See
1009   /// MIBundleBuilder::insert() for a more reliable way of doing that.
1010   instr_iterator insert(instr_iterator I, MachineInstr *M);
1011 
1012   /// Insert a range of instructions into the instruction list before I.
1013   template<typename IT>
1014   void insert(iterator I, IT S, IT E) {
1015     assert((I == end() || I->getParent() == this) &&
1016            "iterator points outside of basic block");
1017     Insts.insert(I.getInstrIterator(), S, E);
1018   }
1019 
1020   /// Insert MI into the instruction list before I.
1021   iterator insert(iterator I, MachineInstr *MI) {
1022     assert((I == end() || I->getParent() == this) &&
1023            "iterator points outside of basic block");
1024     assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1025            "Cannot insert instruction with bundle flags");
1026     return Insts.insert(I.getInstrIterator(), MI);
1027   }
1028 
1029   /// Insert MI into the instruction list after I.
1030   iterator insertAfter(iterator I, MachineInstr *MI) {
1031     assert((I == end() || I->getParent() == this) &&
1032            "iterator points outside of basic block");
1033     assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1034            "Cannot insert instruction with bundle flags");
1035     return Insts.insertAfter(I.getInstrIterator(), MI);
1036   }
1037 
1038   /// If I is bundled then insert MI into the instruction list after the end of
1039   /// the bundle, otherwise insert MI immediately after I.
1040   instr_iterator insertAfterBundle(instr_iterator I, MachineInstr *MI) {
1041     assert((I == instr_end() || I->getParent() == this) &&
1042            "iterator points outside of basic block");
1043     assert(!MI->isBundledWithPred() && !MI->isBundledWithSucc() &&
1044            "Cannot insert instruction with bundle flags");
1045     while (I->isBundledWithSucc())
1046       ++I;
1047     return Insts.insertAfter(I, MI);
1048   }
1049 
1050   /// Remove an instruction from the instruction list and delete it.
1051   ///
1052   /// If the instruction is part of a bundle, the other instructions in the
1053   /// bundle will still be bundled after removing the single instruction.
1054   instr_iterator erase(instr_iterator I);
1055 
1056   /// Remove an instruction from the instruction list and delete it.
1057   ///
1058   /// If the instruction is part of a bundle, the other instructions in the
1059   /// bundle will still be bundled after removing the single instruction.
1060   instr_iterator erase_instr(MachineInstr *I) {
1061     return erase(instr_iterator(I));
1062   }
1063 
1064   /// Remove a range of instructions from the instruction list and delete them.
1065   iterator erase(iterator I, iterator E) {
1066     return Insts.erase(I.getInstrIterator(), E.getInstrIterator());
1067   }
1068 
1069   /// Remove an instruction or bundle from the instruction list and delete it.
1070   ///
1071   /// If I points to a bundle of instructions, they are all erased.
1072   iterator erase(iterator I) {
1073     return erase(I, std::next(I));
1074   }
1075 
1076   /// Remove an instruction from the instruction list and delete it.
1077   ///
1078   /// If I is the head of a bundle of instructions, the whole bundle will be
1079   /// erased.
1080   iterator erase(MachineInstr *I) {
1081     return erase(iterator(I));
1082   }
1083 
1084   /// Remove the unbundled instruction from the instruction list without
1085   /// deleting it.
1086   ///
1087   /// This function can not be used to remove bundled instructions, use
1088   /// remove_instr to remove individual instructions from a bundle.
1089   MachineInstr *remove(MachineInstr *I) {
1090     assert(!I->isBundled() && "Cannot remove bundled instructions");
1091     return Insts.remove(instr_iterator(I));
1092   }
1093 
1094   /// Remove the possibly bundled instruction from the instruction list
1095   /// without deleting it.
1096   ///
1097   /// If the instruction is part of a bundle, the other instructions in the
1098   /// bundle will still be bundled after removing the single instruction.
1099   MachineInstr *remove_instr(MachineInstr *I);
1100 
1101   void clear() {
1102     Insts.clear();
1103   }
1104 
1105   /// Take an instruction from MBB 'Other' at the position From, and insert it
1106   /// into this MBB right before 'Where'.
1107   ///
1108   /// If From points to a bundle of instructions, the whole bundle is moved.
1109   void splice(iterator Where, MachineBasicBlock *Other, iterator From) {
1110     // The range splice() doesn't allow noop moves, but this one does.
1111     if (Where != From)
1112       splice(Where, Other, From, std::next(From));
1113   }
1114 
1115   /// Take a block of instructions from MBB 'Other' in the range [From, To),
1116   /// and insert them into this MBB right before 'Where'.
1117   ///
1118   /// The instruction at 'Where' must not be included in the range of
1119   /// instructions to move.
1120   void splice(iterator Where, MachineBasicBlock *Other,
1121               iterator From, iterator To) {
1122     Insts.splice(Where.getInstrIterator(), Other->Insts,
1123                  From.getInstrIterator(), To.getInstrIterator());
1124   }
1125 
1126   /// This method unlinks 'this' from the containing function, and returns it,
1127   /// but does not delete it.
1128   MachineBasicBlock *removeFromParent();
1129 
1130   /// This method unlinks 'this' from the containing function and deletes it.
1131   void eraseFromParent();
1132 
1133   /// Given a machine basic block that branched to 'Old', change the code and
1134   /// CFG so that it branches to 'New' instead.
1135   void ReplaceUsesOfBlockWith(MachineBasicBlock *Old, MachineBasicBlock *New);
1136 
1137   /// Update all phi nodes in this basic block to refer to basic block \p New
1138   /// instead of basic block \p Old.
1139   void replacePhiUsesWith(MachineBasicBlock *Old, MachineBasicBlock *New);
1140 
1141   /// Find the next valid DebugLoc starting at MBBI, skipping any debug
1142   /// instructions.  Return UnknownLoc if there is none.
1143   DebugLoc findDebugLoc(instr_iterator MBBI);
1144   DebugLoc findDebugLoc(iterator MBBI) {
1145     return findDebugLoc(MBBI.getInstrIterator());
1146   }
1147 
1148   /// Has exact same behavior as @ref findDebugLoc (it also searches towards the
1149   /// end of this MBB) except that this function takes a reverse iterator to
1150   /// identify the starting MI.
1151   DebugLoc rfindDebugLoc(reverse_instr_iterator MBBI);
1152   DebugLoc rfindDebugLoc(reverse_iterator MBBI) {
1153     return rfindDebugLoc(MBBI.getInstrIterator());
1154   }
1155 
1156   /// Find the previous valid DebugLoc preceding MBBI, skipping any debug
1157   /// instructions. It is possible to find the last DebugLoc in the MBB using
1158   /// findPrevDebugLoc(instr_end()).  Return UnknownLoc if there is none.
1159   DebugLoc findPrevDebugLoc(instr_iterator MBBI);
1160   DebugLoc findPrevDebugLoc(iterator MBBI) {
1161     return findPrevDebugLoc(MBBI.getInstrIterator());
1162   }
1163 
1164   /// Has exact same behavior as @ref findPrevDebugLoc (it also searches towards
1165   /// the beginning of this MBB) except that this function takes reverse
1166   /// iterator to identify the starting MI. A minor difference compared to
1167   /// findPrevDebugLoc is that we can't start scanning at "instr_end".
1168   DebugLoc rfindPrevDebugLoc(reverse_instr_iterator MBBI);
1169   DebugLoc rfindPrevDebugLoc(reverse_iterator MBBI) {
1170     return rfindPrevDebugLoc(MBBI.getInstrIterator());
1171   }
1172 
1173   /// Find and return the merged DebugLoc of the branch instructions of the
1174   /// block. Return UnknownLoc if there is none.
1175   DebugLoc findBranchDebugLoc();
1176 
1177   /// Possible outcome of a register liveness query to computeRegisterLiveness()
1178   enum LivenessQueryResult {
1179     LQR_Live,   ///< Register is known to be (at least partially) live.
1180     LQR_Dead,   ///< Register is known to be fully dead.
1181     LQR_Unknown ///< Register liveness not decidable from local neighborhood.
1182   };
1183 
1184   /// Return whether (physical) register \p Reg has been defined and not
1185   /// killed as of just before \p Before.
1186   ///
1187   /// Search is localised to a neighborhood of \p Neighborhood instructions
1188   /// before (searching for defs or kills) and \p Neighborhood instructions
1189   /// after (searching just for defs) \p Before.
1190   ///
1191   /// \p Reg must be a physical register.
1192   LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI,
1193                                               MCRegister Reg,
1194                                               const_iterator Before,
1195                                               unsigned Neighborhood = 10) const;
1196 
1197   // Debugging methods.
1198   void dump() const;
1199   void print(raw_ostream &OS, const SlotIndexes * = nullptr,
1200              bool IsStandalone = true) const;
1201   void print(raw_ostream &OS, ModuleSlotTracker &MST,
1202              const SlotIndexes * = nullptr, bool IsStandalone = true) const;
1203 
1204   enum PrintNameFlag {
1205     PrintNameIr = (1 << 0), ///< Add IR name where available
1206     PrintNameAttributes = (1 << 1), ///< Print attributes
1207   };
1208 
1209   void printName(raw_ostream &os, unsigned printNameFlags = PrintNameIr,
1210                  ModuleSlotTracker *moduleSlotTracker = nullptr) const;
1211 
1212   // Printing method used by LoopInfo.
1213   void printAsOperand(raw_ostream &OS, bool PrintType = true) const;
1214 
1215   /// MachineBasicBlocks are uniquely numbered at the function level, unless
1216   /// they're not in a MachineFunction yet, in which case this will return -1.
1217   int getNumber() const { return Number; }
1218   void setNumber(int N) { Number = N; }
1219 
1220   /// Return the call frame size on entry to this basic block.
1221   unsigned getCallFrameSize() const { return CallFrameSize; }
1222   /// Set the call frame size on entry to this basic block.
1223   void setCallFrameSize(unsigned N) { CallFrameSize = N; }
1224 
1225   /// Return the MCSymbol for this basic block.
1226   MCSymbol *getSymbol() const;
1227 
1228   /// Return the EHCatchret Symbol for this basic block.
1229   MCSymbol *getEHCatchretSymbol() const;
1230 
1231   std::optional<uint64_t> getIrrLoopHeaderWeight() const {
1232     return IrrLoopHeaderWeight;
1233   }
1234 
1235   void setIrrLoopHeaderWeight(uint64_t Weight) {
1236     IrrLoopHeaderWeight = Weight;
1237   }
1238 
1239   /// Return probability of the edge from this block to MBB. This method should
1240   /// NOT be called directly, but by using getEdgeProbability method from
1241   /// MachineBranchProbabilityInfo class.
1242   BranchProbability getSuccProbability(const_succ_iterator Succ) const;
1243 
1244 private:
1245   /// Return probability iterator corresponding to the I successor iterator.
1246   probability_iterator getProbabilityIterator(succ_iterator I);
1247   const_probability_iterator
1248   getProbabilityIterator(const_succ_iterator I) const;
1249 
1250   friend class MachineBranchProbabilityInfo;
1251   friend class MIPrinter;
1252 
1253   // Methods used to maintain doubly linked list of blocks...
1254   friend struct ilist_callback_traits<MachineBasicBlock>;
1255 
1256   // Machine-CFG mutators
1257 
1258   /// Add Pred as a predecessor of this MachineBasicBlock. Don't do this
1259   /// unless you know what you're doing, because it doesn't update Pred's
1260   /// successors list. Use Pred->addSuccessor instead.
1261   void addPredecessor(MachineBasicBlock *Pred);
1262 
1263   /// Remove Pred as a predecessor of this MachineBasicBlock. Don't do this
1264   /// unless you know what you're doing, because it doesn't update Pred's
1265   /// successors list. Use Pred->removeSuccessor instead.
1266   void removePredecessor(MachineBasicBlock *Pred);
1267 };
1268 
1269 raw_ostream& operator<<(raw_ostream &OS, const MachineBasicBlock &MBB);
1270 
1271 /// Prints a machine basic block reference.
1272 ///
1273 /// The format is:
1274 ///   %bb.5           - a machine basic block with MBB.getNumber() == 5.
1275 ///
1276 /// Usage: OS << printMBBReference(MBB) << '\n';
1277 Printable printMBBReference(const MachineBasicBlock &MBB);
1278 
1279 // This is useful when building IndexedMaps keyed on basic block pointers.
1280 struct MBB2NumberFunctor {
1281   using argument_type = const MachineBasicBlock *;
1282   unsigned operator()(const MachineBasicBlock *MBB) const {
1283     return MBB->getNumber();
1284   }
1285 };
1286 
1287 //===--------------------------------------------------------------------===//
1288 // GraphTraits specializations for machine basic block graphs (machine-CFGs)
1289 //===--------------------------------------------------------------------===//
1290 
1291 // Provide specializations of GraphTraits to be able to treat a
1292 // MachineFunction as a graph of MachineBasicBlocks.
1293 //
1294 
1295 template <> struct GraphTraits<MachineBasicBlock *> {
1296   using NodeRef = MachineBasicBlock *;
1297   using ChildIteratorType = MachineBasicBlock::succ_iterator;
1298 
1299   static NodeRef getEntryNode(MachineBasicBlock *BB) { return BB; }
1300   static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
1301   static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
1302 
1303   static unsigned getNumber(MachineBasicBlock *BB) {
1304     assert(BB->getNumber() >= 0 && "negative block number");
1305     return BB->getNumber();
1306   }
1307 };
1308 
1309 static_assert(GraphHasNodeNumbers<MachineBasicBlock *>,
1310               "GraphTraits getNumber() not detected");
1311 
1312 template <> struct GraphTraits<const MachineBasicBlock *> {
1313   using NodeRef = const MachineBasicBlock *;
1314   using ChildIteratorType = MachineBasicBlock::const_succ_iterator;
1315 
1316   static NodeRef getEntryNode(const MachineBasicBlock *BB) { return BB; }
1317   static ChildIteratorType child_begin(NodeRef N) { return N->succ_begin(); }
1318   static ChildIteratorType child_end(NodeRef N) { return N->succ_end(); }
1319 
1320   static unsigned getNumber(const MachineBasicBlock *BB) {
1321     assert(BB->getNumber() >= 0 && "negative block number");
1322     return BB->getNumber();
1323   }
1324 };
1325 
1326 static_assert(GraphHasNodeNumbers<const MachineBasicBlock *>,
1327               "GraphTraits getNumber() not detected");
1328 
1329 // Provide specializations of GraphTraits to be able to treat a
1330 // MachineFunction as a graph of MachineBasicBlocks and to walk it
1331 // in inverse order.  Inverse order for a function is considered
1332 // to be when traversing the predecessor edges of a MBB
1333 // instead of the successor edges.
1334 //
1335 template <> struct GraphTraits<Inverse<MachineBasicBlock*>> {
1336   using NodeRef = MachineBasicBlock *;
1337   using ChildIteratorType = MachineBasicBlock::pred_iterator;
1338 
1339   static NodeRef getEntryNode(Inverse<MachineBasicBlock *> G) {
1340     return G.Graph;
1341   }
1342 
1343   static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
1344   static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
1345 
1346   static unsigned getNumber(MachineBasicBlock *BB) {
1347     assert(BB->getNumber() >= 0 && "negative block number");
1348     return BB->getNumber();
1349   }
1350 };
1351 
1352 static_assert(GraphHasNodeNumbers<Inverse<MachineBasicBlock *>>,
1353               "GraphTraits getNumber() not detected");
1354 
1355 template <> struct GraphTraits<Inverse<const MachineBasicBlock*>> {
1356   using NodeRef = const MachineBasicBlock *;
1357   using ChildIteratorType = MachineBasicBlock::const_pred_iterator;
1358 
1359   static NodeRef getEntryNode(Inverse<const MachineBasicBlock *> G) {
1360     return G.Graph;
1361   }
1362 
1363   static ChildIteratorType child_begin(NodeRef N) { return N->pred_begin(); }
1364   static ChildIteratorType child_end(NodeRef N) { return N->pred_end(); }
1365 
1366   static unsigned getNumber(const MachineBasicBlock *BB) {
1367     assert(BB->getNumber() >= 0 && "negative block number");
1368     return BB->getNumber();
1369   }
1370 };
1371 
1372 static_assert(GraphHasNodeNumbers<Inverse<const MachineBasicBlock *>>,
1373               "GraphTraits getNumber() not detected");
1374 
1375 // These accessors are handy for sharing templated code between IR and MIR.
1376 inline auto successors(const MachineBasicBlock *BB) { return BB->successors(); }
1377 inline auto predecessors(const MachineBasicBlock *BB) {
1378   return BB->predecessors();
1379 }
1380 inline auto succ_size(const MachineBasicBlock *BB) { return BB->succ_size(); }
1381 inline auto pred_size(const MachineBasicBlock *BB) { return BB->pred_size(); }
1382 inline auto succ_begin(const MachineBasicBlock *BB) { return BB->succ_begin(); }
1383 inline auto pred_begin(const MachineBasicBlock *BB) { return BB->pred_begin(); }
1384 inline auto succ_end(const MachineBasicBlock *BB) { return BB->succ_end(); }
1385 inline auto pred_end(const MachineBasicBlock *BB) { return BB->pred_end(); }
1386 
1387 /// MachineInstrSpan provides an interface to get an iteration range
1388 /// containing the instruction it was initialized with, along with all
1389 /// those instructions inserted prior to or following that instruction
1390 /// at some point after the MachineInstrSpan is constructed.
1391 class MachineInstrSpan {
1392   MachineBasicBlock &MBB;
1393   MachineBasicBlock::iterator I, B, E;
1394 
1395 public:
1396   MachineInstrSpan(MachineBasicBlock::iterator I, MachineBasicBlock *BB)
1397       : MBB(*BB), I(I), B(I == MBB.begin() ? MBB.end() : std::prev(I)),
1398         E(std::next(I)) {
1399     assert(I == BB->end() || I->getParent() == BB);
1400   }
1401 
1402   MachineBasicBlock::iterator begin() {
1403     return B == MBB.end() ? MBB.begin() : std::next(B);
1404   }
1405   MachineBasicBlock::iterator end() { return E; }
1406   bool empty() { return begin() == end(); }
1407 
1408   MachineBasicBlock::iterator getInitial() { return I; }
1409 };
1410 
1411 /// Increment \p It until it points to a non-debug instruction or to \p End
1412 /// and return the resulting iterator. This function should only be used
1413 /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
1414 /// const_instr_iterator} and the respective reverse iterators.
1415 template <typename IterT>
1416 inline IterT skipDebugInstructionsForward(IterT It, IterT End,
1417                                           bool SkipPseudoOp = true) {
1418   while (It != End &&
1419          (It->isDebugInstr() || (SkipPseudoOp && It->isPseudoProbe())))
1420     ++It;
1421   return It;
1422 }
1423 
1424 /// Decrement \p It until it points to a non-debug instruction or to \p Begin
1425 /// and return the resulting iterator. This function should only be used
1426 /// MachineBasicBlock::{iterator, const_iterator, instr_iterator,
1427 /// const_instr_iterator} and the respective reverse iterators.
1428 template <class IterT>
1429 inline IterT skipDebugInstructionsBackward(IterT It, IterT Begin,
1430                                            bool SkipPseudoOp = true) {
1431   while (It != Begin &&
1432          (It->isDebugInstr() || (SkipPseudoOp && It->isPseudoProbe())))
1433     --It;
1434   return It;
1435 }
1436 
1437 /// Increment \p It, then continue incrementing it while it points to a debug
1438 /// instruction. A replacement for std::next.
1439 template <typename IterT>
1440 inline IterT next_nodbg(IterT It, IterT End, bool SkipPseudoOp = true) {
1441   return skipDebugInstructionsForward(std::next(It), End, SkipPseudoOp);
1442 }
1443 
1444 /// Decrement \p It, then continue decrementing it while it points to a debug
1445 /// instruction. A replacement for std::prev.
1446 template <typename IterT>
1447 inline IterT prev_nodbg(IterT It, IterT Begin, bool SkipPseudoOp = true) {
1448   return skipDebugInstructionsBackward(std::prev(It), Begin, SkipPseudoOp);
1449 }
1450 
1451 /// Construct a range iterator which begins at \p It and moves forwards until
1452 /// \p End is reached, skipping any debug instructions.
1453 template <typename IterT>
1454 inline auto instructionsWithoutDebug(IterT It, IterT End,
1455                                      bool SkipPseudoOp = true) {
1456   return make_filter_range(make_range(It, End), [=](const MachineInstr &MI) {
1457     return !MI.isDebugInstr() && !(SkipPseudoOp && MI.isPseudoProbe());
1458   });
1459 }
1460 
1461 } // end namespace llvm
1462 
1463 #endif // LLVM_CODEGEN_MACHINEBASICBLOCK_H
1464