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