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