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