1 //===-- AMDGPUAsmPrinter.cpp - AMDGPU assembly printer --------------------===//
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 /// The AMDGPUAsmPrinter is used to print both assembly string and also binary
12 /// code.  When passed an MCAsmStreamer it prints assembly and when passed
13 /// an MCObjectStreamer it outputs binary code.
14 //
15 //===----------------------------------------------------------------------===//
16 //
17 
18 #include "AMDGPUAsmPrinter.h"
19 #include "AMDGPU.h"
20 #include "AMDGPUSubtarget.h"
21 #include "AMDGPUTargetMachine.h"
22 #include "MCTargetDesc/AMDGPUInstPrinter.h"
23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
24 #include "MCTargetDesc/AMDGPUTargetStreamer.h"
25 #include "R600AsmPrinter.h"
26 #include "R600Defines.h"
27 #include "R600MachineFunctionInfo.h"
28 #include "R600RegisterInfo.h"
29 #include "SIDefines.h"
30 #include "SIInstrInfo.h"
31 #include "SIMachineFunctionInfo.h"
32 #include "SIRegisterInfo.h"
33 #include "TargetInfo/AMDGPUTargetInfo.h"
34 #include "Utils/AMDGPUBaseInfo.h"
35 #include "llvm/BinaryFormat/ELF.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/IR/DiagnosticInfo.h"
38 #include "llvm/MC/MCAssembler.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCSectionELF.h"
41 #include "llvm/MC/MCStreamer.h"
42 #include "llvm/Support/AMDGPUMetadata.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/Support/TargetParser.h"
45 #include "llvm/Support/TargetRegistry.h"
46 #include "llvm/Target/TargetLoweringObjectFile.h"
47 
48 using namespace llvm;
49 using namespace llvm::AMDGPU;
50 using namespace llvm::AMDGPU::HSAMD;
51 
52 // We need to tell the runtime some amount ahead of time if we don't know the
53 // true stack size. Assume a smaller number if this is only due to dynamic /
54 // non-entry block allocas.
55 static cl::opt<uint32_t> AssumedStackSizeForExternalCall(
56   "amdgpu-assume-external-call-stack-size",
57   cl::desc("Assumed stack use of any external call (in bytes)"),
58   cl::Hidden,
59   cl::init(16384));
60 
61 static cl::opt<uint32_t> AssumedStackSizeForDynamicSizeObjects(
62   "amdgpu-assume-dynamic-stack-object-size",
63   cl::desc("Assumed extra stack use if there are any "
64            "variable sized objects (in bytes)"),
65   cl::Hidden,
66   cl::init(4096));
67 
68 // This should get the default rounding mode from the kernel. We just set the
69 // default here, but this could change if the OpenCL rounding mode pragmas are
70 // used.
71 //
72 // The denormal mode here should match what is reported by the OpenCL runtime
73 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
74 // can also be override to flush with the -cl-denorms-are-zero compiler flag.
75 //
76 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
77 // precision, and leaves single precision to flush all and does not report
78 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
79 // CL_FP_DENORM for both.
80 //
81 // FIXME: It seems some instructions do not support single precision denormals
82 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
83 // and sin_f32, cos_f32 on most parts).
84 
85 // We want to use these instructions, and using fp32 denormals also causes
86 // instructions to run at the double precision rate for the device so it's
87 // probably best to just report no single precision denormals.
88 static uint32_t getFPMode(AMDGPU::SIModeRegisterDefaults Mode) {
89   return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) |
90          FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) |
91          FP_DENORM_MODE_SP(Mode.fpDenormModeSPValue()) |
92          FP_DENORM_MODE_DP(Mode.fpDenormModeDPValue());
93 }
94 
95 static AsmPrinter *
96 createAMDGPUAsmPrinterPass(TargetMachine &tm,
97                            std::unique_ptr<MCStreamer> &&Streamer) {
98   return new AMDGPUAsmPrinter(tm, std::move(Streamer));
99 }
100 
101 extern "C" void LLVM_EXTERNAL_VISIBILITY LLVMInitializeAMDGPUAsmPrinter() {
102   TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(),
103                                      llvm::createR600AsmPrinterPass);
104   TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(),
105                                      createAMDGPUAsmPrinterPass);
106 }
107 
108 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM,
109                                    std::unique_ptr<MCStreamer> Streamer)
110   : AsmPrinter(TM, std::move(Streamer)) {
111     if (IsaInfo::hasCodeObjectV3(getGlobalSTI()))
112       HSAMetadataStream.reset(new MetadataStreamerV3());
113     else
114       HSAMetadataStream.reset(new MetadataStreamerV2());
115 }
116 
117 StringRef AMDGPUAsmPrinter::getPassName() const {
118   return "AMDGPU Assembly Printer";
119 }
120 
121 const MCSubtargetInfo *AMDGPUAsmPrinter::getGlobalSTI() const {
122   return TM.getMCSubtargetInfo();
123 }
124 
125 AMDGPUTargetStreamer* AMDGPUAsmPrinter::getTargetStreamer() const {
126   if (!OutStreamer)
127     return nullptr;
128   return static_cast<AMDGPUTargetStreamer*>(OutStreamer->getTargetStreamer());
129 }
130 
131 void AMDGPUAsmPrinter::emitStartOfAsmFile(Module &M) {
132   if (IsaInfo::hasCodeObjectV3(getGlobalSTI())) {
133     std::string ExpectedTarget;
134     raw_string_ostream ExpectedTargetOS(ExpectedTarget);
135     IsaInfo::streamIsaVersion(getGlobalSTI(), ExpectedTargetOS);
136 
137     getTargetStreamer()->EmitDirectiveAMDGCNTarget(ExpectedTarget);
138   }
139 
140   if (TM.getTargetTriple().getOS() != Triple::AMDHSA &&
141       TM.getTargetTriple().getOS() != Triple::AMDPAL)
142     return;
143 
144   if (TM.getTargetTriple().getOS() == Triple::AMDHSA)
145     HSAMetadataStream->begin(M);
146 
147   if (TM.getTargetTriple().getOS() == Triple::AMDPAL)
148     getTargetStreamer()->getPALMetadata()->readFromIR(M);
149 
150   if (IsaInfo::hasCodeObjectV3(getGlobalSTI()))
151     return;
152 
153   // HSA emits NT_AMDGPU_HSA_CODE_OBJECT_VERSION for code objects v2.
154   if (TM.getTargetTriple().getOS() == Triple::AMDHSA)
155     getTargetStreamer()->EmitDirectiveHSACodeObjectVersion(2, 1);
156 
157   // HSA and PAL emit NT_AMDGPU_HSA_ISA for code objects v2.
158   IsaVersion Version = getIsaVersion(getGlobalSTI()->getCPU());
159   getTargetStreamer()->EmitDirectiveHSACodeObjectISA(
160       Version.Major, Version.Minor, Version.Stepping, "AMD", "AMDGPU");
161 }
162 
163 void AMDGPUAsmPrinter::emitEndOfAsmFile(Module &M) {
164   // Following code requires TargetStreamer to be present.
165   if (!getTargetStreamer())
166     return;
167 
168   if (!IsaInfo::hasCodeObjectV3(getGlobalSTI())) {
169     // Emit ISA Version (NT_AMD_AMDGPU_ISA).
170     std::string ISAVersionString;
171     raw_string_ostream ISAVersionStream(ISAVersionString);
172     IsaInfo::streamIsaVersion(getGlobalSTI(), ISAVersionStream);
173     getTargetStreamer()->EmitISAVersion(ISAVersionStream.str());
174   }
175 
176   // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA).
177   if (TM.getTargetTriple().getOS() == Triple::AMDHSA) {
178     HSAMetadataStream->end();
179     bool Success = HSAMetadataStream->emitTo(*getTargetStreamer());
180     (void)Success;
181     assert(Success && "Malformed HSA Metadata");
182   }
183 }
184 
185 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough(
186   const MachineBasicBlock *MBB) const {
187   if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB))
188     return false;
189 
190   if (MBB->empty())
191     return true;
192 
193   // If this is a block implementing a long branch, an expression relative to
194   // the start of the block is needed.  to the start of the block.
195   // XXX - Is there a smarter way to check this?
196   return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64);
197 }
198 
199 void AMDGPUAsmPrinter::emitFunctionBodyStart() {
200   const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
201   if (!MFI.isEntryFunction())
202     return;
203 
204   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
205   const Function &F = MF->getFunction();
206   if (!STM.hasCodeObjectV3() && STM.isAmdHsaOrMesa(F) &&
207       (F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
208        F.getCallingConv() == CallingConv::SPIR_KERNEL)) {
209     amd_kernel_code_t KernelCode;
210     getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF);
211     getTargetStreamer()->EmitAMDKernelCodeT(KernelCode);
212   }
213 
214   if (STM.isAmdHsaOS())
215     HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo);
216 }
217 
218 void AMDGPUAsmPrinter::emitFunctionBodyEnd() {
219   const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
220   if (!MFI.isEntryFunction())
221     return;
222 
223   if (!IsaInfo::hasCodeObjectV3(getGlobalSTI()) ||
224       TM.getTargetTriple().getOS() != Triple::AMDHSA)
225     return;
226 
227   auto &Streamer = getTargetStreamer()->getStreamer();
228   auto &Context = Streamer.getContext();
229   auto &ObjectFileInfo = *Context.getObjectFileInfo();
230   auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection();
231 
232   Streamer.PushSection();
233   Streamer.SwitchSection(&ReadOnlySection);
234 
235   // CP microcode requires the kernel descriptor to be allocated on 64 byte
236   // alignment.
237   Streamer.emitValueToAlignment(64, 0, 1, 0);
238   if (ReadOnlySection.getAlignment() < 64)
239     ReadOnlySection.setAlignment(Align(64));
240 
241   const MCSubtargetInfo &STI = MF->getSubtarget();
242 
243   SmallString<128> KernelName;
244   getNameWithPrefix(KernelName, &MF->getFunction());
245   getTargetStreamer()->EmitAmdhsaKernelDescriptor(
246       STI, KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo),
247       CurrentProgramInfo.NumVGPRsForWavesPerEU,
248       CurrentProgramInfo.NumSGPRsForWavesPerEU -
249           IsaInfo::getNumExtraSGPRs(&STI,
250                                     CurrentProgramInfo.VCCUsed,
251                                     CurrentProgramInfo.FlatUsed),
252       CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed,
253       hasXNACK(STI));
254 
255   Streamer.PopSection();
256 }
257 
258 void AMDGPUAsmPrinter::emitFunctionEntryLabel() {
259   if (IsaInfo::hasCodeObjectV3(getGlobalSTI()) &&
260       TM.getTargetTriple().getOS() == Triple::AMDHSA) {
261     AsmPrinter::emitFunctionEntryLabel();
262     return;
263   }
264 
265   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
266   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
267   if (MFI->isEntryFunction() && STM.isAmdHsaOrMesa(MF->getFunction())) {
268     SmallString<128> SymbolName;
269     getNameWithPrefix(SymbolName, &MF->getFunction()),
270     getTargetStreamer()->EmitAMDGPUSymbolType(
271         SymbolName, ELF::STT_AMDGPU_HSA_KERNEL);
272   }
273   if (DumpCodeInstEmitter) {
274     // Disassemble function name label to text.
275     DisasmLines.push_back(MF->getName().str() + ":");
276     DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
277     HexLines.push_back("");
278   }
279 
280   AsmPrinter::emitFunctionEntryLabel();
281 }
282 
283 void AMDGPUAsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
284   if (DumpCodeInstEmitter && !isBlockOnlyReachableByFallthrough(&MBB)) {
285     // Write a line for the basic block label if it is not only fallthrough.
286     DisasmLines.push_back(
287         (Twine("BB") + Twine(getFunctionNumber())
288          + "_" + Twine(MBB.getNumber()) + ":").str());
289     DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
290     HexLines.push_back("");
291   }
292   AsmPrinter::emitBasicBlockStart(MBB);
293 }
294 
295 void AMDGPUAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
296   if (GV->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
297     if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) {
298       OutContext.reportError({},
299                              Twine(GV->getName()) +
300                                  ": unsupported initializer for address space");
301       return;
302     }
303 
304     // LDS variables aren't emitted in HSA or PAL yet.
305     const Triple::OSType OS = TM.getTargetTriple().getOS();
306     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
307       return;
308 
309     MCSymbol *GVSym = getSymbol(GV);
310 
311     GVSym->redefineIfPossible();
312     if (GVSym->isDefined() || GVSym->isVariable())
313       report_fatal_error("symbol '" + Twine(GVSym->getName()) +
314                          "' is already defined");
315 
316     const DataLayout &DL = GV->getParent()->getDataLayout();
317     uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
318     unsigned Align = GV->getAlignment();
319     if (!Align)
320       Align = 4;
321 
322     emitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
323     emitLinkage(GV, GVSym);
324     if (auto TS = getTargetStreamer())
325       TS->emitAMDGPULDS(GVSym, Size, Align);
326     return;
327   }
328 
329   AsmPrinter::emitGlobalVariable(GV);
330 }
331 
332 bool AMDGPUAsmPrinter::doFinalization(Module &M) {
333   CallGraphResourceInfo.clear();
334 
335   // Pad with s_code_end to help tools and guard against instruction prefetch
336   // causing stale data in caches. Arguably this should be done by the linker,
337   // which is why this isn't done for Mesa.
338   const MCSubtargetInfo &STI = *getGlobalSTI();
339   if (AMDGPU::isGFX10(STI) &&
340       (STI.getTargetTriple().getOS() == Triple::AMDHSA ||
341        STI.getTargetTriple().getOS() == Triple::AMDPAL)) {
342     OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
343     getTargetStreamer()->EmitCodeEnd();
344   }
345 
346   return AsmPrinter::doFinalization(M);
347 }
348 
349 // Print comments that apply to both callable functions and entry points.
350 void AMDGPUAsmPrinter::emitCommonFunctionComments(
351   uint32_t NumVGPR,
352   Optional<uint32_t> NumAGPR,
353   uint32_t TotalNumVGPR,
354   uint32_t NumSGPR,
355   uint64_t ScratchSize,
356   uint64_t CodeSize,
357   const AMDGPUMachineFunction *MFI) {
358   OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false);
359   OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false);
360   OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false);
361   if (NumAGPR) {
362     OutStreamer->emitRawComment(" NumAgprs: " + Twine(*NumAGPR), false);
363     OutStreamer->emitRawComment(" TotalNumVgprs: " + Twine(TotalNumVGPR),
364                                 false);
365   }
366   OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false);
367   OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()),
368                               false);
369 }
370 
371 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties(
372     const MachineFunction &MF) const {
373   const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
374   uint16_t KernelCodeProperties = 0;
375 
376   if (MFI.hasPrivateSegmentBuffer()) {
377     KernelCodeProperties |=
378         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
379   }
380   if (MFI.hasDispatchPtr()) {
381     KernelCodeProperties |=
382         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
383   }
384   if (MFI.hasQueuePtr()) {
385     KernelCodeProperties |=
386         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
387   }
388   if (MFI.hasKernargSegmentPtr()) {
389     KernelCodeProperties |=
390         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
391   }
392   if (MFI.hasDispatchID()) {
393     KernelCodeProperties |=
394         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
395   }
396   if (MFI.hasFlatScratchInit()) {
397     KernelCodeProperties |=
398         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
399   }
400   if (MF.getSubtarget<GCNSubtarget>().isWave32()) {
401     KernelCodeProperties |=
402         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32;
403   }
404 
405   return KernelCodeProperties;
406 }
407 
408 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor(
409     const MachineFunction &MF,
410     const SIProgramInfo &PI) const {
411   amdhsa::kernel_descriptor_t KernelDescriptor;
412   memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor));
413 
414   assert(isUInt<32>(PI.ScratchSize));
415   assert(isUInt<32>(PI.ComputePGMRSrc1));
416   assert(isUInt<32>(PI.ComputePGMRSrc2));
417 
418   KernelDescriptor.group_segment_fixed_size = PI.LDSSize;
419   KernelDescriptor.private_segment_fixed_size = PI.ScratchSize;
420   KernelDescriptor.compute_pgm_rsrc1 = PI.ComputePGMRSrc1;
421   KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2;
422   KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF);
423 
424   return KernelDescriptor;
425 }
426 
427 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
428   CurrentProgramInfo = SIProgramInfo();
429 
430   const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
431 
432   // The starting address of all shader programs must be 256 bytes aligned.
433   // Regular functions just need the basic required instruction alignment.
434   MF.setAlignment(MFI->isEntryFunction() ? Align(256) : Align(4));
435 
436   SetupMachineFunction(MF);
437 
438   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
439   MCContext &Context = getObjFileLowering().getContext();
440   // FIXME: This should be an explicit check for Mesa.
441   if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) {
442     MCSectionELF *ConfigSection =
443         Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
444     OutStreamer->SwitchSection(ConfigSection);
445   }
446 
447   if (MFI->isEntryFunction()) {
448     getSIProgramInfo(CurrentProgramInfo, MF);
449   } else {
450     auto I = CallGraphResourceInfo.insert(
451       std::make_pair(&MF.getFunction(), SIFunctionResourceInfo()));
452     SIFunctionResourceInfo &Info = I.first->second;
453     assert(I.second && "should only be called once per function");
454     Info = analyzeResourceUsage(MF);
455   }
456 
457   if (STM.isAmdPalOS())
458     EmitPALMetadata(MF, CurrentProgramInfo);
459   else if (!STM.isAmdHsaOS()) {
460     EmitProgramInfoSI(MF, CurrentProgramInfo);
461   }
462 
463   DumpCodeInstEmitter = nullptr;
464   if (STM.dumpCode()) {
465     // For -dumpcode, get the assembler out of the streamer, even if it does
466     // not really want to let us have it. This only works with -filetype=obj.
467     bool SaveFlag = OutStreamer->getUseAssemblerInfoForParsing();
468     OutStreamer->setUseAssemblerInfoForParsing(true);
469     MCAssembler *Assembler = OutStreamer->getAssemblerPtr();
470     OutStreamer->setUseAssemblerInfoForParsing(SaveFlag);
471     if (Assembler)
472       DumpCodeInstEmitter = Assembler->getEmitterPtr();
473   }
474 
475   DisasmLines.clear();
476   HexLines.clear();
477   DisasmLineMaxLen = 0;
478 
479   emitFunctionBody();
480 
481   if (isVerbose()) {
482     MCSectionELF *CommentSection =
483         Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
484     OutStreamer->SwitchSection(CommentSection);
485 
486     if (!MFI->isEntryFunction()) {
487       OutStreamer->emitRawComment(" Function info:", false);
488       SIFunctionResourceInfo &Info = CallGraphResourceInfo[&MF.getFunction()];
489       emitCommonFunctionComments(
490         Info.NumVGPR,
491         STM.hasMAIInsts() ? Info.NumAGPR : Optional<uint32_t>(),
492         Info.getTotalNumVGPRs(STM),
493         Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()),
494         Info.PrivateSegmentSize,
495         getFunctionCodeSize(MF), MFI);
496       return false;
497     }
498 
499     OutStreamer->emitRawComment(" Kernel info:", false);
500     emitCommonFunctionComments(CurrentProgramInfo.NumArchVGPR,
501                                STM.hasMAIInsts()
502                                  ? CurrentProgramInfo.NumAccVGPR
503                                  : Optional<uint32_t>(),
504                                CurrentProgramInfo.NumVGPR,
505                                CurrentProgramInfo.NumSGPR,
506                                CurrentProgramInfo.ScratchSize,
507                                getFunctionCodeSize(MF), MFI);
508 
509     OutStreamer->emitRawComment(
510       " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false);
511     OutStreamer->emitRawComment(
512       " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false);
513     OutStreamer->emitRawComment(
514       " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) +
515       " bytes/workgroup (compile time only)", false);
516 
517     OutStreamer->emitRawComment(
518       " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false);
519     OutStreamer->emitRawComment(
520       " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false);
521 
522     OutStreamer->emitRawComment(
523       " NumSGPRsForWavesPerEU: " +
524       Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false);
525     OutStreamer->emitRawComment(
526       " NumVGPRsForWavesPerEU: " +
527       Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false);
528 
529     OutStreamer->emitRawComment(
530       " Occupancy: " +
531       Twine(CurrentProgramInfo.Occupancy), false);
532 
533     OutStreamer->emitRawComment(
534       " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false);
535 
536     OutStreamer->emitRawComment(
537       " COMPUTE_PGM_RSRC2:USER_SGPR: " +
538       Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false);
539     OutStreamer->emitRawComment(
540       " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " +
541       Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false);
542     OutStreamer->emitRawComment(
543       " COMPUTE_PGM_RSRC2:TGID_X_EN: " +
544       Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
545     OutStreamer->emitRawComment(
546       " COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
547       Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
548     OutStreamer->emitRawComment(
549       " COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
550       Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
551     OutStreamer->emitRawComment(
552       " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
553       Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)),
554       false);
555   }
556 
557   if (DumpCodeInstEmitter) {
558 
559     OutStreamer->SwitchSection(
560         Context.getELFSection(".AMDGPU.disasm", ELF::SHT_PROGBITS, 0));
561 
562     for (size_t i = 0; i < DisasmLines.size(); ++i) {
563       std::string Comment = "\n";
564       if (!HexLines[i].empty()) {
565         Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
566         Comment += " ; " + HexLines[i] + "\n";
567       }
568 
569       OutStreamer->emitBytes(StringRef(DisasmLines[i]));
570       OutStreamer->emitBytes(StringRef(Comment));
571     }
572   }
573 
574   return false;
575 }
576 
577 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const {
578   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
579   const SIInstrInfo *TII = STM.getInstrInfo();
580 
581   uint64_t CodeSize = 0;
582 
583   for (const MachineBasicBlock &MBB : MF) {
584     for (const MachineInstr &MI : MBB) {
585       // TODO: CodeSize should account for multiple functions.
586 
587       // TODO: Should we count size of debug info?
588       if (MI.isDebugInstr())
589         continue;
590 
591       CodeSize += TII->getInstSizeInBytes(MI);
592     }
593   }
594 
595   return CodeSize;
596 }
597 
598 static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI,
599                                   const SIInstrInfo &TII,
600                                   unsigned Reg) {
601   for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) {
602     if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent()))
603       return true;
604   }
605 
606   return false;
607 }
608 
609 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumSGPRs(
610   const GCNSubtarget &ST) const {
611   return NumExplicitSGPR + IsaInfo::getNumExtraSGPRs(&ST,
612                                                      UsesVCC, UsesFlatScratch);
613 }
614 
615 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumVGPRs(
616   const GCNSubtarget &ST) const {
617   return std::max(NumVGPR, NumAGPR);
618 }
619 
620 static const Function *getCalleeFunction(const MachineOperand &Op) {
621   if (Op.isImm()) {
622     assert(Op.getImm() == 0);
623     return nullptr;
624   }
625 
626   return cast<Function>(Op.getGlobal());
627 }
628 
629 AMDGPUAsmPrinter::SIFunctionResourceInfo AMDGPUAsmPrinter::analyzeResourceUsage(
630   const MachineFunction &MF) const {
631   SIFunctionResourceInfo Info;
632 
633   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
634   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
635   const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
636   const MachineRegisterInfo &MRI = MF.getRegInfo();
637   const SIInstrInfo *TII = ST.getInstrInfo();
638   const SIRegisterInfo &TRI = TII->getRegisterInfo();
639 
640   Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) ||
641                          MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI);
642 
643   // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat
644   // instructions aren't used to access the scratch buffer. Inline assembly may
645   // need it though.
646   //
647   // If we only have implicit uses of flat_scr on flat instructions, it is not
648   // really needed.
649   if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() &&
650       (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) &&
651        !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) &&
652        !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) {
653     Info.UsesFlatScratch = false;
654   }
655 
656   Info.PrivateSegmentSize = FrameInfo.getStackSize();
657 
658   // Assume a big number if there are any unknown sized objects.
659   Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects();
660   if (Info.HasDynamicallySizedStack)
661     Info.PrivateSegmentSize += AssumedStackSizeForDynamicSizeObjects;
662 
663   if (MFI->isStackRealigned())
664     Info.PrivateSegmentSize += FrameInfo.getMaxAlign().value();
665 
666   Info.UsesVCC = MRI.isPhysRegUsed(AMDGPU::VCC_LO) ||
667                  MRI.isPhysRegUsed(AMDGPU::VCC_HI);
668 
669   // If there are no calls, MachineRegisterInfo can tell us the used register
670   // count easily.
671   // A tail call isn't considered a call for MachineFrameInfo's purposes.
672   if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) {
673     MCPhysReg HighestVGPRReg = AMDGPU::NoRegister;
674     for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) {
675       if (MRI.isPhysRegUsed(Reg)) {
676         HighestVGPRReg = Reg;
677         break;
678       }
679     }
680 
681     if (ST.hasMAIInsts()) {
682       MCPhysReg HighestAGPRReg = AMDGPU::NoRegister;
683       for (MCPhysReg Reg : reverse(AMDGPU::AGPR_32RegClass.getRegisters())) {
684         if (MRI.isPhysRegUsed(Reg)) {
685           HighestAGPRReg = Reg;
686           break;
687         }
688       }
689       Info.NumAGPR = HighestAGPRReg == AMDGPU::NoRegister ? 0 :
690         TRI.getHWRegIndex(HighestAGPRReg) + 1;
691     }
692 
693     MCPhysReg HighestSGPRReg = AMDGPU::NoRegister;
694     for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) {
695       if (MRI.isPhysRegUsed(Reg)) {
696         HighestSGPRReg = Reg;
697         break;
698       }
699     }
700 
701     // We found the maximum register index. They start at 0, so add one to get the
702     // number of registers.
703     Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister ? 0 :
704       TRI.getHWRegIndex(HighestVGPRReg) + 1;
705     Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister ? 0 :
706       TRI.getHWRegIndex(HighestSGPRReg) + 1;
707 
708     return Info;
709   }
710 
711   int32_t MaxVGPR = -1;
712   int32_t MaxAGPR = -1;
713   int32_t MaxSGPR = -1;
714   uint64_t CalleeFrameSize = 0;
715 
716   for (const MachineBasicBlock &MBB : MF) {
717     for (const MachineInstr &MI : MBB) {
718       // TODO: Check regmasks? Do they occur anywhere except calls?
719       for (const MachineOperand &MO : MI.operands()) {
720         unsigned Width = 0;
721         bool IsSGPR = false;
722         bool IsAGPR = false;
723 
724         if (!MO.isReg())
725           continue;
726 
727         Register Reg = MO.getReg();
728         switch (Reg) {
729         case AMDGPU::EXEC:
730         case AMDGPU::EXEC_LO:
731         case AMDGPU::EXEC_HI:
732         case AMDGPU::SCC:
733         case AMDGPU::M0:
734         case AMDGPU::SRC_SHARED_BASE:
735         case AMDGPU::SRC_SHARED_LIMIT:
736         case AMDGPU::SRC_PRIVATE_BASE:
737         case AMDGPU::SRC_PRIVATE_LIMIT:
738         case AMDGPU::SGPR_NULL:
739         case AMDGPU::MODE:
740           continue;
741 
742         case AMDGPU::SRC_POPS_EXITING_WAVE_ID:
743           llvm_unreachable("src_pops_exiting_wave_id should not be used");
744 
745         case AMDGPU::NoRegister:
746           assert(MI.isDebugInstr());
747           continue;
748 
749         case AMDGPU::VCC:
750         case AMDGPU::VCC_LO:
751         case AMDGPU::VCC_HI:
752         case AMDGPU::VCC_LO_LO16:
753         case AMDGPU::VCC_LO_HI16:
754         case AMDGPU::VCC_HI_LO16:
755         case AMDGPU::VCC_HI_HI16:
756           Info.UsesVCC = true;
757           continue;
758 
759         case AMDGPU::FLAT_SCR:
760         case AMDGPU::FLAT_SCR_LO:
761         case AMDGPU::FLAT_SCR_HI:
762           continue;
763 
764         case AMDGPU::XNACK_MASK:
765         case AMDGPU::XNACK_MASK_LO:
766         case AMDGPU::XNACK_MASK_HI:
767           llvm_unreachable("xnack_mask registers should not be used");
768 
769         case AMDGPU::LDS_DIRECT:
770           llvm_unreachable("lds_direct register should not be used");
771 
772         case AMDGPU::TBA:
773         case AMDGPU::TBA_LO:
774         case AMDGPU::TBA_HI:
775         case AMDGPU::TMA:
776         case AMDGPU::TMA_LO:
777         case AMDGPU::TMA_HI:
778           llvm_unreachable("trap handler registers should not be used");
779 
780         case AMDGPU::SRC_VCCZ:
781           llvm_unreachable("src_vccz register should not be used");
782 
783         case AMDGPU::SRC_EXECZ:
784           llvm_unreachable("src_execz register should not be used");
785 
786         case AMDGPU::SRC_SCC:
787           llvm_unreachable("src_scc register should not be used");
788 
789         default:
790           break;
791         }
792 
793         if (AMDGPU::SReg_32RegClass.contains(Reg) ||
794             AMDGPU::SReg_LO16RegClass.contains(Reg) ||
795             AMDGPU::SGPR_HI16RegClass.contains(Reg)) {
796           assert(!AMDGPU::TTMP_32RegClass.contains(Reg) &&
797                  "trap handler registers should not be used");
798           IsSGPR = true;
799           Width = 1;
800         } else if (AMDGPU::VGPR_32RegClass.contains(Reg) ||
801                    AMDGPU::VGPR_LO16RegClass.contains(Reg) ||
802                    AMDGPU::VGPR_HI16RegClass.contains(Reg)) {
803           IsSGPR = false;
804           Width = 1;
805         } else if (AMDGPU::AGPR_32RegClass.contains(Reg) ||
806                    AMDGPU::AGPR_LO16RegClass.contains(Reg)) {
807           IsSGPR = false;
808           IsAGPR = true;
809           Width = 1;
810         } else if (AMDGPU::SReg_64RegClass.contains(Reg)) {
811           assert(!AMDGPU::TTMP_64RegClass.contains(Reg) &&
812                  "trap handler registers should not be used");
813           IsSGPR = true;
814           Width = 2;
815         } else if (AMDGPU::VReg_64RegClass.contains(Reg)) {
816           IsSGPR = false;
817           Width = 2;
818         } else if (AMDGPU::AReg_64RegClass.contains(Reg)) {
819           IsSGPR = false;
820           IsAGPR = true;
821           Width = 2;
822         } else if (AMDGPU::VReg_96RegClass.contains(Reg)) {
823           IsSGPR = false;
824           Width = 3;
825         } else if (AMDGPU::SReg_96RegClass.contains(Reg)) {
826           IsSGPR = true;
827           Width = 3;
828         } else if (AMDGPU::AReg_96RegClass.contains(Reg)) {
829           IsSGPR = false;
830           IsAGPR = true;
831           Width = 3;
832         } else if (AMDGPU::SReg_128RegClass.contains(Reg)) {
833           assert(!AMDGPU::TTMP_128RegClass.contains(Reg) &&
834             "trap handler registers should not be used");
835           IsSGPR = true;
836           Width = 4;
837         } else if (AMDGPU::VReg_128RegClass.contains(Reg)) {
838           IsSGPR = false;
839           Width = 4;
840         } else if (AMDGPU::AReg_128RegClass.contains(Reg)) {
841           IsSGPR = false;
842           IsAGPR = true;
843           Width = 4;
844         } else if (AMDGPU::VReg_160RegClass.contains(Reg)) {
845           IsSGPR = false;
846           Width = 5;
847         } else if (AMDGPU::SReg_160RegClass.contains(Reg)) {
848           IsSGPR = true;
849           Width = 5;
850         } else if (AMDGPU::AReg_160RegClass.contains(Reg)) {
851           IsSGPR = false;
852           IsAGPR = true;
853           Width = 5;
854         } else if (AMDGPU::VReg_192RegClass.contains(Reg)) {
855           IsSGPR = false;
856           Width = 6;
857         } else if (AMDGPU::SReg_192RegClass.contains(Reg)) {
858           IsSGPR = true;
859           Width = 6;
860         } else if (AMDGPU::AReg_192RegClass.contains(Reg)) {
861           IsSGPR = false;
862           IsAGPR = true;
863           Width = 6;
864         } else if (AMDGPU::SReg_256RegClass.contains(Reg)) {
865           assert(!AMDGPU::TTMP_256RegClass.contains(Reg) &&
866             "trap handler registers should not be used");
867           IsSGPR = true;
868           Width = 8;
869         } else if (AMDGPU::VReg_256RegClass.contains(Reg)) {
870           IsSGPR = false;
871           Width = 8;
872         } else if (AMDGPU::AReg_256RegClass.contains(Reg)) {
873           IsSGPR = false;
874           IsAGPR = true;
875           Width = 8;
876         } else if (AMDGPU::SReg_512RegClass.contains(Reg)) {
877           assert(!AMDGPU::TTMP_512RegClass.contains(Reg) &&
878             "trap handler registers should not be used");
879           IsSGPR = true;
880           Width = 16;
881         } else if (AMDGPU::VReg_512RegClass.contains(Reg)) {
882           IsSGPR = false;
883           Width = 16;
884         } else if (AMDGPU::AReg_512RegClass.contains(Reg)) {
885           IsSGPR = false;
886           IsAGPR = true;
887           Width = 16;
888         } else if (AMDGPU::SReg_1024RegClass.contains(Reg)) {
889           IsSGPR = true;
890           Width = 32;
891         } else if (AMDGPU::VReg_1024RegClass.contains(Reg)) {
892           IsSGPR = false;
893           Width = 32;
894         } else if (AMDGPU::AReg_1024RegClass.contains(Reg)) {
895           IsSGPR = false;
896           IsAGPR = true;
897           Width = 32;
898         } else {
899           llvm_unreachable("Unknown register class");
900         }
901         unsigned HWReg = TRI.getHWRegIndex(Reg);
902         int MaxUsed = HWReg + Width - 1;
903         if (IsSGPR) {
904           MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR;
905         } else if (IsAGPR) {
906           MaxAGPR = MaxUsed > MaxAGPR ? MaxUsed : MaxAGPR;
907         } else {
908           MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR;
909         }
910       }
911 
912       if (MI.isCall()) {
913         // Pseudo used just to encode the underlying global. Is there a better
914         // way to track this?
915 
916         const MachineOperand *CalleeOp
917           = TII->getNamedOperand(MI, AMDGPU::OpName::callee);
918 
919         const Function *Callee = getCalleeFunction(*CalleeOp);
920         if (!Callee || Callee->isDeclaration()) {
921           // If this is a call to an external function, we can't do much. Make
922           // conservative guesses.
923 
924           // 48 SGPRs - vcc, - flat_scr, -xnack
925           int MaxSGPRGuess =
926             47 - IsaInfo::getNumExtraSGPRs(&ST, true, ST.hasFlatAddressSpace());
927           MaxSGPR = std::max(MaxSGPR, MaxSGPRGuess);
928           MaxVGPR = std::max(MaxVGPR, 23);
929           MaxAGPR = std::max(MaxAGPR, 23);
930 
931           CalleeFrameSize = std::max(CalleeFrameSize,
932             static_cast<uint64_t>(AssumedStackSizeForExternalCall));
933 
934           Info.UsesVCC = true;
935           Info.UsesFlatScratch = ST.hasFlatAddressSpace();
936           Info.HasDynamicallySizedStack = true;
937         } else {
938           // We force CodeGen to run in SCC order, so the callee's register
939           // usage etc. should be the cumulative usage of all callees.
940 
941           auto I = CallGraphResourceInfo.find(Callee);
942           if (I == CallGraphResourceInfo.end()) {
943             // Avoid crashing on undefined behavior with an illegal call to a
944             // kernel. If a callsite's calling convention doesn't match the
945             // function's, it's undefined behavior. If the callsite calling
946             // convention does match, that would have errored earlier.
947             // FIXME: The verifier shouldn't allow this.
948             if (AMDGPU::isEntryFunctionCC(Callee->getCallingConv()))
949               report_fatal_error("invalid call to entry function");
950 
951             llvm_unreachable("callee should have been handled before caller");
952           }
953 
954           MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR);
955           MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR);
956           MaxAGPR = std::max(I->second.NumAGPR - 1, MaxAGPR);
957           CalleeFrameSize
958             = std::max(I->second.PrivateSegmentSize, CalleeFrameSize);
959           Info.UsesVCC |= I->second.UsesVCC;
960           Info.UsesFlatScratch |= I->second.UsesFlatScratch;
961           Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack;
962           Info.HasRecursion |= I->second.HasRecursion;
963         }
964 
965         // FIXME: Call site could have norecurse on it
966         if (!Callee || !Callee->doesNotRecurse())
967           Info.HasRecursion = true;
968       }
969     }
970   }
971 
972   Info.NumExplicitSGPR = MaxSGPR + 1;
973   Info.NumVGPR = MaxVGPR + 1;
974   Info.NumAGPR = MaxAGPR + 1;
975   Info.PrivateSegmentSize += CalleeFrameSize;
976 
977   return Info;
978 }
979 
980 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
981                                         const MachineFunction &MF) {
982   SIFunctionResourceInfo Info = analyzeResourceUsage(MF);
983   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
984 
985   ProgInfo.NumArchVGPR = Info.NumVGPR;
986   ProgInfo.NumAccVGPR = Info.NumAGPR;
987   ProgInfo.NumVGPR = Info.getTotalNumVGPRs(STM);
988   ProgInfo.NumSGPR = Info.NumExplicitSGPR;
989   ProgInfo.ScratchSize = Info.PrivateSegmentSize;
990   ProgInfo.VCCUsed = Info.UsesVCC;
991   ProgInfo.FlatUsed = Info.UsesFlatScratch;
992   ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion;
993 
994   if (!isUInt<32>(ProgInfo.ScratchSize)) {
995     DiagnosticInfoStackSize DiagStackSize(MF.getFunction(),
996                                           ProgInfo.ScratchSize, DS_Error);
997     MF.getFunction().getContext().diagnose(DiagStackSize);
998   }
999 
1000   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1001 
1002   // TODO(scott.linder): The calculations related to SGPR/VGPR blocks are
1003   // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be
1004   // unified.
1005   unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs(
1006       &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed);
1007 
1008   // Check the addressable register limit before we add ExtraSGPRs.
1009   if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
1010       !STM.hasSGPRInitBug()) {
1011     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
1012     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
1013       // This can happen due to a compiler bug or when using inline asm.
1014       LLVMContext &Ctx = MF.getFunction().getContext();
1015       DiagnosticInfoResourceLimit Diag(MF.getFunction(),
1016                                        "addressable scalar registers",
1017                                        ProgInfo.NumSGPR, DS_Error,
1018                                        DK_ResourceLimit,
1019                                        MaxAddressableNumSGPRs);
1020       Ctx.diagnose(Diag);
1021       ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1;
1022     }
1023   }
1024 
1025   // Account for extra SGPRs and VGPRs reserved for debugger use.
1026   ProgInfo.NumSGPR += ExtraSGPRs;
1027 
1028   // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave
1029   // dispatch registers are function args.
1030   unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0;
1031   for (auto &Arg : MF.getFunction().args()) {
1032     unsigned NumRegs = (Arg.getType()->getPrimitiveSizeInBits() + 31) / 32;
1033     if (Arg.hasAttribute(Attribute::InReg))
1034       WaveDispatchNumSGPR += NumRegs;
1035     else
1036       WaveDispatchNumVGPR += NumRegs;
1037   }
1038   ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR);
1039   ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR);
1040 
1041   // Adjust number of registers used to meet default/requested minimum/maximum
1042   // number of waves per execution unit request.
1043   ProgInfo.NumSGPRsForWavesPerEU = std::max(
1044     std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU()));
1045   ProgInfo.NumVGPRsForWavesPerEU = std::max(
1046     std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU()));
1047 
1048   if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS ||
1049       STM.hasSGPRInitBug()) {
1050     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
1051     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
1052       // This can happen due to a compiler bug or when using inline asm to use
1053       // the registers which are usually reserved for vcc etc.
1054       LLVMContext &Ctx = MF.getFunction().getContext();
1055       DiagnosticInfoResourceLimit Diag(MF.getFunction(),
1056                                        "scalar registers",
1057                                        ProgInfo.NumSGPR, DS_Error,
1058                                        DK_ResourceLimit,
1059                                        MaxAddressableNumSGPRs);
1060       Ctx.diagnose(Diag);
1061       ProgInfo.NumSGPR = MaxAddressableNumSGPRs;
1062       ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs;
1063     }
1064   }
1065 
1066   if (STM.hasSGPRInitBug()) {
1067     ProgInfo.NumSGPR =
1068         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
1069     ProgInfo.NumSGPRsForWavesPerEU =
1070         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
1071   }
1072 
1073   if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) {
1074     LLVMContext &Ctx = MF.getFunction().getContext();
1075     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs",
1076                                      MFI->getNumUserSGPRs(), DS_Error);
1077     Ctx.diagnose(Diag);
1078   }
1079 
1080   if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) {
1081     LLVMContext &Ctx = MF.getFunction().getContext();
1082     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory",
1083                                      MFI->getLDSSize(), DS_Error);
1084     Ctx.diagnose(Diag);
1085   }
1086 
1087   ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks(
1088       &STM, ProgInfo.NumSGPRsForWavesPerEU);
1089   ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks(
1090       &STM, ProgInfo.NumVGPRsForWavesPerEU);
1091 
1092   const SIModeRegisterDefaults Mode = MFI->getMode();
1093 
1094   // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
1095   // register.
1096   ProgInfo.FloatMode = getFPMode(Mode);
1097 
1098   ProgInfo.IEEEMode = Mode.IEEE;
1099 
1100   // Make clamp modifier on NaN input returns 0.
1101   ProgInfo.DX10Clamp = Mode.DX10Clamp;
1102 
1103   unsigned LDSAlignShift;
1104   if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
1105     // LDS is allocated in 64 dword blocks.
1106     LDSAlignShift = 8;
1107   } else {
1108     // LDS is allocated in 128 dword blocks.
1109     LDSAlignShift = 9;
1110   }
1111 
1112   unsigned LDSSpillSize =
1113     MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize();
1114 
1115   ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize;
1116   ProgInfo.LDSBlocks =
1117       alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
1118 
1119   // Scratch is allocated in 256 dword blocks.
1120   unsigned ScratchAlignShift = 10;
1121   // We need to program the hardware with the amount of scratch memory that
1122   // is used by the entire wave.  ProgInfo.ScratchSize is the amount of
1123   // scratch memory used per thread.
1124   ProgInfo.ScratchBlocks =
1125       alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(),
1126               1ULL << ScratchAlignShift) >>
1127       ScratchAlignShift;
1128 
1129   if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) {
1130     ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1;
1131     ProgInfo.MemOrdered = 1;
1132   }
1133 
1134   ProgInfo.ComputePGMRSrc1 =
1135       S_00B848_VGPRS(ProgInfo.VGPRBlocks) |
1136       S_00B848_SGPRS(ProgInfo.SGPRBlocks) |
1137       S_00B848_PRIORITY(ProgInfo.Priority) |
1138       S_00B848_FLOAT_MODE(ProgInfo.FloatMode) |
1139       S_00B848_PRIV(ProgInfo.Priv) |
1140       S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) |
1141       S_00B848_DEBUG_MODE(ProgInfo.DebugMode) |
1142       S_00B848_IEEE_MODE(ProgInfo.IEEEMode) |
1143       S_00B848_WGP_MODE(ProgInfo.WgpMode) |
1144       S_00B848_MEM_ORDERED(ProgInfo.MemOrdered);
1145 
1146   // 0 = X, 1 = XY, 2 = XYZ
1147   unsigned TIDIGCompCnt = 0;
1148   if (MFI->hasWorkItemIDZ())
1149     TIDIGCompCnt = 2;
1150   else if (MFI->hasWorkItemIDY())
1151     TIDIGCompCnt = 1;
1152 
1153   ProgInfo.ComputePGMRSrc2 =
1154       S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) |
1155       S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
1156       // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP.
1157       S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) |
1158       S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
1159       S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
1160       S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
1161       S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
1162       S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
1163       S_00B84C_EXCP_EN_MSB(0) |
1164       // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP.
1165       S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) |
1166       S_00B84C_EXCP_EN(0);
1167 
1168   ProgInfo.Occupancy = STM.computeOccupancy(MF, ProgInfo.LDSSize,
1169                                             ProgInfo.NumSGPRsForWavesPerEU,
1170                                             ProgInfo.NumVGPRsForWavesPerEU);
1171 }
1172 
1173 static unsigned getRsrcReg(CallingConv::ID CallConv) {
1174   switch (CallConv) {
1175   default: LLVM_FALLTHROUGH;
1176   case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1;
1177   case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS;
1178   case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS;
1179   case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES;
1180   case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS;
1181   case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS;
1182   case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS;
1183   }
1184 }
1185 
1186 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
1187                                          const SIProgramInfo &CurrentProgramInfo) {
1188   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1189   unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv());
1190 
1191   if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) {
1192     OutStreamer->emitInt32(R_00B848_COMPUTE_PGM_RSRC1);
1193 
1194     OutStreamer->emitInt32(CurrentProgramInfo.ComputePGMRSrc1);
1195 
1196     OutStreamer->emitInt32(R_00B84C_COMPUTE_PGM_RSRC2);
1197     OutStreamer->emitInt32(CurrentProgramInfo.ComputePGMRSrc2);
1198 
1199     OutStreamer->emitInt32(R_00B860_COMPUTE_TMPRING_SIZE);
1200     OutStreamer->emitInt32(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks));
1201 
1202     // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
1203     // 0" comment but I don't see a corresponding field in the register spec.
1204   } else {
1205     OutStreamer->emitInt32(RsrcReg);
1206     OutStreamer->emitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) |
1207                               S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4);
1208     OutStreamer->emitInt32(R_0286E8_SPI_TMPRING_SIZE);
1209     OutStreamer->emitIntValue(
1210         S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4);
1211   }
1212 
1213   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
1214     OutStreamer->emitInt32(R_00B02C_SPI_SHADER_PGM_RSRC2_PS);
1215     OutStreamer->emitInt32(
1216         S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks));
1217     OutStreamer->emitInt32(R_0286CC_SPI_PS_INPUT_ENA);
1218     OutStreamer->emitInt32(MFI->getPSInputEnable());
1219     OutStreamer->emitInt32(R_0286D0_SPI_PS_INPUT_ADDR);
1220     OutStreamer->emitInt32(MFI->getPSInputAddr());
1221   }
1222 
1223   OutStreamer->emitInt32(R_SPILLED_SGPRS);
1224   OutStreamer->emitInt32(MFI->getNumSpilledSGPRs());
1225   OutStreamer->emitInt32(R_SPILLED_VGPRS);
1226   OutStreamer->emitInt32(MFI->getNumSpilledVGPRs());
1227 }
1228 
1229 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type
1230 // is AMDPAL.  It stores each compute/SPI register setting and other PAL
1231 // metadata items into the PALMD::Metadata, combining with any provided by the
1232 // frontend as LLVM metadata. Once all functions are written, the PAL metadata
1233 // is then written as a single block in the .note section.
1234 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF,
1235        const SIProgramInfo &CurrentProgramInfo) {
1236   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1237   auto CC = MF.getFunction().getCallingConv();
1238   auto MD = getTargetStreamer()->getPALMetadata();
1239 
1240   MD->setEntryPoint(CC, MF.getFunction().getName());
1241   MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU);
1242   MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU);
1243   if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) {
1244     MD->setRsrc1(CC, CurrentProgramInfo.ComputePGMRSrc1);
1245     MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2);
1246   } else {
1247     MD->setRsrc1(CC, S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) |
1248         S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks));
1249     if (CurrentProgramInfo.ScratchBlocks > 0)
1250       MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1));
1251   }
1252   // ScratchSize is in bytes, 16 aligned.
1253   MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16));
1254   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
1255     MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks));
1256     MD->setSpiPsInputEna(MFI->getPSInputEnable());
1257     MD->setSpiPsInputAddr(MFI->getPSInputAddr());
1258   }
1259 
1260   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1261   if (STM.isWave32())
1262     MD->setWave32(MF.getFunction().getCallingConv());
1263 }
1264 
1265 // This is supposed to be log2(Size)
1266 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) {
1267   switch (Size) {
1268   case 4:
1269     return AMD_ELEMENT_4_BYTES;
1270   case 8:
1271     return AMD_ELEMENT_8_BYTES;
1272   case 16:
1273     return AMD_ELEMENT_16_BYTES;
1274   default:
1275     llvm_unreachable("invalid private_element_size");
1276   }
1277 }
1278 
1279 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out,
1280                                         const SIProgramInfo &CurrentProgramInfo,
1281                                         const MachineFunction &MF) const {
1282   const Function &F = MF.getFunction();
1283   assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
1284          F.getCallingConv() == CallingConv::SPIR_KERNEL);
1285 
1286   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1287   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1288 
1289   AMDGPU::initDefaultAMDKernelCodeT(Out, &STM);
1290 
1291   Out.compute_pgm_resource_registers =
1292       CurrentProgramInfo.ComputePGMRSrc1 |
1293       (CurrentProgramInfo.ComputePGMRSrc2 << 32);
1294   Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64;
1295 
1296   if (CurrentProgramInfo.DynamicCallStack)
1297     Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK;
1298 
1299   AMD_HSA_BITS_SET(Out.code_properties,
1300                    AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE,
1301                    getElementByteSizeValue(STM.getMaxPrivateElementSize()));
1302 
1303   if (MFI->hasPrivateSegmentBuffer()) {
1304     Out.code_properties |=
1305       AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
1306   }
1307 
1308   if (MFI->hasDispatchPtr())
1309     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1310 
1311   if (MFI->hasQueuePtr())
1312     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
1313 
1314   if (MFI->hasKernargSegmentPtr())
1315     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
1316 
1317   if (MFI->hasDispatchID())
1318     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
1319 
1320   if (MFI->hasFlatScratchInit())
1321     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
1322 
1323   if (MFI->hasDispatchPtr())
1324     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1325 
1326   if (STM.isXNACKEnabled())
1327     Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
1328 
1329   Align MaxKernArgAlign;
1330   Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign);
1331   Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR;
1332   Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR;
1333   Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize;
1334   Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize;
1335 
1336   // kernarg_segment_alignment is specified as log of the alignment.
1337   // The minimum alignment is 16.
1338   Out.kernarg_segment_alignment = Log2(std::max(Align(16), MaxKernArgAlign));
1339 }
1340 
1341 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1342                                        const char *ExtraCode, raw_ostream &O) {
1343   // First try the generic code, which knows about modifiers like 'c' and 'n'.
1344   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O))
1345     return false;
1346 
1347   if (ExtraCode && ExtraCode[0]) {
1348     if (ExtraCode[1] != 0)
1349       return true; // Unknown modifier.
1350 
1351     switch (ExtraCode[0]) {
1352     case 'r':
1353       break;
1354     default:
1355       return true;
1356     }
1357   }
1358 
1359   // TODO: Should be able to support other operand types like globals.
1360   const MachineOperand &MO = MI->getOperand(OpNo);
1361   if (MO.isReg()) {
1362     AMDGPUInstPrinter::printRegOperand(MO.getReg(), O,
1363                                        *MF->getSubtarget().getRegisterInfo());
1364     return false;
1365   } else if (MO.isImm()) {
1366     int64_t Val = MO.getImm();
1367     if (AMDGPU::isInlinableIntLiteral(Val)) {
1368       O << Val;
1369     } else if (isUInt<16>(Val)) {
1370       O << format("0x%" PRIx64, static_cast<uint16_t>(Val));
1371     } else if (isUInt<32>(Val)) {
1372       O << format("0x%" PRIx64, static_cast<uint32_t>(Val));
1373     } else {
1374       O << format("0x%" PRIx64, static_cast<uint64_t>(Val));
1375     }
1376     return false;
1377   }
1378   return true;
1379 }
1380