xref: /freebsd/contrib/llvm-project/llvm/lib/Target/AMDGPU/AMDGPUAsmPrinter.cpp (revision ec0ea6efa1ad229d75c394c1a9b9cac33af2b1d3)
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/Support/AMDHSAKernelDescriptor.h"
36 #include "llvm/Support/TargetRegistry.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, DS_Error);
682     MF.getFunction().getContext().diagnose(DiagStackSize);
683   }
684 
685   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
686 
687   // The calculations related to SGPR/VGPR blocks are
688   // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be
689   // unified.
690   unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs(
691       &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed);
692 
693   // Check the addressable register limit before we add ExtraSGPRs.
694   if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
695       !STM.hasSGPRInitBug()) {
696     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
697     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
698       // This can happen due to a compiler bug or when using inline asm.
699       LLVMContext &Ctx = MF.getFunction().getContext();
700       DiagnosticInfoResourceLimit Diag(MF.getFunction(),
701                                        "addressable scalar registers",
702                                        ProgInfo.NumSGPR, DS_Error,
703                                        DK_ResourceLimit,
704                                        MaxAddressableNumSGPRs);
705       Ctx.diagnose(Diag);
706       ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1;
707     }
708   }
709 
710   // Account for extra SGPRs and VGPRs reserved for debugger use.
711   ProgInfo.NumSGPR += ExtraSGPRs;
712 
713   const Function &F = MF.getFunction();
714 
715   // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave
716   // dispatch registers are function args.
717   unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0;
718 
719   if (isShader(F.getCallingConv())) {
720     // FIXME: We should be using the number of registers determined during
721     // calling convention lowering to legalize the types.
722     const DataLayout &DL = F.getParent()->getDataLayout();
723     for (auto &Arg : F.args()) {
724       unsigned NumRegs = (DL.getTypeSizeInBits(Arg.getType()) + 31) / 32;
725       if (Arg.hasAttribute(Attribute::InReg))
726         WaveDispatchNumSGPR += NumRegs;
727       else
728         WaveDispatchNumVGPR += NumRegs;
729     }
730     ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR);
731     ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR);
732   }
733 
734   // Adjust number of registers used to meet default/requested minimum/maximum
735   // number of waves per execution unit request.
736   ProgInfo.NumSGPRsForWavesPerEU = std::max(
737     std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU()));
738   ProgInfo.NumVGPRsForWavesPerEU = std::max(
739     std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU()));
740 
741   if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS ||
742       STM.hasSGPRInitBug()) {
743     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
744     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
745       // This can happen due to a compiler bug or when using inline asm to use
746       // the registers which are usually reserved for vcc etc.
747       LLVMContext &Ctx = MF.getFunction().getContext();
748       DiagnosticInfoResourceLimit Diag(MF.getFunction(),
749                                        "scalar registers",
750                                        ProgInfo.NumSGPR, DS_Error,
751                                        DK_ResourceLimit,
752                                        MaxAddressableNumSGPRs);
753       Ctx.diagnose(Diag);
754       ProgInfo.NumSGPR = MaxAddressableNumSGPRs;
755       ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs;
756     }
757   }
758 
759   if (STM.hasSGPRInitBug()) {
760     ProgInfo.NumSGPR =
761         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
762     ProgInfo.NumSGPRsForWavesPerEU =
763         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
764   }
765 
766   if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) {
767     LLVMContext &Ctx = MF.getFunction().getContext();
768     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs",
769                                      MFI->getNumUserSGPRs(), DS_Error);
770     Ctx.diagnose(Diag);
771   }
772 
773   if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) {
774     LLVMContext &Ctx = MF.getFunction().getContext();
775     DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory",
776                                      MFI->getLDSSize(), DS_Error);
777     Ctx.diagnose(Diag);
778   }
779 
780   ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks(
781       &STM, ProgInfo.NumSGPRsForWavesPerEU);
782   ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks(
783       &STM, ProgInfo.NumVGPRsForWavesPerEU);
784 
785   const SIModeRegisterDefaults Mode = MFI->getMode();
786 
787   // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
788   // register.
789   ProgInfo.FloatMode = getFPMode(Mode);
790 
791   ProgInfo.IEEEMode = Mode.IEEE;
792 
793   // Make clamp modifier on NaN input returns 0.
794   ProgInfo.DX10Clamp = Mode.DX10Clamp;
795 
796   unsigned LDSAlignShift;
797   if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) {
798     // LDS is allocated in 64 dword blocks.
799     LDSAlignShift = 8;
800   } else {
801     // LDS is allocated in 128 dword blocks.
802     LDSAlignShift = 9;
803   }
804 
805   unsigned LDSSpillSize =
806     MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize();
807 
808   ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize;
809   ProgInfo.LDSBlocks =
810       alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
811 
812   // Scratch is allocated in 256 dword blocks.
813   unsigned ScratchAlignShift = 10;
814   // We need to program the hardware with the amount of scratch memory that
815   // is used by the entire wave.  ProgInfo.ScratchSize is the amount of
816   // scratch memory used per thread.
817   ProgInfo.ScratchBlocks =
818       alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(),
819               1ULL << ScratchAlignShift) >>
820       ScratchAlignShift;
821 
822   if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) {
823     ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1;
824     ProgInfo.MemOrdered = 1;
825   }
826 
827   // 0 = X, 1 = XY, 2 = XYZ
828   unsigned TIDIGCompCnt = 0;
829   if (MFI->hasWorkItemIDZ())
830     TIDIGCompCnt = 2;
831   else if (MFI->hasWorkItemIDY())
832     TIDIGCompCnt = 1;
833 
834   ProgInfo.ComputePGMRSrc2 =
835       S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) |
836       S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
837       // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP.
838       S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) |
839       S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
840       S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
841       S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
842       S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
843       S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
844       S_00B84C_EXCP_EN_MSB(0) |
845       // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP.
846       S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) |
847       S_00B84C_EXCP_EN(0);
848 
849   if (STM.hasGFX90AInsts()) {
850     AMDHSA_BITS_SET(ProgInfo.ComputePGMRSrc3GFX90A,
851                     amdhsa::COMPUTE_PGM_RSRC3_GFX90A_ACCUM_OFFSET,
852                     ProgInfo.AccumOffset);
853     AMDHSA_BITS_SET(ProgInfo.ComputePGMRSrc3GFX90A,
854                     amdhsa::COMPUTE_PGM_RSRC3_GFX90A_TG_SPLIT,
855                     ProgInfo.TgSplit);
856   }
857 
858   ProgInfo.Occupancy = STM.computeOccupancy(MF.getFunction(), ProgInfo.LDSSize,
859                                             ProgInfo.NumSGPRsForWavesPerEU,
860                                             ProgInfo.NumVGPRsForWavesPerEU);
861 }
862 
863 static unsigned getRsrcReg(CallingConv::ID CallConv) {
864   switch (CallConv) {
865   default: LLVM_FALLTHROUGH;
866   case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1;
867   case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS;
868   case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS;
869   case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES;
870   case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS;
871   case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS;
872   case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS;
873   }
874 }
875 
876 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
877                                          const SIProgramInfo &CurrentProgramInfo) {
878   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
879   unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv());
880 
881   if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) {
882     OutStreamer->emitInt32(R_00B848_COMPUTE_PGM_RSRC1);
883 
884     OutStreamer->emitInt32(CurrentProgramInfo.getComputePGMRSrc1());
885 
886     OutStreamer->emitInt32(R_00B84C_COMPUTE_PGM_RSRC2);
887     OutStreamer->emitInt32(CurrentProgramInfo.ComputePGMRSrc2);
888 
889     OutStreamer->emitInt32(R_00B860_COMPUTE_TMPRING_SIZE);
890     OutStreamer->emitInt32(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks));
891 
892     // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
893     // 0" comment but I don't see a corresponding field in the register spec.
894   } else {
895     OutStreamer->emitInt32(RsrcReg);
896     OutStreamer->emitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) |
897                               S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4);
898     OutStreamer->emitInt32(R_0286E8_SPI_TMPRING_SIZE);
899     OutStreamer->emitIntValue(
900         S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4);
901   }
902 
903   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
904     OutStreamer->emitInt32(R_00B02C_SPI_SHADER_PGM_RSRC2_PS);
905     OutStreamer->emitInt32(
906         S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks));
907     OutStreamer->emitInt32(R_0286CC_SPI_PS_INPUT_ENA);
908     OutStreamer->emitInt32(MFI->getPSInputEnable());
909     OutStreamer->emitInt32(R_0286D0_SPI_PS_INPUT_ADDR);
910     OutStreamer->emitInt32(MFI->getPSInputAddr());
911   }
912 
913   OutStreamer->emitInt32(R_SPILLED_SGPRS);
914   OutStreamer->emitInt32(MFI->getNumSpilledSGPRs());
915   OutStreamer->emitInt32(R_SPILLED_VGPRS);
916   OutStreamer->emitInt32(MFI->getNumSpilledVGPRs());
917 }
918 
919 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type
920 // is AMDPAL.  It stores each compute/SPI register setting and other PAL
921 // metadata items into the PALMD::Metadata, combining with any provided by the
922 // frontend as LLVM metadata. Once all functions are written, the PAL metadata
923 // is then written as a single block in the .note section.
924 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF,
925        const SIProgramInfo &CurrentProgramInfo) {
926   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
927   auto CC = MF.getFunction().getCallingConv();
928   auto MD = getTargetStreamer()->getPALMetadata();
929 
930   MD->setEntryPoint(CC, MF.getFunction().getName());
931   MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU);
932   MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU);
933   MD->setRsrc1(CC, CurrentProgramInfo.getPGMRSrc1(CC));
934   if (AMDGPU::isCompute(CC)) {
935     MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2);
936   } else {
937     if (CurrentProgramInfo.ScratchBlocks > 0)
938       MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1));
939   }
940   // ScratchSize is in bytes, 16 aligned.
941   MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16));
942   if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) {
943     MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks));
944     MD->setSpiPsInputEna(MFI->getPSInputEnable());
945     MD->setSpiPsInputAddr(MFI->getPSInputAddr());
946   }
947 
948   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
949   if (STM.isWave32())
950     MD->setWave32(MF.getFunction().getCallingConv());
951 }
952 
953 void AMDGPUAsmPrinter::emitPALFunctionMetadata(const MachineFunction &MF) {
954   auto *MD = getTargetStreamer()->getPALMetadata();
955   const MachineFrameInfo &MFI = MF.getFrameInfo();
956   MD->setFunctionScratchSize(MF, MFI.getStackSize());
957 
958   // Set compute registers
959   MD->setRsrc1(CallingConv::AMDGPU_CS,
960                CurrentProgramInfo.getPGMRSrc1(CallingConv::AMDGPU_CS));
961   MD->setRsrc2(CallingConv::AMDGPU_CS, CurrentProgramInfo.ComputePGMRSrc2);
962 
963   // Set optional info
964   MD->setFunctionLdsSize(MF, CurrentProgramInfo.LDSSize);
965   MD->setFunctionNumUsedVgprs(MF, CurrentProgramInfo.NumVGPRsForWavesPerEU);
966   MD->setFunctionNumUsedSgprs(MF, CurrentProgramInfo.NumSGPRsForWavesPerEU);
967 }
968 
969 // This is supposed to be log2(Size)
970 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) {
971   switch (Size) {
972   case 4:
973     return AMD_ELEMENT_4_BYTES;
974   case 8:
975     return AMD_ELEMENT_8_BYTES;
976   case 16:
977     return AMD_ELEMENT_16_BYTES;
978   default:
979     llvm_unreachable("invalid private_element_size");
980   }
981 }
982 
983 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out,
984                                         const SIProgramInfo &CurrentProgramInfo,
985                                         const MachineFunction &MF) const {
986   const Function &F = MF.getFunction();
987   assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL ||
988          F.getCallingConv() == CallingConv::SPIR_KERNEL);
989 
990   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
991   const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>();
992 
993   AMDGPU::initDefaultAMDKernelCodeT(Out, &STM);
994 
995   Out.compute_pgm_resource_registers =
996       CurrentProgramInfo.getComputePGMRSrc1() |
997       (CurrentProgramInfo.ComputePGMRSrc2 << 32);
998   Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64;
999 
1000   if (CurrentProgramInfo.DynamicCallStack)
1001     Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK;
1002 
1003   AMD_HSA_BITS_SET(Out.code_properties,
1004                    AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE,
1005                    getElementByteSizeValue(STM.getMaxPrivateElementSize(true)));
1006 
1007   if (MFI->hasPrivateSegmentBuffer()) {
1008     Out.code_properties |=
1009       AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
1010   }
1011 
1012   if (MFI->hasDispatchPtr())
1013     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1014 
1015   if (MFI->hasQueuePtr())
1016     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
1017 
1018   if (MFI->hasKernargSegmentPtr())
1019     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
1020 
1021   if (MFI->hasDispatchID())
1022     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
1023 
1024   if (MFI->hasFlatScratchInit())
1025     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
1026 
1027   if (MFI->hasDispatchPtr())
1028     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
1029 
1030   if (STM.isXNACKEnabled())
1031     Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
1032 
1033   Align MaxKernArgAlign;
1034   Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign);
1035   Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR;
1036   Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR;
1037   Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize;
1038   Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize;
1039 
1040   // kernarg_segment_alignment is specified as log of the alignment.
1041   // The minimum alignment is 16.
1042   Out.kernarg_segment_alignment = Log2(std::max(Align(16), MaxKernArgAlign));
1043 }
1044 
1045 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
1046                                        const char *ExtraCode, raw_ostream &O) {
1047   // First try the generic code, which knows about modifiers like 'c' and 'n'.
1048   if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O))
1049     return false;
1050 
1051   if (ExtraCode && ExtraCode[0]) {
1052     if (ExtraCode[1] != 0)
1053       return true; // Unknown modifier.
1054 
1055     switch (ExtraCode[0]) {
1056     case 'r':
1057       break;
1058     default:
1059       return true;
1060     }
1061   }
1062 
1063   // TODO: Should be able to support other operand types like globals.
1064   const MachineOperand &MO = MI->getOperand(OpNo);
1065   if (MO.isReg()) {
1066     AMDGPUInstPrinter::printRegOperand(MO.getReg(), O,
1067                                        *MF->getSubtarget().getRegisterInfo());
1068     return false;
1069   } else if (MO.isImm()) {
1070     int64_t Val = MO.getImm();
1071     if (AMDGPU::isInlinableIntLiteral(Val)) {
1072       O << Val;
1073     } else if (isUInt<16>(Val)) {
1074       O << format("0x%" PRIx16, static_cast<uint16_t>(Val));
1075     } else if (isUInt<32>(Val)) {
1076       O << format("0x%" PRIx32, static_cast<uint32_t>(Val));
1077     } else {
1078       O << format("0x%" PRIx64, static_cast<uint64_t>(Val));
1079     }
1080     return false;
1081   }
1082   return true;
1083 }
1084 
1085 void AMDGPUAsmPrinter::getAnalysisUsage(AnalysisUsage &AU) const {
1086   AU.addRequired<AMDGPUResourceUsageAnalysis>();
1087   AU.addPreserved<AMDGPUResourceUsageAnalysis>();
1088   AsmPrinter::getAnalysisUsage(AU);
1089 }
1090