xref: /llvm-project/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h (revision aa144fbeaf213d93f8a244a353db4c3301d8b1b0)
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 NoSignedZerosFPMath = false;
260   bool MemoryBound = false;
261   bool WaveLimiter = false;
262   bool HasSpilledSGPRs = false;
263   bool HasSpilledVGPRs = false;
264   uint32_t HighBitsOf32BitAddress = 0;
265 
266   // TODO: 10 may be a better default since it's the maximum.
267   unsigned Occupancy = 0;
268 
269   SmallVector<StringValue> WWMReservedRegs;
270 
271   StringValue ScratchRSrcReg = "$private_rsrc_reg";
272   StringValue FrameOffsetReg = "$fp_reg";
273   StringValue StackPtrOffsetReg = "$sp_reg";
274 
275   unsigned BytesInStackArgArea = 0;
276   bool ReturnsVoid = true;
277 
278   std::optional<SIArgumentInfo> ArgInfo;
279 
280   unsigned PSInputAddr = 0;
281   unsigned PSInputEnable = 0;
282 
283   SIMode Mode;
284   std::optional<FrameIndex> ScavengeFI;
285   StringValue VGPRForAGPRCopy;
286 
287   SIMachineFunctionInfo() = default;
288   SIMachineFunctionInfo(const llvm::SIMachineFunctionInfo &,
289                         const TargetRegisterInfo &TRI,
290                         const llvm::MachineFunction &MF);
291 
292   void mappingImpl(yaml::IO &YamlIO) override;
293   ~SIMachineFunctionInfo() = default;
294 };
295 
296 template <> struct MappingTraits<SIMachineFunctionInfo> {
297   static void mapping(IO &YamlIO, SIMachineFunctionInfo &MFI) {
298     YamlIO.mapOptional("explicitKernArgSize", MFI.ExplicitKernArgSize,
299                        UINT64_C(0));
300     YamlIO.mapOptional("maxKernArgAlign", MFI.MaxKernArgAlign);
301     YamlIO.mapOptional("ldsSize", MFI.LDSSize, 0u);
302     YamlIO.mapOptional("gdsSize", MFI.GDSSize, 0u);
303     YamlIO.mapOptional("dynLDSAlign", MFI.DynLDSAlign, Align());
304     YamlIO.mapOptional("isEntryFunction", MFI.IsEntryFunction, false);
305     YamlIO.mapOptional("noSignedZerosFPMath", MFI.NoSignedZerosFPMath, false);
306     YamlIO.mapOptional("memoryBound", MFI.MemoryBound, false);
307     YamlIO.mapOptional("waveLimiter", MFI.WaveLimiter, false);
308     YamlIO.mapOptional("hasSpilledSGPRs", MFI.HasSpilledSGPRs, false);
309     YamlIO.mapOptional("hasSpilledVGPRs", MFI.HasSpilledVGPRs, false);
310     YamlIO.mapOptional("scratchRSrcReg", MFI.ScratchRSrcReg,
311                        StringValue("$private_rsrc_reg"));
312     YamlIO.mapOptional("frameOffsetReg", MFI.FrameOffsetReg,
313                        StringValue("$fp_reg"));
314     YamlIO.mapOptional("stackPtrOffsetReg", MFI.StackPtrOffsetReg,
315                        StringValue("$sp_reg"));
316     YamlIO.mapOptional("bytesInStackArgArea", MFI.BytesInStackArgArea, 0u);
317     YamlIO.mapOptional("returnsVoid", MFI.ReturnsVoid, true);
318     YamlIO.mapOptional("argumentInfo", MFI.ArgInfo);
319     YamlIO.mapOptional("psInputAddr", MFI.PSInputAddr, 0u);
320     YamlIO.mapOptional("psInputEnable", MFI.PSInputEnable, 0u);
321     YamlIO.mapOptional("mode", MFI.Mode, SIMode());
322     YamlIO.mapOptional("highBitsOf32BitAddress",
323                        MFI.HighBitsOf32BitAddress, 0u);
324     YamlIO.mapOptional("occupancy", MFI.Occupancy, 0);
325     YamlIO.mapOptional("wwmReservedRegs", MFI.WWMReservedRegs);
326     YamlIO.mapOptional("scavengeFI", MFI.ScavengeFI);
327     YamlIO.mapOptional("vgprForAGPRCopy", MFI.VGPRForAGPRCopy,
328                        StringValue()); // Don't print out when it's empty.
329   }
330 };
331 
332 } // end namespace yaml
333 
334 // A CSR SGPR value can be preserved inside a callee using one of the following
335 // methods.
336 //   1. Copy to an unused scratch SGPR.
337 //   2. Spill to a VGPR lane.
338 //   3. Spill to memory via. a scratch VGPR.
339 // class PrologEpilogSGPRSaveRestoreInfo represents the save/restore method used
340 // for an SGPR at function prolog/epilog.
341 enum class SGPRSaveKind : uint8_t {
342   COPY_TO_SCRATCH_SGPR,
343   SPILL_TO_VGPR_LANE,
344   SPILL_TO_MEM
345 };
346 
347 class PrologEpilogSGPRSaveRestoreInfo {
348   SGPRSaveKind Kind;
349   union {
350     int Index;
351     Register Reg;
352   };
353 
354 public:
355   PrologEpilogSGPRSaveRestoreInfo(SGPRSaveKind K, int I) : Kind(K), Index(I) {}
356   PrologEpilogSGPRSaveRestoreInfo(SGPRSaveKind K, Register R)
357       : Kind(K), Reg(R) {}
358   Register getReg() const { return Reg; }
359   int getIndex() const { return Index; }
360   SGPRSaveKind getKind() const { return Kind; }
361 };
362 
363 /// This class keeps track of the SPI_SP_INPUT_ADDR config register, which
364 /// tells the hardware which interpolation parameters to load.
365 class SIMachineFunctionInfo final : public AMDGPUMachineFunction {
366   friend class GCNTargetMachine;
367 
368   // State of MODE register, assumed FP mode.
369   SIModeRegisterDefaults Mode;
370 
371   // Registers that may be reserved for spilling purposes. These may be the same
372   // as the input registers.
373   Register ScratchRSrcReg = AMDGPU::PRIVATE_RSRC_REG;
374 
375   // This is the unswizzled offset from the current dispatch's scratch wave
376   // base to the beginning of the current function's frame.
377   Register FrameOffsetReg = AMDGPU::FP_REG;
378 
379   // This is an ABI register used in the non-entry calling convention to
380   // communicate the unswizzled offset from the current dispatch's scratch wave
381   // base to the beginning of the new function's frame.
382   Register StackPtrOffsetReg = AMDGPU::SP_REG;
383 
384   AMDGPUFunctionArgInfo ArgInfo;
385 
386   // Graphics info.
387   unsigned PSInputAddr = 0;
388   unsigned PSInputEnable = 0;
389 
390   /// Number of bytes of arguments this function has on the stack. If the callee
391   /// is expected to restore the argument stack this should be a multiple of 16,
392   /// all usable during a tail call.
393   ///
394   /// The alternative would forbid tail call optimisation in some cases: if we
395   /// want to transfer control from a function with 8-bytes of stack-argument
396   /// space to a function with 16-bytes then misalignment of this value would
397   /// make a stack adjustment necessary, which could not be undone by the
398   /// callee.
399   unsigned BytesInStackArgArea = 0;
400 
401   bool ReturnsVoid = true;
402 
403   // A pair of default/requested minimum/maximum flat work group sizes.
404   // Minimum - first, maximum - second.
405   std::pair<unsigned, unsigned> FlatWorkGroupSizes = {0, 0};
406 
407   // A pair of default/requested minimum/maximum number of waves per execution
408   // unit. Minimum - first, maximum - second.
409   std::pair<unsigned, unsigned> WavesPerEU = {0, 0};
410 
411   const AMDGPUGWSResourcePseudoSourceValue GWSResourcePSV;
412 
413 private:
414   unsigned NumUserSGPRs = 0;
415   unsigned NumSystemSGPRs = 0;
416 
417   bool HasSpilledSGPRs = false;
418   bool HasSpilledVGPRs = false;
419   bool HasNonSpillStackObjects = false;
420   bool IsStackRealigned = false;
421 
422   unsigned NumSpilledSGPRs = 0;
423   unsigned NumSpilledVGPRs = 0;
424 
425   // Feature bits required for inputs passed in user SGPRs.
426   bool PrivateSegmentBuffer : 1;
427   bool DispatchPtr : 1;
428   bool QueuePtr : 1;
429   bool KernargSegmentPtr : 1;
430   bool DispatchID : 1;
431   bool FlatScratchInit : 1;
432 
433   // Feature bits required for inputs passed in system SGPRs.
434   bool WorkGroupIDX : 1; // Always initialized.
435   bool WorkGroupIDY : 1;
436   bool WorkGroupIDZ : 1;
437   bool WorkGroupInfo : 1;
438   bool LDSKernelId : 1;
439   bool PrivateSegmentWaveByteOffset : 1;
440 
441   bool WorkItemIDX : 1; // Always initialized.
442   bool WorkItemIDY : 1;
443   bool WorkItemIDZ : 1;
444 
445   // Private memory buffer
446   // Compute directly in sgpr[0:1]
447   // Other shaders indirect 64-bits at sgpr[0:1]
448   bool ImplicitBufferPtr : 1;
449 
450   // Pointer to where the ABI inserts special kernel arguments separate from the
451   // user arguments. This is an offset from the KernargSegmentPtr.
452   bool ImplicitArgPtr : 1;
453 
454   bool MayNeedAGPRs : 1;
455 
456   // The hard-wired high half of the address of the global information table
457   // for AMDPAL OS type. 0xffffffff represents no hard-wired high half, since
458   // current hardware only allows a 16 bit value.
459   unsigned GITPtrHigh;
460 
461   unsigned HighBitsOf32BitAddress;
462 
463   // Current recorded maximum possible occupancy.
464   unsigned Occupancy;
465 
466   mutable std::optional<bool> UsesAGPRs;
467 
468   MCPhysReg getNextUserSGPR() const;
469 
470   MCPhysReg getNextSystemSGPR() const;
471 
472 public:
473   struct VGPRSpillToAGPR {
474     SmallVector<MCPhysReg, 32> Lanes;
475     bool FullyAllocated = false;
476     bool IsDead = false;
477   };
478 
479 private:
480   // To track VGPR + lane index for each subregister of the SGPR spilled to
481   // frameindex key during SILowerSGPRSpills pass.
482   DenseMap<int, std::vector<SIRegisterInfo::SpilledReg>> SGPRSpillToVGPRLanes;
483   // To track VGPR + lane index for spilling special SGPRs like Frame Pointer
484   // identified during PrologEpilogInserter.
485   DenseMap<int, std::vector<SIRegisterInfo::SpilledReg>>
486       PrologEpilogSGPRSpillToVGPRLanes;
487   unsigned NumVGPRSpillLanes = 0;
488   unsigned NumVGPRPrologEpilogSpillLanes = 0;
489   SmallVector<Register, 2> SpillVGPRs;
490   using WWMSpillsMap = MapVector<Register, int>;
491   // To track the registers used in instructions that can potentially modify the
492   // inactive lanes. The WWM instructions and the writelane instructions for
493   // spilling SGPRs to VGPRs fall under such category of operations. The VGPRs
494   // modified by them should be spilled/restored at function prolog/epilog to
495   // avoid any undesired outcome. Each entry in this map holds a pair of values,
496   // the VGPR and its stack slot index.
497   WWMSpillsMap WWMSpills;
498 
499   using ReservedRegSet = SmallSetVector<Register, 8>;
500   // To track the VGPRs reserved for WWM instructions. They get stack slots
501   // later during PrologEpilogInserter and get added into the superset WWMSpills
502   // for actual spilling. A separate set makes the register reserved part and
503   // the serialization easier.
504   ReservedRegSet WWMReservedRegs;
505 
506   using PrologEpilogSGPRSpillsMap =
507       DenseMap<Register, PrologEpilogSGPRSaveRestoreInfo>;
508   // To track the SGPR spill method used for a CSR SGPR register during
509   // frame lowering. Even though the SGPR spills are handled during
510   // SILowerSGPRSpills pass, some special handling needed later during the
511   // PrologEpilogInserter.
512   PrologEpilogSGPRSpillsMap PrologEpilogSGPRSpills;
513 
514   DenseMap<int, VGPRSpillToAGPR> VGPRToAGPRSpills;
515 
516   // AGPRs used for VGPR spills.
517   SmallVector<MCPhysReg, 32> SpillAGPR;
518 
519   // VGPRs used for AGPR spills.
520   SmallVector<MCPhysReg, 32> SpillVGPR;
521 
522   // Emergency stack slot. Sometimes, we create this before finalizing the stack
523   // frame, so save it here and add it to the RegScavenger later.
524   std::optional<int> ScavengeFI;
525 
526 private:
527   Register VGPRForAGPRCopy;
528 
529   bool allocateVGPRForSGPRSpills(MachineFunction &MF, int FI,
530                                  unsigned LaneIndex);
531   bool allocateVGPRForPrologEpilogSGPRSpills(MachineFunction &MF, int FI,
532                                              unsigned LaneIndex);
533 
534 public:
535   Register getVGPRForAGPRCopy() const {
536     return VGPRForAGPRCopy;
537   }
538 
539   void setVGPRForAGPRCopy(Register NewVGPRForAGPRCopy) {
540     VGPRForAGPRCopy = NewVGPRForAGPRCopy;
541   }
542 
543   bool isCalleeSavedReg(const MCPhysReg *CSRegs, MCPhysReg Reg) const;
544 
545 public:
546   SIMachineFunctionInfo(const SIMachineFunctionInfo &MFI) = default;
547   SIMachineFunctionInfo(const Function &F, const GCNSubtarget *STI);
548 
549   MachineFunctionInfo *
550   clone(BumpPtrAllocator &Allocator, MachineFunction &DestMF,
551         const DenseMap<MachineBasicBlock *, MachineBasicBlock *> &Src2DstMBB)
552       const override;
553 
554   bool initializeBaseYamlFields(const yaml::SIMachineFunctionInfo &YamlMFI,
555                                 const MachineFunction &MF,
556                                 PerFunctionMIParsingState &PFS,
557                                 SMDiagnostic &Error, SMRange &SourceRange);
558 
559   void reserveWWMRegister(Register Reg) { WWMReservedRegs.insert(Reg); }
560 
561   SIModeRegisterDefaults getMode() const { return Mode; }
562 
563   ArrayRef<SIRegisterInfo::SpilledReg>
564   getSGPRSpillToVGPRLanes(int FrameIndex) const {
565     auto I = SGPRSpillToVGPRLanes.find(FrameIndex);
566     return (I == SGPRSpillToVGPRLanes.end())
567                ? ArrayRef<SIRegisterInfo::SpilledReg>()
568                : ArrayRef(I->second);
569   }
570 
571   ArrayRef<Register> getSGPRSpillVGPRs() const { return SpillVGPRs; }
572   const WWMSpillsMap &getWWMSpills() const { return WWMSpills; }
573   const ReservedRegSet &getWWMReservedRegs() const { return WWMReservedRegs; }
574 
575   const PrologEpilogSGPRSpillsMap &getPrologEpilogSGPRSpills() const {
576     return PrologEpilogSGPRSpills;
577   }
578 
579   void addToPrologEpilogSGPRSpills(Register Reg,
580                                    PrologEpilogSGPRSaveRestoreInfo SI) {
581     PrologEpilogSGPRSpills.insert(std::make_pair(Reg, SI));
582   }
583 
584   // Check if an entry created for \p Reg in PrologEpilogSGPRSpills. Return true
585   // on success and false otherwise.
586   bool hasPrologEpilogSGPRSpillEntry(Register Reg) const {
587     return PrologEpilogSGPRSpills.contains(Reg);
588   }
589 
590   // Get the scratch SGPR if allocated to save/restore \p Reg.
591   Register getScratchSGPRCopyDstReg(Register Reg) const {
592     auto I = PrologEpilogSGPRSpills.find(Reg);
593     if (I != PrologEpilogSGPRSpills.end() &&
594         I->second.getKind() == SGPRSaveKind::COPY_TO_SCRATCH_SGPR)
595       return I->second.getReg();
596 
597     return AMDGPU::NoRegister;
598   }
599 
600   // Get all scratch SGPRs allocated to copy/restore the SGPR spills.
601   void getAllScratchSGPRCopyDstRegs(SmallVectorImpl<Register> &Regs) const {
602     for (const auto &SI : PrologEpilogSGPRSpills) {
603       if (SI.second.getKind() == SGPRSaveKind::COPY_TO_SCRATCH_SGPR)
604         Regs.push_back(SI.second.getReg());
605     }
606   }
607 
608   // Check if \p FI is allocated for any SGPR spill to a VGPR lane during PEI.
609   bool checkIndexInPrologEpilogSGPRSpills(int FI) const {
610     return find_if(PrologEpilogSGPRSpills,
611                    [FI](const std::pair<Register,
612                                         PrologEpilogSGPRSaveRestoreInfo> &SI) {
613                      return SI.second.getKind() ==
614                                 SGPRSaveKind::SPILL_TO_VGPR_LANE &&
615                             SI.second.getIndex() == FI;
616                    }) != PrologEpilogSGPRSpills.end();
617   }
618 
619   const PrologEpilogSGPRSaveRestoreInfo &
620   getPrologEpilogSGPRSaveRestoreInfo(Register Reg) const {
621     auto I = PrologEpilogSGPRSpills.find(Reg);
622     assert(I != PrologEpilogSGPRSpills.end());
623 
624     return I->second;
625   }
626 
627   ArrayRef<SIRegisterInfo::SpilledReg>
628   getPrologEpilogSGPRSpillToVGPRLanes(int FrameIndex) const {
629     auto I = PrologEpilogSGPRSpillToVGPRLanes.find(FrameIndex);
630     return (I == PrologEpilogSGPRSpillToVGPRLanes.end())
631                ? ArrayRef<SIRegisterInfo::SpilledReg>()
632                : ArrayRef(I->second);
633   }
634 
635   void allocateWWMSpill(MachineFunction &MF, Register VGPR, uint64_t Size = 4,
636                         Align Alignment = Align(4));
637 
638   void splitWWMSpillRegisters(
639       MachineFunction &MF,
640       SmallVectorImpl<std::pair<Register, int>> &CalleeSavedRegs,
641       SmallVectorImpl<std::pair<Register, int>> &ScratchRegs) const;
642 
643   ArrayRef<MCPhysReg> getAGPRSpillVGPRs() const {
644     return SpillAGPR;
645   }
646 
647   ArrayRef<MCPhysReg> getVGPRSpillAGPRs() const {
648     return SpillVGPR;
649   }
650 
651   MCPhysReg getVGPRToAGPRSpill(int FrameIndex, unsigned Lane) const {
652     auto I = VGPRToAGPRSpills.find(FrameIndex);
653     return (I == VGPRToAGPRSpills.end()) ? (MCPhysReg)AMDGPU::NoRegister
654                                          : I->second.Lanes[Lane];
655   }
656 
657   void setVGPRToAGPRSpillDead(int FrameIndex) {
658     auto I = VGPRToAGPRSpills.find(FrameIndex);
659     if (I != VGPRToAGPRSpills.end())
660       I->second.IsDead = true;
661   }
662 
663   bool allocateSGPRSpillToVGPRLane(MachineFunction &MF, int FI,
664                                    bool IsPrologEpilog = false);
665   bool allocateVGPRSpillToAGPR(MachineFunction &MF, int FI, bool isAGPRtoVGPR);
666 
667   /// If \p ResetSGPRSpillStackIDs is true, reset the stack ID from sgpr-spill
668   /// to the default stack.
669   bool removeDeadFrameIndices(MachineFrameInfo &MFI,
670                               bool ResetSGPRSpillStackIDs);
671 
672   int getScavengeFI(MachineFrameInfo &MFI, const SIRegisterInfo &TRI);
673   std::optional<int> getOptionalScavengeFI() const { return ScavengeFI; }
674 
675   unsigned getBytesInStackArgArea() const {
676     return BytesInStackArgArea;
677   }
678 
679   void setBytesInStackArgArea(unsigned Bytes) {
680     BytesInStackArgArea = Bytes;
681   }
682 
683   // Add user SGPRs.
684   Register addPrivateSegmentBuffer(const SIRegisterInfo &TRI);
685   Register addDispatchPtr(const SIRegisterInfo &TRI);
686   Register addQueuePtr(const SIRegisterInfo &TRI);
687   Register addKernargSegmentPtr(const SIRegisterInfo &TRI);
688   Register addDispatchID(const SIRegisterInfo &TRI);
689   Register addFlatScratchInit(const SIRegisterInfo &TRI);
690   Register addImplicitBufferPtr(const SIRegisterInfo &TRI);
691   Register addLDSKernelId();
692 
693   /// Increment user SGPRs used for padding the argument list only.
694   Register addReservedUserSGPR() {
695     Register Next = getNextUserSGPR();
696     ++NumUserSGPRs;
697     return Next;
698   }
699 
700   // Add system SGPRs.
701   Register addWorkGroupIDX(bool HasArchitectedSGPRs) {
702     Register Reg =
703         HasArchitectedSGPRs ? (MCPhysReg)AMDGPU::TTMP9 : getNextSystemSGPR();
704     ArgInfo.WorkGroupIDX = ArgDescriptor::createRegister(Reg);
705     if (!HasArchitectedSGPRs)
706       NumSystemSGPRs += 1;
707 
708     return ArgInfo.WorkGroupIDX.getRegister();
709   }
710 
711   Register addWorkGroupIDY(bool HasArchitectedSGPRs) {
712     Register Reg =
713         HasArchitectedSGPRs ? (MCPhysReg)AMDGPU::TTMP7 : getNextSystemSGPR();
714     unsigned Mask = HasArchitectedSGPRs && hasWorkGroupIDZ() ? 0xffff : ~0u;
715     ArgInfo.WorkGroupIDY = ArgDescriptor::createRegister(Reg, Mask);
716     if (!HasArchitectedSGPRs)
717       NumSystemSGPRs += 1;
718 
719     return ArgInfo.WorkGroupIDY.getRegister();
720   }
721 
722   Register addWorkGroupIDZ(bool HasArchitectedSGPRs) {
723     Register Reg =
724         HasArchitectedSGPRs ? (MCPhysReg)AMDGPU::TTMP7 : getNextSystemSGPR();
725     unsigned Mask = HasArchitectedSGPRs ? 0xffff << 16 : ~0u;
726     ArgInfo.WorkGroupIDZ = ArgDescriptor::createRegister(Reg, Mask);
727     if (!HasArchitectedSGPRs)
728       NumSystemSGPRs += 1;
729 
730     return ArgInfo.WorkGroupIDZ.getRegister();
731   }
732 
733   Register addWorkGroupInfo() {
734     ArgInfo.WorkGroupInfo = ArgDescriptor::createRegister(getNextSystemSGPR());
735     NumSystemSGPRs += 1;
736     return ArgInfo.WorkGroupInfo.getRegister();
737   }
738 
739   // Add special VGPR inputs
740   void setWorkItemIDX(ArgDescriptor Arg) {
741     ArgInfo.WorkItemIDX = Arg;
742   }
743 
744   void setWorkItemIDY(ArgDescriptor Arg) {
745     ArgInfo.WorkItemIDY = Arg;
746   }
747 
748   void setWorkItemIDZ(ArgDescriptor Arg) {
749     ArgInfo.WorkItemIDZ = Arg;
750   }
751 
752   Register addPrivateSegmentWaveByteOffset() {
753     ArgInfo.PrivateSegmentWaveByteOffset
754       = ArgDescriptor::createRegister(getNextSystemSGPR());
755     NumSystemSGPRs += 1;
756     return ArgInfo.PrivateSegmentWaveByteOffset.getRegister();
757   }
758 
759   void setPrivateSegmentWaveByteOffset(Register Reg) {
760     ArgInfo.PrivateSegmentWaveByteOffset = ArgDescriptor::createRegister(Reg);
761   }
762 
763   bool hasPrivateSegmentBuffer() const {
764     return PrivateSegmentBuffer;
765   }
766 
767   bool hasDispatchPtr() const {
768     return DispatchPtr;
769   }
770 
771   bool hasQueuePtr() const {
772     return QueuePtr;
773   }
774 
775   bool hasKernargSegmentPtr() const {
776     return KernargSegmentPtr;
777   }
778 
779   bool hasDispatchID() const {
780     return DispatchID;
781   }
782 
783   bool hasFlatScratchInit() const {
784     return FlatScratchInit;
785   }
786 
787   bool hasWorkGroupIDX() const {
788     return WorkGroupIDX;
789   }
790 
791   bool hasWorkGroupIDY() const {
792     return WorkGroupIDY;
793   }
794 
795   bool hasWorkGroupIDZ() const {
796     return WorkGroupIDZ;
797   }
798 
799   bool hasWorkGroupInfo() const {
800     return WorkGroupInfo;
801   }
802 
803   bool hasLDSKernelId() const { return LDSKernelId; }
804 
805   bool hasPrivateSegmentWaveByteOffset() const {
806     return PrivateSegmentWaveByteOffset;
807   }
808 
809   bool hasWorkItemIDX() const {
810     return WorkItemIDX;
811   }
812 
813   bool hasWorkItemIDY() const {
814     return WorkItemIDY;
815   }
816 
817   bool hasWorkItemIDZ() const {
818     return WorkItemIDZ;
819   }
820 
821   bool hasImplicitArgPtr() const {
822     return ImplicitArgPtr;
823   }
824 
825   bool hasImplicitBufferPtr() const {
826     return ImplicitBufferPtr;
827   }
828 
829   AMDGPUFunctionArgInfo &getArgInfo() {
830     return ArgInfo;
831   }
832 
833   const AMDGPUFunctionArgInfo &getArgInfo() const {
834     return ArgInfo;
835   }
836 
837   std::tuple<const ArgDescriptor *, const TargetRegisterClass *, LLT>
838   getPreloadedValue(AMDGPUFunctionArgInfo::PreloadedValue Value) const {
839     return ArgInfo.getPreloadedValue(Value);
840   }
841 
842   MCRegister getPreloadedReg(AMDGPUFunctionArgInfo::PreloadedValue Value) const {
843     auto Arg = std::get<0>(ArgInfo.getPreloadedValue(Value));
844     return Arg ? Arg->getRegister() : MCRegister();
845   }
846 
847   unsigned getGITPtrHigh() const {
848     return GITPtrHigh;
849   }
850 
851   Register getGITPtrLoReg(const MachineFunction &MF) const;
852 
853   uint32_t get32BitAddressHighBits() const {
854     return HighBitsOf32BitAddress;
855   }
856 
857   unsigned getNumUserSGPRs() const {
858     return NumUserSGPRs;
859   }
860 
861   unsigned getNumPreloadedSGPRs() const {
862     return NumUserSGPRs + NumSystemSGPRs;
863   }
864 
865   Register getPrivateSegmentWaveByteOffsetSystemSGPR() const {
866     return ArgInfo.PrivateSegmentWaveByteOffset.getRegister();
867   }
868 
869   /// Returns the physical register reserved for use as the resource
870   /// descriptor for scratch accesses.
871   Register getScratchRSrcReg() const {
872     return ScratchRSrcReg;
873   }
874 
875   void setScratchRSrcReg(Register Reg) {
876     assert(Reg != 0 && "Should never be unset");
877     ScratchRSrcReg = Reg;
878   }
879 
880   Register getFrameOffsetReg() const {
881     return FrameOffsetReg;
882   }
883 
884   void setFrameOffsetReg(Register Reg) {
885     assert(Reg != 0 && "Should never be unset");
886     FrameOffsetReg = Reg;
887   }
888 
889   void setStackPtrOffsetReg(Register Reg) {
890     assert(Reg != 0 && "Should never be unset");
891     StackPtrOffsetReg = Reg;
892   }
893 
894   // Note the unset value for this is AMDGPU::SP_REG rather than
895   // NoRegister. This is mostly a workaround for MIR tests where state that
896   // can't be directly computed from the function is not preserved in serialized
897   // MIR.
898   Register getStackPtrOffsetReg() const {
899     return StackPtrOffsetReg;
900   }
901 
902   Register getQueuePtrUserSGPR() const {
903     return ArgInfo.QueuePtr.getRegister();
904   }
905 
906   Register getImplicitBufferPtrUserSGPR() const {
907     return ArgInfo.ImplicitBufferPtr.getRegister();
908   }
909 
910   bool hasSpilledSGPRs() const {
911     return HasSpilledSGPRs;
912   }
913 
914   void setHasSpilledSGPRs(bool Spill = true) {
915     HasSpilledSGPRs = Spill;
916   }
917 
918   bool hasSpilledVGPRs() const {
919     return HasSpilledVGPRs;
920   }
921 
922   void setHasSpilledVGPRs(bool Spill = true) {
923     HasSpilledVGPRs = Spill;
924   }
925 
926   bool hasNonSpillStackObjects() const {
927     return HasNonSpillStackObjects;
928   }
929 
930   void setHasNonSpillStackObjects(bool StackObject = true) {
931     HasNonSpillStackObjects = StackObject;
932   }
933 
934   bool isStackRealigned() const {
935     return IsStackRealigned;
936   }
937 
938   void setIsStackRealigned(bool Realigned = true) {
939     IsStackRealigned = Realigned;
940   }
941 
942   unsigned getNumSpilledSGPRs() const {
943     return NumSpilledSGPRs;
944   }
945 
946   unsigned getNumSpilledVGPRs() const {
947     return NumSpilledVGPRs;
948   }
949 
950   void addToSpilledSGPRs(unsigned num) {
951     NumSpilledSGPRs += num;
952   }
953 
954   void addToSpilledVGPRs(unsigned num) {
955     NumSpilledVGPRs += num;
956   }
957 
958   unsigned getPSInputAddr() const {
959     return PSInputAddr;
960   }
961 
962   unsigned getPSInputEnable() const {
963     return PSInputEnable;
964   }
965 
966   bool isPSInputAllocated(unsigned Index) const {
967     return PSInputAddr & (1 << Index);
968   }
969 
970   void markPSInputAllocated(unsigned Index) {
971     PSInputAddr |= 1 << Index;
972   }
973 
974   void markPSInputEnabled(unsigned Index) {
975     PSInputEnable |= 1 << Index;
976   }
977 
978   bool returnsVoid() const {
979     return ReturnsVoid;
980   }
981 
982   void setIfReturnsVoid(bool Value) {
983     ReturnsVoid = Value;
984   }
985 
986   /// \returns A pair of default/requested minimum/maximum flat work group sizes
987   /// for this function.
988   std::pair<unsigned, unsigned> getFlatWorkGroupSizes() const {
989     return FlatWorkGroupSizes;
990   }
991 
992   /// \returns Default/requested minimum flat work group size for this function.
993   unsigned getMinFlatWorkGroupSize() const {
994     return FlatWorkGroupSizes.first;
995   }
996 
997   /// \returns Default/requested maximum flat work group size for this function.
998   unsigned getMaxFlatWorkGroupSize() const {
999     return FlatWorkGroupSizes.second;
1000   }
1001 
1002   /// \returns A pair of default/requested minimum/maximum number of waves per
1003   /// execution unit.
1004   std::pair<unsigned, unsigned> getWavesPerEU() const {
1005     return WavesPerEU;
1006   }
1007 
1008   /// \returns Default/requested minimum number of waves per execution unit.
1009   unsigned getMinWavesPerEU() const {
1010     return WavesPerEU.first;
1011   }
1012 
1013   /// \returns Default/requested maximum number of waves per execution unit.
1014   unsigned getMaxWavesPerEU() const {
1015     return WavesPerEU.second;
1016   }
1017 
1018   /// \returns SGPR used for \p Dim's work group ID.
1019   Register getWorkGroupIDSGPR(unsigned Dim) const {
1020     switch (Dim) {
1021     case 0:
1022       assert(hasWorkGroupIDX());
1023       return ArgInfo.WorkGroupIDX.getRegister();
1024     case 1:
1025       assert(hasWorkGroupIDY());
1026       return ArgInfo.WorkGroupIDY.getRegister();
1027     case 2:
1028       assert(hasWorkGroupIDZ());
1029       return ArgInfo.WorkGroupIDZ.getRegister();
1030     }
1031     llvm_unreachable("unexpected dimension");
1032   }
1033 
1034   const AMDGPUGWSResourcePseudoSourceValue *
1035   getGWSPSV(const AMDGPUTargetMachine &TM) {
1036     return &GWSResourcePSV;
1037   }
1038 
1039   unsigned getOccupancy() const {
1040     return Occupancy;
1041   }
1042 
1043   unsigned getMinAllowedOccupancy() const {
1044     if (!isMemoryBound() && !needsWaveLimiter())
1045       return Occupancy;
1046     return (Occupancy < 4) ? Occupancy : 4;
1047   }
1048 
1049   void limitOccupancy(const MachineFunction &MF);
1050 
1051   void limitOccupancy(unsigned Limit) {
1052     if (Occupancy > Limit)
1053       Occupancy = Limit;
1054   }
1055 
1056   void increaseOccupancy(const MachineFunction &MF, unsigned Limit) {
1057     if (Occupancy < Limit)
1058       Occupancy = Limit;
1059     limitOccupancy(MF);
1060   }
1061 
1062   bool mayNeedAGPRs() const {
1063     return MayNeedAGPRs;
1064   }
1065 
1066   // \returns true if a function has a use of AGPRs via inline asm or
1067   // has a call which may use it.
1068   bool mayUseAGPRs(const Function &F) const;
1069 
1070   // \returns true if a function needs or may need AGPRs.
1071   bool usesAGPRs(const MachineFunction &MF) const;
1072 };
1073 
1074 } // end namespace llvm
1075 
1076 #endif // LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
1077