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