xref: /llvm-project/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h (revision 5272ae667dd5c628689097687f4679a8be29bc4d)
1 //==- SIMachineFunctionInfo.h - SIMachineFunctionInfo interface --*- 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 /// \file
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
14 #define LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
15 
16 #include "AMDGPUArgumentUsageInfo.h"
17 #include "AMDGPUMachineFunction.h"
18 #include "AMDGPUTargetMachine.h"
19 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
20 #include "SIInstrInfo.h"
21 #include "SIModeRegisterDefaults.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/CodeGen/MIRYamlMapping.h"
24 #include "llvm/CodeGen/PseudoSourceValue.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include <optional>
27 
28 namespace llvm {
29 
30 class MachineFrameInfo;
31 class MachineFunction;
32 class SIMachineFunctionInfo;
33 class SIRegisterInfo;
34 class TargetRegisterClass;
35 
36 class AMDGPUPseudoSourceValue : public PseudoSourceValue {
37 public:
38   enum AMDGPUPSVKind : unsigned {
39     PSVImage = PseudoSourceValue::TargetCustom,
40     GWSResource
41   };
42 
43 protected:
44   AMDGPUPseudoSourceValue(unsigned Kind, const AMDGPUTargetMachine &TM)
45       : PseudoSourceValue(Kind, TM) {}
46 
47 public:
48   bool isConstant(const MachineFrameInfo *) const override {
49     // This should probably be true for most images, but we will start by being
50     // conservative.
51     return false;
52   }
53 
54   bool isAliased(const MachineFrameInfo *) const override {
55     return true;
56   }
57 
58   bool mayAlias(const MachineFrameInfo *) const override {
59     return true;
60   }
61 };
62 
63 class AMDGPUGWSResourcePseudoSourceValue final : public AMDGPUPseudoSourceValue {
64 public:
65   explicit AMDGPUGWSResourcePseudoSourceValue(const AMDGPUTargetMachine &TM)
66       : AMDGPUPseudoSourceValue(GWSResource, TM) {}
67 
68   static bool classof(const PseudoSourceValue *V) {
69     return V->kind() == GWSResource;
70   }
71 
72   // These are inaccessible memory from IR.
73   bool isAliased(const MachineFrameInfo *) const override {
74     return false;
75   }
76 
77   // These are inaccessible memory from IR.
78   bool mayAlias(const MachineFrameInfo *) const override {
79     return false;
80   }
81 
82   void printCustom(raw_ostream &OS) const override {
83     OS << "GWSResource";
84   }
85 };
86 
87 namespace yaml {
88 
89 struct SIArgument {
90   bool IsRegister;
91   union {
92     StringValue RegisterName;
93     unsigned StackOffset;
94   };
95   std::optional<unsigned> Mask;
96 
97   // Default constructor, which creates a stack argument.
98   SIArgument() : IsRegister(false), StackOffset(0) {}
99   SIArgument(const SIArgument &Other) {
100     IsRegister = Other.IsRegister;
101     if (IsRegister) {
102       ::new ((void *)std::addressof(RegisterName))
103           StringValue(Other.RegisterName);
104     } else
105       StackOffset = Other.StackOffset;
106     Mask = Other.Mask;
107   }
108   SIArgument &operator=(const SIArgument &Other) {
109     IsRegister = Other.IsRegister;
110     if (IsRegister) {
111       ::new ((void *)std::addressof(RegisterName))
112           StringValue(Other.RegisterName);
113     } else
114       StackOffset = Other.StackOffset;
115     Mask = Other.Mask;
116     return *this;
117   }
118   ~SIArgument() {
119     if (IsRegister)
120       RegisterName.~StringValue();
121   }
122 
123   // Helper to create a register or stack argument.
124   static inline SIArgument createArgument(bool IsReg) {
125     if (IsReg)
126       return SIArgument(IsReg);
127     return SIArgument();
128   }
129 
130 private:
131   // Construct a register argument.
132   SIArgument(bool) : IsRegister(true), RegisterName() {}
133 };
134 
135 template <> struct MappingTraits<SIArgument> {
136   static void mapping(IO &YamlIO, SIArgument &A) {
137     if (YamlIO.outputting()) {
138       if (A.IsRegister)
139         YamlIO.mapRequired("reg", A.RegisterName);
140       else
141         YamlIO.mapRequired("offset", A.StackOffset);
142     } else {
143       auto Keys = YamlIO.keys();
144       if (is_contained(Keys, "reg")) {
145         A = SIArgument::createArgument(true);
146         YamlIO.mapRequired("reg", A.RegisterName);
147       } else if (is_contained(Keys, "offset"))
148         YamlIO.mapRequired("offset", A.StackOffset);
149       else
150         YamlIO.setError("missing required key 'reg' or 'offset'");
151     }
152     YamlIO.mapOptional("mask", A.Mask);
153   }
154   static const bool flow = true;
155 };
156 
157 struct SIArgumentInfo {
158   std::optional<SIArgument> PrivateSegmentBuffer;
159   std::optional<SIArgument> DispatchPtr;
160   std::optional<SIArgument> QueuePtr;
161   std::optional<SIArgument> KernargSegmentPtr;
162   std::optional<SIArgument> DispatchID;
163   std::optional<SIArgument> FlatScratchInit;
164   std::optional<SIArgument> PrivateSegmentSize;
165 
166   std::optional<SIArgument> WorkGroupIDX;
167   std::optional<SIArgument> WorkGroupIDY;
168   std::optional<SIArgument> WorkGroupIDZ;
169   std::optional<SIArgument> WorkGroupInfo;
170   std::optional<SIArgument> LDSKernelId;
171   std::optional<SIArgument> PrivateSegmentWaveByteOffset;
172 
173   std::optional<SIArgument> ImplicitArgPtr;
174   std::optional<SIArgument> ImplicitBufferPtr;
175 
176   std::optional<SIArgument> WorkItemIDX;
177   std::optional<SIArgument> WorkItemIDY;
178   std::optional<SIArgument> WorkItemIDZ;
179 };
180 
181 template <> struct MappingTraits<SIArgumentInfo> {
182   static void mapping(IO &YamlIO, SIArgumentInfo &AI) {
183     YamlIO.mapOptional("privateSegmentBuffer", AI.PrivateSegmentBuffer);
184     YamlIO.mapOptional("dispatchPtr", AI.DispatchPtr);
185     YamlIO.mapOptional("queuePtr", AI.QueuePtr);
186     YamlIO.mapOptional("kernargSegmentPtr", AI.KernargSegmentPtr);
187     YamlIO.mapOptional("dispatchID", AI.DispatchID);
188     YamlIO.mapOptional("flatScratchInit", AI.FlatScratchInit);
189     YamlIO.mapOptional("privateSegmentSize", AI.PrivateSegmentSize);
190 
191     YamlIO.mapOptional("workGroupIDX", AI.WorkGroupIDX);
192     YamlIO.mapOptional("workGroupIDY", AI.WorkGroupIDY);
193     YamlIO.mapOptional("workGroupIDZ", AI.WorkGroupIDZ);
194     YamlIO.mapOptional("workGroupInfo", AI.WorkGroupInfo);
195     YamlIO.mapOptional("LDSKernelId", AI.LDSKernelId);
196     YamlIO.mapOptional("privateSegmentWaveByteOffset",
197                        AI.PrivateSegmentWaveByteOffset);
198 
199     YamlIO.mapOptional("implicitArgPtr", AI.ImplicitArgPtr);
200     YamlIO.mapOptional("implicitBufferPtr", AI.ImplicitBufferPtr);
201 
202     YamlIO.mapOptional("workItemIDX", AI.WorkItemIDX);
203     YamlIO.mapOptional("workItemIDY", AI.WorkItemIDY);
204     YamlIO.mapOptional("workItemIDZ", AI.WorkItemIDZ);
205   }
206 };
207 
208 // Default to default mode for default calling convention.
209 struct SIMode {
210   bool IEEE = true;
211   bool DX10Clamp = true;
212   bool FP32InputDenormals = true;
213   bool FP32OutputDenormals = true;
214   bool FP64FP16InputDenormals = true;
215   bool FP64FP16OutputDenormals = true;
216 
217   SIMode() = default;
218 
219   SIMode(const SIModeRegisterDefaults &Mode) {
220     IEEE = Mode.IEEE;
221     DX10Clamp = Mode.DX10Clamp;
222     FP32InputDenormals = Mode.FP32Denormals.Input != DenormalMode::PreserveSign;
223     FP32OutputDenormals =
224         Mode.FP32Denormals.Output != DenormalMode::PreserveSign;
225     FP64FP16InputDenormals =
226         Mode.FP64FP16Denormals.Input != DenormalMode::PreserveSign;
227     FP64FP16OutputDenormals =
228         Mode.FP64FP16Denormals.Output != DenormalMode::PreserveSign;
229   }
230 
231   bool operator ==(const SIMode Other) const {
232     return IEEE == Other.IEEE &&
233            DX10Clamp == Other.DX10Clamp &&
234            FP32InputDenormals == Other.FP32InputDenormals &&
235            FP32OutputDenormals == Other.FP32OutputDenormals &&
236            FP64FP16InputDenormals == Other.FP64FP16InputDenormals &&
237            FP64FP16OutputDenormals == Other.FP64FP16OutputDenormals;
238   }
239 };
240 
241 template <> struct MappingTraits<SIMode> {
242   static void mapping(IO &YamlIO, SIMode &Mode) {
243     YamlIO.mapOptional("ieee", Mode.IEEE, true);
244     YamlIO.mapOptional("dx10-clamp", Mode.DX10Clamp, true);
245     YamlIO.mapOptional("fp32-input-denormals", Mode.FP32InputDenormals, true);
246     YamlIO.mapOptional("fp32-output-denormals", Mode.FP32OutputDenormals, true);
247     YamlIO.mapOptional("fp64-fp16-input-denormals", Mode.FP64FP16InputDenormals, true);
248     YamlIO.mapOptional("fp64-fp16-output-denormals", Mode.FP64FP16OutputDenormals, true);
249   }
250 };
251 
252 struct SIMachineFunctionInfo final : public yaml::MachineFunctionInfo {
253   uint64_t ExplicitKernArgSize = 0;
254   Align MaxKernArgAlign;
255   uint32_t LDSSize = 0;
256   uint32_t GDSSize = 0;
257   Align DynLDSAlign;
258   bool IsEntryFunction = false;
259   bool IsChainFunction = false;
260   bool NoSignedZerosFPMath = false;
261   bool MemoryBound = false;
262   bool WaveLimiter = false;
263   bool HasSpilledSGPRs = false;
264   bool HasSpilledVGPRs = false;
265   uint32_t HighBitsOf32BitAddress = 0;
266 
267   // TODO: 10 may be a better default since it's the maximum.
268   unsigned Occupancy = 0;
269 
270   SmallVector<StringValue> WWMReservedRegs;
271 
272   StringValue ScratchRSrcReg = "$private_rsrc_reg";
273   StringValue FrameOffsetReg = "$fp_reg";
274   StringValue StackPtrOffsetReg = "$sp_reg";
275 
276   unsigned BytesInStackArgArea = 0;
277   bool ReturnsVoid = true;
278 
279   std::optional<SIArgumentInfo> ArgInfo;
280 
281   unsigned PSInputAddr = 0;
282   unsigned PSInputEnable = 0;
283 
284   SIMode Mode;
285   std::optional<FrameIndex> ScavengeFI;
286   StringValue VGPRForAGPRCopy;
287   StringValue SGPRForEXECCopy;
288   StringValue LongBranchReservedReg;
289 
290   SIMachineFunctionInfo() = default;
291   SIMachineFunctionInfo(const llvm::SIMachineFunctionInfo &,
292                         const TargetRegisterInfo &TRI,
293                         const llvm::MachineFunction &MF);
294 
295   void mappingImpl(yaml::IO &YamlIO) override;
296   ~SIMachineFunctionInfo() = default;
297 };
298 
299 template <> struct MappingTraits<SIMachineFunctionInfo> {
300   static void mapping(IO &YamlIO, SIMachineFunctionInfo &MFI) {
301     YamlIO.mapOptional("explicitKernArgSize", MFI.ExplicitKernArgSize,
302                        UINT64_C(0));
303     YamlIO.mapOptional("maxKernArgAlign", MFI.MaxKernArgAlign);
304     YamlIO.mapOptional("ldsSize", MFI.LDSSize, 0u);
305     YamlIO.mapOptional("gdsSize", MFI.GDSSize, 0u);
306     YamlIO.mapOptional("dynLDSAlign", MFI.DynLDSAlign, Align());
307     YamlIO.mapOptional("isEntryFunction", MFI.IsEntryFunction, false);
308     YamlIO.mapOptional("isChainFunction", MFI.IsChainFunction, false);
309     YamlIO.mapOptional("noSignedZerosFPMath", MFI.NoSignedZerosFPMath, false);
310     YamlIO.mapOptional("memoryBound", MFI.MemoryBound, false);
311     YamlIO.mapOptional("waveLimiter", MFI.WaveLimiter, false);
312     YamlIO.mapOptional("hasSpilledSGPRs", MFI.HasSpilledSGPRs, false);
313     YamlIO.mapOptional("hasSpilledVGPRs", MFI.HasSpilledVGPRs, false);
314     YamlIO.mapOptional("scratchRSrcReg", MFI.ScratchRSrcReg,
315                        StringValue("$private_rsrc_reg"));
316     YamlIO.mapOptional("frameOffsetReg", MFI.FrameOffsetReg,
317                        StringValue("$fp_reg"));
318     YamlIO.mapOptional("stackPtrOffsetReg", MFI.StackPtrOffsetReg,
319                        StringValue("$sp_reg"));
320     YamlIO.mapOptional("bytesInStackArgArea", MFI.BytesInStackArgArea, 0u);
321     YamlIO.mapOptional("returnsVoid", MFI.ReturnsVoid, true);
322     YamlIO.mapOptional("argumentInfo", MFI.ArgInfo);
323     YamlIO.mapOptional("psInputAddr", MFI.PSInputAddr, 0u);
324     YamlIO.mapOptional("psInputEnable", MFI.PSInputEnable, 0u);
325     YamlIO.mapOptional("mode", MFI.Mode, SIMode());
326     YamlIO.mapOptional("highBitsOf32BitAddress",
327                        MFI.HighBitsOf32BitAddress, 0u);
328     YamlIO.mapOptional("occupancy", MFI.Occupancy, 0);
329     YamlIO.mapOptional("wwmReservedRegs", MFI.WWMReservedRegs);
330     YamlIO.mapOptional("scavengeFI", MFI.ScavengeFI);
331     YamlIO.mapOptional("vgprForAGPRCopy", MFI.VGPRForAGPRCopy,
332                        StringValue()); // Don't print out when it's empty.
333     YamlIO.mapOptional("sgprForEXECCopy", MFI.SGPRForEXECCopy,
334                        StringValue()); // Don't print out when it's empty.
335     YamlIO.mapOptional("longBranchReservedReg", MFI.LongBranchReservedReg,
336                        StringValue());
337   }
338 };
339 
340 } // end namespace yaml
341 
342 // A CSR SGPR value can be preserved inside a callee using one of the following
343 // methods.
344 //   1. Copy to an unused scratch SGPR.
345 //   2. Spill to a VGPR lane.
346 //   3. Spill to memory via. a scratch VGPR.
347 // class PrologEpilogSGPRSaveRestoreInfo represents the save/restore method used
348 // for an SGPR at function prolog/epilog.
349 enum class SGPRSaveKind : uint8_t {
350   COPY_TO_SCRATCH_SGPR,
351   SPILL_TO_VGPR_LANE,
352   SPILL_TO_MEM
353 };
354 
355 class PrologEpilogSGPRSaveRestoreInfo {
356   SGPRSaveKind Kind;
357   union {
358     int Index;
359     Register Reg;
360   };
361 
362 public:
363   PrologEpilogSGPRSaveRestoreInfo(SGPRSaveKind K, int I) : Kind(K), Index(I) {}
364   PrologEpilogSGPRSaveRestoreInfo(SGPRSaveKind K, Register R)
365       : Kind(K), Reg(R) {}
366   Register getReg() const { return Reg; }
367   int getIndex() const { return Index; }
368   SGPRSaveKind getKind() const { return Kind; }
369 };
370 
371 /// This class keeps track of the SPI_SP_INPUT_ADDR config register, which
372 /// tells the hardware which interpolation parameters to load.
373 class SIMachineFunctionInfo final : public AMDGPUMachineFunction,
374                                     private MachineRegisterInfo::Delegate {
375   friend class GCNTargetMachine;
376 
377   // State of MODE register, assumed FP mode.
378   SIModeRegisterDefaults Mode;
379 
380   // Registers that may be reserved for spilling purposes. These may be the same
381   // as the input registers.
382   Register ScratchRSrcReg = AMDGPU::PRIVATE_RSRC_REG;
383 
384   // This is the unswizzled offset from the current dispatch's scratch wave
385   // base to the beginning of the current function's frame.
386   Register FrameOffsetReg = AMDGPU::FP_REG;
387 
388   // This is an ABI register used in the non-entry calling convention to
389   // communicate the unswizzled offset from the current dispatch's scratch wave
390   // base to the beginning of the new function's frame.
391   Register StackPtrOffsetReg = AMDGPU::SP_REG;
392 
393   // Registers that may be reserved when RA doesn't allocate enough
394   // registers to plan for the case where an indirect branch ends up
395   // being needed during branch relaxation.
396   Register LongBranchReservedReg;
397 
398   AMDGPUFunctionArgInfo ArgInfo;
399 
400   // Graphics info.
401   unsigned PSInputAddr = 0;
402   unsigned PSInputEnable = 0;
403 
404   /// Number of bytes of arguments this function has on the stack. If the callee
405   /// is expected to restore the argument stack this should be a multiple of 16,
406   /// all usable during a tail call.
407   ///
408   /// The alternative would forbid tail call optimisation in some cases: if we
409   /// want to transfer control from a function with 8-bytes of stack-argument
410   /// space to a function with 16-bytes then misalignment of this value would
411   /// make a stack adjustment necessary, which could not be undone by the
412   /// callee.
413   unsigned BytesInStackArgArea = 0;
414 
415   bool ReturnsVoid = true;
416 
417   // A pair of default/requested minimum/maximum flat work group sizes.
418   // Minimum - first, maximum - second.
419   std::pair<unsigned, unsigned> FlatWorkGroupSizes = {0, 0};
420 
421   // A pair of default/requested minimum/maximum number of waves per execution
422   // unit. Minimum - first, maximum - second.
423   std::pair<unsigned, unsigned> WavesPerEU = {0, 0};
424 
425   const AMDGPUGWSResourcePseudoSourceValue GWSResourcePSV;
426 
427 private:
428   unsigned NumUserSGPRs = 0;
429   unsigned NumSystemSGPRs = 0;
430 
431   bool HasSpilledSGPRs = false;
432   bool HasSpilledVGPRs = false;
433   bool HasNonSpillStackObjects = false;
434   bool IsStackRealigned = false;
435 
436   unsigned NumSpilledSGPRs = 0;
437   unsigned NumSpilledVGPRs = 0;
438 
439   // Feature bits required for inputs passed in user SGPRs.
440   bool PrivateSegmentBuffer : 1;
441   bool DispatchPtr : 1;
442   bool QueuePtr : 1;
443   bool KernargSegmentPtr : 1;
444   bool DispatchID : 1;
445   bool FlatScratchInit : 1;
446 
447   // Feature bits required for inputs passed in system SGPRs.
448   bool WorkGroupIDX : 1; // Always initialized.
449   bool WorkGroupIDY : 1;
450   bool WorkGroupIDZ : 1;
451   bool WorkGroupInfo : 1;
452   bool LDSKernelId : 1;
453   bool PrivateSegmentWaveByteOffset : 1;
454 
455   bool WorkItemIDX : 1; // Always initialized.
456   bool WorkItemIDY : 1;
457   bool WorkItemIDZ : 1;
458 
459   // Private memory buffer
460   // Compute directly in sgpr[0:1]
461   // Other shaders indirect 64-bits at sgpr[0:1]
462   bool ImplicitBufferPtr : 1;
463 
464   // Pointer to where the ABI inserts special kernel arguments separate from the
465   // user arguments. This is an offset from the KernargSegmentPtr.
466   bool ImplicitArgPtr : 1;
467 
468   bool MayNeedAGPRs : 1;
469 
470   // The hard-wired high half of the address of the global information table
471   // for AMDPAL OS type. 0xffffffff represents no hard-wired high half, since
472   // current hardware only allows a 16 bit value.
473   unsigned GITPtrHigh;
474 
475   unsigned HighBitsOf32BitAddress;
476 
477   // Flags associated with the virtual registers.
478   IndexedMap<uint8_t, VirtReg2IndexFunctor> VRegFlags;
479 
480   // Current recorded maximum possible occupancy.
481   unsigned Occupancy;
482 
483   mutable std::optional<bool> UsesAGPRs;
484 
485   MCPhysReg getNextUserSGPR() const;
486 
487   MCPhysReg getNextSystemSGPR() const;
488 
489   // MachineRegisterInfo callback functions to notify events.
490   void MRI_NoteNewVirtualRegister(Register Reg) override;
491   void MRI_NoteCloneVirtualRegister(Register NewReg, Register SrcReg) override;
492 
493 public:
494   struct VGPRSpillToAGPR {
495     SmallVector<MCPhysReg, 32> Lanes;
496     bool FullyAllocated = false;
497     bool IsDead = false;
498   };
499 
500 private:
501   // To track virtual VGPR + lane index for each subregister of the SGPR spilled
502   // to frameindex key during SILowerSGPRSpills pass.
503   DenseMap<int, std::vector<SIRegisterInfo::SpilledReg>>
504       SGPRSpillsToVirtualVGPRLanes;
505   // To track physical VGPR + lane index for CSR SGPR spills and special SGPRs
506   // like Frame Pointer identified during PrologEpilogInserter.
507   DenseMap<int, std::vector<SIRegisterInfo::SpilledReg>>
508       SGPRSpillsToPhysicalVGPRLanes;
509   unsigned NumVirtualVGPRSpillLanes = 0;
510   unsigned NumPhysicalVGPRSpillLanes = 0;
511   SmallVector<Register, 2> SpillVGPRs;
512   using WWMSpillsMap = MapVector<Register, int>;
513   // To track the registers used in instructions that can potentially modify the
514   // inactive lanes. The WWM instructions and the writelane instructions for
515   // spilling SGPRs to VGPRs fall under such category of operations. The VGPRs
516   // modified by them should be spilled/restored at function prolog/epilog to
517   // avoid any undesired outcome. Each entry in this map holds a pair of values,
518   // the VGPR and its stack slot index.
519   WWMSpillsMap WWMSpills;
520 
521   using ReservedRegSet = SmallSetVector<Register, 8>;
522   // To track the VGPRs reserved for WWM instructions. They get stack slots
523   // later during PrologEpilogInserter and get added into the superset WWMSpills
524   // for actual spilling. A separate set makes the register reserved part and
525   // the serialization easier.
526   ReservedRegSet WWMReservedRegs;
527 
528   using PrologEpilogSGPRSpillsMap =
529       DenseMap<Register, PrologEpilogSGPRSaveRestoreInfo>;
530   // To track the SGPR spill method used for a CSR SGPR register during
531   // frame lowering. Even though the SGPR spills are handled during
532   // SILowerSGPRSpills pass, some special handling needed later during the
533   // PrologEpilogInserter.
534   PrologEpilogSGPRSpillsMap PrologEpilogSGPRSpills;
535 
536   // To save/restore EXEC MASK around WWM spills and copies.
537   Register SGPRForEXECCopy;
538 
539   DenseMap<int, VGPRSpillToAGPR> VGPRToAGPRSpills;
540 
541   // AGPRs used for VGPR spills.
542   SmallVector<MCPhysReg, 32> SpillAGPR;
543 
544   // VGPRs used for AGPR spills.
545   SmallVector<MCPhysReg, 32> SpillVGPR;
546 
547   // Emergency stack slot. Sometimes, we create this before finalizing the stack
548   // frame, so save it here and add it to the RegScavenger later.
549   std::optional<int> ScavengeFI;
550 
551 private:
552   Register VGPRForAGPRCopy;
553 
554   bool allocateVirtualVGPRForSGPRSpills(MachineFunction &MF, int FI,
555                                         unsigned LaneIndex);
556   bool allocatePhysicalVGPRForSGPRSpills(MachineFunction &MF, int FI,
557                                          unsigned LaneIndex);
558 
559 public:
560   Register getVGPRForAGPRCopy() const {
561     return VGPRForAGPRCopy;
562   }
563 
564   void setVGPRForAGPRCopy(Register NewVGPRForAGPRCopy) {
565     VGPRForAGPRCopy = NewVGPRForAGPRCopy;
566   }
567 
568   bool isCalleeSavedReg(const MCPhysReg *CSRegs, MCPhysReg Reg) const;
569 
570 public:
571   SIMachineFunctionInfo(const SIMachineFunctionInfo &MFI) = default;
572   SIMachineFunctionInfo(const Function &F, const GCNSubtarget *STI);
573 
574   MachineFunctionInfo *
575   clone(BumpPtrAllocator &Allocator, MachineFunction &DestMF,
576         const DenseMap<MachineBasicBlock *, MachineBasicBlock *> &Src2DstMBB)
577       const override;
578 
579   bool initializeBaseYamlFields(const yaml::SIMachineFunctionInfo &YamlMFI,
580                                 const MachineFunction &MF,
581                                 PerFunctionMIParsingState &PFS,
582                                 SMDiagnostic &Error, SMRange &SourceRange);
583 
584   void reserveWWMRegister(Register Reg) { WWMReservedRegs.insert(Reg); }
585 
586   SIModeRegisterDefaults getMode() const { return Mode; }
587 
588   ArrayRef<SIRegisterInfo::SpilledReg>
589   getSGPRSpillToVirtualVGPRLanes(int FrameIndex) const {
590     auto I = SGPRSpillsToVirtualVGPRLanes.find(FrameIndex);
591     return (I == SGPRSpillsToVirtualVGPRLanes.end())
592                ? ArrayRef<SIRegisterInfo::SpilledReg>()
593                : ArrayRef(I->second);
594   }
595 
596   ArrayRef<Register> getSGPRSpillVGPRs() const { return SpillVGPRs; }
597   const WWMSpillsMap &getWWMSpills() const { return WWMSpills; }
598   const ReservedRegSet &getWWMReservedRegs() const { return WWMReservedRegs; }
599 
600   const PrologEpilogSGPRSpillsMap &getPrologEpilogSGPRSpills() const {
601     return PrologEpilogSGPRSpills;
602   }
603 
604   void addToPrologEpilogSGPRSpills(Register Reg,
605                                    PrologEpilogSGPRSaveRestoreInfo SI) {
606     PrologEpilogSGPRSpills.insert(std::make_pair(Reg, SI));
607   }
608 
609   // Check if an entry created for \p Reg in PrologEpilogSGPRSpills. Return true
610   // on success and false otherwise.
611   bool hasPrologEpilogSGPRSpillEntry(Register Reg) const {
612     return PrologEpilogSGPRSpills.contains(Reg);
613   }
614 
615   // Get the scratch SGPR if allocated to save/restore \p Reg.
616   Register getScratchSGPRCopyDstReg(Register Reg) const {
617     auto I = PrologEpilogSGPRSpills.find(Reg);
618     if (I != PrologEpilogSGPRSpills.end() &&
619         I->second.getKind() == SGPRSaveKind::COPY_TO_SCRATCH_SGPR)
620       return I->second.getReg();
621 
622     return AMDGPU::NoRegister;
623   }
624 
625   // Get all scratch SGPRs allocated to copy/restore the SGPR spills.
626   void getAllScratchSGPRCopyDstRegs(SmallVectorImpl<Register> &Regs) const {
627     for (const auto &SI : PrologEpilogSGPRSpills) {
628       if (SI.second.getKind() == SGPRSaveKind::COPY_TO_SCRATCH_SGPR)
629         Regs.push_back(SI.second.getReg());
630     }
631   }
632 
633   // Check if \p FI is allocated for any SGPR spill to a VGPR lane during PEI.
634   bool checkIndexInPrologEpilogSGPRSpills(int FI) const {
635     return find_if(PrologEpilogSGPRSpills,
636                    [FI](const std::pair<Register,
637                                         PrologEpilogSGPRSaveRestoreInfo> &SI) {
638                      return SI.second.getKind() ==
639                                 SGPRSaveKind::SPILL_TO_VGPR_LANE &&
640                             SI.second.getIndex() == FI;
641                    }) != PrologEpilogSGPRSpills.end();
642   }
643 
644   const PrologEpilogSGPRSaveRestoreInfo &
645   getPrologEpilogSGPRSaveRestoreInfo(Register Reg) const {
646     auto I = PrologEpilogSGPRSpills.find(Reg);
647     assert(I != PrologEpilogSGPRSpills.end());
648 
649     return I->second;
650   }
651 
652   ArrayRef<SIRegisterInfo::SpilledReg>
653   getSGPRSpillToPhysicalVGPRLanes(int FrameIndex) const {
654     auto I = SGPRSpillsToPhysicalVGPRLanes.find(FrameIndex);
655     return (I == SGPRSpillsToPhysicalVGPRLanes.end())
656                ? ArrayRef<SIRegisterInfo::SpilledReg>()
657                : ArrayRef(I->second);
658   }
659 
660   void setFlag(Register Reg, uint8_t Flag) {
661     assert(Reg.isVirtual());
662     if (VRegFlags.inBounds(Reg))
663       VRegFlags[Reg] |= Flag;
664   }
665 
666   bool checkFlag(Register Reg, uint8_t Flag) const {
667     if (Reg.isPhysical())
668       return false;
669 
670     return VRegFlags.inBounds(Reg) && VRegFlags[Reg] & Flag;
671   }
672 
673   bool hasVRegFlags() { return VRegFlags.size(); }
674 
675   void allocateWWMSpill(MachineFunction &MF, Register VGPR, uint64_t Size = 4,
676                         Align Alignment = Align(4));
677 
678   void splitWWMSpillRegisters(
679       MachineFunction &MF,
680       SmallVectorImpl<std::pair<Register, int>> &CalleeSavedRegs,
681       SmallVectorImpl<std::pair<Register, int>> &ScratchRegs) const;
682 
683   ArrayRef<MCPhysReg> getAGPRSpillVGPRs() const {
684     return SpillAGPR;
685   }
686 
687   Register getSGPRForEXECCopy() const { return SGPRForEXECCopy; }
688 
689   void setSGPRForEXECCopy(Register Reg) { SGPRForEXECCopy = Reg; }
690 
691   ArrayRef<MCPhysReg> getVGPRSpillAGPRs() const {
692     return SpillVGPR;
693   }
694 
695   MCPhysReg getVGPRToAGPRSpill(int FrameIndex, unsigned Lane) const {
696     auto I = VGPRToAGPRSpills.find(FrameIndex);
697     return (I == VGPRToAGPRSpills.end()) ? (MCPhysReg)AMDGPU::NoRegister
698                                          : I->second.Lanes[Lane];
699   }
700 
701   void setVGPRToAGPRSpillDead(int FrameIndex) {
702     auto I = VGPRToAGPRSpills.find(FrameIndex);
703     if (I != VGPRToAGPRSpills.end())
704       I->second.IsDead = true;
705   }
706 
707   bool allocateSGPRSpillToVGPRLane(MachineFunction &MF, int FI,
708                                    bool IsPrologEpilog = false);
709   bool allocateVGPRSpillToAGPR(MachineFunction &MF, int FI, bool isAGPRtoVGPR);
710 
711   /// If \p ResetSGPRSpillStackIDs is true, reset the stack ID from sgpr-spill
712   /// to the default stack.
713   bool removeDeadFrameIndices(MachineFrameInfo &MFI,
714                               bool ResetSGPRSpillStackIDs);
715 
716   int getScavengeFI(MachineFrameInfo &MFI, const SIRegisterInfo &TRI);
717   std::optional<int> getOptionalScavengeFI() const { return ScavengeFI; }
718 
719   unsigned getBytesInStackArgArea() const {
720     return BytesInStackArgArea;
721   }
722 
723   void setBytesInStackArgArea(unsigned Bytes) {
724     BytesInStackArgArea = Bytes;
725   }
726 
727   // Add user SGPRs.
728   Register addPrivateSegmentBuffer(const SIRegisterInfo &TRI);
729   Register addDispatchPtr(const SIRegisterInfo &TRI);
730   Register addQueuePtr(const SIRegisterInfo &TRI);
731   Register addKernargSegmentPtr(const SIRegisterInfo &TRI);
732   Register addDispatchID(const SIRegisterInfo &TRI);
733   Register addFlatScratchInit(const SIRegisterInfo &TRI);
734   Register addImplicitBufferPtr(const SIRegisterInfo &TRI);
735   Register addLDSKernelId();
736 
737   /// Increment user SGPRs used for padding the argument list only.
738   Register addReservedUserSGPR() {
739     Register Next = getNextUserSGPR();
740     ++NumUserSGPRs;
741     return Next;
742   }
743 
744   // Add system SGPRs.
745   Register addWorkGroupIDX(bool HasArchitectedSGPRs) {
746     Register Reg =
747         HasArchitectedSGPRs ? (MCPhysReg)AMDGPU::TTMP9 : getNextSystemSGPR();
748     ArgInfo.WorkGroupIDX = ArgDescriptor::createRegister(Reg);
749     if (!HasArchitectedSGPRs)
750       NumSystemSGPRs += 1;
751 
752     return ArgInfo.WorkGroupIDX.getRegister();
753   }
754 
755   Register addWorkGroupIDY(bool HasArchitectedSGPRs) {
756     Register Reg =
757         HasArchitectedSGPRs ? (MCPhysReg)AMDGPU::TTMP7 : getNextSystemSGPR();
758     unsigned Mask = HasArchitectedSGPRs && hasWorkGroupIDZ() ? 0xffff : ~0u;
759     ArgInfo.WorkGroupIDY = ArgDescriptor::createRegister(Reg, Mask);
760     if (!HasArchitectedSGPRs)
761       NumSystemSGPRs += 1;
762 
763     return ArgInfo.WorkGroupIDY.getRegister();
764   }
765 
766   Register addWorkGroupIDZ(bool HasArchitectedSGPRs) {
767     Register Reg =
768         HasArchitectedSGPRs ? (MCPhysReg)AMDGPU::TTMP7 : getNextSystemSGPR();
769     unsigned Mask = HasArchitectedSGPRs ? 0xffff << 16 : ~0u;
770     ArgInfo.WorkGroupIDZ = ArgDescriptor::createRegister(Reg, Mask);
771     if (!HasArchitectedSGPRs)
772       NumSystemSGPRs += 1;
773 
774     return ArgInfo.WorkGroupIDZ.getRegister();
775   }
776 
777   Register addWorkGroupInfo() {
778     ArgInfo.WorkGroupInfo = ArgDescriptor::createRegister(getNextSystemSGPR());
779     NumSystemSGPRs += 1;
780     return ArgInfo.WorkGroupInfo.getRegister();
781   }
782 
783   // Add special VGPR inputs
784   void setWorkItemIDX(ArgDescriptor Arg) {
785     ArgInfo.WorkItemIDX = Arg;
786   }
787 
788   void setWorkItemIDY(ArgDescriptor Arg) {
789     ArgInfo.WorkItemIDY = Arg;
790   }
791 
792   void setWorkItemIDZ(ArgDescriptor Arg) {
793     ArgInfo.WorkItemIDZ = Arg;
794   }
795 
796   Register addPrivateSegmentWaveByteOffset() {
797     ArgInfo.PrivateSegmentWaveByteOffset
798       = ArgDescriptor::createRegister(getNextSystemSGPR());
799     NumSystemSGPRs += 1;
800     return ArgInfo.PrivateSegmentWaveByteOffset.getRegister();
801   }
802 
803   void setPrivateSegmentWaveByteOffset(Register Reg) {
804     ArgInfo.PrivateSegmentWaveByteOffset = ArgDescriptor::createRegister(Reg);
805   }
806 
807   bool hasPrivateSegmentBuffer() const {
808     return PrivateSegmentBuffer;
809   }
810 
811   bool hasDispatchPtr() const {
812     return DispatchPtr;
813   }
814 
815   bool hasQueuePtr() const {
816     return QueuePtr;
817   }
818 
819   bool hasKernargSegmentPtr() const {
820     return KernargSegmentPtr;
821   }
822 
823   bool hasDispatchID() const {
824     return DispatchID;
825   }
826 
827   bool hasFlatScratchInit() const {
828     return FlatScratchInit;
829   }
830 
831   bool hasWorkGroupIDX() const {
832     return WorkGroupIDX;
833   }
834 
835   bool hasWorkGroupIDY() const {
836     return WorkGroupIDY;
837   }
838 
839   bool hasWorkGroupIDZ() const {
840     return WorkGroupIDZ;
841   }
842 
843   bool hasWorkGroupInfo() const {
844     return WorkGroupInfo;
845   }
846 
847   bool hasLDSKernelId() const { return LDSKernelId; }
848 
849   bool hasPrivateSegmentWaveByteOffset() const {
850     return PrivateSegmentWaveByteOffset;
851   }
852 
853   bool hasWorkItemIDX() const {
854     return WorkItemIDX;
855   }
856 
857   bool hasWorkItemIDY() const {
858     return WorkItemIDY;
859   }
860 
861   bool hasWorkItemIDZ() const {
862     return WorkItemIDZ;
863   }
864 
865   bool hasImplicitArgPtr() const {
866     return ImplicitArgPtr;
867   }
868 
869   bool hasImplicitBufferPtr() const {
870     return ImplicitBufferPtr;
871   }
872 
873   AMDGPUFunctionArgInfo &getArgInfo() {
874     return ArgInfo;
875   }
876 
877   const AMDGPUFunctionArgInfo &getArgInfo() const {
878     return ArgInfo;
879   }
880 
881   std::tuple<const ArgDescriptor *, const TargetRegisterClass *, LLT>
882   getPreloadedValue(AMDGPUFunctionArgInfo::PreloadedValue Value) const {
883     return ArgInfo.getPreloadedValue(Value);
884   }
885 
886   MCRegister getPreloadedReg(AMDGPUFunctionArgInfo::PreloadedValue Value) const {
887     auto Arg = std::get<0>(ArgInfo.getPreloadedValue(Value));
888     return Arg ? Arg->getRegister() : MCRegister();
889   }
890 
891   unsigned getGITPtrHigh() const {
892     return GITPtrHigh;
893   }
894 
895   Register getGITPtrLoReg(const MachineFunction &MF) const;
896 
897   uint32_t get32BitAddressHighBits() const {
898     return HighBitsOf32BitAddress;
899   }
900 
901   unsigned getNumUserSGPRs() const {
902     return NumUserSGPRs;
903   }
904 
905   unsigned getNumPreloadedSGPRs() const {
906     return NumUserSGPRs + NumSystemSGPRs;
907   }
908 
909   Register getPrivateSegmentWaveByteOffsetSystemSGPR() const {
910     return ArgInfo.PrivateSegmentWaveByteOffset.getRegister();
911   }
912 
913   /// Returns the physical register reserved for use as the resource
914   /// descriptor for scratch accesses.
915   Register getScratchRSrcReg() const {
916     return ScratchRSrcReg;
917   }
918 
919   void setScratchRSrcReg(Register Reg) {
920     assert(Reg != 0 && "Should never be unset");
921     ScratchRSrcReg = Reg;
922   }
923 
924   Register getFrameOffsetReg() const {
925     return FrameOffsetReg;
926   }
927 
928   void setFrameOffsetReg(Register Reg) {
929     assert(Reg != 0 && "Should never be unset");
930     FrameOffsetReg = Reg;
931   }
932 
933   void setStackPtrOffsetReg(Register Reg) {
934     assert(Reg != 0 && "Should never be unset");
935     StackPtrOffsetReg = Reg;
936   }
937 
938   void setLongBranchReservedReg(Register Reg) { LongBranchReservedReg = Reg; }
939 
940   // Note the unset value for this is AMDGPU::SP_REG rather than
941   // NoRegister. This is mostly a workaround for MIR tests where state that
942   // can't be directly computed from the function is not preserved in serialized
943   // MIR.
944   Register getStackPtrOffsetReg() const {
945     return StackPtrOffsetReg;
946   }
947 
948   Register getLongBranchReservedReg() const { return LongBranchReservedReg; }
949 
950   Register getQueuePtrUserSGPR() const {
951     return ArgInfo.QueuePtr.getRegister();
952   }
953 
954   Register getImplicitBufferPtrUserSGPR() const {
955     return ArgInfo.ImplicitBufferPtr.getRegister();
956   }
957 
958   bool hasSpilledSGPRs() const {
959     return HasSpilledSGPRs;
960   }
961 
962   void setHasSpilledSGPRs(bool Spill = true) {
963     HasSpilledSGPRs = Spill;
964   }
965 
966   bool hasSpilledVGPRs() const {
967     return HasSpilledVGPRs;
968   }
969 
970   void setHasSpilledVGPRs(bool Spill = true) {
971     HasSpilledVGPRs = Spill;
972   }
973 
974   bool hasNonSpillStackObjects() const {
975     return HasNonSpillStackObjects;
976   }
977 
978   void setHasNonSpillStackObjects(bool StackObject = true) {
979     HasNonSpillStackObjects = StackObject;
980   }
981 
982   bool isStackRealigned() const {
983     return IsStackRealigned;
984   }
985 
986   void setIsStackRealigned(bool Realigned = true) {
987     IsStackRealigned = Realigned;
988   }
989 
990   unsigned getNumSpilledSGPRs() const {
991     return NumSpilledSGPRs;
992   }
993 
994   unsigned getNumSpilledVGPRs() const {
995     return NumSpilledVGPRs;
996   }
997 
998   void addToSpilledSGPRs(unsigned num) {
999     NumSpilledSGPRs += num;
1000   }
1001 
1002   void addToSpilledVGPRs(unsigned num) {
1003     NumSpilledVGPRs += num;
1004   }
1005 
1006   unsigned getPSInputAddr() const {
1007     return PSInputAddr;
1008   }
1009 
1010   unsigned getPSInputEnable() const {
1011     return PSInputEnable;
1012   }
1013 
1014   bool isPSInputAllocated(unsigned Index) const {
1015     return PSInputAddr & (1 << Index);
1016   }
1017 
1018   void markPSInputAllocated(unsigned Index) {
1019     PSInputAddr |= 1 << Index;
1020   }
1021 
1022   void markPSInputEnabled(unsigned Index) {
1023     PSInputEnable |= 1 << Index;
1024   }
1025 
1026   bool returnsVoid() const {
1027     return ReturnsVoid;
1028   }
1029 
1030   void setIfReturnsVoid(bool Value) {
1031     ReturnsVoid = Value;
1032   }
1033 
1034   /// \returns A pair of default/requested minimum/maximum flat work group sizes
1035   /// for this function.
1036   std::pair<unsigned, unsigned> getFlatWorkGroupSizes() const {
1037     return FlatWorkGroupSizes;
1038   }
1039 
1040   /// \returns Default/requested minimum flat work group size for this function.
1041   unsigned getMinFlatWorkGroupSize() const {
1042     return FlatWorkGroupSizes.first;
1043   }
1044 
1045   /// \returns Default/requested maximum flat work group size for this function.
1046   unsigned getMaxFlatWorkGroupSize() const {
1047     return FlatWorkGroupSizes.second;
1048   }
1049 
1050   /// \returns A pair of default/requested minimum/maximum number of waves per
1051   /// execution unit.
1052   std::pair<unsigned, unsigned> getWavesPerEU() const {
1053     return WavesPerEU;
1054   }
1055 
1056   /// \returns Default/requested minimum number of waves per execution unit.
1057   unsigned getMinWavesPerEU() const {
1058     return WavesPerEU.first;
1059   }
1060 
1061   /// \returns Default/requested maximum number of waves per execution unit.
1062   unsigned getMaxWavesPerEU() const {
1063     return WavesPerEU.second;
1064   }
1065 
1066   /// \returns SGPR used for \p Dim's work group ID.
1067   Register getWorkGroupIDSGPR(unsigned Dim) const {
1068     switch (Dim) {
1069     case 0:
1070       assert(hasWorkGroupIDX());
1071       return ArgInfo.WorkGroupIDX.getRegister();
1072     case 1:
1073       assert(hasWorkGroupIDY());
1074       return ArgInfo.WorkGroupIDY.getRegister();
1075     case 2:
1076       assert(hasWorkGroupIDZ());
1077       return ArgInfo.WorkGroupIDZ.getRegister();
1078     }
1079     llvm_unreachable("unexpected dimension");
1080   }
1081 
1082   const AMDGPUGWSResourcePseudoSourceValue *
1083   getGWSPSV(const AMDGPUTargetMachine &TM) {
1084     return &GWSResourcePSV;
1085   }
1086 
1087   unsigned getOccupancy() const {
1088     return Occupancy;
1089   }
1090 
1091   unsigned getMinAllowedOccupancy() const {
1092     if (!isMemoryBound() && !needsWaveLimiter())
1093       return Occupancy;
1094     return (Occupancy < 4) ? Occupancy : 4;
1095   }
1096 
1097   void limitOccupancy(const MachineFunction &MF);
1098 
1099   void limitOccupancy(unsigned Limit) {
1100     if (Occupancy > Limit)
1101       Occupancy = Limit;
1102   }
1103 
1104   void increaseOccupancy(const MachineFunction &MF, unsigned Limit) {
1105     if (Occupancy < Limit)
1106       Occupancy = Limit;
1107     limitOccupancy(MF);
1108   }
1109 
1110   bool mayNeedAGPRs() const {
1111     return MayNeedAGPRs;
1112   }
1113 
1114   // \returns true if a function has a use of AGPRs via inline asm or
1115   // has a call which may use it.
1116   bool mayUseAGPRs(const Function &F) const;
1117 
1118   // \returns true if a function needs or may need AGPRs.
1119   bool usesAGPRs(const MachineFunction &MF) const;
1120 };
1121 
1122 } // end namespace llvm
1123 
1124 #endif // LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
1125