xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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 "AMDGPUHSAMetadataStreamer.h"
21 #include "AMDGPUResourceUsageAnalysis.h"
22 #include "AMDKernelCodeT.h"
23 #include "GCNSubtarget.h"
24 #include "MCTargetDesc/AMDGPUInstPrinter.h"
25 #include "MCTargetDesc/AMDGPUTargetStreamer.h"
26 #include "R600AsmPrinter.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "TargetInfo/AMDGPUTargetInfo.h"
29 #include "Utils/AMDGPUBaseInfo.h"
30 #include "llvm/IR/DiagnosticInfo.h"
31 #include "llvm/MC/MCAssembler.h"
32 #include "llvm/MC/MCContext.h"
33 #include "llvm/MC/MCSectionELF.h"
34 #include "llvm/MC/MCStreamer.h"
35 #include "llvm/MC/TargetRegistry.h"
36 #include "llvm/Support/AMDHSAKernelDescriptor.h"
37 #include "llvm/Target/TargetLoweringObjectFile.h"
38 #include "llvm/Target/TargetMachine.h"
39 
40 using namespace llvm;
41 using namespace llvm::AMDGPU;
42 
43 // This should get the default rounding mode from the kernel. We just set the
44 // default here, but this could change if the OpenCL rounding mode pragmas are
45 // used.
46 //
47 // The denormal mode here should match what is reported by the OpenCL runtime
48 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
49 // can also be override to flush with the -cl-denorms-are-zero compiler flag.
50 //
51 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
52 // precision, and leaves single precision to flush all and does not report
53 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
54 // CL_FP_DENORM for both.
55 //
56 // FIXME: It seems some instructions do not support single precision denormals
57 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
58 // and sin_f32, cos_f32 on most parts).
59 
60 // We want to use these instructions, and using fp32 denormals also causes
61 // instructions to run at the double precision rate for the device so it's
62 // probably best to just report no single precision denormals.
63 static uint32_t getFPMode(AMDGPU::SIModeRegisterDefaults Mode) {
64   return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) |
65          FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) |
66          FP_DENORM_MODE_SP(Mode.fpDenormModeSPValue()) |
67          FP_DENORM_MODE_DP(Mode.fpDenormModeDPValue());
68 }
69 
70 static AsmPrinter *
71 createAMDGPUAsmPrinterPass(TargetMachine &tm,
72                            std::unique_ptr<MCStreamer> &&Streamer) {
73   return new AMDGPUAsmPrinter(tm, std::move(Streamer));
74 }
75 
76 extern "C" void LLVM_EXTERNAL_VISIBILITY LLVMInitializeAMDGPUAsmPrinter() {
77   TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(),
78                                      llvm::createR600AsmPrinterPass);
79   TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(),
80                                      createAMDGPUAsmPrinterPass);
81 }
82 
83 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM,
84                                    std::unique_ptr<MCStreamer> Streamer)
85     : AsmPrinter(TM, std::move(Streamer)) {
86   if (TM.getTargetTriple().getOS() == Triple::AMDHSA) {
87     if (isHsaAbiVersion2(getGlobalSTI())) {
88       HSAMetadataStream.reset(new HSAMD::MetadataStreamerV2());
89     } else if (isHsaAbiVersion3(getGlobalSTI())) {
90       HSAMetadataStream.reset(new HSAMD::MetadataStreamerV3());
91     } else {
92       HSAMetadataStream.reset(new HSAMD::MetadataStreamerV4());
93     }
94   }
95 }
96 
97 StringRef AMDGPUAsmPrinter::getPassName() const {
98   return "AMDGPU Assembly Printer";
99 }
100 
101 const MCSubtargetInfo *AMDGPUAsmPrinter::getGlobalSTI() const {
102   return TM.getMCSubtargetInfo();
103 }
104 
105 AMDGPUTargetStreamer* AMDGPUAsmPrinter::getTargetStreamer() const {
106   if (!OutStreamer)
107     return nullptr;
108   return static_cast<AMDGPUTargetStreamer*>(OutStreamer->getTargetStreamer());
109 }
110 
111 void AMDGPUAsmPrinter::emitStartOfAsmFile(Module &M) {
112   // TODO: Which one is called first, emitStartOfAsmFile or
113   // emitFunctionBodyStart?
114   if (getTargetStreamer() && !getTargetStreamer()->getTargetID())
115     initializeTargetID(M);
116 
117   if (TM.getTargetTriple().getOS() != Triple::AMDHSA &&
118       TM.getTargetTriple().getOS() != Triple::AMDPAL)
119     return;
120 
121   if (isHsaAbiVersion3Or4(getGlobalSTI()))
122     getTargetStreamer()->EmitDirectiveAMDGCNTarget();
123 
124   if (TM.getTargetTriple().getOS() == Triple::AMDHSA)
125     HSAMetadataStream->begin(M, *getTargetStreamer()->getTargetID());
126 
127   if (TM.getTargetTriple().getOS() == Triple::AMDPAL)
128     getTargetStreamer()->getPALMetadata()->readFromIR(M);
129 
130   if (isHsaAbiVersion3Or4(getGlobalSTI()))
131     return;
132 
133   // HSA emits NT_AMD_HSA_CODE_OBJECT_VERSION for code objects v2.
134   if (TM.getTargetTriple().getOS() == Triple::AMDHSA)
135     getTargetStreamer()->EmitDirectiveHSACodeObjectVersion(2, 1);
136 
137   // HSA and PAL emit NT_AMD_HSA_ISA_VERSION for code objects v2.
138   IsaVersion Version = getIsaVersion(getGlobalSTI()->getCPU());
139   getTargetStreamer()->EmitDirectiveHSACodeObjectISAV2(
140       Version.Major, Version.Minor, Version.Stepping, "AMD", "AMDGPU");
141 }
142 
143 void AMDGPUAsmPrinter::emitEndOfAsmFile(Module &M) {
144   // Following code requires TargetStreamer to be present.
145   if (!getTargetStreamer())
146     return;
147 
148   if (TM.getTargetTriple().getOS() != Triple::AMDHSA ||
149       isHsaAbiVersion2(getGlobalSTI()))
150     getTargetStreamer()->EmitISAVersion();
151 
152   // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA).
153   // Emit HSA Metadata (NT_AMD_HSA_METADATA).
154   if (TM.getTargetTriple().getOS() == Triple::AMDHSA) {
155     HSAMetadataStream->end();
156     bool Success = HSAMetadataStream->emitTo(*getTargetStreamer());
157     (void)Success;
158     assert(Success && "Malformed HSA Metadata");
159   }
160 }
161 
162 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough(
163   const MachineBasicBlock *MBB) const {
164   if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB))
165     return false;
166 
167   if (MBB->empty())
168     return true;
169 
170   // If this is a block implementing a long branch, an expression relative to
171   // the start of the block is needed.  to the start of the block.
172   // XXX - Is there a smarter way to check this?
173   return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64);
174 }
175 
176 void AMDGPUAsmPrinter::emitFunctionBodyStart() {
177   const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
178   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
179   const Function &F = MF->getFunction();
180 
181   // TODO: Which one is called first, emitStartOfAsmFile or
182   // emitFunctionBodyStart?
183   if (getTargetStreamer() && !getTargetStreamer()->getTargetID())
184     initializeTargetID(*F.getParent());
185 
186   const auto &FunctionTargetID = STM.getTargetID();
187   // Make sure function's xnack settings are compatible with module's
188   // xnack settings.
189   if (FunctionTargetID.isXnackSupported() &&
190       FunctionTargetID.getXnackSetting() != IsaInfo::TargetIDSetting::Any &&
191       FunctionTargetID.getXnackSetting() != getTargetStreamer()->getTargetID()->getXnackSetting()) {
192     OutContext.reportError({}, "xnack setting of '" + Twine(MF->getName()) +
193                            "' function does not match module xnack setting");
194     return;
195   }
196   // Make sure function's sramecc settings are compatible with module's
197   // sramecc settings.
198   if (FunctionTargetID.isSramEccSupported() &&
199       FunctionTargetID.getSramEccSetting() != IsaInfo::TargetIDSetting::Any &&
200       FunctionTargetID.getSramEccSetting() != getTargetStreamer()->getTargetID()->getSramEccSetting()) {
201     OutContext.reportError({}, "sramecc setting of '" + Twine(MF->getName()) +
202                            "' function does not match module sramecc setting");
203     return;
204   }
205 
206   if (!MFI.isEntryFunction())
207     return;
208 
209   if ((STM.isMesaKernel(F) || isHsaAbiVersion2(getGlobalSTI())) &&
210       (F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
211        F.getCallingConv() == CallingConv::SPIR_KERNEL)) {
212     amd_kernel_code_t KernelCode;
213     getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF);
214     getTargetStreamer()->EmitAMDKernelCodeT(KernelCode);
215   }
216 
217   if (STM.isAmdHsaOS())
218     HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo);
219 }
220 
221 void AMDGPUAsmPrinter::emitFunctionBodyEnd() {
222   const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>();
223   if (!MFI.isEntryFunction())
224     return;
225 
226   if (TM.getTargetTriple().getOS() != Triple::AMDHSA ||
227       isHsaAbiVersion2(getGlobalSTI()))
228     return;
229 
230   auto &Streamer = getTargetStreamer()->getStreamer();
231   auto &Context = Streamer.getContext();
232   auto &ObjectFileInfo = *Context.getObjectFileInfo();
233   auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection();
234 
235   Streamer.PushSection();
236   Streamer.SwitchSection(&ReadOnlySection);
237 
238   // CP microcode requires the kernel descriptor to be allocated on 64 byte
239   // alignment.
240   Streamer.emitValueToAlignment(64, 0, 1, 0);
241   if (ReadOnlySection.getAlignment() < 64)
242     ReadOnlySection.setAlignment(Align(64));
243 
244   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
245 
246   SmallString<128> KernelName;
247   getNameWithPrefix(KernelName, &MF->getFunction());
248   getTargetStreamer()->EmitAmdhsaKernelDescriptor(
249       STM, KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo),
250       CurrentProgramInfo.NumVGPRsForWavesPerEU,
251       CurrentProgramInfo.NumSGPRsForWavesPerEU -
252           IsaInfo::getNumExtraSGPRs(&STM,
253                                     CurrentProgramInfo.VCCUsed,
254                                     CurrentProgramInfo.FlatUsed),
255       CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed);
256 
257   Streamer.PopSection();
258 }
259 
260 void AMDGPUAsmPrinter::emitFunctionEntryLabel() {
261   if (TM.getTargetTriple().getOS() == Triple::AMDHSA &&
262       isHsaAbiVersion3Or4(getGlobalSTI())) {
263     AsmPrinter::emitFunctionEntryLabel();
264     return;
265   }
266 
267   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
268   const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>();
269   if (MFI->isEntryFunction() && STM.isAmdHsaOrMesa(MF->getFunction())) {
270     SmallString<128> SymbolName;
271     getNameWithPrefix(SymbolName, &MF->getFunction()),
272     getTargetStreamer()->EmitAMDGPUSymbolType(
273         SymbolName, ELF::STT_AMDGPU_HSA_KERNEL);
274   }
275   if (DumpCodeInstEmitter) {
276     // Disassemble function name label to text.
277     DisasmLines.push_back(MF->getName().str() + ":");
278     DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
279     HexLines.push_back("");
280   }
281 
282   AsmPrinter::emitFunctionEntryLabel();
283 }
284 
285 void AMDGPUAsmPrinter::emitBasicBlockStart(const MachineBasicBlock &MBB) {
286   if (DumpCodeInstEmitter && !isBlockOnlyReachableByFallthrough(&MBB)) {
287     // Write a line for the basic block label if it is not only fallthrough.
288     DisasmLines.push_back(
289         (Twine("BB") + Twine(getFunctionNumber())
290          + "_" + Twine(MBB.getNumber()) + ":").str());
291     DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size());
292     HexLines.push_back("");
293   }
294   AsmPrinter::emitBasicBlockStart(MBB);
295 }
296 
297 void AMDGPUAsmPrinter::emitGlobalVariable(const GlobalVariable *GV) {
298   if (GV->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
299     if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) {
300       OutContext.reportError({},
301                              Twine(GV->getName()) +
302                                  ": unsupported initializer for address space");
303       return;
304     }
305 
306     // LDS variables aren't emitted in HSA or PAL yet.
307     const Triple::OSType OS = TM.getTargetTriple().getOS();
308     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
309       return;
310 
311     MCSymbol *GVSym = getSymbol(GV);
312 
313     GVSym->redefineIfPossible();
314     if (GVSym->isDefined() || GVSym->isVariable())
315       report_fatal_error("symbol '" + Twine(GVSym->getName()) +
316                          "' is already defined");
317 
318     const DataLayout &DL = GV->getParent()->getDataLayout();
319     uint64_t Size = DL.getTypeAllocSize(GV->getValueType());
320     Align Alignment = GV->getAlign().getValueOr(Align(4));
321 
322     emitVisibility(GVSym, GV->getVisibility(), !GV->isDeclaration());
323     emitLinkage(GV, GVSym);
324     if (auto TS = getTargetStreamer())
325       TS->emitAMDGPULDS(GVSym, Size, Alignment);
326     return;
327   }
328 
329   AsmPrinter::emitGlobalVariable(GV);
330 }
331 
332 bool AMDGPUAsmPrinter::doFinalization(Module &M) {
333   // Pad with s_code_end to help tools and guard against instruction prefetch
334   // causing stale data in caches. Arguably this should be done by the linker,
335   // which is why this isn't done for Mesa.
336   const MCSubtargetInfo &STI = *getGlobalSTI();
337   if ((AMDGPU::isGFX10Plus(STI) || AMDGPU::isGFX90A(STI)) &&
338       (STI.getTargetTriple().getOS() == Triple::AMDHSA ||
339        STI.getTargetTriple().getOS() == Triple::AMDPAL)) {
340     OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
341     getTargetStreamer()->EmitCodeEnd(STI);
342   }
343 
344   return AsmPrinter::doFinalization(M);
345 }
346 
347 // Print comments that apply to both callable functions and entry points.
348 void AMDGPUAsmPrinter::emitCommonFunctionComments(
349   uint32_t NumVGPR,
350   Optional<uint32_t> NumAGPR,
351   uint32_t TotalNumVGPR,
352   uint32_t NumSGPR,
353   uint64_t ScratchSize,
354   uint64_t CodeSize,
355   const AMDGPUMachineFunction *MFI) {
356   OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false);
357   OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false);
358   OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false);
359   if (NumAGPR) {
360     OutStreamer->emitRawComment(" NumAgprs: " + Twine(*NumAGPR), false);
361     OutStreamer->emitRawComment(" TotalNumVgprs: " + Twine(TotalNumVGPR),
362                                 false);
363   }
364   OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false);
365   OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()),
366                               false);
367 }
368 
369 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties(
370     const MachineFunction &MF) const {
371   const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>();
372   uint16_t KernelCodeProperties = 0;
373 
374   if (MFI.hasPrivateSegmentBuffer()) {
375     KernelCodeProperties |=
376         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
377   }
378   if (MFI.hasDispatchPtr()) {
379     KernelCodeProperties |=
380         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
381   }
382   if (MFI.hasQueuePtr()) {
383     KernelCodeProperties |=
384         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
385   }
386   if (MFI.hasKernargSegmentPtr()) {
387     KernelCodeProperties |=
388         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
389   }
390   if (MFI.hasDispatchID()) {
391     KernelCodeProperties |=
392         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
393   }
394   if (MFI.hasFlatScratchInit()) {
395     KernelCodeProperties |=
396         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
397   }
398   if (MF.getSubtarget<GCNSubtarget>().isWave32()) {
399     KernelCodeProperties |=
400         amdhsa::KERNEL_CODE_PROPERTY_ENABLE_WAVEFRONT_SIZE32;
401   }
402 
403   return KernelCodeProperties;
404 }
405 
406 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor(
407     const MachineFunction &MF,
408     const SIProgramInfo &PI) const {
409   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
410   const Function &F = MF.getFunction();
411 
412   amdhsa::kernel_descriptor_t KernelDescriptor;
413   memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor));
414 
415   assert(isUInt<32>(PI.ScratchSize));
416   assert(isUInt<32>(PI.getComputePGMRSrc1()));
417   assert(isUInt<32>(PI.ComputePGMRSrc2));
418 
419   KernelDescriptor.group_segment_fixed_size = PI.LDSSize;
420   KernelDescriptor.private_segment_fixed_size = PI.ScratchSize;
421 
422   Align MaxKernArgAlign;
423   KernelDescriptor.kernarg_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign);
424 
425   KernelDescriptor.compute_pgm_rsrc1 = PI.getComputePGMRSrc1();
426   KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2;
427   KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF);
428 
429   assert(STM.hasGFX90AInsts() || CurrentProgramInfo.ComputePGMRSrc3GFX90A == 0);
430   if (STM.hasGFX90AInsts())
431     KernelDescriptor.compute_pgm_rsrc3 =
432       CurrentProgramInfo.ComputePGMRSrc3GFX90A;
433 
434   return KernelDescriptor;
435 }
436 
437 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
438   ResourceUsage = &getAnalysis<AMDGPUResourceUsageAnalysis>();
439   CurrentProgramInfo = SIProgramInfo();
440 
441   const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>();
442 
443   // The starting address of all shader programs must be 256 bytes aligned.
444   // Regular functions just need the basic required instruction alignment.
445   MF.setAlignment(MFI->isEntryFunction() ? Align(256) : Align(4));
446 
447   SetupMachineFunction(MF);
448 
449   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
450   MCContext &Context = getObjFileLowering().getContext();
451   // FIXME: This should be an explicit check for Mesa.
452   if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) {
453     MCSectionELF *ConfigSection =
454         Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
455     OutStreamer->SwitchSection(ConfigSection);
456   }
457 
458   if (MFI->isModuleEntryFunction()) {
459     getSIProgramInfo(CurrentProgramInfo, MF);
460   }
461 
462   if (STM.isAmdPalOS()) {
463     if (MFI->isEntryFunction())
464       EmitPALMetadata(MF, CurrentProgramInfo);
465     else if (MFI->isModuleEntryFunction())
466       emitPALFunctionMetadata(MF);
467   } else if (!STM.isAmdHsaOS()) {
468     EmitProgramInfoSI(MF, CurrentProgramInfo);
469   }
470 
471   DumpCodeInstEmitter = nullptr;
472   if (STM.dumpCode()) {
473     // For -dumpcode, get the assembler out of the streamer, even if it does
474     // not really want to let us have it. This only works with -filetype=obj.
475     bool SaveFlag = OutStreamer->getUseAssemblerInfoForParsing();
476     OutStreamer->setUseAssemblerInfoForParsing(true);
477     MCAssembler *Assembler = OutStreamer->getAssemblerPtr();
478     OutStreamer->setUseAssemblerInfoForParsing(SaveFlag);
479     if (Assembler)
480       DumpCodeInstEmitter = Assembler->getEmitterPtr();
481   }
482 
483   DisasmLines.clear();
484   HexLines.clear();
485   DisasmLineMaxLen = 0;
486 
487   emitFunctionBody();
488 
489   if (isVerbose()) {
490     MCSectionELF *CommentSection =
491         Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
492     OutStreamer->SwitchSection(CommentSection);
493 
494     if (!MFI->isEntryFunction()) {
495       OutStreamer->emitRawComment(" Function info:", false);
496       const AMDGPUResourceUsageAnalysis::SIFunctionResourceInfo &Info =
497           ResourceUsage->getResourceInfo(&MF.getFunction());
498       emitCommonFunctionComments(
499         Info.NumVGPR,
500         STM.hasMAIInsts() ? Info.NumAGPR : Optional<uint32_t>(),
501         Info.getTotalNumVGPRs(STM),
502         Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()),
503         Info.PrivateSegmentSize,
504         getFunctionCodeSize(MF), MFI);
505       return false;
506     }
507 
508     OutStreamer->emitRawComment(" Kernel info:", false);
509     emitCommonFunctionComments(CurrentProgramInfo.NumArchVGPR,
510                                STM.hasMAIInsts()
511                                  ? CurrentProgramInfo.NumAccVGPR
512                                  : Optional<uint32_t>(),
513                                CurrentProgramInfo.NumVGPR,
514                                CurrentProgramInfo.NumSGPR,
515                                CurrentProgramInfo.ScratchSize,
516                                getFunctionCodeSize(MF), MFI);
517 
518     OutStreamer->emitRawComment(
519       " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false);
520     OutStreamer->emitRawComment(
521       " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false);
522     OutStreamer->emitRawComment(
523       " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) +
524       " bytes/workgroup (compile time only)", false);
525 
526     OutStreamer->emitRawComment(
527       " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false);
528     OutStreamer->emitRawComment(
529       " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false);
530 
531     OutStreamer->emitRawComment(
532       " NumSGPRsForWavesPerEU: " +
533       Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false);
534     OutStreamer->emitRawComment(
535       " NumVGPRsForWavesPerEU: " +
536       Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false);
537 
538     if (STM.hasGFX90AInsts())
539       OutStreamer->emitRawComment(
540         " AccumOffset: " +
541         Twine((CurrentProgramInfo.AccumOffset + 1) * 4), false);
542 
543     OutStreamer->emitRawComment(
544       " Occupancy: " +
545       Twine(CurrentProgramInfo.Occupancy), false);
546 
547     OutStreamer->emitRawComment(
548       " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false);
549 
550     OutStreamer->emitRawComment(
551       " COMPUTE_PGM_RSRC2:SCRATCH_EN: " +
552       Twine(G_00B84C_SCRATCH_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
553     OutStreamer->emitRawComment(
554       " COMPUTE_PGM_RSRC2:USER_SGPR: " +
555       Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false);
556     OutStreamer->emitRawComment(
557       " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " +
558       Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false);
559     OutStreamer->emitRawComment(
560       " COMPUTE_PGM_RSRC2:TGID_X_EN: " +
561       Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
562     OutStreamer->emitRawComment(
563       " COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
564       Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
565     OutStreamer->emitRawComment(
566       " COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
567       Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false);
568     OutStreamer->emitRawComment(
569       " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
570       Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)),
571       false);
572 
573     assert(STM.hasGFX90AInsts() ||
574            CurrentProgramInfo.ComputePGMRSrc3GFX90A == 0);
575     if (STM.hasGFX90AInsts()) {
576       OutStreamer->emitRawComment(
577         " COMPUTE_PGM_RSRC3_GFX90A:ACCUM_OFFSET: " +
578         Twine((AMDHSA_BITS_GET(CurrentProgramInfo.ComputePGMRSrc3GFX90A,
579                                amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET))),
580                                false);
581       OutStreamer->emitRawComment(
582         " COMPUTE_PGM_RSRC3_GFX90A:TG_SPLIT: " +
583         Twine((AMDHSA_BITS_GET(CurrentProgramInfo.ComputePGMRSrc3GFX90A,
584                                amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT))),
585                                false);
586     }
587   }
588 
589   if (DumpCodeInstEmitter) {
590 
591     OutStreamer->SwitchSection(
592         Context.getELFSection(".AMDGPU.disasm", ELF::SHT_PROGBITS, 0));
593 
594     for (size_t i = 0; i < DisasmLines.size(); ++i) {
595       std::string Comment = "\n";
596       if (!HexLines[i].empty()) {
597         Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
598         Comment += " ; " + HexLines[i] + "\n";
599       }
600 
601       OutStreamer->emitBytes(StringRef(DisasmLines[i]));
602       OutStreamer->emitBytes(StringRef(Comment));
603     }
604   }
605 
606   return false;
607 }
608 
609 // TODO: Fold this into emitFunctionBodyStart.
610 void AMDGPUAsmPrinter::initializeTargetID(const Module &M) {
611   // In the beginning all features are either 'Any' or 'NotSupported',
612   // depending on global target features. This will cover empty modules.
613   getTargetStreamer()->initializeTargetID(
614       *getGlobalSTI(), getGlobalSTI()->getFeatureString());
615 
616   // If module is empty, we are done.
617   if (M.empty())
618     return;
619 
620   // If module is not empty, need to find first 'Off' or 'On' feature
621   // setting per feature from functions in module.
622   for (auto &F : M) {
623     auto &TSTargetID = getTargetStreamer()->getTargetID();
624     if ((!TSTargetID->isXnackSupported() || TSTargetID->isXnackOnOrOff()) &&
625         (!TSTargetID->isSramEccSupported() || TSTargetID->isSramEccOnOrOff()))
626       break;
627 
628     const GCNSubtarget &STM = TM.getSubtarget<GCNSubtarget>(F);
629     const IsaInfo::AMDGPUTargetID &STMTargetID = STM.getTargetID();
630     if (TSTargetID->isXnackSupported())
631       if (TSTargetID->getXnackSetting() == IsaInfo::TargetIDSetting::Any)
632         TSTargetID->setXnackSetting(STMTargetID.getXnackSetting());
633     if (TSTargetID->isSramEccSupported())
634       if (TSTargetID->getSramEccSetting() == IsaInfo::TargetIDSetting::Any)
635         TSTargetID->setSramEccSetting(STMTargetID.getSramEccSetting());
636   }
637 }
638 
639 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const {
640   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
641   const SIInstrInfo *TII = STM.getInstrInfo();
642 
643   uint64_t CodeSize = 0;
644 
645   for (const MachineBasicBlock &MBB : MF) {
646     for (const MachineInstr &MI : MBB) {
647       // TODO: CodeSize should account for multiple functions.
648 
649       // TODO: Should we count size of debug info?
650       if (MI.isDebugInstr())
651         continue;
652 
653       CodeSize += TII->getInstSizeInBytes(MI);
654     }
655   }
656 
657   return CodeSize;
658 }
659 
660 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
661                                         const MachineFunction &MF) {
662   const AMDGPUResourceUsageAnalysis::SIFunctionResourceInfo &Info =
663       ResourceUsage->getResourceInfo(&MF.getFunction());
664   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
665 
666   ProgInfo.NumArchVGPR = Info.NumVGPR;
667   ProgInfo.NumAccVGPR = Info.NumAGPR;
668   ProgInfo.NumVGPR = Info.getTotalNumVGPRs(STM);
669   ProgInfo.AccumOffset = alignTo(std::max(1, Info.NumVGPR), 4) / 4 - 1;
670   ProgInfo.TgSplit = STM.isTgSplitEnabled();
671   ProgInfo.NumSGPR = Info.NumExplicitSGPR;
672   ProgInfo.ScratchSize = Info.PrivateSegmentSize;
673   ProgInfo.VCCUsed = Info.UsesVCC;
674   ProgInfo.FlatUsed = Info.UsesFlatScratch;
675   ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion;
676 
677   const uint64_t MaxScratchPerWorkitem =
678       GCNSubtarget::MaxWaveScratchSize / STM.getWavefrontSize();
679   if (ProgInfo.ScratchSize > MaxScratchPerWorkitem) {
680     DiagnosticInfoStackSize DiagStackSize(MF.getFunction(),
681                                           ProgInfo.ScratchSize,
682                                           MaxScratchPerWorkitem, DS_Error);
683     MF.getFunction().getContext().diagnose(DiagStackSize);
684   }
685 
686   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
687 
688   // The calculations related to SGPR/VGPR blocks are
689   // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be
690   // unified.
691   unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs(
692       &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed);
693 
694   // Check the addressable register limit before we add ExtraSGPRs.
695   if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
696       !STM.hasSGPRInitBug()) {
697     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
698     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
699       // This can happen due to a compiler bug or when using inline asm.
700       LLVMContext &Ctx = MF.getFunction().getContext();
701       DiagnosticInfoResourceLimit Diag(
702           MF.getFunction(), "addressable scalar registers", ProgInfo.NumSGPR,
703           MaxAddressableNumSGPRs, DS_Error, DK_ResourceLimit);
704       Ctx.diagnose(Diag);
705       ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1;
706     }
707   }
708 
709   // Account for extra SGPRs and VGPRs reserved for debugger use.
710   ProgInfo.NumSGPR += ExtraSGPRs;
711 
712   const Function &F = MF.getFunction();
713 
714   // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave
715   // dispatch registers are function args.
716   unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0;
717 
718   if (isShader(F.getCallingConv())) {
719     bool IsPixelShader =
720         F.getCallingConv() == CallingConv::AMDGPU_PS && !STM.isAmdHsaOS();
721 
722     // Calculate the number of VGPR registers based on the SPI input registers
723     uint32_t InputEna = 0;
724     uint32_t InputAddr = 0;
725     unsigned LastEna = 0;
726 
727     if (IsPixelShader) {
728       // Note for IsPixelShader:
729       // By this stage, all enabled inputs are tagged in InputAddr as well.
730       // We will use InputAddr to determine whether the input counts against the
731       // vgpr total and only use the InputEnable to determine the last input
732       // that is relevant - if extra arguments are used, then we have to honour
733       // the InputAddr for any intermediate non-enabled inputs.
734       InputEna = MFI->getPSInputEnable();
735       InputAddr = MFI->getPSInputAddr();
736 
737       // We only need to consider input args up to the last used arg.
738       assert((InputEna || InputAddr) &&
739              "PSInputAddr and PSInputEnable should "
740              "never both be 0 for AMDGPU_PS shaders");
741       // There are some rare circumstances where InputAddr is non-zero and
742       // InputEna can be set to 0. In this case we default to setting LastEna
743       // to 1.
744       LastEna = InputEna ? findLastSet(InputEna) + 1 : 1;
745     }
746 
747     // FIXME: We should be using the number of registers determined during
748     // calling convention lowering to legalize the types.
749     const DataLayout &DL = F.getParent()->getDataLayout();
750     unsigned PSArgCount = 0;
751     unsigned IntermediateVGPR = 0;
752     for (auto &Arg : F.args()) {
753       unsigned NumRegs = (DL.getTypeSizeInBits(Arg.getType()) + 31) / 32;
754       if (Arg.hasAttribute(Attribute::InReg)) {
755         WaveDispatchNumSGPR += NumRegs;
756       } else {
757         // If this is a PS shader and we're processing the PS Input args (first
758         // 16 VGPR), use the InputEna and InputAddr bits to define how many
759         // VGPRs are actually used.
760         // Any extra VGPR arguments are handled as normal arguments (and
761         // contribute to the VGPR count whether they're used or not).
762         if (IsPixelShader && PSArgCount < 16) {
763           if ((1 << PSArgCount) & InputAddr) {
764             if (PSArgCount < LastEna)
765               WaveDispatchNumVGPR += NumRegs;
766             else
767               IntermediateVGPR += NumRegs;
768           }
769           PSArgCount++;
770         } else {
771           // If there are extra arguments we have to include the allocation for
772           // the non-used (but enabled with InputAddr) input arguments
773           if (IntermediateVGPR) {
774             WaveDispatchNumVGPR += IntermediateVGPR;
775             IntermediateVGPR = 0;
776           }
777           WaveDispatchNumVGPR += NumRegs;
778         }
779       }
780     }
781     ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR);
782     ProgInfo.NumArchVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR);
783     ProgInfo.NumVGPR =
784         Info.getTotalNumVGPRs(STM, Info.NumAGPR, ProgInfo.NumArchVGPR);
785   }
786 
787   // Adjust number of registers used to meet default/requested minimum/maximum
788   // number of waves per execution unit request.
789   ProgInfo.NumSGPRsForWavesPerEU = std::max(
790     std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU()));
791   ProgInfo.NumVGPRsForWavesPerEU = std::max(
792     std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU()));
793 
794   if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS ||
795       STM.hasSGPRInitBug()) {
796     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
797     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
798       // This can happen due to a compiler bug or when using inline asm to use
799       // the registers which are usually reserved for vcc etc.
800       LLVMContext &Ctx = MF.getFunction().getContext();
801       DiagnosticInfoResourceLimit Diag(MF.getFunction(), "scalar registers",
802                                        ProgInfo.NumSGPR, MaxAddressableNumSGPRs,
803                                        DS_Error, DK_ResourceLimit);
804       Ctx.diagnose(Diag);
805       ProgInfo.NumSGPR = MaxAddressableNumSGPRs;
806       ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs;
807     }
808   }
809 
810   if (STM.hasSGPRInitBug()) {
811     ProgInfo.NumSGPR =
812         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
813     ProgInfo.NumSGPRsForWavesPerEU =
814         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
815   }
816 
817   if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) {
818     LLVMContext &Ctx = MF.getFunction().getContext();
819     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs",
820                                      MFI->getNumUserSGPRs(),
821                                      STM.getMaxNumUserSGPRs(), DS_Error);
822     Ctx.diagnose(Diag);
823   }
824 
825   if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) {
826     LLVMContext &Ctx = MF.getFunction().getContext();
827     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory",
828                                      MFI->getLDSSize(),
829                                      STM.getLocalMemorySize(), DS_Error);
830     Ctx.diagnose(Diag);
831   }
832 
833   ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks(
834       &STM, ProgInfo.NumSGPRsForWavesPerEU);
835   ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks(
836       &STM, ProgInfo.NumVGPRsForWavesPerEU);
837 
838   const SIModeRegisterDefaults Mode = MFI->getMode();
839 
840   // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
841   // register.
842   ProgInfo.FloatMode = getFPMode(Mode);
843 
844   ProgInfo.IEEEMode = Mode.IEEE;
845 
846   // Make clamp modifier on NaN input returns 0.
847   ProgInfo.DX10Clamp = Mode.DX10Clamp;
848 
849   unsigned LDSAlignShift;
850   if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
851     // LDS is allocated in 64 dword blocks.
852     LDSAlignShift = 8;
853   } else {
854     // LDS is allocated in 128 dword blocks.
855     LDSAlignShift = 9;
856   }
857 
858   unsigned LDSSpillSize =
859     MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize();
860 
861   ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize;
862   ProgInfo.LDSBlocks =
863       alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
864 
865   // Scratch is allocated in 256 dword blocks.
866   unsigned ScratchAlignShift = 10;
867   // We need to program the hardware with the amount of scratch memory that
868   // is used by the entire wave.  ProgInfo.ScratchSize is the amount of
869   // scratch memory used per thread.
870   ProgInfo.ScratchBlocks =
871       alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(),
872               1ULL << ScratchAlignShift) >>
873       ScratchAlignShift;
874 
875   if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) {
876     ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1;
877     ProgInfo.MemOrdered = 1;
878   }
879 
880   // 0 = X, 1 = XY, 2 = XYZ
881   unsigned TIDIGCompCnt = 0;
882   if (MFI->hasWorkItemIDZ())
883     TIDIGCompCnt = 2;
884   else if (MFI->hasWorkItemIDY())
885     TIDIGCompCnt = 1;
886 
887   ProgInfo.ComputePGMRSrc2 =
888       S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) |
889       S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
890       // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP.
891       S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) |
892       S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
893       S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
894       S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
895       S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
896       S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
897       S_00B84C_EXCP_EN_MSB(0) |
898       // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP.
899       S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) |
900       S_00B84C_EXCP_EN(0);
901 
902   if (STM.hasGFX90AInsts()) {
903     AMDHSA_BITS_SET(ProgInfo.ComputePGMRSrc3GFX90A,
904                     amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET,
905                     ProgInfo.AccumOffset);
906     AMDHSA_BITS_SET(ProgInfo.ComputePGMRSrc3GFX90A,
907                     amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT,
908                     ProgInfo.TgSplit);
909   }
910 
911   ProgInfo.Occupancy = STM.computeOccupancy(MF.getFunction(), ProgInfo.LDSSize,
912                                             ProgInfo.NumSGPRsForWavesPerEU,
913                                             ProgInfo.NumVGPRsForWavesPerEU);
914 }
915 
916 static unsigned getRsrcReg(CallingConv::ID CallConv) {
917   switch (CallConv) {
918   default: LLVM_FALLTHROUGH;
919   case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1;
920   case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS;
921   case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS;
922   case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES;
923   case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS;
924   case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS;
925   case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS;
926   }
927 }
928 
929 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
930                                          const SIProgramInfo &CurrentProgramInfo) {
931   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
932   unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv());
933 
934   if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) {
935     OutStreamer->emitInt32(R_00B848_COMPUTE_PGM_RSRC1);
936 
937     OutStreamer->emitInt32(CurrentProgramInfo.getComputePGMRSrc1());
938 
939     OutStreamer->emitInt32(R_00B84C_COMPUTE_PGM_RSRC2);
940     OutStreamer->emitInt32(CurrentProgramInfo.ComputePGMRSrc2);
941 
942     OutStreamer->emitInt32(R_00B860_COMPUTE_TMPRING_SIZE);
943     OutStreamer->emitInt32(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks));
944 
945     // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
946     // 0" comment but I don't see a corresponding field in the register spec.
947   } else {
948     OutStreamer->emitInt32(RsrcReg);
949     OutStreamer->emitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) |
950                               S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4);
951     OutStreamer->emitInt32(R_0286E8_SPI_TMPRING_SIZE);
952     OutStreamer->emitIntValue(
953         S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4);
954   }
955 
956   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
957     OutStreamer->emitInt32(R_00B02C_SPI_SHADER_PGM_RSRC2_PS);
958     OutStreamer->emitInt32(
959         S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks));
960     OutStreamer->emitInt32(R_0286CC_SPI_PS_INPUT_ENA);
961     OutStreamer->emitInt32(MFI->getPSInputEnable());
962     OutStreamer->emitInt32(R_0286D0_SPI_PS_INPUT_ADDR);
963     OutStreamer->emitInt32(MFI->getPSInputAddr());
964   }
965 
966   OutStreamer->emitInt32(R_SPILLED_SGPRS);
967   OutStreamer->emitInt32(MFI->getNumSpilledSGPRs());
968   OutStreamer->emitInt32(R_SPILLED_VGPRS);
969   OutStreamer->emitInt32(MFI->getNumSpilledVGPRs());
970 }
971 
972 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type
973 // is AMDPAL.  It stores each compute/SPI register setting and other PAL
974 // metadata items into the PALMD::Metadata, combining with any provided by the
975 // frontend as LLVM metadata. Once all functions are written, the PAL metadata
976 // is then written as a single block in the .note section.
977 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF,
978        const SIProgramInfo &CurrentProgramInfo) {
979   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
980   auto CC = MF.getFunction().getCallingConv();
981   auto MD = getTargetStreamer()->getPALMetadata();
982 
983   MD->setEntryPoint(CC, MF.getFunction().getName());
984   MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU);
985   MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU);
986   MD->setRsrc1(CC, CurrentProgramInfo.getPGMRSrc1(CC));
987   if (AMDGPU::isCompute(CC)) {
988     MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2);
989   } else {
990     if (CurrentProgramInfo.ScratchBlocks > 0)
991       MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1));
992   }
993   // ScratchSize is in bytes, 16 aligned.
994   MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16));
995   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
996     MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks));
997     MD->setSpiPsInputEna(MFI->getPSInputEnable());
998     MD->setSpiPsInputAddr(MFI->getPSInputAddr());
999   }
1000 
1001   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1002   if (STM.isWave32())
1003     MD->setWave32(MF.getFunction().getCallingConv());
1004 }
1005 
1006 void AMDGPUAsmPrinter::emitPALFunctionMetadata(const MachineFunction &MF) {
1007   auto *MD = getTargetStreamer()->getPALMetadata();
1008   const MachineFrameInfo &MFI = MF.getFrameInfo();
1009   MD->setFunctionScratchSize(MF, MFI.getStackSize());
1010 
1011   // Set compute registers
1012   MD->setRsrc1(CallingConv::AMDGPU_CS,
1013                CurrentProgramInfo.getPGMRSrc1(CallingConv::AMDGPU_CS));
1014   MD->setRsrc2(CallingConv::AMDGPU_CS, CurrentProgramInfo.ComputePGMRSrc2);
1015 
1016   // Set optional info
1017   MD->setFunctionLdsSize(MF, CurrentProgramInfo.LDSSize);
1018   MD->setFunctionNumUsedVgprs(MF, CurrentProgramInfo.NumVGPRsForWavesPerEU);
1019   MD->setFunctionNumUsedSgprs(MF, CurrentProgramInfo.NumSGPRsForWavesPerEU);
1020 }
1021 
1022 // This is supposed to be log2(Size)
1023 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) {
1024   switch (Size) {
1025   case 4:
1026     return AMD_ELEMENT_4_BYTES;
1027   case 8:
1028     return AMD_ELEMENT_8_BYTES;
1029   case 16:
1030     return AMD_ELEMENT_16_BYTES;
1031   default:
1032     llvm_unreachable("invalid private_element_size");
1033   }
1034 }
1035 
1036 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out,
1037                                         const SIProgramInfo &CurrentProgramInfo,
1038                                         const MachineFunction &MF) const {
1039   const Function &F = MF.getFunction();
1040   assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
1041          F.getCallingConv() == CallingConv::SPIR_KERNEL);
1042 
1043   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1044   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
1045 
1046   AMDGPU::initDefaultAMDKernelCodeT(Out, &STM);
1047 
1048   Out.compute_pgm_resource_registers =
1049       CurrentProgramInfo.getComputePGMRSrc1() |
1050       (CurrentProgramInfo.ComputePGMRSrc2 << 32);
1051   Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64;
1052 
1053   if (CurrentProgramInfo.DynamicCallStack)
1054     Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK;
1055 
1056   AMD_HSA_BITS_SET(Out.code_properties,
1057                    AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE,
1058                    getElementByteSizeValue(STM.getMaxPrivateElementSize(true)));
1059 
1060   if (MFI->hasPrivateSegmentBuffer()) {
1061     Out.code_properties |=
1062       AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
1063   }
1064 
1065   if (MFI->hasDispatchPtr())
1066     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1067 
1068   if (MFI->hasQueuePtr())
1069     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
1070 
1071   if (MFI->hasKernargSegmentPtr())
1072     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
1073 
1074   if (MFI->hasDispatchID())
1075     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
1076 
1077   if (MFI->hasFlatScratchInit())
1078     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
1079 
1080   if (MFI->hasDispatchPtr())
1081     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1082 
1083   if (STM.isXNACKEnabled())
1084     Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
1085 
1086   Align MaxKernArgAlign;
1087   Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign);
1088   Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR;
1089   Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR;
1090   Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize;
1091   Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize;
1092 
1093   // kernarg_segment_alignment is specified as log of the alignment.
1094   // The minimum alignment is 16.
1095   // FIXME: The metadata treats the minimum as 4?
1096   Out.kernarg_segment_alignment = Log2(std::max(Align(16), MaxKernArgAlign));
1097 }
1098 
1099 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1100                                        const char *ExtraCode, raw_ostream &O) {
1101   // First try the generic code, which knows about modifiers like 'c' and 'n'.
1102   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O))
1103     return false;
1104 
1105   if (ExtraCode && ExtraCode[0]) {
1106     if (ExtraCode[1] != 0)
1107       return true; // Unknown modifier.
1108 
1109     switch (ExtraCode[0]) {
1110     case 'r':
1111       break;
1112     default:
1113       return true;
1114     }
1115   }
1116 
1117   // TODO: Should be able to support other operand types like globals.
1118   const MachineOperand &MO = MI->getOperand(OpNo);
1119   if (MO.isReg()) {
1120     AMDGPUInstPrinter::printRegOperand(MO.getReg(), O,
1121                                        *MF->getSubtarget().getRegisterInfo());
1122     return false;
1123   } else if (MO.isImm()) {
1124     int64_t Val = MO.getImm();
1125     if (AMDGPU::isInlinableIntLiteral(Val)) {
1126       O << Val;
1127     } else if (isUInt<16>(Val)) {
1128       O << format("0x%" PRIx16, static_cast<uint16_t>(Val));
1129     } else if (isUInt<32>(Val)) {
1130       O << format("0x%" PRIx32, static_cast<uint32_t>(Val));
1131     } else {
1132       O << format("0x%" PRIx64, static_cast<uint64_t>(Val));
1133     }
1134     return false;
1135   }
1136   return true;
1137 }
1138 
1139 void AMDGPUAsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
1140   AU.addRequired<AMDGPUResourceUsageAnalysis>();
1141   AU.addPreserved<AMDGPUResourceUsageAnalysis>();
1142   AsmPrinter::getAnalysisUsage(AU);
1143 }
1144