1 //===-- AMDGPUSubtarget.cpp - AMDGPU Subtarget Information ----------------===//
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 /// Implements the AMDGPU specific subclass of TargetSubtarget.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "AMDGPUSubtarget.h"
15 #include "AMDGPUCallLowering.h"
16 #include "AMDGPUInstructionSelector.h"
17 #include "AMDGPULegalizerInfo.h"
18 #include "AMDGPURegisterBankInfo.h"
19 #include "AMDGPUTargetMachine.h"
20 #include "R600Subtarget.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "Utils/AMDGPUBaseInfo.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h"
25 #include "llvm/CodeGen/MachineScheduler.h"
26 #include "llvm/CodeGen/TargetFrameLowering.h"
27 #include "llvm/IR/IntrinsicsAMDGPU.h"
28 #include "llvm/IR/IntrinsicsR600.h"
29 #include "llvm/IR/MDBuilder.h"
30 #include "llvm/MC/MCSubtargetInfo.h"
31 #include <algorithm>
32 
33 using namespace llvm;
34 
35 #define DEBUG_TYPE "amdgpu-subtarget"
36 
37 #define GET_SUBTARGETINFO_TARGET_DESC
38 #define GET_SUBTARGETINFO_CTOR
39 #define AMDGPUSubtarget GCNSubtarget
40 #include "AMDGPUGenSubtargetInfo.inc"
41 #undef AMDGPUSubtarget
42 
43 static cl::opt<bool> DisablePowerSched(
44   "amdgpu-disable-power-sched",
45   cl::desc("Disable scheduling to minimize mAI power bursts"),
46   cl::init(false));
47 
48 static cl::opt<bool> EnableVGPRIndexMode(
49   "amdgpu-vgpr-index-mode",
50   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
51   cl::init(false));
52 
53 static cl::opt<bool> UseAA("amdgpu-use-aa-in-codegen",
54                            cl::desc("Enable the use of AA during codegen."),
55                            cl::init(true));
56 
57 GCNSubtarget::~GCNSubtarget() = default;
58 
59 GCNSubtarget &
60 GCNSubtarget::initializeSubtargetDependencies(const Triple &TT,
61                                               StringRef GPU, StringRef FS) {
62   // Determine default and user-specified characteristics
63   //
64   // We want to be able to turn these off, but making this a subtarget feature
65   // for SI has the unhelpful behavior that it unsets everything else if you
66   // disable it.
67   //
68   // Similarly we want enable-prt-strict-null to be on by default and not to
69   // unset everything else if it is disabled
70 
71   SmallString<256> FullFS("+promote-alloca,+load-store-opt,+enable-ds128,");
72 
73   // Turn on features that HSA ABI requires. Also turn on FlatForGlobal by default
74   if (isAmdHsaOS())
75     FullFS += "+flat-for-global,+unaligned-access-mode,+trap-handler,";
76 
77   FullFS += "+enable-prt-strict-null,"; // This is overridden by a disable in FS
78 
79   // Disable mutually exclusive bits.
80   if (FS.contains_insensitive("+wavefrontsize")) {
81     if (!FS.contains_insensitive("wavefrontsize16"))
82       FullFS += "-wavefrontsize16,";
83     if (!FS.contains_insensitive("wavefrontsize32"))
84       FullFS += "-wavefrontsize32,";
85     if (!FS.contains_insensitive("wavefrontsize64"))
86       FullFS += "-wavefrontsize64,";
87   }
88 
89   FullFS += FS;
90 
91   ParseSubtargetFeatures(GPU, /*TuneCPU*/ GPU, FullFS);
92 
93   // Implement the "generic" processors, which acts as the default when no
94   // generation features are enabled (e.g for -mcpu=''). HSA OS defaults to
95   // the first amdgcn target that supports flat addressing. Other OSes defaults
96   // to the first amdgcn target.
97   if (Gen == AMDGPUSubtarget::INVALID) {
98      Gen = TT.getOS() == Triple::AMDHSA ? AMDGPUSubtarget::SEA_ISLANDS
99                                         : AMDGPUSubtarget::SOUTHERN_ISLANDS;
100   }
101 
102   // We don't support FP64 for EG/NI atm.
103   assert(!hasFP64() || (getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS));
104 
105   // Targets must either support 64-bit offsets for MUBUF instructions, and/or
106   // support flat operations, otherwise they cannot access a 64-bit global
107   // address space
108   assert(hasAddr64() || hasFlat());
109   // Unless +-flat-for-global is specified, turn on FlatForGlobal for targets
110   // that do not support ADDR64 variants of MUBUF instructions. Such targets
111   // cannot use a 64 bit offset with a MUBUF instruction to access the global
112   // address space
113   if (!hasAddr64() && !FS.contains("flat-for-global") && !FlatForGlobal) {
114     ToggleFeature(AMDGPU::FeatureFlatForGlobal);
115     FlatForGlobal = true;
116   }
117   // Unless +-flat-for-global is specified, use MUBUF instructions for global
118   // address space access if flat operations are not available.
119   if (!hasFlat() && !FS.contains("flat-for-global") && FlatForGlobal) {
120     ToggleFeature(AMDGPU::FeatureFlatForGlobal);
121     FlatForGlobal = false;
122   }
123 
124   // Set defaults if needed.
125   if (MaxPrivateElementSize == 0)
126     MaxPrivateElementSize = 4;
127 
128   if (LDSBankCount == 0)
129     LDSBankCount = 32;
130 
131   if (TT.getArch() == Triple::amdgcn) {
132     if (LocalMemorySize == 0)
133       LocalMemorySize = 32768;
134 
135     // Do something sensible for unspecified target.
136     if (!HasMovrel && !HasVGPRIndexMode)
137       HasMovrel = true;
138   }
139 
140   // Don't crash on invalid devices.
141   if (WavefrontSizeLog2 == 0)
142     WavefrontSizeLog2 = 5;
143 
144   HasFminFmaxLegacy = getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS;
145   HasSMulHi = getGeneration() >= AMDGPUSubtarget::GFX9;
146 
147   TargetID.setTargetIDFromFeaturesString(FS);
148 
149   LLVM_DEBUG(dbgs() << "xnack setting for subtarget: "
150                     << TargetID.getXnackSetting() << '\n');
151   LLVM_DEBUG(dbgs() << "sramecc setting for subtarget: "
152                     << TargetID.getSramEccSetting() << '\n');
153 
154   return *this;
155 }
156 
157 AMDGPUSubtarget::AMDGPUSubtarget(const Triple &TT) : TargetTriple(TT) {}
158 
159 GCNSubtarget::GCNSubtarget(const Triple &TT, StringRef GPU, StringRef FS,
160                            const GCNTargetMachine &TM)
161     : // clang-format off
162     AMDGPUGenSubtargetInfo(TT, GPU, /*TuneCPU*/ GPU, FS),
163     AMDGPUSubtarget(TT),
164     TargetTriple(TT),
165     TargetID(*this),
166     InstrItins(getInstrItineraryForCPU(GPU)),
167     InstrInfo(initializeSubtargetDependencies(TT, GPU, FS)),
168     TLInfo(TM, *this),
169     FrameLowering(TargetFrameLowering::StackGrowsUp, getStackAlignment(), 0) {
170   // clang-format on
171   MaxWavesPerEU = AMDGPU::IsaInfo::getMaxWavesPerEU(this);
172   CallLoweringInfo.reset(new AMDGPUCallLowering(*getTargetLowering()));
173   InlineAsmLoweringInfo.reset(new InlineAsmLowering(getTargetLowering()));
174   Legalizer.reset(new AMDGPULegalizerInfo(*this, TM));
175   RegBankInfo.reset(new AMDGPURegisterBankInfo(*this));
176   InstSelector.reset(new AMDGPUInstructionSelector(
177   *this, *static_cast<AMDGPURegisterBankInfo *>(RegBankInfo.get()), TM));
178 }
179 
180 unsigned GCNSubtarget::getConstantBusLimit(unsigned Opcode) const {
181   if (getGeneration() < GFX10)
182     return 1;
183 
184   switch (Opcode) {
185   case AMDGPU::V_LSHLREV_B64_e64:
186   case AMDGPU::V_LSHLREV_B64_gfx10:
187   case AMDGPU::V_LSHL_B64_e64:
188   case AMDGPU::V_LSHRREV_B64_e64:
189   case AMDGPU::V_LSHRREV_B64_gfx10:
190   case AMDGPU::V_LSHR_B64_e64:
191   case AMDGPU::V_ASHRREV_I64_e64:
192   case AMDGPU::V_ASHRREV_I64_gfx10:
193   case AMDGPU::V_ASHR_I64_e64:
194     return 1;
195   }
196 
197   return 2;
198 }
199 
200 /// This list was mostly derived from experimentation.
201 bool GCNSubtarget::zeroesHigh16BitsOfDest(unsigned Opcode) const {
202   switch (Opcode) {
203   case AMDGPU::V_CVT_F16_F32_e32:
204   case AMDGPU::V_CVT_F16_F32_e64:
205   case AMDGPU::V_CVT_F16_U16_e32:
206   case AMDGPU::V_CVT_F16_U16_e64:
207   case AMDGPU::V_CVT_F16_I16_e32:
208   case AMDGPU::V_CVT_F16_I16_e64:
209   case AMDGPU::V_RCP_F16_e64:
210   case AMDGPU::V_RCP_F16_e32:
211   case AMDGPU::V_RSQ_F16_e64:
212   case AMDGPU::V_RSQ_F16_e32:
213   case AMDGPU::V_SQRT_F16_e64:
214   case AMDGPU::V_SQRT_F16_e32:
215   case AMDGPU::V_LOG_F16_e64:
216   case AMDGPU::V_LOG_F16_e32:
217   case AMDGPU::V_EXP_F16_e64:
218   case AMDGPU::V_EXP_F16_e32:
219   case AMDGPU::V_SIN_F16_e64:
220   case AMDGPU::V_SIN_F16_e32:
221   case AMDGPU::V_COS_F16_e64:
222   case AMDGPU::V_COS_F16_e32:
223   case AMDGPU::V_FLOOR_F16_e64:
224   case AMDGPU::V_FLOOR_F16_e32:
225   case AMDGPU::V_CEIL_F16_e64:
226   case AMDGPU::V_CEIL_F16_e32:
227   case AMDGPU::V_TRUNC_F16_e64:
228   case AMDGPU::V_TRUNC_F16_e32:
229   case AMDGPU::V_RNDNE_F16_e64:
230   case AMDGPU::V_RNDNE_F16_e32:
231   case AMDGPU::V_FRACT_F16_e64:
232   case AMDGPU::V_FRACT_F16_e32:
233   case AMDGPU::V_FREXP_MANT_F16_e64:
234   case AMDGPU::V_FREXP_MANT_F16_e32:
235   case AMDGPU::V_FREXP_EXP_I16_F16_e64:
236   case AMDGPU::V_FREXP_EXP_I16_F16_e32:
237   case AMDGPU::V_LDEXP_F16_e64:
238   case AMDGPU::V_LDEXP_F16_e32:
239   case AMDGPU::V_LSHLREV_B16_e64:
240   case AMDGPU::V_LSHLREV_B16_e32:
241   case AMDGPU::V_LSHRREV_B16_e64:
242   case AMDGPU::V_LSHRREV_B16_e32:
243   case AMDGPU::V_ASHRREV_I16_e64:
244   case AMDGPU::V_ASHRREV_I16_e32:
245   case AMDGPU::V_ADD_U16_e64:
246   case AMDGPU::V_ADD_U16_e32:
247   case AMDGPU::V_SUB_U16_e64:
248   case AMDGPU::V_SUB_U16_e32:
249   case AMDGPU::V_SUBREV_U16_e64:
250   case AMDGPU::V_SUBREV_U16_e32:
251   case AMDGPU::V_MUL_LO_U16_e64:
252   case AMDGPU::V_MUL_LO_U16_e32:
253   case AMDGPU::V_ADD_F16_e64:
254   case AMDGPU::V_ADD_F16_e32:
255   case AMDGPU::V_SUB_F16_e64:
256   case AMDGPU::V_SUB_F16_e32:
257   case AMDGPU::V_SUBREV_F16_e64:
258   case AMDGPU::V_SUBREV_F16_e32:
259   case AMDGPU::V_MUL_F16_e64:
260   case AMDGPU::V_MUL_F16_e32:
261   case AMDGPU::V_MAX_F16_e64:
262   case AMDGPU::V_MAX_F16_e32:
263   case AMDGPU::V_MIN_F16_e64:
264   case AMDGPU::V_MIN_F16_e32:
265   case AMDGPU::V_MAX_U16_e64:
266   case AMDGPU::V_MAX_U16_e32:
267   case AMDGPU::V_MIN_U16_e64:
268   case AMDGPU::V_MIN_U16_e32:
269   case AMDGPU::V_MAX_I16_e64:
270   case AMDGPU::V_MAX_I16_e32:
271   case AMDGPU::V_MIN_I16_e64:
272   case AMDGPU::V_MIN_I16_e32:
273   case AMDGPU::V_MAD_F16_e64:
274   case AMDGPU::V_MAD_U16_e64:
275   case AMDGPU::V_MAD_I16_e64:
276   case AMDGPU::V_FMA_F16_e64:
277   case AMDGPU::V_DIV_FIXUP_F16_e64:
278     // On gfx10, all 16-bit instructions preserve the high bits.
279     return getGeneration() <= AMDGPUSubtarget::GFX9;
280   case AMDGPU::V_MADAK_F16:
281   case AMDGPU::V_MADMK_F16:
282   case AMDGPU::V_MAC_F16_e64:
283   case AMDGPU::V_MAC_F16_e32:
284   case AMDGPU::V_FMAMK_F16:
285   case AMDGPU::V_FMAAK_F16:
286   case AMDGPU::V_FMAC_F16_e64:
287   case AMDGPU::V_FMAC_F16_e32:
288     // In gfx9, the preferred handling of the unused high 16-bits changed. Most
289     // instructions maintain the legacy behavior of 0ing. Some instructions
290     // changed to preserving the high bits.
291     return getGeneration() == AMDGPUSubtarget::VOLCANIC_ISLANDS;
292   case AMDGPU::V_MAD_MIXLO_F16:
293   case AMDGPU::V_MAD_MIXHI_F16:
294   default:
295     return false;
296   }
297 }
298 
299 unsigned AMDGPUSubtarget::getMaxLocalMemSizeWithWaveCount(unsigned NWaves,
300   const Function &F) const {
301   if (NWaves == 1)
302     return getLocalMemorySize();
303   unsigned WorkGroupSize = getFlatWorkGroupSizes(F).second;
304   unsigned WorkGroupsPerCu = getMaxWorkGroupsPerCU(WorkGroupSize);
305   if (!WorkGroupsPerCu)
306     return 0;
307   unsigned MaxWaves = getMaxWavesPerEU();
308   return getLocalMemorySize() * MaxWaves / WorkGroupsPerCu / NWaves;
309 }
310 
311 // FIXME: Should return min,max range.
312 unsigned AMDGPUSubtarget::getOccupancyWithLocalMemSize(uint32_t Bytes,
313   const Function &F) const {
314   const unsigned MaxWorkGroupSize = getFlatWorkGroupSizes(F).second;
315   const unsigned MaxWorkGroupsPerCu = getMaxWorkGroupsPerCU(MaxWorkGroupSize);
316   if (!MaxWorkGroupsPerCu)
317     return 0;
318 
319   const unsigned WaveSize = getWavefrontSize();
320 
321   // FIXME: Do we need to account for alignment requirement of LDS rounding the
322   // size up?
323   // Compute restriction based on LDS usage
324   unsigned NumGroups = getLocalMemorySize() / (Bytes ? Bytes : 1u);
325 
326   // This can be queried with more LDS than is possible, so just assume the
327   // worst.
328   if (NumGroups == 0)
329     return 1;
330 
331   NumGroups = std::min(MaxWorkGroupsPerCu, NumGroups);
332 
333   // Round to the number of waves.
334   const unsigned MaxGroupNumWaves = (MaxWorkGroupSize + WaveSize - 1) / WaveSize;
335   unsigned MaxWaves = NumGroups * MaxGroupNumWaves;
336 
337   // Clamp to the maximum possible number of waves.
338   MaxWaves = std::min(MaxWaves, getMaxWavesPerEU());
339 
340   // FIXME: Needs to be a multiple of the group size?
341   //MaxWaves = MaxGroupNumWaves * (MaxWaves / MaxGroupNumWaves);
342 
343   assert(MaxWaves > 0 && MaxWaves <= getMaxWavesPerEU() &&
344          "computed invalid occupancy");
345   return MaxWaves;
346 }
347 
348 unsigned
349 AMDGPUSubtarget::getOccupancyWithLocalMemSize(const MachineFunction &MF) const {
350   const auto *MFI = MF.getInfo<SIMachineFunctionInfo>();
351   return getOccupancyWithLocalMemSize(MFI->getLDSSize(), MF.getFunction());
352 }
353 
354 std::pair<unsigned, unsigned>
355 AMDGPUSubtarget::getDefaultFlatWorkGroupSize(CallingConv::ID CC) const {
356   switch (CC) {
357   case CallingConv::AMDGPU_VS:
358   case CallingConv::AMDGPU_LS:
359   case CallingConv::AMDGPU_HS:
360   case CallingConv::AMDGPU_ES:
361   case CallingConv::AMDGPU_GS:
362   case CallingConv::AMDGPU_PS:
363     return std::make_pair(1, getWavefrontSize());
364   default:
365     return std::make_pair(1u, getMaxFlatWorkGroupSize());
366   }
367 }
368 
369 std::pair<unsigned, unsigned> AMDGPUSubtarget::getFlatWorkGroupSizes(
370   const Function &F) const {
371   // Default minimum/maximum flat work group sizes.
372   std::pair<unsigned, unsigned> Default =
373     getDefaultFlatWorkGroupSize(F.getCallingConv());
374 
375   // Requested minimum/maximum flat work group sizes.
376   std::pair<unsigned, unsigned> Requested = AMDGPU::getIntegerPairAttribute(
377     F, "amdgpu-flat-work-group-size", Default);
378 
379   // Make sure requested minimum is less than requested maximum.
380   if (Requested.first > Requested.second)
381     return Default;
382 
383   // Make sure requested values do not violate subtarget's specifications.
384   if (Requested.first < getMinFlatWorkGroupSize())
385     return Default;
386   if (Requested.second > getMaxFlatWorkGroupSize())
387     return Default;
388 
389   return Requested;
390 }
391 
392 std::pair<unsigned, unsigned> AMDGPUSubtarget::getWavesPerEU(
393     const Function &F, std::pair<unsigned, unsigned> FlatWorkGroupSizes) const {
394   // Default minimum/maximum number of waves per execution unit.
395   std::pair<unsigned, unsigned> Default(1, getMaxWavesPerEU());
396 
397   // If minimum/maximum flat work group sizes were explicitly requested using
398   // "amdgpu-flat-work-group-size" attribute, then set default minimum/maximum
399   // number of waves per execution unit to values implied by requested
400   // minimum/maximum flat work group sizes.
401   unsigned MinImpliedByFlatWorkGroupSize =
402     getWavesPerEUForWorkGroup(FlatWorkGroupSizes.second);
403   Default.first = MinImpliedByFlatWorkGroupSize;
404 
405   // Requested minimum/maximum number of waves per execution unit.
406   std::pair<unsigned, unsigned> Requested = AMDGPU::getIntegerPairAttribute(
407     F, "amdgpu-waves-per-eu", Default, true);
408 
409   // Make sure requested minimum is less than requested maximum.
410   if (Requested.second && Requested.first > Requested.second)
411     return Default;
412 
413   // Make sure requested values do not violate subtarget's specifications.
414   if (Requested.first < getMinWavesPerEU() ||
415       Requested.second > getMaxWavesPerEU())
416     return Default;
417 
418   // Make sure requested values are compatible with values implied by requested
419   // minimum/maximum flat work group sizes.
420   if (Requested.first < MinImpliedByFlatWorkGroupSize)
421     return Default;
422 
423   return Requested;
424 }
425 
426 static unsigned getReqdWorkGroupSize(const Function &Kernel, unsigned Dim) {
427   auto Node = Kernel.getMetadata("reqd_work_group_size");
428   if (Node && Node->getNumOperands() == 3)
429     return mdconst::extract<ConstantInt>(Node->getOperand(Dim))->getZExtValue();
430   return std::numeric_limits<unsigned>::max();
431 }
432 
433 bool AMDGPUSubtarget::isMesaKernel(const Function &F) const {
434   return isMesa3DOS() && !AMDGPU::isShader(F.getCallingConv());
435 }
436 
437 unsigned AMDGPUSubtarget::getMaxWorkitemID(const Function &Kernel,
438                                            unsigned Dimension) const {
439   unsigned ReqdSize = getReqdWorkGroupSize(Kernel, Dimension);
440   if (ReqdSize != std::numeric_limits<unsigned>::max())
441     return ReqdSize - 1;
442   return getFlatWorkGroupSizes(Kernel).second - 1;
443 }
444 
445 bool AMDGPUSubtarget::makeLIDRangeMetadata(Instruction *I) const {
446   Function *Kernel = I->getParent()->getParent();
447   unsigned MinSize = 0;
448   unsigned MaxSize = getFlatWorkGroupSizes(*Kernel).second;
449   bool IdQuery = false;
450 
451   // If reqd_work_group_size is present it narrows value down.
452   if (auto *CI = dyn_cast<CallInst>(I)) {
453     const Function *F = CI->getCalledFunction();
454     if (F) {
455       unsigned Dim = UINT_MAX;
456       switch (F->getIntrinsicID()) {
457       case Intrinsic::amdgcn_workitem_id_x:
458       case Intrinsic::r600_read_tidig_x:
459         IdQuery = true;
460         LLVM_FALLTHROUGH;
461       case Intrinsic::r600_read_local_size_x:
462         Dim = 0;
463         break;
464       case Intrinsic::amdgcn_workitem_id_y:
465       case Intrinsic::r600_read_tidig_y:
466         IdQuery = true;
467         LLVM_FALLTHROUGH;
468       case Intrinsic::r600_read_local_size_y:
469         Dim = 1;
470         break;
471       case Intrinsic::amdgcn_workitem_id_z:
472       case Intrinsic::r600_read_tidig_z:
473         IdQuery = true;
474         LLVM_FALLTHROUGH;
475       case Intrinsic::r600_read_local_size_z:
476         Dim = 2;
477         break;
478       default:
479         break;
480       }
481 
482       if (Dim <= 3) {
483         unsigned ReqdSize = getReqdWorkGroupSize(*Kernel, Dim);
484         if (ReqdSize != std::numeric_limits<unsigned>::max())
485           MinSize = MaxSize = ReqdSize;
486       }
487     }
488   }
489 
490   if (!MaxSize)
491     return false;
492 
493   // Range metadata is [Lo, Hi). For ID query we need to pass max size
494   // as Hi. For size query we need to pass Hi + 1.
495   if (IdQuery)
496     MinSize = 0;
497   else
498     ++MaxSize;
499 
500   MDBuilder MDB(I->getContext());
501   MDNode *MaxWorkGroupSizeRange = MDB.createRange(APInt(32, MinSize),
502                                                   APInt(32, MaxSize));
503   I->setMetadata(LLVMContext::MD_range, MaxWorkGroupSizeRange);
504   return true;
505 }
506 
507 unsigned AMDGPUSubtarget::getImplicitArgNumBytes(const Function &F) const {
508   assert(AMDGPU::isKernel(F.getCallingConv()));
509 
510   // We don't allocate the segment if we know the implicit arguments weren't
511   // used, even if the ABI implies we need them.
512   if (F.hasFnAttribute("amdgpu-no-implicitarg-ptr"))
513     return 0;
514 
515   if (isMesaKernel(F))
516     return 16;
517 
518   // Assume all implicit inputs are used by default
519   unsigned NBytes = (AMDGPU::getAmdhsaCodeObjectVersion() >= 5) ? 256 : 56;
520   return AMDGPU::getIntegerAttribute(F, "amdgpu-implicitarg-num-bytes", NBytes);
521 }
522 
523 uint64_t AMDGPUSubtarget::getExplicitKernArgSize(const Function &F,
524                                                  Align &MaxAlign) const {
525   assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
526          F.getCallingConv() == CallingConv::SPIR_KERNEL);
527 
528   const DataLayout &DL = F.getParent()->getDataLayout();
529   uint64_t ExplicitArgBytes = 0;
530   MaxAlign = Align(1);
531 
532   for (const Argument &Arg : F.args()) {
533     const bool IsByRef = Arg.hasByRefAttr();
534     Type *ArgTy = IsByRef ? Arg.getParamByRefType() : Arg.getType();
535     MaybeAlign Alignment = IsByRef ? Arg.getParamAlign() : None;
536     if (!Alignment)
537       Alignment = DL.getABITypeAlign(ArgTy);
538 
539     uint64_t AllocSize = DL.getTypeAllocSize(ArgTy);
540     ExplicitArgBytes = alignTo(ExplicitArgBytes, Alignment) + AllocSize;
541     MaxAlign = max(MaxAlign, Alignment);
542   }
543 
544   return ExplicitArgBytes;
545 }
546 
547 unsigned AMDGPUSubtarget::getKernArgSegmentSize(const Function &F,
548                                                 Align &MaxAlign) const {
549   uint64_t ExplicitArgBytes = getExplicitKernArgSize(F, MaxAlign);
550 
551   unsigned ExplicitOffset = getExplicitKernelArgOffset(F);
552 
553   uint64_t TotalSize = ExplicitOffset + ExplicitArgBytes;
554   unsigned ImplicitBytes = getImplicitArgNumBytes(F);
555   if (ImplicitBytes != 0) {
556     const Align Alignment = getAlignmentForImplicitArgPtr();
557     TotalSize = alignTo(ExplicitArgBytes, Alignment) + ImplicitBytes;
558     MaxAlign = std::max(MaxAlign, Alignment);
559   }
560 
561   // Being able to dereference past the end is useful for emitting scalar loads.
562   return alignTo(TotalSize, 4);
563 }
564 
565 AMDGPUDwarfFlavour AMDGPUSubtarget::getAMDGPUDwarfFlavour() const {
566   return getWavefrontSize() == 32 ? AMDGPUDwarfFlavour::Wave32
567                                   : AMDGPUDwarfFlavour::Wave64;
568 }
569 
570 void GCNSubtarget::overrideSchedPolicy(MachineSchedPolicy &Policy,
571                                       unsigned NumRegionInstrs) const {
572   // Track register pressure so the scheduler can try to decrease
573   // pressure once register usage is above the threshold defined by
574   // SIRegisterInfo::getRegPressureSetLimit()
575   Policy.ShouldTrackPressure = true;
576 
577   // Enabling both top down and bottom up scheduling seems to give us less
578   // register spills than just using one of these approaches on its own.
579   Policy.OnlyTopDown = false;
580   Policy.OnlyBottomUp = false;
581 
582   // Enabling ShouldTrackLaneMasks crashes the SI Machine Scheduler.
583   if (!enableSIScheduler())
584     Policy.ShouldTrackLaneMasks = true;
585 }
586 
587 bool GCNSubtarget::hasMadF16() const {
588   return InstrInfo.pseudoToMCOpcode(AMDGPU::V_MAD_F16_e64) != -1;
589 }
590 
591 bool GCNSubtarget::useVGPRIndexMode() const {
592   return !hasMovrel() || (EnableVGPRIndexMode && hasVGPRIndexMode());
593 }
594 
595 bool GCNSubtarget::useAA() const { return UseAA; }
596 
597 unsigned GCNSubtarget::getOccupancyWithNumSGPRs(unsigned SGPRs) const {
598   if (getGeneration() >= AMDGPUSubtarget::GFX10)
599     return getMaxWavesPerEU();
600 
601   if (getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
602     if (SGPRs <= 80)
603       return 10;
604     if (SGPRs <= 88)
605       return 9;
606     if (SGPRs <= 100)
607       return 8;
608     return 7;
609   }
610   if (SGPRs <= 48)
611     return 10;
612   if (SGPRs <= 56)
613     return 9;
614   if (SGPRs <= 64)
615     return 8;
616   if (SGPRs <= 72)
617     return 7;
618   if (SGPRs <= 80)
619     return 6;
620   return 5;
621 }
622 
623 unsigned GCNSubtarget::getOccupancyWithNumVGPRs(unsigned VGPRs) const {
624   unsigned MaxWaves = getMaxWavesPerEU();
625   unsigned Granule = getVGPRAllocGranule();
626   if (VGPRs < Granule)
627     return MaxWaves;
628   unsigned RoundedRegs = ((VGPRs + Granule - 1) / Granule) * Granule;
629   return std::min(std::max(getTotalNumVGPRs() / RoundedRegs, 1u), MaxWaves);
630 }
631 
632 unsigned
633 GCNSubtarget::getBaseReservedNumSGPRs(const bool HasFlatScratch) const {
634   if (getGeneration() >= AMDGPUSubtarget::GFX10)
635     return 2; // VCC. FLAT_SCRATCH and XNACK are no longer in SGPRs.
636 
637   if (HasFlatScratch || HasArchitectedFlatScratch) {
638     if (getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
639       return 6; // FLAT_SCRATCH, XNACK, VCC (in that order).
640     if (getGeneration() == AMDGPUSubtarget::SEA_ISLANDS)
641       return 4; // FLAT_SCRATCH, VCC (in that order).
642   }
643 
644   if (isXNACKEnabled())
645     return 4; // XNACK, VCC (in that order).
646   return 2; // VCC.
647 }
648 
649 unsigned GCNSubtarget::getReservedNumSGPRs(const MachineFunction &MF) const {
650   const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
651   return getBaseReservedNumSGPRs(MFI.hasFlatScratchInit());
652 }
653 
654 unsigned GCNSubtarget::getReservedNumSGPRs(const Function &F) const {
655   // In principle we do not need to reserve SGPR pair used for flat_scratch if
656   // we know flat instructions do not access the stack anywhere in the
657   // program. For now assume it's needed if we have flat instructions.
658   const bool KernelUsesFlatScratch = hasFlatAddressSpace();
659   return getBaseReservedNumSGPRs(KernelUsesFlatScratch);
660 }
661 
662 unsigned GCNSubtarget::computeOccupancy(const Function &F, unsigned LDSSize,
663                                         unsigned NumSGPRs,
664                                         unsigned NumVGPRs) const {
665   unsigned Occupancy =
666     std::min(getMaxWavesPerEU(),
667              getOccupancyWithLocalMemSize(LDSSize, F));
668   if (NumSGPRs)
669     Occupancy = std::min(Occupancy, getOccupancyWithNumSGPRs(NumSGPRs));
670   if (NumVGPRs)
671     Occupancy = std::min(Occupancy, getOccupancyWithNumVGPRs(NumVGPRs));
672   return Occupancy;
673 }
674 
675 unsigned GCNSubtarget::getBaseMaxNumSGPRs(
676     const Function &F, std::pair<unsigned, unsigned> WavesPerEU,
677     unsigned PreloadedSGPRs, unsigned ReservedNumSGPRs) const {
678   // Compute maximum number of SGPRs function can use using default/requested
679   // minimum number of waves per execution unit.
680   unsigned MaxNumSGPRs = getMaxNumSGPRs(WavesPerEU.first, false);
681   unsigned MaxAddressableNumSGPRs = getMaxNumSGPRs(WavesPerEU.first, true);
682 
683   // Check if maximum number of SGPRs was explicitly requested using
684   // "amdgpu-num-sgpr" attribute.
685   if (F.hasFnAttribute("amdgpu-num-sgpr")) {
686     unsigned Requested = AMDGPU::getIntegerAttribute(
687       F, "amdgpu-num-sgpr", MaxNumSGPRs);
688 
689     // Make sure requested value does not violate subtarget's specifications.
690     if (Requested && (Requested <= ReservedNumSGPRs))
691       Requested = 0;
692 
693     // If more SGPRs are required to support the input user/system SGPRs,
694     // increase to accommodate them.
695     //
696     // FIXME: This really ends up using the requested number of SGPRs + number
697     // of reserved special registers in total. Theoretically you could re-use
698     // the last input registers for these special registers, but this would
699     // require a lot of complexity to deal with the weird aliasing.
700     unsigned InputNumSGPRs = PreloadedSGPRs;
701     if (Requested && Requested < InputNumSGPRs)
702       Requested = InputNumSGPRs;
703 
704     // Make sure requested value is compatible with values implied by
705     // default/requested minimum/maximum number of waves per execution unit.
706     if (Requested && Requested > getMaxNumSGPRs(WavesPerEU.first, false))
707       Requested = 0;
708     if (WavesPerEU.second &&
709         Requested && Requested < getMinNumSGPRs(WavesPerEU.second))
710       Requested = 0;
711 
712     if (Requested)
713       MaxNumSGPRs = Requested;
714   }
715 
716   if (hasSGPRInitBug())
717     MaxNumSGPRs = AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
718 
719   return std::min(MaxNumSGPRs - ReservedNumSGPRs, MaxAddressableNumSGPRs);
720 }
721 
722 unsigned GCNSubtarget::getMaxNumSGPRs(const MachineFunction &MF) const {
723   const Function &F = MF.getFunction();
724   const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
725   return getBaseMaxNumSGPRs(F, MFI.getWavesPerEU(), MFI.getNumPreloadedSGPRs(),
726                             getReservedNumSGPRs(MF));
727 }
728 
729 static unsigned getMaxNumPreloadedSGPRs() {
730   // Max number of user SGPRs
731   unsigned MaxUserSGPRs = 4 + // private segment buffer
732                           2 + // Dispatch ptr
733                           2 + // queue ptr
734                           2 + // kernel segment ptr
735                           2 + // dispatch ID
736                           2 + // flat scratch init
737                           2;  // Implicit buffer ptr
738   // Max number of system SGPRs
739   unsigned MaxSystemSGPRs = 1 + // WorkGroupIDX
740                             1 + // WorkGroupIDY
741                             1 + // WorkGroupIDZ
742                             1 + // WorkGroupInfo
743                             1;  // private segment wave byte offset
744   return MaxUserSGPRs + MaxSystemSGPRs;
745 }
746 
747 unsigned GCNSubtarget::getMaxNumSGPRs(const Function &F) const {
748   return getBaseMaxNumSGPRs(F, getWavesPerEU(F), getMaxNumPreloadedSGPRs(),
749                             getReservedNumSGPRs(F));
750 }
751 
752 unsigned GCNSubtarget::getBaseMaxNumVGPRs(
753     const Function &F, std::pair<unsigned, unsigned> WavesPerEU) const {
754   // Compute maximum number of VGPRs function can use using default/requested
755   // minimum number of waves per execution unit.
756   unsigned MaxNumVGPRs = getMaxNumVGPRs(WavesPerEU.first);
757 
758   // Check if maximum number of VGPRs was explicitly requested using
759   // "amdgpu-num-vgpr" attribute.
760   if (F.hasFnAttribute("amdgpu-num-vgpr")) {
761     unsigned Requested = AMDGPU::getIntegerAttribute(
762       F, "amdgpu-num-vgpr", MaxNumVGPRs);
763 
764     if (hasGFX90AInsts())
765       Requested *= 2;
766 
767     // Make sure requested value is compatible with values implied by
768     // default/requested minimum/maximum number of waves per execution unit.
769     if (Requested && Requested > getMaxNumVGPRs(WavesPerEU.first))
770       Requested = 0;
771     if (WavesPerEU.second &&
772         Requested && Requested < getMinNumVGPRs(WavesPerEU.second))
773       Requested = 0;
774 
775     if (Requested)
776       MaxNumVGPRs = Requested;
777   }
778 
779   return MaxNumVGPRs;
780 }
781 
782 unsigned GCNSubtarget::getMaxNumVGPRs(const Function &F) const {
783   return getBaseMaxNumVGPRs(F, getWavesPerEU(F));
784 }
785 
786 unsigned GCNSubtarget::getMaxNumVGPRs(const MachineFunction &MF) const {
787   const Function &F = MF.getFunction();
788   const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
789   return getBaseMaxNumVGPRs(F, MFI.getWavesPerEU());
790 }
791 
792 void GCNSubtarget::adjustSchedDependency(SUnit *Def, int DefOpIdx, SUnit *Use,
793                                          int UseOpIdx, SDep &Dep) const {
794   if (Dep.getKind() != SDep::Kind::Data || !Dep.getReg() ||
795       !Def->isInstr() || !Use->isInstr())
796     return;
797 
798   MachineInstr *DefI = Def->getInstr();
799   MachineInstr *UseI = Use->getInstr();
800 
801   if (DefI->isBundle()) {
802     const SIRegisterInfo *TRI = getRegisterInfo();
803     auto Reg = Dep.getReg();
804     MachineBasicBlock::const_instr_iterator I(DefI->getIterator());
805     MachineBasicBlock::const_instr_iterator E(DefI->getParent()->instr_end());
806     unsigned Lat = 0;
807     for (++I; I != E && I->isBundledWithPred(); ++I) {
808       if (I->modifiesRegister(Reg, TRI))
809         Lat = InstrInfo.getInstrLatency(getInstrItineraryData(), *I);
810       else if (Lat)
811         --Lat;
812     }
813     Dep.setLatency(Lat);
814   } else if (UseI->isBundle()) {
815     const SIRegisterInfo *TRI = getRegisterInfo();
816     auto Reg = Dep.getReg();
817     MachineBasicBlock::const_instr_iterator I(UseI->getIterator());
818     MachineBasicBlock::const_instr_iterator E(UseI->getParent()->instr_end());
819     unsigned Lat = InstrInfo.getInstrLatency(getInstrItineraryData(), *DefI);
820     for (++I; I != E && I->isBundledWithPred() && Lat; ++I) {
821       if (I->readsRegister(Reg, TRI))
822         break;
823       --Lat;
824     }
825     Dep.setLatency(Lat);
826   } else if (Dep.getLatency() == 0 && Dep.getReg() == AMDGPU::VCC_LO) {
827     // Work around the fact that SIInstrInfo::fixImplicitOperands modifies
828     // implicit operands which come from the MCInstrDesc, which can fool
829     // ScheduleDAGInstrs::addPhysRegDataDeps into treating them as implicit
830     // pseudo operands.
831     Dep.setLatency(InstrInfo.getSchedModel().computeOperandLatency(
832         DefI, DefOpIdx, UseI, UseOpIdx));
833   }
834 }
835 
836 namespace {
837 struct FillMFMAShadowMutation : ScheduleDAGMutation {
838   const SIInstrInfo *TII;
839 
840   ScheduleDAGMI *DAG;
841 
842   FillMFMAShadowMutation(const SIInstrInfo *tii) : TII(tii) {}
843 
844   bool isSALU(const SUnit *SU) const {
845     const MachineInstr *MI = SU->getInstr();
846     return MI && TII->isSALU(*MI) && !MI->isTerminator();
847   }
848 
849   bool isVALU(const SUnit *SU) const {
850     const MachineInstr *MI = SU->getInstr();
851     return MI && TII->isVALU(*MI);
852   }
853 
854   bool canAddEdge(const SUnit *Succ, const SUnit *Pred) const {
855     if (Pred->NodeNum < Succ->NodeNum)
856       return true;
857 
858     SmallVector<const SUnit*, 64> Succs({Succ}), Preds({Pred});
859 
860     for (unsigned I = 0; I < Succs.size(); ++I) {
861       for (const SDep &SI : Succs[I]->Succs) {
862         const SUnit *SU = SI.getSUnit();
863         if (SU != Succs[I] && !llvm::is_contained(Succs, SU))
864           Succs.push_back(SU);
865       }
866     }
867 
868     SmallPtrSet<const SUnit*, 32> Visited;
869     while (!Preds.empty()) {
870       const SUnit *SU = Preds.pop_back_val();
871       if (llvm::is_contained(Succs, SU))
872         return false;
873       Visited.insert(SU);
874       for (const SDep &SI : SU->Preds)
875         if (SI.getSUnit() != SU && !Visited.count(SI.getSUnit()))
876           Preds.push_back(SI.getSUnit());
877     }
878 
879     return true;
880   }
881 
882   // Link as many SALU instructions in chain as possible. Return the size
883   // of the chain. Links up to MaxChain instructions.
884   unsigned linkSALUChain(SUnit *From, SUnit *To, unsigned MaxChain,
885                          SmallPtrSetImpl<SUnit *> &Visited) const {
886     SmallVector<SUnit *, 8> Worklist({To});
887     unsigned Linked = 0;
888 
889     while (!Worklist.empty() && MaxChain-- > 0) {
890       SUnit *SU = Worklist.pop_back_val();
891       if (!Visited.insert(SU).second)
892         continue;
893 
894       LLVM_DEBUG(dbgs() << "Inserting edge from\n" ; DAG->dumpNode(*From);
895                  dbgs() << "to\n"; DAG->dumpNode(*SU); dbgs() << '\n');
896 
897       if (SU->addPred(SDep(From, SDep::Artificial), false))
898         ++Linked;
899 
900       for (SDep &SI : From->Succs) {
901         SUnit *SUv = SI.getSUnit();
902         if (SUv != From && isVALU(SUv) && canAddEdge(SUv, SU))
903           SUv->addPred(SDep(SU, SDep::Artificial), false);
904       }
905 
906       for (SDep &SI : SU->Succs) {
907         SUnit *Succ = SI.getSUnit();
908         if (Succ != SU && isSALU(Succ) && canAddEdge(From, Succ))
909           Worklist.push_back(Succ);
910       }
911     }
912 
913     return Linked;
914   }
915 
916   void apply(ScheduleDAGInstrs *DAGInstrs) override {
917     const GCNSubtarget &ST = DAGInstrs->MF.getSubtarget<GCNSubtarget>();
918     if (!ST.hasMAIInsts() || DisablePowerSched)
919       return;
920     DAG = static_cast<ScheduleDAGMI*>(DAGInstrs);
921     const TargetSchedModel *TSchedModel = DAGInstrs->getSchedModel();
922     if (!TSchedModel || DAG->SUnits.empty())
923       return;
924 
925     // Scan for MFMA long latency instructions and try to add a dependency
926     // of available SALU instructions to give them a chance to fill MFMA
927     // shadow. That is desirable to fill MFMA shadow with SALU instructions
928     // rather than VALU to prevent power consumption bursts and throttle.
929     auto LastSALU = DAG->SUnits.begin();
930     auto E = DAG->SUnits.end();
931     SmallPtrSet<SUnit*, 32> Visited;
932     for (SUnit &SU : DAG->SUnits) {
933       MachineInstr &MAI = *SU.getInstr();
934       if (!TII->isMAI(MAI) ||
935            MAI.getOpcode() == AMDGPU::V_ACCVGPR_WRITE_B32_e64 ||
936            MAI.getOpcode() == AMDGPU::V_ACCVGPR_READ_B32_e64)
937         continue;
938 
939       unsigned Lat = TSchedModel->computeInstrLatency(&MAI) - 1;
940 
941       LLVM_DEBUG(dbgs() << "Found MFMA: "; DAG->dumpNode(SU);
942                  dbgs() << "Need " << Lat
943                         << " instructions to cover latency.\n");
944 
945       // Find up to Lat independent scalar instructions as early as
946       // possible such that they can be scheduled after this MFMA.
947       for ( ; Lat && LastSALU != E; ++LastSALU) {
948         if (Visited.count(&*LastSALU))
949           continue;
950 
951         if (!isSALU(&*LastSALU) || !canAddEdge(&*LastSALU, &SU))
952           continue;
953 
954         Lat -= linkSALUChain(&SU, &*LastSALU, Lat, Visited);
955       }
956     }
957   }
958 };
959 } // namespace
960 
961 void GCNSubtarget::getPostRAMutations(
962     std::vector<std::unique_ptr<ScheduleDAGMutation>> &Mutations) const {
963   Mutations.push_back(std::make_unique<FillMFMAShadowMutation>(&InstrInfo));
964 }
965 
966 std::unique_ptr<ScheduleDAGMutation>
967 GCNSubtarget::createFillMFMAShadowMutation(const TargetInstrInfo *TII) const {
968   return std::make_unique<FillMFMAShadowMutation>(&InstrInfo);
969 }
970 
971 const AMDGPUSubtarget &AMDGPUSubtarget::get(const MachineFunction &MF) {
972   if (MF.getTarget().getTargetTriple().getArch() == Triple::amdgcn)
973     return static_cast<const AMDGPUSubtarget&>(MF.getSubtarget<GCNSubtarget>());
974   else
975     return static_cast<const AMDGPUSubtarget&>(MF.getSubtarget<R600Subtarget>());
976 }
977 
978 const AMDGPUSubtarget &AMDGPUSubtarget::get(const TargetMachine &TM, const Function &F) {
979   if (TM.getTargetTriple().getArch() == Triple::amdgcn)
980     return static_cast<const AMDGPUSubtarget&>(TM.getSubtarget<GCNSubtarget>(F));
981   else
982     return static_cast<const AMDGPUSubtarget&>(TM.getSubtarget<R600Subtarget>(F));
983 }
984