xref: /llvm-project/llvm/lib/Target/AMDGPU/SIMachineFunctionInfo.h (revision 7ac3ab34cb7aa3da1ff1b0c024a8767e089519cd)
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 = HasArchitectedSGPRs ? AMDGPU::TTMP9 : getNextSystemSGPR();
703     ArgInfo.WorkGroupIDX = ArgDescriptor::createRegister(Reg);
704     if (!HasArchitectedSGPRs)
705       NumSystemSGPRs += 1;
706 
707     return ArgInfo.WorkGroupIDX.getRegister();
708   }
709 
710   Register addWorkGroupIDY(bool HasArchitectedSGPRs) {
711     Register Reg = HasArchitectedSGPRs ? AMDGPU::TTMP7 : getNextSystemSGPR();
712     unsigned Mask = HasArchitectedSGPRs && hasWorkGroupIDZ() ? 0xffff : ~0u;
713     ArgInfo.WorkGroupIDY = ArgDescriptor::createRegister(Reg, Mask);
714     if (!HasArchitectedSGPRs)
715       NumSystemSGPRs += 1;
716 
717     return ArgInfo.WorkGroupIDY.getRegister();
718   }
719 
720   Register addWorkGroupIDZ(bool HasArchitectedSGPRs) {
721     Register Reg = HasArchitectedSGPRs ? AMDGPU::TTMP7 : getNextSystemSGPR();
722     unsigned Mask = HasArchitectedSGPRs ? 0xffff << 16 : ~0u;
723     ArgInfo.WorkGroupIDZ = ArgDescriptor::createRegister(Reg, Mask);
724     if (!HasArchitectedSGPRs)
725       NumSystemSGPRs += 1;
726 
727     return ArgInfo.WorkGroupIDZ.getRegister();
728   }
729 
730   Register addWorkGroupInfo() {
731     ArgInfo.WorkGroupInfo = ArgDescriptor::createRegister(getNextSystemSGPR());
732     NumSystemSGPRs += 1;
733     return ArgInfo.WorkGroupInfo.getRegister();
734   }
735 
736   // Add special VGPR inputs
737   void setWorkItemIDX(ArgDescriptor Arg) {
738     ArgInfo.WorkItemIDX = Arg;
739   }
740 
741   void setWorkItemIDY(ArgDescriptor Arg) {
742     ArgInfo.WorkItemIDY = Arg;
743   }
744 
745   void setWorkItemIDZ(ArgDescriptor Arg) {
746     ArgInfo.WorkItemIDZ = Arg;
747   }
748 
749   Register addPrivateSegmentWaveByteOffset() {
750     ArgInfo.PrivateSegmentWaveByteOffset
751       = ArgDescriptor::createRegister(getNextSystemSGPR());
752     NumSystemSGPRs += 1;
753     return ArgInfo.PrivateSegmentWaveByteOffset.getRegister();
754   }
755 
756   void setPrivateSegmentWaveByteOffset(Register Reg) {
757     ArgInfo.PrivateSegmentWaveByteOffset = ArgDescriptor::createRegister(Reg);
758   }
759 
760   bool hasPrivateSegmentBuffer() const {
761     return PrivateSegmentBuffer;
762   }
763 
764   bool hasDispatchPtr() const {
765     return DispatchPtr;
766   }
767 
768   bool hasQueuePtr() const {
769     return QueuePtr;
770   }
771 
772   bool hasKernargSegmentPtr() const {
773     return KernargSegmentPtr;
774   }
775 
776   bool hasDispatchID() const {
777     return DispatchID;
778   }
779 
780   bool hasFlatScratchInit() const {
781     return FlatScratchInit;
782   }
783 
784   bool hasWorkGroupIDX() const {
785     return WorkGroupIDX;
786   }
787 
788   bool hasWorkGroupIDY() const {
789     return WorkGroupIDY;
790   }
791 
792   bool hasWorkGroupIDZ() const {
793     return WorkGroupIDZ;
794   }
795 
796   bool hasWorkGroupInfo() const {
797     return WorkGroupInfo;
798   }
799 
800   bool hasLDSKernelId() const { return LDSKernelId; }
801 
802   bool hasPrivateSegmentWaveByteOffset() const {
803     return PrivateSegmentWaveByteOffset;
804   }
805 
806   bool hasWorkItemIDX() const {
807     return WorkItemIDX;
808   }
809 
810   bool hasWorkItemIDY() const {
811     return WorkItemIDY;
812   }
813 
814   bool hasWorkItemIDZ() const {
815     return WorkItemIDZ;
816   }
817 
818   bool hasImplicitArgPtr() const {
819     return ImplicitArgPtr;
820   }
821 
822   bool hasImplicitBufferPtr() const {
823     return ImplicitBufferPtr;
824   }
825 
826   AMDGPUFunctionArgInfo &getArgInfo() {
827     return ArgInfo;
828   }
829 
830   const AMDGPUFunctionArgInfo &getArgInfo() const {
831     return ArgInfo;
832   }
833 
834   std::tuple<const ArgDescriptor *, const TargetRegisterClass *, LLT>
835   getPreloadedValue(AMDGPUFunctionArgInfo::PreloadedValue Value) const {
836     return ArgInfo.getPreloadedValue(Value);
837   }
838 
839   MCRegister getPreloadedReg(AMDGPUFunctionArgInfo::PreloadedValue Value) const {
840     auto Arg = std::get<0>(ArgInfo.getPreloadedValue(Value));
841     return Arg ? Arg->getRegister() : MCRegister();
842   }
843 
844   unsigned getGITPtrHigh() const {
845     return GITPtrHigh;
846   }
847 
848   Register getGITPtrLoReg(const MachineFunction &MF) const;
849 
850   uint32_t get32BitAddressHighBits() const {
851     return HighBitsOf32BitAddress;
852   }
853 
854   unsigned getNumUserSGPRs() const {
855     return NumUserSGPRs;
856   }
857 
858   unsigned getNumPreloadedSGPRs() const {
859     return NumUserSGPRs + NumSystemSGPRs;
860   }
861 
862   Register getPrivateSegmentWaveByteOffsetSystemSGPR() const {
863     return ArgInfo.PrivateSegmentWaveByteOffset.getRegister();
864   }
865 
866   /// Returns the physical register reserved for use as the resource
867   /// descriptor for scratch accesses.
868   Register getScratchRSrcReg() const {
869     return ScratchRSrcReg;
870   }
871 
872   void setScratchRSrcReg(Register Reg) {
873     assert(Reg != 0 && "Should never be unset");
874     ScratchRSrcReg = Reg;
875   }
876 
877   Register getFrameOffsetReg() const {
878     return FrameOffsetReg;
879   }
880 
881   void setFrameOffsetReg(Register Reg) {
882     assert(Reg != 0 && "Should never be unset");
883     FrameOffsetReg = Reg;
884   }
885 
886   void setStackPtrOffsetReg(Register Reg) {
887     assert(Reg != 0 && "Should never be unset");
888     StackPtrOffsetReg = Reg;
889   }
890 
891   // Note the unset value for this is AMDGPU::SP_REG rather than
892   // NoRegister. This is mostly a workaround for MIR tests where state that
893   // can't be directly computed from the function is not preserved in serialized
894   // MIR.
895   Register getStackPtrOffsetReg() const {
896     return StackPtrOffsetReg;
897   }
898 
899   Register getQueuePtrUserSGPR() const {
900     return ArgInfo.QueuePtr.getRegister();
901   }
902 
903   Register getImplicitBufferPtrUserSGPR() const {
904     return ArgInfo.ImplicitBufferPtr.getRegister();
905   }
906 
907   bool hasSpilledSGPRs() const {
908     return HasSpilledSGPRs;
909   }
910 
911   void setHasSpilledSGPRs(bool Spill = true) {
912     HasSpilledSGPRs = Spill;
913   }
914 
915   bool hasSpilledVGPRs() const {
916     return HasSpilledVGPRs;
917   }
918 
919   void setHasSpilledVGPRs(bool Spill = true) {
920     HasSpilledVGPRs = Spill;
921   }
922 
923   bool hasNonSpillStackObjects() const {
924     return HasNonSpillStackObjects;
925   }
926 
927   void setHasNonSpillStackObjects(bool StackObject = true) {
928     HasNonSpillStackObjects = StackObject;
929   }
930 
931   bool isStackRealigned() const {
932     return IsStackRealigned;
933   }
934 
935   void setIsStackRealigned(bool Realigned = true) {
936     IsStackRealigned = Realigned;
937   }
938 
939   unsigned getNumSpilledSGPRs() const {
940     return NumSpilledSGPRs;
941   }
942 
943   unsigned getNumSpilledVGPRs() const {
944     return NumSpilledVGPRs;
945   }
946 
947   void addToSpilledSGPRs(unsigned num) {
948     NumSpilledSGPRs += num;
949   }
950 
951   void addToSpilledVGPRs(unsigned num) {
952     NumSpilledVGPRs += num;
953   }
954 
955   unsigned getPSInputAddr() const {
956     return PSInputAddr;
957   }
958 
959   unsigned getPSInputEnable() const {
960     return PSInputEnable;
961   }
962 
963   bool isPSInputAllocated(unsigned Index) const {
964     return PSInputAddr & (1 << Index);
965   }
966 
967   void markPSInputAllocated(unsigned Index) {
968     PSInputAddr |= 1 << Index;
969   }
970 
971   void markPSInputEnabled(unsigned Index) {
972     PSInputEnable |= 1 << Index;
973   }
974 
975   bool returnsVoid() const {
976     return ReturnsVoid;
977   }
978 
979   void setIfReturnsVoid(bool Value) {
980     ReturnsVoid = Value;
981   }
982 
983   /// \returns A pair of default/requested minimum/maximum flat work group sizes
984   /// for this function.
985   std::pair<unsigned, unsigned> getFlatWorkGroupSizes() const {
986     return FlatWorkGroupSizes;
987   }
988 
989   /// \returns Default/requested minimum flat work group size for this function.
990   unsigned getMinFlatWorkGroupSize() const {
991     return FlatWorkGroupSizes.first;
992   }
993 
994   /// \returns Default/requested maximum flat work group size for this function.
995   unsigned getMaxFlatWorkGroupSize() const {
996     return FlatWorkGroupSizes.second;
997   }
998 
999   /// \returns A pair of default/requested minimum/maximum number of waves per
1000   /// execution unit.
1001   std::pair<unsigned, unsigned> getWavesPerEU() const {
1002     return WavesPerEU;
1003   }
1004 
1005   /// \returns Default/requested minimum number of waves per execution unit.
1006   unsigned getMinWavesPerEU() const {
1007     return WavesPerEU.first;
1008   }
1009 
1010   /// \returns Default/requested maximum number of waves per execution unit.
1011   unsigned getMaxWavesPerEU() const {
1012     return WavesPerEU.second;
1013   }
1014 
1015   /// \returns SGPR used for \p Dim's work group ID.
1016   Register getWorkGroupIDSGPR(unsigned Dim) const {
1017     switch (Dim) {
1018     case 0:
1019       assert(hasWorkGroupIDX());
1020       return ArgInfo.WorkGroupIDX.getRegister();
1021     case 1:
1022       assert(hasWorkGroupIDY());
1023       return ArgInfo.WorkGroupIDY.getRegister();
1024     case 2:
1025       assert(hasWorkGroupIDZ());
1026       return ArgInfo.WorkGroupIDZ.getRegister();
1027     }
1028     llvm_unreachable("unexpected dimension");
1029   }
1030 
1031   const AMDGPUGWSResourcePseudoSourceValue *
1032   getGWSPSV(const AMDGPUTargetMachine &TM) {
1033     return &GWSResourcePSV;
1034   }
1035 
1036   unsigned getOccupancy() const {
1037     return Occupancy;
1038   }
1039 
1040   unsigned getMinAllowedOccupancy() const {
1041     if (!isMemoryBound() && !needsWaveLimiter())
1042       return Occupancy;
1043     return (Occupancy < 4) ? Occupancy : 4;
1044   }
1045 
1046   void limitOccupancy(const MachineFunction &MF);
1047 
1048   void limitOccupancy(unsigned Limit) {
1049     if (Occupancy > Limit)
1050       Occupancy = Limit;
1051   }
1052 
1053   void increaseOccupancy(const MachineFunction &MF, unsigned Limit) {
1054     if (Occupancy < Limit)
1055       Occupancy = Limit;
1056     limitOccupancy(MF);
1057   }
1058 
1059   bool mayNeedAGPRs() const {
1060     return MayNeedAGPRs;
1061   }
1062 
1063   // \returns true if a function has a use of AGPRs via inline asm or
1064   // has a call which may use it.
1065   bool mayUseAGPRs(const Function &F) const;
1066 
1067   // \returns true if a function needs or may need AGPRs.
1068   bool usesAGPRs(const MachineFunction &MF) const;
1069 };
1070 
1071 } // end namespace llvm
1072 
1073 #endif // LLVM_LIB_TARGET_AMDGPU_SIMACHINEFUNCTIONINFO_H
1074