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