xref: /freebsd/contrib/llvm-project/llvm/include/llvm/CodeGen/MachineFunction.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1 //===- llvm/CodeGen/MachineFunction.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 native machine code for a function.  This class contains a list of
10 // MachineBasicBlock instances that make up the current compiled function.
11 //
12 // This class also contains pointers to various classes which hold
13 // target-specific information about the generated code.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #ifndef LLVM_CODEGEN_MACHINEFUNCTION_H
18 #define LLVM_CODEGEN_MACHINEFUNCTION_H
19 
20 #include "llvm/ADT/ArrayRef.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/GraphTraits.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/ilist.h"
25 #include "llvm/ADT/iterator.h"
26 #include "llvm/CodeGen/MachineBasicBlock.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineMemOperand.h"
29 #include "llvm/IR/EHPersonalities.h"
30 #include "llvm/Support/Allocator.h"
31 #include "llvm/Support/ArrayRecycler.h"
32 #include "llvm/Support/AtomicOrdering.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Recycler.h"
35 #include "llvm/Target/TargetOptions.h"
36 #include <bitset>
37 #include <cassert>
38 #include <cstdint>
39 #include <memory>
40 #include <utility>
41 #include <variant>
42 #include <vector>
43 
44 namespace llvm {
45 
46 class BasicBlock;
47 class BlockAddress;
48 class DataLayout;
49 class DebugLoc;
50 struct DenormalMode;
51 class DIExpression;
52 class DILocalVariable;
53 class DILocation;
54 class Function;
55 class GISelChangeObserver;
56 class GlobalValue;
57 class LLVMTargetMachine;
58 class MachineConstantPool;
59 class MachineFrameInfo;
60 class MachineFunction;
61 class MachineJumpTableInfo;
62 class MachineModuleInfo;
63 class MachineRegisterInfo;
64 class MCContext;
65 class MCInstrDesc;
66 class MCSymbol;
67 class MCSection;
68 class Pass;
69 class PseudoSourceValueManager;
70 class raw_ostream;
71 class SlotIndexes;
72 class StringRef;
73 class TargetRegisterClass;
74 class TargetSubtargetInfo;
75 struct WasmEHFuncInfo;
76 struct WinEHFuncInfo;
77 
78 template <> struct ilist_alloc_traits<MachineBasicBlock> {
79   void deleteNode(MachineBasicBlock *MBB);
80 };
81 
82 template <> struct ilist_callback_traits<MachineBasicBlock> {
83   void addNodeToList(MachineBasicBlock* N);
84   void removeNodeFromList(MachineBasicBlock* N);
85 
86   template <class Iterator>
87   void transferNodesFromList(ilist_callback_traits &OldList, Iterator, Iterator) {
88     assert(this == &OldList && "never transfer MBBs between functions");
89   }
90 };
91 
92 /// MachineFunctionInfo - This class can be derived from and used by targets to
93 /// hold private target-specific information for each MachineFunction.  Objects
94 /// of type are accessed/created with MF::getInfo and destroyed when the
95 /// MachineFunction is destroyed.
96 struct MachineFunctionInfo {
97   virtual ~MachineFunctionInfo();
98 
99   /// Factory function: default behavior is to call new using the
100   /// supplied allocator.
101   ///
102   /// This function can be overridden in a derive class.
103   template <typename FuncInfoTy, typename SubtargetTy = TargetSubtargetInfo>
104   static FuncInfoTy *create(BumpPtrAllocator &Allocator, const Function &F,
105                             const SubtargetTy *STI) {
106     return new (Allocator.Allocate<FuncInfoTy>()) FuncInfoTy(F, STI);
107   }
108 
109   template <typename Ty>
110   static Ty *create(BumpPtrAllocator &Allocator, const Ty &MFI) {
111     return new (Allocator.Allocate<Ty>()) Ty(MFI);
112   }
113 
114   /// Make a functionally equivalent copy of this MachineFunctionInfo in \p MF.
115   /// This requires remapping MachineBasicBlock references from the original
116   /// parent to values in the new function. Targets may assume that virtual
117   /// register and frame index values are preserved in the new function.
118   virtual MachineFunctionInfo *
119   clone(BumpPtrAllocator &Allocator, MachineFunction &DestMF,
120         const DenseMap<MachineBasicBlock *, MachineBasicBlock *> &Src2DstMBB)
121       const {
122     return nullptr;
123   }
124 };
125 
126 /// Properties which a MachineFunction may have at a given point in time.
127 /// Each of these has checking code in the MachineVerifier, and passes can
128 /// require that a property be set.
129 class MachineFunctionProperties {
130   // Possible TODO: Allow targets to extend this (perhaps by allowing the
131   // constructor to specify the size of the bit vector)
132   // Possible TODO: Allow requiring the negative (e.g. VRegsAllocated could be
133   // stated as the negative of "has vregs"
134 
135 public:
136   // The properties are stated in "positive" form; i.e. a pass could require
137   // that the property hold, but not that it does not hold.
138 
139   // Property descriptions:
140   // IsSSA: True when the machine function is in SSA form and virtual registers
141   //  have a single def.
142   // NoPHIs: The machine function does not contain any PHI instruction.
143   // TracksLiveness: True when tracking register liveness accurately.
144   //  While this property is set, register liveness information in basic block
145   //  live-in lists and machine instruction operands (e.g. implicit defs) is
146   //  accurate, kill flags are conservatively accurate (kill flag correctly
147   //  indicates the last use of a register, an operand without kill flag may or
148   //  may not be the last use of a register). This means it can be used to
149   //  change the code in ways that affect the values in registers, for example
150   //  by the register scavenger.
151   //  When this property is cleared at a very late time, liveness is no longer
152   //  reliable.
153   // NoVRegs: The machine function does not use any virtual registers.
154   // Legalized: In GlobalISel: the MachineLegalizer ran and all pre-isel generic
155   //  instructions have been legalized; i.e., all instructions are now one of:
156   //   - generic and always legal (e.g., COPY)
157   //   - target-specific
158   //   - legal pre-isel generic instructions.
159   // RegBankSelected: In GlobalISel: the RegBankSelect pass ran and all generic
160   //  virtual registers have been assigned to a register bank.
161   // Selected: In GlobalISel: the InstructionSelect pass ran and all pre-isel
162   //  generic instructions have been eliminated; i.e., all instructions are now
163   //  target-specific or non-pre-isel generic instructions (e.g., COPY).
164   //  Since only pre-isel generic instructions can have generic virtual register
165   //  operands, this also means that all generic virtual registers have been
166   //  constrained to virtual registers (assigned to register classes) and that
167   //  all sizes attached to them have been eliminated.
168   // TiedOpsRewritten: The twoaddressinstruction pass will set this flag, it
169   //  means that tied-def have been rewritten to meet the RegConstraint.
170   // FailsVerification: Means that the function is not expected to pass machine
171   //  verification. This can be set by passes that introduce known problems that
172   //  have not been fixed yet.
173   // TracksDebugUserValues: Without this property enabled, debug instructions
174   // such as DBG_VALUE are allowed to reference virtual registers even if those
175   // registers do not have a definition. With the property enabled virtual
176   // registers must only be used if they have a definition. This property
177   // allows earlier passes in the pipeline to skip updates of `DBG_VALUE`
178   // instructions to save compile time.
179   enum class Property : unsigned {
180     IsSSA,
181     NoPHIs,
182     TracksLiveness,
183     NoVRegs,
184     FailedISel,
185     Legalized,
186     RegBankSelected,
187     Selected,
188     TiedOpsRewritten,
189     FailsVerification,
190     TracksDebugUserValues,
191     LastProperty = TracksDebugUserValues,
192   };
193 
194   bool hasProperty(Property P) const {
195     return Properties[static_cast<unsigned>(P)];
196   }
197 
198   MachineFunctionProperties &set(Property P) {
199     Properties.set(static_cast<unsigned>(P));
200     return *this;
201   }
202 
203   MachineFunctionProperties &reset(Property P) {
204     Properties.reset(static_cast<unsigned>(P));
205     return *this;
206   }
207 
208   /// Reset all the properties.
209   MachineFunctionProperties &reset() {
210     Properties.reset();
211     return *this;
212   }
213 
214   MachineFunctionProperties &set(const MachineFunctionProperties &MFP) {
215     Properties |= MFP.Properties;
216     return *this;
217   }
218 
219   MachineFunctionProperties &reset(const MachineFunctionProperties &MFP) {
220     Properties &= ~MFP.Properties;
221     return *this;
222   }
223 
224   // Returns true if all properties set in V (i.e. required by a pass) are set
225   // in this.
226   bool verifyRequiredProperties(const MachineFunctionProperties &V) const {
227     return (Properties | ~V.Properties).all();
228   }
229 
230   /// Print the MachineFunctionProperties in human-readable form.
231   void print(raw_ostream &OS) const;
232 
233 private:
234   std::bitset<static_cast<unsigned>(Property::LastProperty) + 1> Properties;
235 };
236 
237 struct SEHHandler {
238   /// Filter or finally function. Null indicates a catch-all.
239   const Function *FilterOrFinally;
240 
241   /// Address of block to recover at. Null for a finally handler.
242   const BlockAddress *RecoverBA;
243 };
244 
245 /// This structure is used to retain landing pad info for the current function.
246 struct LandingPadInfo {
247   MachineBasicBlock *LandingPadBlock;      // Landing pad block.
248   SmallVector<MCSymbol *, 1> BeginLabels;  // Labels prior to invoke.
249   SmallVector<MCSymbol *, 1> EndLabels;    // Labels after invoke.
250   SmallVector<SEHHandler, 1> SEHHandlers;  // SEH handlers active at this lpad.
251   MCSymbol *LandingPadLabel = nullptr;     // Label at beginning of landing pad.
252   std::vector<int> TypeIds;                // List of type ids (filters negative).
253 
254   explicit LandingPadInfo(MachineBasicBlock *MBB)
255       : LandingPadBlock(MBB) {}
256 };
257 
258 class LLVM_EXTERNAL_VISIBILITY MachineFunction {
259   Function &F;
260   const LLVMTargetMachine &Target;
261   const TargetSubtargetInfo *STI;
262   MCContext &Ctx;
263   MachineModuleInfo &MMI;
264 
265   // RegInfo - Information about each register in use in the function.
266   MachineRegisterInfo *RegInfo;
267 
268   // Used to keep track of target-specific per-machine-function information for
269   // the target implementation.
270   MachineFunctionInfo *MFInfo;
271 
272   // Keep track of objects allocated on the stack.
273   MachineFrameInfo *FrameInfo;
274 
275   // Keep track of constants which are spilled to memory
276   MachineConstantPool *ConstantPool;
277 
278   // Keep track of jump tables for switch instructions
279   MachineJumpTableInfo *JumpTableInfo;
280 
281   // Keep track of the function section.
282   MCSection *Section = nullptr;
283 
284   // Catchpad unwind destination info for wasm EH.
285   // Keeps track of Wasm exception handling related data. This will be null for
286   // functions that aren't using a wasm EH personality.
287   WasmEHFuncInfo *WasmEHInfo = nullptr;
288 
289   // Keeps track of Windows exception handling related data. This will be null
290   // for functions that aren't using a funclet-based EH personality.
291   WinEHFuncInfo *WinEHInfo = nullptr;
292 
293   // Function-level unique numbering for MachineBasicBlocks.  When a
294   // MachineBasicBlock is inserted into a MachineFunction is it automatically
295   // numbered and this vector keeps track of the mapping from ID's to MBB's.
296   std::vector<MachineBasicBlock*> MBBNumbering;
297 
298   // Pool-allocate MachineFunction-lifetime and IR objects.
299   BumpPtrAllocator Allocator;
300 
301   // Allocation management for instructions in function.
302   Recycler<MachineInstr> InstructionRecycler;
303 
304   // Allocation management for operand arrays on instructions.
305   ArrayRecycler<MachineOperand> OperandRecycler;
306 
307   // Allocation management for basic blocks in function.
308   Recycler<MachineBasicBlock> BasicBlockRecycler;
309 
310   // List of machine basic blocks in function
311   using BasicBlockListType = ilist<MachineBasicBlock>;
312   BasicBlockListType BasicBlocks;
313 
314   /// FunctionNumber - This provides a unique ID for each function emitted in
315   /// this translation unit.
316   ///
317   unsigned FunctionNumber;
318 
319   /// Alignment - The alignment of the function.
320   Align Alignment;
321 
322   /// ExposesReturnsTwice - True if the function calls setjmp or related
323   /// functions with attribute "returns twice", but doesn't have
324   /// the attribute itself.
325   /// This is used to limit optimizations which cannot reason
326   /// about the control flow of such functions.
327   bool ExposesReturnsTwice = false;
328 
329   /// True if the function includes any inline assembly.
330   bool HasInlineAsm = false;
331 
332   /// True if any WinCFI instruction have been emitted in this function.
333   bool HasWinCFI = false;
334 
335   /// Current high-level properties of the IR of the function (e.g. is in SSA
336   /// form or whether registers have been allocated)
337   MachineFunctionProperties Properties;
338 
339   // Allocation management for pseudo source values.
340   std::unique_ptr<PseudoSourceValueManager> PSVManager;
341 
342   /// List of moves done by a function's prolog.  Used to construct frame maps
343   /// by debug and exception handling consumers.
344   std::vector<MCCFIInstruction> FrameInstructions;
345 
346   /// List of basic blocks immediately following calls to _setjmp. Used to
347   /// construct a table of valid longjmp targets for Windows Control Flow Guard.
348   std::vector<MCSymbol *> LongjmpTargets;
349 
350   /// List of basic blocks that are the target of catchrets. Used to construct
351   /// a table of valid targets for Windows EHCont Guard.
352   std::vector<MCSymbol *> CatchretTargets;
353 
354   /// \name Exception Handling
355   /// \{
356 
357   /// List of LandingPadInfo describing the landing pad information.
358   std::vector<LandingPadInfo> LandingPads;
359 
360   /// Map a landing pad's EH symbol to the call site indexes.
361   DenseMap<MCSymbol*, SmallVector<unsigned, 4>> LPadToCallSiteMap;
362 
363   /// Map a landing pad to its index.
364   DenseMap<const MachineBasicBlock *, unsigned> WasmLPadToIndexMap;
365 
366   /// Map of invoke call site index values to associated begin EH_LABEL.
367   DenseMap<MCSymbol*, unsigned> CallSiteMap;
368 
369   /// CodeView label annotations.
370   std::vector<std::pair<MCSymbol *, MDNode *>> CodeViewAnnotations;
371 
372   bool CallsEHReturn = false;
373   bool CallsUnwindInit = false;
374   bool HasEHCatchret = false;
375   bool HasEHScopes = false;
376   bool HasEHFunclets = false;
377   bool IsOutlined = false;
378 
379   /// BBID to assign to the next basic block of this function.
380   unsigned NextBBID = 0;
381 
382   /// Section Type for basic blocks, only relevant with basic block sections.
383   BasicBlockSection BBSectionsType = BasicBlockSection::None;
384 
385   /// List of C++ TypeInfo used.
386   std::vector<const GlobalValue *> TypeInfos;
387 
388   /// List of typeids encoding filters used.
389   std::vector<unsigned> FilterIds;
390 
391   /// List of the indices in FilterIds corresponding to filter terminators.
392   std::vector<unsigned> FilterEnds;
393 
394   EHPersonality PersonalityTypeCache = EHPersonality::Unknown;
395 
396   /// \}
397 
398   /// Clear all the members of this MachineFunction, but the ones used
399   /// to initialize again the MachineFunction.
400   /// More specifically, this deallocates all the dynamically allocated
401   /// objects and get rid of all the XXXInfo data structure, but keep
402   /// unchanged the references to Fn, Target, MMI, and FunctionNumber.
403   void clear();
404   /// Allocate and initialize the different members.
405   /// In particular, the XXXInfo data structure.
406   /// \pre Fn, Target, MMI, and FunctionNumber are properly set.
407   void init();
408 
409 public:
410   /// Description of the location of a variable whose Address is valid and
411   /// unchanging during function execution. The Address may be:
412   /// * A stack index, which can be negative for fixed stack objects.
413   /// * A MCRegister, whose entry value contains the address of the variable.
414   class VariableDbgInfo {
415     std::variant<int, MCRegister> Address;
416 
417   public:
418     const DILocalVariable *Var;
419     const DIExpression *Expr;
420     const DILocation *Loc;
421 
422     VariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
423                     int Slot, const DILocation *Loc)
424         : Address(Slot), Var(Var), Expr(Expr), Loc(Loc) {}
425 
426     VariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
427                     MCRegister EntryValReg, const DILocation *Loc)
428         : Address(EntryValReg), Var(Var), Expr(Expr), Loc(Loc) {}
429 
430     /// Return true if this variable is in a stack slot.
431     bool inStackSlot() const { return std::holds_alternative<int>(Address); }
432 
433     /// Return true if this variable is in the entry value of a register.
434     bool inEntryValueRegister() const {
435       return std::holds_alternative<MCRegister>(Address);
436     }
437 
438     /// Returns the stack slot of this variable, assuming `inStackSlot()` is
439     /// true.
440     int getStackSlot() const { return std::get<int>(Address); }
441 
442     /// Returns the MCRegister of this variable, assuming
443     /// `inEntryValueRegister()` is true.
444     MCRegister getEntryValueRegister() const {
445       return std::get<MCRegister>(Address);
446     }
447 
448     /// Updates the stack slot of this variable, assuming `inStackSlot()` is
449     /// true.
450     void updateStackSlot(int NewSlot) {
451       assert(inStackSlot());
452       Address = NewSlot;
453     }
454   };
455 
456   class Delegate {
457     virtual void anchor();
458 
459   public:
460     virtual ~Delegate() = default;
461     /// Callback after an insertion. This should not modify the MI directly.
462     virtual void MF_HandleInsertion(MachineInstr &MI) = 0;
463     /// Callback before a removal. This should not modify the MI directly.
464     virtual void MF_HandleRemoval(MachineInstr &MI) = 0;
465     /// Callback before changing MCInstrDesc. This should not modify the MI
466     /// directly.
467     virtual void MF_HandleChangeDesc(MachineInstr &MI, const MCInstrDesc &TID) {
468       return;
469     }
470   };
471 
472   /// Structure used to represent pair of argument number after call lowering
473   /// and register used to transfer that argument.
474   /// For now we support only cases when argument is transferred through one
475   /// register.
476   struct ArgRegPair {
477     Register Reg;
478     uint16_t ArgNo;
479     ArgRegPair(Register R, unsigned Arg) : Reg(R), ArgNo(Arg) {
480       assert(Arg < (1 << 16) && "Arg out of range");
481     }
482   };
483 
484   struct CallSiteInfo {
485     /// Vector of call argument and its forwarding register.
486     SmallVector<ArgRegPair, 1> ArgRegPairs;
487   };
488 
489 private:
490   Delegate *TheDelegate = nullptr;
491   GISelChangeObserver *Observer = nullptr;
492 
493   using CallSiteInfoMap = DenseMap<const MachineInstr *, CallSiteInfo>;
494   /// Map a call instruction to call site arguments forwarding info.
495   CallSiteInfoMap CallSitesInfo;
496 
497   /// A helper function that returns call site info for a give call
498   /// instruction if debug entry value support is enabled.
499   CallSiteInfoMap::iterator getCallSiteInfo(const MachineInstr *MI);
500 
501   // Callbacks for insertion and removal.
502   void handleInsertion(MachineInstr &MI);
503   void handleRemoval(MachineInstr &MI);
504   friend struct ilist_traits<MachineInstr>;
505 
506 public:
507   // Need to be accessed from MachineInstr::setDesc.
508   void handleChangeDesc(MachineInstr &MI, const MCInstrDesc &TID);
509 
510   using VariableDbgInfoMapTy = SmallVector<VariableDbgInfo, 4>;
511   VariableDbgInfoMapTy VariableDbgInfos;
512 
513   /// A count of how many instructions in the function have had numbers
514   /// assigned to them. Used for debug value tracking, to determine the
515   /// next instruction number.
516   unsigned DebugInstrNumberingCount = 0;
517 
518   /// Set value of DebugInstrNumberingCount field. Avoid using this unless
519   /// you're deserializing this data.
520   void setDebugInstrNumberingCount(unsigned Num);
521 
522   /// Pair of instruction number and operand number.
523   using DebugInstrOperandPair = std::pair<unsigned, unsigned>;
524 
525   /// Replacement definition for a debug instruction reference. Made up of a
526   /// source instruction / operand pair, destination pair, and a qualifying
527   /// subregister indicating what bits in the operand make up the substitution.
528   // For example, a debug user
529   /// of %1:
530   ///    %0:gr32 = someinst, debug-instr-number 1
531   ///    %1:gr16 = %0.some_16_bit_subreg, debug-instr-number 2
532   /// Would receive the substitution {{2, 0}, {1, 0}, $subreg}, where $subreg is
533   /// the subregister number for some_16_bit_subreg.
534   class DebugSubstitution {
535   public:
536     DebugInstrOperandPair Src;  ///< Source instruction / operand pair.
537     DebugInstrOperandPair Dest; ///< Replacement instruction / operand pair.
538     unsigned Subreg;            ///< Qualifier for which part of Dest is read.
539 
540     DebugSubstitution(const DebugInstrOperandPair &Src,
541                       const DebugInstrOperandPair &Dest, unsigned Subreg)
542         : Src(Src), Dest(Dest), Subreg(Subreg) {}
543 
544     /// Order only by source instruction / operand pair: there should never
545     /// be duplicate entries for the same source in any collection.
546     bool operator<(const DebugSubstitution &Other) const {
547       return Src < Other.Src;
548     }
549   };
550 
551   /// Debug value substitutions: a collection of DebugSubstitution objects,
552   /// recording changes in where a value is defined. For example, when one
553   /// instruction is substituted for another. Keeping a record allows recovery
554   /// of variable locations after compilation finishes.
555   SmallVector<DebugSubstitution, 8> DebugValueSubstitutions;
556 
557   /// Location of a PHI instruction that is also a debug-info variable value,
558   /// for the duration of register allocation. Loaded by the PHI-elimination
559   /// pass, and emitted as DBG_PHI instructions during VirtRegRewriter, with
560   /// maintenance applied by intermediate passes that edit registers (such as
561   /// coalescing and the allocator passes).
562   class DebugPHIRegallocPos {
563   public:
564     MachineBasicBlock *MBB; ///< Block where this PHI was originally located.
565     Register Reg;           ///< VReg where the control-flow-merge happens.
566     unsigned SubReg;        ///< Optional subreg qualifier within Reg.
567     DebugPHIRegallocPos(MachineBasicBlock *MBB, Register Reg, unsigned SubReg)
568         : MBB(MBB), Reg(Reg), SubReg(SubReg) {}
569   };
570 
571   /// Map of debug instruction numbers to the position of their PHI instructions
572   /// during register allocation. See DebugPHIRegallocPos.
573   DenseMap<unsigned, DebugPHIRegallocPos> DebugPHIPositions;
574 
575   /// Flag for whether this function contains DBG_VALUEs (false) or
576   /// DBG_INSTR_REF (true).
577   bool UseDebugInstrRef = false;
578 
579   /// Create a substitution between one <instr,operand> value to a different,
580   /// new value.
581   void makeDebugValueSubstitution(DebugInstrOperandPair, DebugInstrOperandPair,
582                                   unsigned SubReg = 0);
583 
584   /// Create substitutions for any tracked values in \p Old, to point at
585   /// \p New. Needed when we re-create an instruction during optimization,
586   /// which has the same signature (i.e., def operands in the same place) but
587   /// a modified instruction type, flags, or otherwise. An example: X86 moves
588   /// are sometimes transformed into equivalent LEAs.
589   /// If the two instructions are not the same opcode, limit which operands to
590   /// examine for substitutions to the first N operands by setting
591   /// \p MaxOperand.
592   void substituteDebugValuesForInst(const MachineInstr &Old, MachineInstr &New,
593                                     unsigned MaxOperand = UINT_MAX);
594 
595   /// Find the underlying  defining instruction / operand for a COPY instruction
596   /// while in SSA form. Copies do not actually define values -- they move them
597   /// between registers. Labelling a COPY-like instruction with an instruction
598   /// number is to be avoided as it makes value numbers non-unique later in
599   /// compilation. This method follows the definition chain for any sequence of
600   /// COPY-like instructions to find whatever non-COPY-like instruction defines
601   /// the copied value; or for parameters, creates a DBG_PHI on entry.
602   /// May insert instructions into the entry block!
603   /// \p MI The copy-like instruction to salvage.
604   /// \p DbgPHICache A container to cache already-solved COPYs.
605   /// \returns An instruction/operand pair identifying the defining value.
606   DebugInstrOperandPair
607   salvageCopySSA(MachineInstr &MI,
608                  DenseMap<Register, DebugInstrOperandPair> &DbgPHICache);
609 
610   DebugInstrOperandPair salvageCopySSAImpl(MachineInstr &MI);
611 
612   /// Finalise any partially emitted debug instructions. These are DBG_INSTR_REF
613   /// instructions where we only knew the vreg of the value they use, not the
614   /// instruction that defines that vreg. Once isel finishes, we should have
615   /// enough information for every DBG_INSTR_REF to point at an instruction
616   /// (or DBG_PHI).
617   void finalizeDebugInstrRefs();
618 
619   /// Determine whether, in the current machine configuration, we should use
620   /// instruction referencing or not.
621   bool shouldUseDebugInstrRef() const;
622 
623   /// Returns true if the function's variable locations are tracked with
624   /// instruction referencing.
625   bool useDebugInstrRef() const;
626 
627   /// Set whether this function will use instruction referencing or not.
628   void setUseDebugInstrRef(bool UseInstrRef);
629 
630   /// A reserved operand number representing the instructions memory operand,
631   /// for instructions that have a stack spill fused into them.
632   const static unsigned int DebugOperandMemNumber;
633 
634   MachineFunction(Function &F, const LLVMTargetMachine &Target,
635                   const TargetSubtargetInfo &STI, unsigned FunctionNum,
636                   MachineModuleInfo &MMI);
637   MachineFunction(const MachineFunction &) = delete;
638   MachineFunction &operator=(const MachineFunction &) = delete;
639   ~MachineFunction();
640 
641   /// Reset the instance as if it was just created.
642   void reset() {
643     clear();
644     init();
645   }
646 
647   /// Reset the currently registered delegate - otherwise assert.
648   void resetDelegate(Delegate *delegate) {
649     assert(TheDelegate == delegate &&
650            "Only the current delegate can perform reset!");
651     TheDelegate = nullptr;
652   }
653 
654   /// Set the delegate. resetDelegate must be called before attempting
655   /// to set.
656   void setDelegate(Delegate *delegate) {
657     assert(delegate && !TheDelegate &&
658            "Attempted to set delegate to null, or to change it without "
659            "first resetting it!");
660 
661     TheDelegate = delegate;
662   }
663 
664   void setObserver(GISelChangeObserver *O) { Observer = O; }
665 
666   GISelChangeObserver *getObserver() const { return Observer; }
667 
668   MachineModuleInfo &getMMI() const { return MMI; }
669   MCContext &getContext() const { return Ctx; }
670 
671   /// Returns the Section this function belongs to.
672   MCSection *getSection() const { return Section; }
673 
674   /// Indicates the Section this function belongs to.
675   void setSection(MCSection *S) { Section = S; }
676 
677   PseudoSourceValueManager &getPSVManager() const { return *PSVManager; }
678 
679   /// Return the DataLayout attached to the Module associated to this MF.
680   const DataLayout &getDataLayout() const;
681 
682   /// Return the LLVM function that this machine code represents
683   Function &getFunction() { return F; }
684 
685   /// Return the LLVM function that this machine code represents
686   const Function &getFunction() const { return F; }
687 
688   /// getName - Return the name of the corresponding LLVM function.
689   StringRef getName() const;
690 
691   /// getFunctionNumber - Return a unique ID for the current function.
692   unsigned getFunctionNumber() const { return FunctionNumber; }
693 
694   /// Returns true if this function has basic block sections enabled.
695   bool hasBBSections() const {
696     return (BBSectionsType == BasicBlockSection::All ||
697             BBSectionsType == BasicBlockSection::List ||
698             BBSectionsType == BasicBlockSection::Preset);
699   }
700 
701   /// Returns true if basic block labels are to be generated for this function.
702   bool hasBBLabels() const {
703     return BBSectionsType == BasicBlockSection::Labels;
704   }
705 
706   void setBBSectionsType(BasicBlockSection V) { BBSectionsType = V; }
707 
708   /// Assign IsBeginSection IsEndSection fields for basic blocks in this
709   /// function.
710   void assignBeginEndSections();
711 
712   /// getTarget - Return the target machine this machine code is compiled with
713   const LLVMTargetMachine &getTarget() const { return Target; }
714 
715   /// getSubtarget - Return the subtarget for which this machine code is being
716   /// compiled.
717   const TargetSubtargetInfo &getSubtarget() const { return *STI; }
718 
719   /// getSubtarget - This method returns a pointer to the specified type of
720   /// TargetSubtargetInfo.  In debug builds, it verifies that the object being
721   /// returned is of the correct type.
722   template<typename STC> const STC &getSubtarget() const {
723     return *static_cast<const STC *>(STI);
724   }
725 
726   /// getRegInfo - Return information about the registers currently in use.
727   MachineRegisterInfo &getRegInfo() { return *RegInfo; }
728   const MachineRegisterInfo &getRegInfo() const { return *RegInfo; }
729 
730   /// getFrameInfo - Return the frame info object for the current function.
731   /// This object contains information about objects allocated on the stack
732   /// frame of the current function in an abstract way.
733   MachineFrameInfo &getFrameInfo() { return *FrameInfo; }
734   const MachineFrameInfo &getFrameInfo() const { return *FrameInfo; }
735 
736   /// getJumpTableInfo - Return the jump table info object for the current
737   /// function.  This object contains information about jump tables in the
738   /// current function.  If the current function has no jump tables, this will
739   /// return null.
740   const MachineJumpTableInfo *getJumpTableInfo() const { return JumpTableInfo; }
741   MachineJumpTableInfo *getJumpTableInfo() { return JumpTableInfo; }
742 
743   /// getOrCreateJumpTableInfo - Get the JumpTableInfo for this function, if it
744   /// does already exist, allocate one.
745   MachineJumpTableInfo *getOrCreateJumpTableInfo(unsigned JTEntryKind);
746 
747   /// getConstantPool - Return the constant pool object for the current
748   /// function.
749   MachineConstantPool *getConstantPool() { return ConstantPool; }
750   const MachineConstantPool *getConstantPool() const { return ConstantPool; }
751 
752   /// getWasmEHFuncInfo - Return information about how the current function uses
753   /// Wasm exception handling. Returns null for functions that don't use wasm
754   /// exception handling.
755   const WasmEHFuncInfo *getWasmEHFuncInfo() const { return WasmEHInfo; }
756   WasmEHFuncInfo *getWasmEHFuncInfo() { return WasmEHInfo; }
757 
758   /// getWinEHFuncInfo - Return information about how the current function uses
759   /// Windows exception handling. Returns null for functions that don't use
760   /// funclets for exception handling.
761   const WinEHFuncInfo *getWinEHFuncInfo() const { return WinEHInfo; }
762   WinEHFuncInfo *getWinEHFuncInfo() { return WinEHInfo; }
763 
764   /// getAlignment - Return the alignment of the function.
765   Align getAlignment() const { return Alignment; }
766 
767   /// setAlignment - Set the alignment of the function.
768   void setAlignment(Align A) { Alignment = A; }
769 
770   /// ensureAlignment - Make sure the function is at least A bytes aligned.
771   void ensureAlignment(Align A) {
772     if (Alignment < A)
773       Alignment = A;
774   }
775 
776   /// exposesReturnsTwice - Returns true if the function calls setjmp or
777   /// any other similar functions with attribute "returns twice" without
778   /// having the attribute itself.
779   bool exposesReturnsTwice() const {
780     return ExposesReturnsTwice;
781   }
782 
783   /// setCallsSetJmp - Set a flag that indicates if there's a call to
784   /// a "returns twice" function.
785   void setExposesReturnsTwice(bool B) {
786     ExposesReturnsTwice = B;
787   }
788 
789   /// Returns true if the function contains any inline assembly.
790   bool hasInlineAsm() const {
791     return HasInlineAsm;
792   }
793 
794   /// Set a flag that indicates that the function contains inline assembly.
795   void setHasInlineAsm(bool B) {
796     HasInlineAsm = B;
797   }
798 
799   bool hasWinCFI() const {
800     return HasWinCFI;
801   }
802   void setHasWinCFI(bool v) { HasWinCFI = v; }
803 
804   /// True if this function needs frame moves for debug or exceptions.
805   bool needsFrameMoves() const;
806 
807   /// Get the function properties
808   const MachineFunctionProperties &getProperties() const { return Properties; }
809   MachineFunctionProperties &getProperties() { return Properties; }
810 
811   /// getInfo - Keep track of various per-function pieces of information for
812   /// backends that would like to do so.
813   ///
814   template<typename Ty>
815   Ty *getInfo() {
816     return static_cast<Ty*>(MFInfo);
817   }
818 
819   template<typename Ty>
820   const Ty *getInfo() const {
821     return static_cast<const Ty *>(MFInfo);
822   }
823 
824   template <typename Ty> Ty *cloneInfo(const Ty &Old) {
825     assert(!MFInfo);
826     MFInfo = Ty::template create<Ty>(Allocator, Old);
827     return static_cast<Ty *>(MFInfo);
828   }
829 
830   /// Initialize the target specific MachineFunctionInfo
831   void initTargetMachineFunctionInfo(const TargetSubtargetInfo &STI);
832 
833   MachineFunctionInfo *cloneInfoFrom(
834       const MachineFunction &OrigMF,
835       const DenseMap<MachineBasicBlock *, MachineBasicBlock *> &Src2DstMBB) {
836     assert(!MFInfo && "new function already has MachineFunctionInfo");
837     if (!OrigMF.MFInfo)
838       return nullptr;
839     return OrigMF.MFInfo->clone(Allocator, *this, Src2DstMBB);
840   }
841 
842   /// Returns the denormal handling type for the default rounding mode of the
843   /// function.
844   DenormalMode getDenormalMode(const fltSemantics &FPType) const;
845 
846   /// getBlockNumbered - MachineBasicBlocks are automatically numbered when they
847   /// are inserted into the machine function.  The block number for a machine
848   /// basic block can be found by using the MBB::getNumber method, this method
849   /// provides the inverse mapping.
850   MachineBasicBlock *getBlockNumbered(unsigned N) const {
851     assert(N < MBBNumbering.size() && "Illegal block number");
852     assert(MBBNumbering[N] && "Block was removed from the machine function!");
853     return MBBNumbering[N];
854   }
855 
856   /// Should we be emitting segmented stack stuff for the function
857   bool shouldSplitStack() const;
858 
859   /// getNumBlockIDs - Return the number of MBB ID's allocated.
860   unsigned getNumBlockIDs() const { return (unsigned)MBBNumbering.size(); }
861 
862   /// RenumberBlocks - This discards all of the MachineBasicBlock numbers and
863   /// recomputes them.  This guarantees that the MBB numbers are sequential,
864   /// dense, and match the ordering of the blocks within the function.  If a
865   /// specific MachineBasicBlock is specified, only that block and those after
866   /// it are renumbered.
867   void RenumberBlocks(MachineBasicBlock *MBBFrom = nullptr);
868 
869   /// print - Print out the MachineFunction in a format suitable for debugging
870   /// to the specified stream.
871   void print(raw_ostream &OS, const SlotIndexes* = nullptr) const;
872 
873   /// viewCFG - This function is meant for use from the debugger.  You can just
874   /// say 'call F->viewCFG()' and a ghostview window should pop up from the
875   /// program, displaying the CFG of the current function with the code for each
876   /// basic block inside.  This depends on there being a 'dot' and 'gv' program
877   /// in your path.
878   void viewCFG() const;
879 
880   /// viewCFGOnly - This function is meant for use from the debugger.  It works
881   /// just like viewCFG, but it does not include the contents of basic blocks
882   /// into the nodes, just the label.  If you are only interested in the CFG
883   /// this can make the graph smaller.
884   ///
885   void viewCFGOnly() const;
886 
887   /// dump - Print the current MachineFunction to cerr, useful for debugger use.
888   void dump() const;
889 
890   /// Run the current MachineFunction through the machine code verifier, useful
891   /// for debugger use.
892   /// \returns true if no problems were found.
893   bool verify(Pass *p = nullptr, const char *Banner = nullptr,
894               bool AbortOnError = true) const;
895 
896   /// Run the current MachineFunction through the machine code verifier, useful
897   /// for debugger use.
898   /// \returns true if no problems were found.
899   bool verify(LiveIntervals *LiveInts, SlotIndexes *Indexes,
900               const char *Banner = nullptr, bool AbortOnError = true) const;
901 
902   // Provide accessors for the MachineBasicBlock list...
903   using iterator = BasicBlockListType::iterator;
904   using const_iterator = BasicBlockListType::const_iterator;
905   using const_reverse_iterator = BasicBlockListType::const_reverse_iterator;
906   using reverse_iterator = BasicBlockListType::reverse_iterator;
907 
908   /// Support for MachineBasicBlock::getNextNode().
909   static BasicBlockListType MachineFunction::*
910   getSublistAccess(MachineBasicBlock *) {
911     return &MachineFunction::BasicBlocks;
912   }
913 
914   /// addLiveIn - Add the specified physical register as a live-in value and
915   /// create a corresponding virtual register for it.
916   Register addLiveIn(MCRegister PReg, const TargetRegisterClass *RC);
917 
918   //===--------------------------------------------------------------------===//
919   // BasicBlock accessor functions.
920   //
921   iterator                 begin()       { return BasicBlocks.begin(); }
922   const_iterator           begin() const { return BasicBlocks.begin(); }
923   iterator                 end  ()       { return BasicBlocks.end();   }
924   const_iterator           end  () const { return BasicBlocks.end();   }
925 
926   reverse_iterator        rbegin()       { return BasicBlocks.rbegin(); }
927   const_reverse_iterator  rbegin() const { return BasicBlocks.rbegin(); }
928   reverse_iterator        rend  ()       { return BasicBlocks.rend();   }
929   const_reverse_iterator  rend  () const { return BasicBlocks.rend();   }
930 
931   unsigned                  size() const { return (unsigned)BasicBlocks.size();}
932   bool                     empty() const { return BasicBlocks.empty(); }
933   const MachineBasicBlock &front() const { return BasicBlocks.front(); }
934         MachineBasicBlock &front()       { return BasicBlocks.front(); }
935   const MachineBasicBlock & back() const { return BasicBlocks.back(); }
936         MachineBasicBlock & back()       { return BasicBlocks.back(); }
937 
938   void push_back (MachineBasicBlock *MBB) { BasicBlocks.push_back (MBB); }
939   void push_front(MachineBasicBlock *MBB) { BasicBlocks.push_front(MBB); }
940   void insert(iterator MBBI, MachineBasicBlock *MBB) {
941     BasicBlocks.insert(MBBI, MBB);
942   }
943   void splice(iterator InsertPt, iterator MBBI) {
944     BasicBlocks.splice(InsertPt, BasicBlocks, MBBI);
945   }
946   void splice(iterator InsertPt, MachineBasicBlock *MBB) {
947     BasicBlocks.splice(InsertPt, BasicBlocks, MBB);
948   }
949   void splice(iterator InsertPt, iterator MBBI, iterator MBBE) {
950     BasicBlocks.splice(InsertPt, BasicBlocks, MBBI, MBBE);
951   }
952 
953   void remove(iterator MBBI) { BasicBlocks.remove(MBBI); }
954   void remove(MachineBasicBlock *MBBI) { BasicBlocks.remove(MBBI); }
955   void erase(iterator MBBI) { BasicBlocks.erase(MBBI); }
956   void erase(MachineBasicBlock *MBBI) { BasicBlocks.erase(MBBI); }
957 
958   template <typename Comp>
959   void sort(Comp comp) {
960     BasicBlocks.sort(comp);
961   }
962 
963   /// Return the number of \p MachineInstrs in this \p MachineFunction.
964   unsigned getInstructionCount() const {
965     unsigned InstrCount = 0;
966     for (const MachineBasicBlock &MBB : BasicBlocks)
967       InstrCount += MBB.size();
968     return InstrCount;
969   }
970 
971   //===--------------------------------------------------------------------===//
972   // Internal functions used to automatically number MachineBasicBlocks
973 
974   /// Adds the MBB to the internal numbering. Returns the unique number
975   /// assigned to the MBB.
976   unsigned addToMBBNumbering(MachineBasicBlock *MBB) {
977     MBBNumbering.push_back(MBB);
978     return (unsigned)MBBNumbering.size()-1;
979   }
980 
981   /// removeFromMBBNumbering - Remove the specific machine basic block from our
982   /// tracker, this is only really to be used by the MachineBasicBlock
983   /// implementation.
984   void removeFromMBBNumbering(unsigned N) {
985     assert(N < MBBNumbering.size() && "Illegal basic block #");
986     MBBNumbering[N] = nullptr;
987   }
988 
989   /// CreateMachineInstr - Allocate a new MachineInstr. Use this instead
990   /// of `new MachineInstr'.
991   MachineInstr *CreateMachineInstr(const MCInstrDesc &MCID, DebugLoc DL,
992                                    bool NoImplicit = false);
993 
994   /// Create a new MachineInstr which is a copy of \p Orig, identical in all
995   /// ways except the instruction has no parent, prev, or next. Bundling flags
996   /// are reset.
997   ///
998   /// Note: Clones a single instruction, not whole instruction bundles.
999   /// Does not perform target specific adjustments; consider using
1000   /// TargetInstrInfo::duplicate() instead.
1001   MachineInstr *CloneMachineInstr(const MachineInstr *Orig);
1002 
1003   /// Clones instruction or the whole instruction bundle \p Orig and insert
1004   /// into \p MBB before \p InsertBefore.
1005   ///
1006   /// Note: Does not perform target specific adjustments; consider using
1007   /// TargetInstrInfo::duplicate() intead.
1008   MachineInstr &
1009   cloneMachineInstrBundle(MachineBasicBlock &MBB,
1010                           MachineBasicBlock::iterator InsertBefore,
1011                           const MachineInstr &Orig);
1012 
1013   /// DeleteMachineInstr - Delete the given MachineInstr.
1014   void deleteMachineInstr(MachineInstr *MI);
1015 
1016   /// CreateMachineBasicBlock - Allocate a new MachineBasicBlock. Use this
1017   /// instead of `new MachineBasicBlock'. Sets `MachineBasicBlock::BBID` if
1018   /// basic-block-sections is enabled for the function.
1019   MachineBasicBlock *
1020   CreateMachineBasicBlock(const BasicBlock *BB = nullptr,
1021                           std::optional<UniqueBBID> BBID = std::nullopt);
1022 
1023   /// DeleteMachineBasicBlock - Delete the given MachineBasicBlock.
1024   void deleteMachineBasicBlock(MachineBasicBlock *MBB);
1025 
1026   /// getMachineMemOperand - Allocate a new MachineMemOperand.
1027   /// MachineMemOperands are owned by the MachineFunction and need not be
1028   /// explicitly deallocated.
1029   MachineMemOperand *getMachineMemOperand(
1030       MachinePointerInfo PtrInfo, MachineMemOperand::Flags f, LLT MemTy,
1031       Align base_alignment, const AAMDNodes &AAInfo = AAMDNodes(),
1032       const MDNode *Ranges = nullptr, SyncScope::ID SSID = SyncScope::System,
1033       AtomicOrdering Ordering = AtomicOrdering::NotAtomic,
1034       AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic);
1035   MachineMemOperand *getMachineMemOperand(
1036       MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, LocationSize Size,
1037       Align BaseAlignment, const AAMDNodes &AAInfo = AAMDNodes(),
1038       const MDNode *Ranges = nullptr, SyncScope::ID SSID = SyncScope::System,
1039       AtomicOrdering Ordering = AtomicOrdering::NotAtomic,
1040       AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic);
1041   MachineMemOperand *getMachineMemOperand(
1042       MachinePointerInfo PtrInfo, MachineMemOperand::Flags F, uint64_t Size,
1043       Align BaseAlignment, const AAMDNodes &AAInfo = AAMDNodes(),
1044       const MDNode *Ranges = nullptr, SyncScope::ID SSID = SyncScope::System,
1045       AtomicOrdering Ordering = AtomicOrdering::NotAtomic,
1046       AtomicOrdering FailureOrdering = AtomicOrdering::NotAtomic) {
1047     return getMachineMemOperand(PtrInfo, F, LocationSize::precise(Size),
1048                                 BaseAlignment, AAInfo, Ranges, SSID, Ordering,
1049                                 FailureOrdering);
1050   }
1051 
1052   /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
1053   /// an existing one, adjusting by an offset and using the given size.
1054   /// MachineMemOperands are owned by the MachineFunction and need not be
1055   /// explicitly deallocated.
1056   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
1057                                           int64_t Offset, LLT Ty);
1058   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
1059                                           int64_t Offset, LocationSize Size) {
1060     return getMachineMemOperand(
1061         MMO, Offset,
1062         !Size.hasValue() ? LLT()
1063         : Size.isScalable()
1064             ? LLT::scalable_vector(1, 8 * Size.getValue().getKnownMinValue())
1065             : LLT::scalar(8 * Size.getValue().getKnownMinValue()));
1066   }
1067   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
1068                                           int64_t Offset, uint64_t Size) {
1069     return getMachineMemOperand(MMO, Offset, LocationSize::precise(Size));
1070   }
1071 
1072   /// getMachineMemOperand - Allocate a new MachineMemOperand by copying
1073   /// an existing one, replacing only the MachinePointerInfo and size.
1074   /// MachineMemOperands are owned by the MachineFunction and need not be
1075   /// explicitly deallocated.
1076   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
1077                                           const MachinePointerInfo &PtrInfo,
1078                                           LocationSize Size);
1079   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
1080                                           const MachinePointerInfo &PtrInfo,
1081                                           LLT Ty);
1082   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
1083                                           const MachinePointerInfo &PtrInfo,
1084                                           uint64_t Size) {
1085     return getMachineMemOperand(MMO, PtrInfo, LocationSize::precise(Size));
1086   }
1087 
1088   /// Allocate a new MachineMemOperand by copying an existing one,
1089   /// replacing only AliasAnalysis information. MachineMemOperands are owned
1090   /// by the MachineFunction and need not be explicitly deallocated.
1091   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
1092                                           const AAMDNodes &AAInfo);
1093 
1094   /// Allocate a new MachineMemOperand by copying an existing one,
1095   /// replacing the flags. MachineMemOperands are owned
1096   /// by the MachineFunction and need not be explicitly deallocated.
1097   MachineMemOperand *getMachineMemOperand(const MachineMemOperand *MMO,
1098                                           MachineMemOperand::Flags Flags);
1099 
1100   using OperandCapacity = ArrayRecycler<MachineOperand>::Capacity;
1101 
1102   /// Allocate an array of MachineOperands. This is only intended for use by
1103   /// internal MachineInstr functions.
1104   MachineOperand *allocateOperandArray(OperandCapacity Cap) {
1105     return OperandRecycler.allocate(Cap, Allocator);
1106   }
1107 
1108   /// Dellocate an array of MachineOperands and recycle the memory. This is
1109   /// only intended for use by internal MachineInstr functions.
1110   /// Cap must be the same capacity that was used to allocate the array.
1111   void deallocateOperandArray(OperandCapacity Cap, MachineOperand *Array) {
1112     OperandRecycler.deallocate(Cap, Array);
1113   }
1114 
1115   /// Allocate and initialize a register mask with @p NumRegister bits.
1116   uint32_t *allocateRegMask();
1117 
1118   ArrayRef<int> allocateShuffleMask(ArrayRef<int> Mask);
1119 
1120   /// Allocate and construct an extra info structure for a `MachineInstr`.
1121   ///
1122   /// This is allocated on the function's allocator and so lives the life of
1123   /// the function.
1124   MachineInstr::ExtraInfo *createMIExtraInfo(
1125       ArrayRef<MachineMemOperand *> MMOs, MCSymbol *PreInstrSymbol = nullptr,
1126       MCSymbol *PostInstrSymbol = nullptr, MDNode *HeapAllocMarker = nullptr,
1127       MDNode *PCSections = nullptr, uint32_t CFIType = 0,
1128       MDNode *MMRAs = nullptr);
1129 
1130   /// Allocate a string and populate it with the given external symbol name.
1131   const char *createExternalSymbolName(StringRef Name);
1132 
1133   //===--------------------------------------------------------------------===//
1134   // Label Manipulation.
1135 
1136   /// getJTISymbol - Return the MCSymbol for the specified non-empty jump table.
1137   /// If isLinkerPrivate is specified, an 'l' label is returned, otherwise a
1138   /// normal 'L' label is returned.
1139   MCSymbol *getJTISymbol(unsigned JTI, MCContext &Ctx,
1140                          bool isLinkerPrivate = false) const;
1141 
1142   /// getPICBaseSymbol - Return a function-local symbol to represent the PIC
1143   /// base.
1144   MCSymbol *getPICBaseSymbol() const;
1145 
1146   /// Returns a reference to a list of cfi instructions in the function's
1147   /// prologue.  Used to construct frame maps for debug and exception handling
1148   /// comsumers.
1149   const std::vector<MCCFIInstruction> &getFrameInstructions() const {
1150     return FrameInstructions;
1151   }
1152 
1153   [[nodiscard]] unsigned addFrameInst(const MCCFIInstruction &Inst);
1154 
1155   /// Returns a reference to a list of symbols immediately following calls to
1156   /// _setjmp in the function. Used to construct the longjmp target table used
1157   /// by Windows Control Flow Guard.
1158   const std::vector<MCSymbol *> &getLongjmpTargets() const {
1159     return LongjmpTargets;
1160   }
1161 
1162   /// Add the specified symbol to the list of valid longjmp targets for Windows
1163   /// Control Flow Guard.
1164   void addLongjmpTarget(MCSymbol *Target) { LongjmpTargets.push_back(Target); }
1165 
1166   /// Returns a reference to a list of symbols that we have catchrets.
1167   /// Used to construct the catchret target table used by Windows EHCont Guard.
1168   const std::vector<MCSymbol *> &getCatchretTargets() const {
1169     return CatchretTargets;
1170   }
1171 
1172   /// Add the specified symbol to the list of valid catchret targets for Windows
1173   /// EHCont Guard.
1174   void addCatchretTarget(MCSymbol *Target) {
1175     CatchretTargets.push_back(Target);
1176   }
1177 
1178   /// \name Exception Handling
1179   /// \{
1180 
1181   bool callsEHReturn() const { return CallsEHReturn; }
1182   void setCallsEHReturn(bool b) { CallsEHReturn = b; }
1183 
1184   bool callsUnwindInit() const { return CallsUnwindInit; }
1185   void setCallsUnwindInit(bool b) { CallsUnwindInit = b; }
1186 
1187   bool hasEHCatchret() const { return HasEHCatchret; }
1188   void setHasEHCatchret(bool V) { HasEHCatchret = V; }
1189 
1190   bool hasEHScopes() const { return HasEHScopes; }
1191   void setHasEHScopes(bool V) { HasEHScopes = V; }
1192 
1193   bool hasEHFunclets() const { return HasEHFunclets; }
1194   void setHasEHFunclets(bool V) { HasEHFunclets = V; }
1195 
1196   bool isOutlined() const { return IsOutlined; }
1197   void setIsOutlined(bool V) { IsOutlined = V; }
1198 
1199   /// Find or create an LandingPadInfo for the specified MachineBasicBlock.
1200   LandingPadInfo &getOrCreateLandingPadInfo(MachineBasicBlock *LandingPad);
1201 
1202   /// Return a reference to the landing pad info for the current function.
1203   const std::vector<LandingPadInfo> &getLandingPads() const {
1204     return LandingPads;
1205   }
1206 
1207   /// Provide the begin and end labels of an invoke style call and associate it
1208   /// with a try landing pad block.
1209   void addInvoke(MachineBasicBlock *LandingPad,
1210                  MCSymbol *BeginLabel, MCSymbol *EndLabel);
1211 
1212   /// Add a new panding pad, and extract the exception handling information from
1213   /// the landingpad instruction. Returns the label ID for the landing pad
1214   /// entry.
1215   MCSymbol *addLandingPad(MachineBasicBlock *LandingPad);
1216 
1217   /// Return the type id for the specified typeinfo.  This is function wide.
1218   unsigned getTypeIDFor(const GlobalValue *TI);
1219 
1220   /// Return the id of the filter encoded by TyIds.  This is function wide.
1221   int getFilterIDFor(ArrayRef<unsigned> TyIds);
1222 
1223   /// Map the landing pad's EH symbol to the call site indexes.
1224   void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef<unsigned> Sites);
1225 
1226   /// Return if there is any wasm exception handling.
1227   bool hasAnyWasmLandingPadIndex() const {
1228     return !WasmLPadToIndexMap.empty();
1229   }
1230 
1231   /// Map the landing pad to its index. Used for Wasm exception handling.
1232   void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index) {
1233     WasmLPadToIndexMap[LPad] = Index;
1234   }
1235 
1236   /// Returns true if the landing pad has an associate index in wasm EH.
1237   bool hasWasmLandingPadIndex(const MachineBasicBlock *LPad) const {
1238     return WasmLPadToIndexMap.count(LPad);
1239   }
1240 
1241   /// Get the index in wasm EH for a given landing pad.
1242   unsigned getWasmLandingPadIndex(const MachineBasicBlock *LPad) const {
1243     assert(hasWasmLandingPadIndex(LPad));
1244     return WasmLPadToIndexMap.lookup(LPad);
1245   }
1246 
1247   bool hasAnyCallSiteLandingPad() const {
1248     return !LPadToCallSiteMap.empty();
1249   }
1250 
1251   /// Get the call site indexes for a landing pad EH symbol.
1252   SmallVectorImpl<unsigned> &getCallSiteLandingPad(MCSymbol *Sym) {
1253     assert(hasCallSiteLandingPad(Sym) &&
1254            "missing call site number for landing pad!");
1255     return LPadToCallSiteMap[Sym];
1256   }
1257 
1258   /// Return true if the landing pad Eh symbol has an associated call site.
1259   bool hasCallSiteLandingPad(MCSymbol *Sym) {
1260     return !LPadToCallSiteMap[Sym].empty();
1261   }
1262 
1263   bool hasAnyCallSiteLabel() const {
1264     return !CallSiteMap.empty();
1265   }
1266 
1267   /// Map the begin label for a call site.
1268   void setCallSiteBeginLabel(MCSymbol *BeginLabel, unsigned Site) {
1269     CallSiteMap[BeginLabel] = Site;
1270   }
1271 
1272   /// Get the call site number for a begin label.
1273   unsigned getCallSiteBeginLabel(MCSymbol *BeginLabel) const {
1274     assert(hasCallSiteBeginLabel(BeginLabel) &&
1275            "Missing call site number for EH_LABEL!");
1276     return CallSiteMap.lookup(BeginLabel);
1277   }
1278 
1279   /// Return true if the begin label has a call site number associated with it.
1280   bool hasCallSiteBeginLabel(MCSymbol *BeginLabel) const {
1281     return CallSiteMap.count(BeginLabel);
1282   }
1283 
1284   /// Record annotations associated with a particular label.
1285   void addCodeViewAnnotation(MCSymbol *Label, MDNode *MD) {
1286     CodeViewAnnotations.push_back({Label, MD});
1287   }
1288 
1289   ArrayRef<std::pair<MCSymbol *, MDNode *>> getCodeViewAnnotations() const {
1290     return CodeViewAnnotations;
1291   }
1292 
1293   /// Return a reference to the C++ typeinfo for the current function.
1294   const std::vector<const GlobalValue *> &getTypeInfos() const {
1295     return TypeInfos;
1296   }
1297 
1298   /// Return a reference to the typeids encoding filters used in the current
1299   /// function.
1300   const std::vector<unsigned> &getFilterIds() const {
1301     return FilterIds;
1302   }
1303 
1304   /// \}
1305 
1306   /// Collect information used to emit debugging information of a variable in a
1307   /// stack slot.
1308   void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
1309                           int Slot, const DILocation *Loc) {
1310     VariableDbgInfos.emplace_back(Var, Expr, Slot, Loc);
1311   }
1312 
1313   /// Collect information used to emit debugging information of a variable in
1314   /// the entry value of a register.
1315   void setVariableDbgInfo(const DILocalVariable *Var, const DIExpression *Expr,
1316                           MCRegister Reg, const DILocation *Loc) {
1317     VariableDbgInfos.emplace_back(Var, Expr, Reg, Loc);
1318   }
1319 
1320   VariableDbgInfoMapTy &getVariableDbgInfo() { return VariableDbgInfos; }
1321   const VariableDbgInfoMapTy &getVariableDbgInfo() const {
1322     return VariableDbgInfos;
1323   }
1324 
1325   /// Returns the collection of variables for which we have debug info and that
1326   /// have been assigned a stack slot.
1327   auto getInStackSlotVariableDbgInfo() {
1328     return make_filter_range(getVariableDbgInfo(), [](auto &VarInfo) {
1329       return VarInfo.inStackSlot();
1330     });
1331   }
1332 
1333   /// Returns the collection of variables for which we have debug info and that
1334   /// have been assigned a stack slot.
1335   auto getInStackSlotVariableDbgInfo() const {
1336     return make_filter_range(getVariableDbgInfo(), [](const auto &VarInfo) {
1337       return VarInfo.inStackSlot();
1338     });
1339   }
1340 
1341   /// Returns the collection of variables for which we have debug info and that
1342   /// have been assigned an entry value register.
1343   auto getEntryValueVariableDbgInfo() const {
1344     return make_filter_range(getVariableDbgInfo(), [](const auto &VarInfo) {
1345       return VarInfo.inEntryValueRegister();
1346     });
1347   }
1348 
1349   /// Start tracking the arguments passed to the call \p CallI.
1350   void addCallSiteInfo(const MachineInstr *CallI, CallSiteInfo &&CallInfo) {
1351     assert(CallI->isCandidateForCallSiteEntry());
1352     bool Inserted =
1353         CallSitesInfo.try_emplace(CallI, std::move(CallInfo)).second;
1354     (void)Inserted;
1355     assert(Inserted && "Call site info not unique");
1356   }
1357 
1358   const CallSiteInfoMap &getCallSitesInfo() const {
1359     return CallSitesInfo;
1360   }
1361 
1362   /// Following functions update call site info. They should be called before
1363   /// removing, replacing or copying call instruction.
1364 
1365   /// Erase the call site info for \p MI. It is used to remove a call
1366   /// instruction from the instruction stream.
1367   void eraseCallSiteInfo(const MachineInstr *MI);
1368   /// Copy the call site info from \p Old to \ New. Its usage is when we are
1369   /// making a copy of the instruction that will be inserted at different point
1370   /// of the instruction stream.
1371   void copyCallSiteInfo(const MachineInstr *Old,
1372                         const MachineInstr *New);
1373 
1374   /// Move the call site info from \p Old to \New call site info. This function
1375   /// is used when we are replacing one call instruction with another one to
1376   /// the same callee.
1377   void moveCallSiteInfo(const MachineInstr *Old,
1378                         const MachineInstr *New);
1379 
1380   unsigned getNewDebugInstrNum() {
1381     return ++DebugInstrNumberingCount;
1382   }
1383 };
1384 
1385 //===--------------------------------------------------------------------===//
1386 // GraphTraits specializations for function basic block graphs (CFGs)
1387 //===--------------------------------------------------------------------===//
1388 
1389 // Provide specializations of GraphTraits to be able to treat a
1390 // machine function as a graph of machine basic blocks... these are
1391 // the same as the machine basic block iterators, except that the root
1392 // node is implicitly the first node of the function.
1393 //
1394 template <> struct GraphTraits<MachineFunction*> :
1395   public GraphTraits<MachineBasicBlock*> {
1396   static NodeRef getEntryNode(MachineFunction *F) { return &F->front(); }
1397 
1398   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
1399   using nodes_iterator = pointer_iterator<MachineFunction::iterator>;
1400 
1401   static nodes_iterator nodes_begin(MachineFunction *F) {
1402     return nodes_iterator(F->begin());
1403   }
1404 
1405   static nodes_iterator nodes_end(MachineFunction *F) {
1406     return nodes_iterator(F->end());
1407   }
1408 
1409   static unsigned       size       (MachineFunction *F) { return F->size(); }
1410 };
1411 template <> struct GraphTraits<const MachineFunction*> :
1412   public GraphTraits<const MachineBasicBlock*> {
1413   static NodeRef getEntryNode(const MachineFunction *F) { return &F->front(); }
1414 
1415   // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
1416   using nodes_iterator = pointer_iterator<MachineFunction::const_iterator>;
1417 
1418   static nodes_iterator nodes_begin(const MachineFunction *F) {
1419     return nodes_iterator(F->begin());
1420   }
1421 
1422   static nodes_iterator nodes_end  (const MachineFunction *F) {
1423     return nodes_iterator(F->end());
1424   }
1425 
1426   static unsigned       size       (const MachineFunction *F)  {
1427     return F->size();
1428   }
1429 };
1430 
1431 // Provide specializations of GraphTraits to be able to treat a function as a
1432 // graph of basic blocks... and to walk it in inverse order.  Inverse order for
1433 // a function is considered to be when traversing the predecessor edges of a BB
1434 // instead of the successor edges.
1435 //
1436 template <> struct GraphTraits<Inverse<MachineFunction*>> :
1437   public GraphTraits<Inverse<MachineBasicBlock*>> {
1438   static NodeRef getEntryNode(Inverse<MachineFunction *> G) {
1439     return &G.Graph->front();
1440   }
1441 };
1442 template <> struct GraphTraits<Inverse<const MachineFunction*>> :
1443   public GraphTraits<Inverse<const MachineBasicBlock*>> {
1444   static NodeRef getEntryNode(Inverse<const MachineFunction *> G) {
1445     return &G.Graph->front();
1446   }
1447 };
1448 
1449 void verifyMachineFunction(const std::string &Banner,
1450                            const MachineFunction &MF);
1451 
1452 } // end namespace llvm
1453 
1454 #endif // LLVM_CODEGEN_MACHINEFUNCTION_H
1455