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 "AMDGPUSubtarget.h" 21 #include "AMDGPUTargetMachine.h" 22 #include "MCTargetDesc/AMDGPUInstPrinter.h" 23 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 24 #include "MCTargetDesc/AMDGPUTargetStreamer.h" 25 #include "R600AsmPrinter.h" 26 #include "R600Defines.h" 27 #include "R600MachineFunctionInfo.h" 28 #include "R600RegisterInfo.h" 29 #include "SIDefines.h" 30 #include "SIInstrInfo.h" 31 #include "SIMachineFunctionInfo.h" 32 #include "SIRegisterInfo.h" 33 #include "Utils/AMDGPUBaseInfo.h" 34 #include "llvm/BinaryFormat/ELF.h" 35 #include "llvm/CodeGen/MachineFrameInfo.h" 36 #include "llvm/IR/DiagnosticInfo.h" 37 #include "llvm/MC/MCAssembler.h" 38 #include "llvm/MC/MCContext.h" 39 #include "llvm/MC/MCSectionELF.h" 40 #include "llvm/MC/MCStreamer.h" 41 #include "llvm/Support/AMDGPUMetadata.h" 42 #include "llvm/Support/MathExtras.h" 43 #include "llvm/Support/TargetParser.h" 44 #include "llvm/Support/TargetRegistry.h" 45 #include "llvm/Target/TargetLoweringObjectFile.h" 46 47 using namespace llvm; 48 using namespace llvm::AMDGPU; 49 using namespace llvm::AMDGPU::HSAMD; 50 51 // TODO: This should get the default rounding mode from the kernel. We just set 52 // the default here, but this could change if the OpenCL rounding mode pragmas 53 // are used. 54 // 55 // The denormal mode here should match what is reported by the OpenCL runtime 56 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but 57 // can also be override to flush with the -cl-denorms-are-zero compiler flag. 58 // 59 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double 60 // precision, and leaves single precision to flush all and does not report 61 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports 62 // CL_FP_DENORM for both. 63 // 64 // FIXME: It seems some instructions do not support single precision denormals 65 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32, 66 // and sin_f32, cos_f32 on most parts). 67 68 // We want to use these instructions, and using fp32 denormals also causes 69 // instructions to run at the double precision rate for the device so it's 70 // probably best to just report no single precision denormals. 71 static uint32_t getFPMode(const MachineFunction &F) { 72 const GCNSubtarget& ST = F.getSubtarget<GCNSubtarget>(); 73 // TODO: Is there any real use for the flush in only / flush out only modes? 74 75 uint32_t FP32Denormals = 76 ST.hasFP32Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT; 77 78 uint32_t FP64Denormals = 79 ST.hasFP64Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT; 80 81 return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) | 82 FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) | 83 FP_DENORM_MODE_SP(FP32Denormals) | 84 FP_DENORM_MODE_DP(FP64Denormals); 85 } 86 87 static AsmPrinter * 88 createAMDGPUAsmPrinterPass(TargetMachine &tm, 89 std::unique_ptr<MCStreamer> &&Streamer) { 90 return new AMDGPUAsmPrinter(tm, std::move(Streamer)); 91 } 92 93 extern "C" void LLVMInitializeAMDGPUAsmPrinter() { 94 TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(), 95 llvm::createR600AsmPrinterPass); 96 TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(), 97 createAMDGPUAsmPrinterPass); 98 } 99 100 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, 101 std::unique_ptr<MCStreamer> Streamer) 102 : AsmPrinter(TM, std::move(Streamer)) { 103 if (IsaInfo::hasCodeObjectV3(getGlobalSTI())) 104 HSAMetadataStream.reset(new MetadataStreamerV3()); 105 else 106 HSAMetadataStream.reset(new MetadataStreamerV2()); 107 } 108 109 StringRef AMDGPUAsmPrinter::getPassName() const { 110 return "AMDGPU Assembly Printer"; 111 } 112 113 const MCSubtargetInfo *AMDGPUAsmPrinter::getGlobalSTI() const { 114 return TM.getMCSubtargetInfo(); 115 } 116 117 AMDGPUTargetStreamer* AMDGPUAsmPrinter::getTargetStreamer() const { 118 if (!OutStreamer) 119 return nullptr; 120 return static_cast<AMDGPUTargetStreamer*>(OutStreamer->getTargetStreamer()); 121 } 122 123 void AMDGPUAsmPrinter::EmitStartOfAsmFile(Module &M) { 124 if (IsaInfo::hasCodeObjectV3(getGlobalSTI())) { 125 std::string ExpectedTarget; 126 raw_string_ostream ExpectedTargetOS(ExpectedTarget); 127 IsaInfo::streamIsaVersion(getGlobalSTI(), ExpectedTargetOS); 128 129 getTargetStreamer()->EmitDirectiveAMDGCNTarget(ExpectedTarget); 130 } 131 132 if (TM.getTargetTriple().getOS() != Triple::AMDHSA && 133 TM.getTargetTriple().getOS() != Triple::AMDPAL) 134 return; 135 136 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) 137 HSAMetadataStream->begin(M); 138 139 if (TM.getTargetTriple().getOS() == Triple::AMDPAL) 140 getTargetStreamer()->getPALMetadata()->readFromIR(M); 141 142 if (IsaInfo::hasCodeObjectV3(getGlobalSTI())) 143 return; 144 145 // HSA emits NT_AMDGPU_HSA_CODE_OBJECT_VERSION for code objects v2. 146 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) 147 getTargetStreamer()->EmitDirectiveHSACodeObjectVersion(2, 1); 148 149 // HSA and PAL emit NT_AMDGPU_HSA_ISA for code objects v2. 150 IsaVersion Version = getIsaVersion(getGlobalSTI()->getCPU()); 151 getTargetStreamer()->EmitDirectiveHSACodeObjectISA( 152 Version.Major, Version.Minor, Version.Stepping, "AMD", "AMDGPU"); 153 } 154 155 void AMDGPUAsmPrinter::EmitEndOfAsmFile(Module &M) { 156 // Following code requires TargetStreamer to be present. 157 if (!getTargetStreamer()) 158 return; 159 160 if (!IsaInfo::hasCodeObjectV3(getGlobalSTI())) { 161 // Emit ISA Version (NT_AMD_AMDGPU_ISA). 162 std::string ISAVersionString; 163 raw_string_ostream ISAVersionStream(ISAVersionString); 164 IsaInfo::streamIsaVersion(getGlobalSTI(), ISAVersionStream); 165 getTargetStreamer()->EmitISAVersion(ISAVersionStream.str()); 166 } 167 168 // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA). 169 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) { 170 HSAMetadataStream->end(); 171 bool Success = HSAMetadataStream->emitTo(*getTargetStreamer()); 172 (void)Success; 173 assert(Success && "Malformed HSA Metadata"); 174 } 175 } 176 177 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough( 178 const MachineBasicBlock *MBB) const { 179 if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB)) 180 return false; 181 182 if (MBB->empty()) 183 return true; 184 185 // If this is a block implementing a long branch, an expression relative to 186 // the start of the block is needed. to the start of the block. 187 // XXX - Is there a smarter way to check this? 188 return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64); 189 } 190 191 void AMDGPUAsmPrinter::EmitFunctionBodyStart() { 192 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 193 if (!MFI.isEntryFunction()) 194 return; 195 196 const GCNSubtarget &STM = MF->getSubtarget<GCNSubtarget>(); 197 const Function &F = MF->getFunction(); 198 if (!STM.hasCodeObjectV3() && STM.isAmdHsaOrMesa(F) && 199 (F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 200 F.getCallingConv() == CallingConv::SPIR_KERNEL)) { 201 amd_kernel_code_t KernelCode; 202 getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF); 203 getTargetStreamer()->EmitAMDKernelCodeT(KernelCode); 204 } 205 206 if (STM.isAmdHsaOS()) 207 HSAMetadataStream->emitKernel(*MF, CurrentProgramInfo); 208 209 DumpCodeInstEmitter = nullptr; 210 if (STM.dumpCode()) { 211 // For -dumpcode, get the assembler out of the streamer, even if it does 212 // not really want to let us have it. This only works with -filetype=obj. 213 bool SaveFlag = OutStreamer->getUseAssemblerInfoForParsing(); 214 OutStreamer->setUseAssemblerInfoForParsing(true); 215 MCAssembler *Assembler = OutStreamer->getAssemblerPtr(); 216 OutStreamer->setUseAssemblerInfoForParsing(SaveFlag); 217 if (Assembler) 218 DumpCodeInstEmitter = Assembler->getEmitterPtr(); 219 } 220 } 221 222 void AMDGPUAsmPrinter::EmitFunctionBodyEnd() { 223 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 224 if (!MFI.isEntryFunction()) 225 return; 226 227 if (!IsaInfo::hasCodeObjectV3(getGlobalSTI()) || 228 TM.getTargetTriple().getOS() != Triple::AMDHSA) 229 return; 230 231 auto &Streamer = getTargetStreamer()->getStreamer(); 232 auto &Context = Streamer.getContext(); 233 auto &ObjectFileInfo = *Context.getObjectFileInfo(); 234 auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection(); 235 236 Streamer.PushSection(); 237 Streamer.SwitchSection(&ReadOnlySection); 238 239 // CP microcode requires the kernel descriptor to be allocated on 64 byte 240 // alignment. 241 Streamer.EmitValueToAlignment(64, 0, 1, 0); 242 if (ReadOnlySection.getAlignment() < 64) 243 ReadOnlySection.setAlignment(64); 244 245 const MCSubtargetInfo &STI = MF->getSubtarget(); 246 247 SmallString<128> KernelName; 248 getNameWithPrefix(KernelName, &MF->getFunction()); 249 getTargetStreamer()->EmitAmdhsaKernelDescriptor( 250 STI, KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo), 251 CurrentProgramInfo.NumVGPRsForWavesPerEU, 252 CurrentProgramInfo.NumSGPRsForWavesPerEU - 253 IsaInfo::getNumExtraSGPRs(&STI, 254 CurrentProgramInfo.VCCUsed, 255 CurrentProgramInfo.FlatUsed), 256 CurrentProgramInfo.VCCUsed, CurrentProgramInfo.FlatUsed, 257 hasXNACK(STI)); 258 259 Streamer.PopSection(); 260 } 261 262 void AMDGPUAsmPrinter::EmitFunctionEntryLabel() { 263 if (IsaInfo::hasCodeObjectV3(getGlobalSTI()) && 264 TM.getTargetTriple().getOS() == Triple::AMDHSA) { 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) const { 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 301 // Group segment variables aren't emitted in HSA. 302 if (AMDGPU::isGroupSegment(GV)) 303 return; 304 305 AsmPrinter::EmitGlobalVariable(GV); 306 } 307 308 bool AMDGPUAsmPrinter::doFinalization(Module &M) { 309 CallGraphResourceInfo.clear(); 310 311 if (AMDGPU::isGFX10(*getGlobalSTI())) { 312 OutStreamer->SwitchSection(getObjFileLowering().getTextSection()); 313 getTargetStreamer()->EmitCodeEnd(); 314 } 315 316 return AsmPrinter::doFinalization(M); 317 } 318 319 // Print comments that apply to both callable functions and entry points. 320 void AMDGPUAsmPrinter::emitCommonFunctionComments( 321 uint32_t NumVGPR, 322 uint32_t NumSGPR, 323 uint64_t ScratchSize, 324 uint64_t CodeSize, 325 const AMDGPUMachineFunction *MFI) { 326 OutStreamer->emitRawComment(" codeLenInByte = " + Twine(CodeSize), false); 327 OutStreamer->emitRawComment(" NumSgprs: " + Twine(NumSGPR), false); 328 OutStreamer->emitRawComment(" NumVgprs: " + Twine(NumVGPR), false); 329 OutStreamer->emitRawComment(" ScratchSize: " + Twine(ScratchSize), false); 330 OutStreamer->emitRawComment(" MemoryBound: " + Twine(MFI->isMemoryBound()), 331 false); 332 } 333 334 uint16_t AMDGPUAsmPrinter::getAmdhsaKernelCodeProperties( 335 const MachineFunction &MF) const { 336 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 337 uint16_t KernelCodeProperties = 0; 338 339 if (MFI.hasPrivateSegmentBuffer()) { 340 KernelCodeProperties |= 341 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 342 } 343 if (MFI.hasDispatchPtr()) { 344 KernelCodeProperties |= 345 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 346 } 347 if (MFI.hasQueuePtr()) { 348 KernelCodeProperties |= 349 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 350 } 351 if (MFI.hasKernargSegmentPtr()) { 352 KernelCodeProperties |= 353 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 354 } 355 if (MFI.hasDispatchID()) { 356 KernelCodeProperties |= 357 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 358 } 359 if (MFI.hasFlatScratchInit()) { 360 KernelCodeProperties |= 361 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 362 } 363 364 return KernelCodeProperties; 365 } 366 367 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor( 368 const MachineFunction &MF, 369 const SIProgramInfo &PI) const { 370 amdhsa::kernel_descriptor_t KernelDescriptor; 371 memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor)); 372 373 assert(isUInt<32>(PI.ScratchSize)); 374 assert(isUInt<32>(PI.ComputePGMRSrc1)); 375 assert(isUInt<32>(PI.ComputePGMRSrc2)); 376 377 KernelDescriptor.group_segment_fixed_size = PI.LDSSize; 378 KernelDescriptor.private_segment_fixed_size = PI.ScratchSize; 379 KernelDescriptor.compute_pgm_rsrc1 = PI.ComputePGMRSrc1; 380 KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2; 381 KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF); 382 383 return KernelDescriptor; 384 } 385 386 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) { 387 CurrentProgramInfo = SIProgramInfo(); 388 389 const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>(); 390 391 // The starting address of all shader programs must be 256 bytes aligned. 392 // Regular functions just need the basic required instruction alignment. 393 MF.setAlignment(MFI->isEntryFunction() ? 8 : 2); 394 395 SetupMachineFunction(MF); 396 397 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 398 MCContext &Context = getObjFileLowering().getContext(); 399 // FIXME: This should be an explicit check for Mesa. 400 if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) { 401 MCSectionELF *ConfigSection = 402 Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0); 403 OutStreamer->SwitchSection(ConfigSection); 404 } 405 406 if (MFI->isEntryFunction()) { 407 getSIProgramInfo(CurrentProgramInfo, MF); 408 } else { 409 auto I = CallGraphResourceInfo.insert( 410 std::make_pair(&MF.getFunction(), SIFunctionResourceInfo())); 411 SIFunctionResourceInfo &Info = I.first->second; 412 assert(I.second && "should only be called once per function"); 413 Info = analyzeResourceUsage(MF); 414 } 415 416 if (STM.isAmdPalOS()) 417 EmitPALMetadata(MF, CurrentProgramInfo); 418 else if (!STM.isAmdHsaOS()) { 419 EmitProgramInfoSI(MF, CurrentProgramInfo); 420 } 421 422 DisasmLines.clear(); 423 HexLines.clear(); 424 DisasmLineMaxLen = 0; 425 426 EmitFunctionBody(); 427 428 if (isVerbose()) { 429 MCSectionELF *CommentSection = 430 Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0); 431 OutStreamer->SwitchSection(CommentSection); 432 433 if (!MFI->isEntryFunction()) { 434 OutStreamer->emitRawComment(" Function info:", false); 435 SIFunctionResourceInfo &Info = CallGraphResourceInfo[&MF.getFunction()]; 436 emitCommonFunctionComments( 437 Info.NumVGPR, 438 Info.getTotalNumSGPRs(MF.getSubtarget<GCNSubtarget>()), 439 Info.PrivateSegmentSize, 440 getFunctionCodeSize(MF), MFI); 441 return false; 442 } 443 444 OutStreamer->emitRawComment(" Kernel info:", false); 445 emitCommonFunctionComments(CurrentProgramInfo.NumVGPR, 446 CurrentProgramInfo.NumSGPR, 447 CurrentProgramInfo.ScratchSize, 448 getFunctionCodeSize(MF), MFI); 449 450 OutStreamer->emitRawComment( 451 " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false); 452 OutStreamer->emitRawComment( 453 " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false); 454 OutStreamer->emitRawComment( 455 " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) + 456 " bytes/workgroup (compile time only)", false); 457 458 OutStreamer->emitRawComment( 459 " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false); 460 OutStreamer->emitRawComment( 461 " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false); 462 463 OutStreamer->emitRawComment( 464 " NumSGPRsForWavesPerEU: " + 465 Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false); 466 OutStreamer->emitRawComment( 467 " NumVGPRsForWavesPerEU: " + 468 Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false); 469 470 OutStreamer->emitRawComment( 471 " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false); 472 473 OutStreamer->emitRawComment( 474 " COMPUTE_PGM_RSRC2:USER_SGPR: " + 475 Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false); 476 OutStreamer->emitRawComment( 477 " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " + 478 Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false); 479 OutStreamer->emitRawComment( 480 " COMPUTE_PGM_RSRC2:TGID_X_EN: " + 481 Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 482 OutStreamer->emitRawComment( 483 " COMPUTE_PGM_RSRC2:TGID_Y_EN: " + 484 Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 485 OutStreamer->emitRawComment( 486 " COMPUTE_PGM_RSRC2:TGID_Z_EN: " + 487 Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 488 OutStreamer->emitRawComment( 489 " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " + 490 Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)), 491 false); 492 } 493 494 if (DumpCodeInstEmitter) { 495 496 OutStreamer->SwitchSection( 497 Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0)); 498 499 for (size_t i = 0; i < DisasmLines.size(); ++i) { 500 std::string Comment = "\n"; 501 if (!HexLines[i].empty()) { 502 Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' '); 503 Comment += " ; " + HexLines[i] + "\n"; 504 } 505 506 OutStreamer->EmitBytes(StringRef(DisasmLines[i])); 507 OutStreamer->EmitBytes(StringRef(Comment)); 508 } 509 } 510 511 return false; 512 } 513 514 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const { 515 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 516 const SIInstrInfo *TII = STM.getInstrInfo(); 517 518 uint64_t CodeSize = 0; 519 520 for (const MachineBasicBlock &MBB : MF) { 521 for (const MachineInstr &MI : MBB) { 522 // TODO: CodeSize should account for multiple functions. 523 524 // TODO: Should we count size of debug info? 525 if (MI.isDebugInstr()) 526 continue; 527 528 CodeSize += TII->getInstSizeInBytes(MI); 529 } 530 } 531 532 return CodeSize; 533 } 534 535 static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI, 536 const SIInstrInfo &TII, 537 unsigned Reg) { 538 for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) { 539 if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent())) 540 return true; 541 } 542 543 return false; 544 } 545 546 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumSGPRs( 547 const GCNSubtarget &ST) const { 548 return NumExplicitSGPR + IsaInfo::getNumExtraSGPRs(&ST, 549 UsesVCC, UsesFlatScratch); 550 } 551 552 AMDGPUAsmPrinter::SIFunctionResourceInfo AMDGPUAsmPrinter::analyzeResourceUsage( 553 const MachineFunction &MF) const { 554 SIFunctionResourceInfo Info; 555 556 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 557 const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); 558 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 559 const MachineRegisterInfo &MRI = MF.getRegInfo(); 560 const SIInstrInfo *TII = ST.getInstrInfo(); 561 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 562 563 Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) || 564 MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI); 565 566 // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat 567 // instructions aren't used to access the scratch buffer. Inline assembly may 568 // need it though. 569 // 570 // If we only have implicit uses of flat_scr on flat instructions, it is not 571 // really needed. 572 if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() && 573 (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) && 574 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) && 575 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) { 576 Info.UsesFlatScratch = false; 577 } 578 579 Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects(); 580 Info.PrivateSegmentSize = FrameInfo.getStackSize(); 581 if (MFI->isStackRealigned()) 582 Info.PrivateSegmentSize += FrameInfo.getMaxAlignment(); 583 584 585 Info.UsesVCC = MRI.isPhysRegUsed(AMDGPU::VCC_LO) || 586 MRI.isPhysRegUsed(AMDGPU::VCC_HI); 587 588 // If there are no calls, MachineRegisterInfo can tell us the used register 589 // count easily. 590 // A tail call isn't considered a call for MachineFrameInfo's purposes. 591 if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) { 592 MCPhysReg HighestVGPRReg = AMDGPU::NoRegister; 593 for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) { 594 if (MRI.isPhysRegUsed(Reg)) { 595 HighestVGPRReg = Reg; 596 break; 597 } 598 } 599 600 MCPhysReg HighestSGPRReg = AMDGPU::NoRegister; 601 for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) { 602 if (MRI.isPhysRegUsed(Reg)) { 603 HighestSGPRReg = Reg; 604 break; 605 } 606 } 607 608 // We found the maximum register index. They start at 0, so add one to get the 609 // number of registers. 610 Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister ? 0 : 611 TRI.getHWRegIndex(HighestVGPRReg) + 1; 612 Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister ? 0 : 613 TRI.getHWRegIndex(HighestSGPRReg) + 1; 614 615 return Info; 616 } 617 618 int32_t MaxVGPR = -1; 619 int32_t MaxSGPR = -1; 620 uint64_t CalleeFrameSize = 0; 621 622 for (const MachineBasicBlock &MBB : MF) { 623 for (const MachineInstr &MI : MBB) { 624 // TODO: Check regmasks? Do they occur anywhere except calls? 625 for (const MachineOperand &MO : MI.operands()) { 626 unsigned Width = 0; 627 bool IsSGPR = false; 628 629 if (!MO.isReg()) 630 continue; 631 632 unsigned Reg = MO.getReg(); 633 switch (Reg) { 634 case AMDGPU::EXEC: 635 case AMDGPU::EXEC_LO: 636 case AMDGPU::EXEC_HI: 637 case AMDGPU::SCC: 638 case AMDGPU::M0: 639 case AMDGPU::SRC_SHARED_BASE: 640 case AMDGPU::SRC_SHARED_LIMIT: 641 case AMDGPU::SRC_PRIVATE_BASE: 642 case AMDGPU::SRC_PRIVATE_LIMIT: 643 case AMDGPU::SGPR_NULL: 644 continue; 645 646 case AMDGPU::SRC_POPS_EXITING_WAVE_ID: 647 llvm_unreachable("src_pops_exiting_wave_id should not be used"); 648 649 case AMDGPU::NoRegister: 650 assert(MI.isDebugInstr()); 651 continue; 652 653 case AMDGPU::VCC: 654 case AMDGPU::VCC_LO: 655 case AMDGPU::VCC_HI: 656 Info.UsesVCC = true; 657 continue; 658 659 case AMDGPU::FLAT_SCR: 660 case AMDGPU::FLAT_SCR_LO: 661 case AMDGPU::FLAT_SCR_HI: 662 continue; 663 664 case AMDGPU::XNACK_MASK: 665 case AMDGPU::XNACK_MASK_LO: 666 case AMDGPU::XNACK_MASK_HI: 667 llvm_unreachable("xnack_mask registers should not be used"); 668 669 case AMDGPU::LDS_DIRECT: 670 llvm_unreachable("lds_direct register should not be used"); 671 672 case AMDGPU::TBA: 673 case AMDGPU::TBA_LO: 674 case AMDGPU::TBA_HI: 675 case AMDGPU::TMA: 676 case AMDGPU::TMA_LO: 677 case AMDGPU::TMA_HI: 678 llvm_unreachable("trap handler registers should not be used"); 679 680 default: 681 break; 682 } 683 684 if (AMDGPU::SReg_32RegClass.contains(Reg)) { 685 assert(!AMDGPU::TTMP_32RegClass.contains(Reg) && 686 "trap handler registers should not be used"); 687 IsSGPR = true; 688 Width = 1; 689 } else if (AMDGPU::VGPR_32RegClass.contains(Reg)) { 690 IsSGPR = false; 691 Width = 1; 692 } else if (AMDGPU::SReg_64RegClass.contains(Reg)) { 693 assert(!AMDGPU::TTMP_64RegClass.contains(Reg) && 694 "trap handler registers should not be used"); 695 IsSGPR = true; 696 Width = 2; 697 } else if (AMDGPU::VReg_64RegClass.contains(Reg)) { 698 IsSGPR = false; 699 Width = 2; 700 } else if (AMDGPU::VReg_96RegClass.contains(Reg)) { 701 IsSGPR = false; 702 Width = 3; 703 } else if (AMDGPU::SReg_128RegClass.contains(Reg)) { 704 assert(!AMDGPU::TTMP_128RegClass.contains(Reg) && 705 "trap handler registers should not be used"); 706 IsSGPR = true; 707 Width = 4; 708 } else if (AMDGPU::VReg_128RegClass.contains(Reg)) { 709 IsSGPR = false; 710 Width = 4; 711 } else if (AMDGPU::SReg_256RegClass.contains(Reg)) { 712 assert(!AMDGPU::TTMP_256RegClass.contains(Reg) && 713 "trap handler registers should not be used"); 714 IsSGPR = true; 715 Width = 8; 716 } else if (AMDGPU::VReg_256RegClass.contains(Reg)) { 717 IsSGPR = false; 718 Width = 8; 719 } else if (AMDGPU::SReg_512RegClass.contains(Reg)) { 720 assert(!AMDGPU::TTMP_512RegClass.contains(Reg) && 721 "trap handler registers should not be used"); 722 IsSGPR = true; 723 Width = 16; 724 } else if (AMDGPU::VReg_512RegClass.contains(Reg)) { 725 IsSGPR = false; 726 Width = 16; 727 } else if (AMDGPU::SReg_96RegClass.contains(Reg)) { 728 IsSGPR = true; 729 Width = 3; 730 } else { 731 llvm_unreachable("Unknown register class"); 732 } 733 unsigned HWReg = TRI.getHWRegIndex(Reg); 734 int MaxUsed = HWReg + Width - 1; 735 if (IsSGPR) { 736 MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR; 737 } else { 738 MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR; 739 } 740 } 741 742 if (MI.isCall()) { 743 // Pseudo used just to encode the underlying global. Is there a better 744 // way to track this? 745 746 const MachineOperand *CalleeOp 747 = TII->getNamedOperand(MI, AMDGPU::OpName::callee); 748 const Function *Callee = cast<Function>(CalleeOp->getGlobal()); 749 if (Callee->isDeclaration()) { 750 // If this is a call to an external function, we can't do much. Make 751 // conservative guesses. 752 753 // 48 SGPRs - vcc, - flat_scr, -xnack 754 int MaxSGPRGuess = 755 47 - IsaInfo::getNumExtraSGPRs(&ST, true, ST.hasFlatAddressSpace()); 756 MaxSGPR = std::max(MaxSGPR, MaxSGPRGuess); 757 MaxVGPR = std::max(MaxVGPR, 23); 758 759 CalleeFrameSize = std::max(CalleeFrameSize, UINT64_C(16384)); 760 Info.UsesVCC = true; 761 Info.UsesFlatScratch = ST.hasFlatAddressSpace(); 762 Info.HasDynamicallySizedStack = true; 763 } else { 764 // We force CodeGen to run in SCC order, so the callee's register 765 // usage etc. should be the cumulative usage of all callees. 766 767 auto I = CallGraphResourceInfo.find(Callee); 768 if (I == CallGraphResourceInfo.end()) { 769 // Avoid crashing on undefined behavior with an illegal call to a 770 // kernel. If a callsite's calling convention doesn't match the 771 // function's, it's undefined behavior. If the callsite calling 772 // convention does match, that would have errored earlier. 773 // FIXME: The verifier shouldn't allow this. 774 if (AMDGPU::isEntryFunctionCC(Callee->getCallingConv())) 775 report_fatal_error("invalid call to entry function"); 776 777 llvm_unreachable("callee should have been handled before caller"); 778 } 779 780 MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR); 781 MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR); 782 CalleeFrameSize 783 = std::max(I->second.PrivateSegmentSize, CalleeFrameSize); 784 Info.UsesVCC |= I->second.UsesVCC; 785 Info.UsesFlatScratch |= I->second.UsesFlatScratch; 786 Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack; 787 Info.HasRecursion |= I->second.HasRecursion; 788 } 789 790 if (!Callee->doesNotRecurse()) 791 Info.HasRecursion = true; 792 } 793 } 794 } 795 796 Info.NumExplicitSGPR = MaxSGPR + 1; 797 Info.NumVGPR = MaxVGPR + 1; 798 Info.PrivateSegmentSize += CalleeFrameSize; 799 800 return Info; 801 } 802 803 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo, 804 const MachineFunction &MF) { 805 SIFunctionResourceInfo Info = analyzeResourceUsage(MF); 806 807 ProgInfo.NumVGPR = Info.NumVGPR; 808 ProgInfo.NumSGPR = Info.NumExplicitSGPR; 809 ProgInfo.ScratchSize = Info.PrivateSegmentSize; 810 ProgInfo.VCCUsed = Info.UsesVCC; 811 ProgInfo.FlatUsed = Info.UsesFlatScratch; 812 ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion; 813 814 if (!isUInt<32>(ProgInfo.ScratchSize)) { 815 DiagnosticInfoStackSize DiagStackSize(MF.getFunction(), 816 ProgInfo.ScratchSize, DS_Error); 817 MF.getFunction().getContext().diagnose(DiagStackSize); 818 } 819 820 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 821 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 822 823 // TODO(scott.linder): The calculations related to SGPR/VGPR blocks are 824 // duplicated in part in AMDGPUAsmParser::calculateGPRBlocks, and could be 825 // unified. 826 unsigned ExtraSGPRs = IsaInfo::getNumExtraSGPRs( 827 &STM, ProgInfo.VCCUsed, ProgInfo.FlatUsed); 828 829 // Check the addressable register limit before we add ExtraSGPRs. 830 if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS && 831 !STM.hasSGPRInitBug()) { 832 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 833 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 834 // This can happen due to a compiler bug or when using inline asm. 835 LLVMContext &Ctx = MF.getFunction().getContext(); 836 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 837 "addressable scalar registers", 838 ProgInfo.NumSGPR, DS_Error, 839 DK_ResourceLimit, 840 MaxAddressableNumSGPRs); 841 Ctx.diagnose(Diag); 842 ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1; 843 } 844 } 845 846 // Account for extra SGPRs and VGPRs reserved for debugger use. 847 ProgInfo.NumSGPR += ExtraSGPRs; 848 849 // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave 850 // dispatch registers are function args. 851 unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0; 852 for (auto &Arg : MF.getFunction().args()) { 853 unsigned NumRegs = (Arg.getType()->getPrimitiveSizeInBits() + 31) / 32; 854 if (Arg.hasAttribute(Attribute::InReg)) 855 WaveDispatchNumSGPR += NumRegs; 856 else 857 WaveDispatchNumVGPR += NumRegs; 858 } 859 ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR); 860 ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR); 861 862 // Adjust number of registers used to meet default/requested minimum/maximum 863 // number of waves per execution unit request. 864 ProgInfo.NumSGPRsForWavesPerEU = std::max( 865 std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU())); 866 ProgInfo.NumVGPRsForWavesPerEU = std::max( 867 std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU())); 868 869 if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS || 870 STM.hasSGPRInitBug()) { 871 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 872 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 873 // This can happen due to a compiler bug or when using inline asm to use 874 // the registers which are usually reserved for vcc etc. 875 LLVMContext &Ctx = MF.getFunction().getContext(); 876 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 877 "scalar registers", 878 ProgInfo.NumSGPR, DS_Error, 879 DK_ResourceLimit, 880 MaxAddressableNumSGPRs); 881 Ctx.diagnose(Diag); 882 ProgInfo.NumSGPR = MaxAddressableNumSGPRs; 883 ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs; 884 } 885 } 886 887 if (STM.hasSGPRInitBug()) { 888 ProgInfo.NumSGPR = 889 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 890 ProgInfo.NumSGPRsForWavesPerEU = 891 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 892 } 893 894 if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) { 895 LLVMContext &Ctx = MF.getFunction().getContext(); 896 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs", 897 MFI->getNumUserSGPRs(), DS_Error); 898 Ctx.diagnose(Diag); 899 } 900 901 if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) { 902 LLVMContext &Ctx = MF.getFunction().getContext(); 903 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory", 904 MFI->getLDSSize(), DS_Error); 905 Ctx.diagnose(Diag); 906 } 907 908 ProgInfo.SGPRBlocks = IsaInfo::getNumSGPRBlocks( 909 &STM, ProgInfo.NumSGPRsForWavesPerEU); 910 ProgInfo.VGPRBlocks = IsaInfo::getNumVGPRBlocks( 911 &STM, ProgInfo.NumVGPRsForWavesPerEU); 912 913 // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode 914 // register. 915 ProgInfo.FloatMode = getFPMode(MF); 916 917 const SIModeRegisterDefaults Mode = MFI->getMode(); 918 ProgInfo.IEEEMode = Mode.IEEE; 919 920 // Make clamp modifier on NaN input returns 0. 921 ProgInfo.DX10Clamp = Mode.DX10Clamp; 922 923 unsigned LDSAlignShift; 924 if (STM.getGeneration() < AMDGPUSubtarget::SEA_ISLANDS) { 925 // LDS is allocated in 64 dword blocks. 926 LDSAlignShift = 8; 927 } else { 928 // LDS is allocated in 128 dword blocks. 929 LDSAlignShift = 9; 930 } 931 932 unsigned LDSSpillSize = 933 MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize(); 934 935 ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize; 936 ProgInfo.LDSBlocks = 937 alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift; 938 939 // Scratch is allocated in 256 dword blocks. 940 unsigned ScratchAlignShift = 10; 941 // We need to program the hardware with the amount of scratch memory that 942 // is used by the entire wave. ProgInfo.ScratchSize is the amount of 943 // scratch memory used per thread. 944 ProgInfo.ScratchBlocks = 945 alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(), 946 1ULL << ScratchAlignShift) >> 947 ScratchAlignShift; 948 949 if (getIsaVersion(getGlobalSTI()->getCPU()).Major >= 10) { 950 ProgInfo.WgpMode = STM.isCuModeEnabled() ? 0 : 1; 951 ProgInfo.MemOrdered = 1; 952 } 953 954 ProgInfo.ComputePGMRSrc1 = 955 S_00B848_VGPRS(ProgInfo.VGPRBlocks) | 956 S_00B848_SGPRS(ProgInfo.SGPRBlocks) | 957 S_00B848_PRIORITY(ProgInfo.Priority) | 958 S_00B848_FLOAT_MODE(ProgInfo.FloatMode) | 959 S_00B848_PRIV(ProgInfo.Priv) | 960 S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) | 961 S_00B848_DEBUG_MODE(ProgInfo.DebugMode) | 962 S_00B848_IEEE_MODE(ProgInfo.IEEEMode) | 963 S_00B848_WGP_MODE(ProgInfo.WgpMode) | 964 S_00B848_MEM_ORDERED(ProgInfo.MemOrdered); 965 966 // 0 = X, 1 = XY, 2 = XYZ 967 unsigned TIDIGCompCnt = 0; 968 if (MFI->hasWorkItemIDZ()) 969 TIDIGCompCnt = 2; 970 else if (MFI->hasWorkItemIDY()) 971 TIDIGCompCnt = 1; 972 973 ProgInfo.ComputePGMRSrc2 = 974 S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) | 975 S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) | 976 // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP. 977 S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) | 978 S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) | 979 S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) | 980 S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) | 981 S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) | 982 S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) | 983 S_00B84C_EXCP_EN_MSB(0) | 984 // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP. 985 S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) | 986 S_00B84C_EXCP_EN(0); 987 } 988 989 static unsigned getRsrcReg(CallingConv::ID CallConv) { 990 switch (CallConv) { 991 default: LLVM_FALLTHROUGH; 992 case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1; 993 case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS; 994 case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS; 995 case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES; 996 case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS; 997 case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS; 998 case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS; 999 } 1000 } 1001 1002 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF, 1003 const SIProgramInfo &CurrentProgramInfo) { 1004 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1005 unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv()); 1006 1007 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 1008 OutStreamer->EmitIntValue(R_00B848_COMPUTE_PGM_RSRC1, 4); 1009 1010 OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc1, 4); 1011 1012 OutStreamer->EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4); 1013 OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc2, 4); 1014 1015 OutStreamer->EmitIntValue(R_00B860_COMPUTE_TMPRING_SIZE, 4); 1016 OutStreamer->EmitIntValue(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 1017 1018 // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 = 1019 // 0" comment but I don't see a corresponding field in the register spec. 1020 } else { 1021 OutStreamer->EmitIntValue(RsrcReg, 4); 1022 OutStreamer->EmitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 1023 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4); 1024 OutStreamer->EmitIntValue(R_0286E8_SPI_TMPRING_SIZE, 4); 1025 OutStreamer->EmitIntValue( 1026 S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 1027 } 1028 1029 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1030 OutStreamer->EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4); 1031 OutStreamer->EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks), 4); 1032 OutStreamer->EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4); 1033 OutStreamer->EmitIntValue(MFI->getPSInputEnable(), 4); 1034 OutStreamer->EmitIntValue(R_0286D0_SPI_PS_INPUT_ADDR, 4); 1035 OutStreamer->EmitIntValue(MFI->getPSInputAddr(), 4); 1036 } 1037 1038 OutStreamer->EmitIntValue(R_SPILLED_SGPRS, 4); 1039 OutStreamer->EmitIntValue(MFI->getNumSpilledSGPRs(), 4); 1040 OutStreamer->EmitIntValue(R_SPILLED_VGPRS, 4); 1041 OutStreamer->EmitIntValue(MFI->getNumSpilledVGPRs(), 4); 1042 } 1043 1044 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type 1045 // is AMDPAL. It stores each compute/SPI register setting and other PAL 1046 // metadata items into the PALMD::Metadata, combining with any provided by the 1047 // frontend as LLVM metadata. Once all functions are written, the PAL metadata 1048 // is then written as a single block in the .note section. 1049 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF, 1050 const SIProgramInfo &CurrentProgramInfo) { 1051 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1052 auto CC = MF.getFunction().getCallingConv(); 1053 auto MD = getTargetStreamer()->getPALMetadata(); 1054 1055 MD->setEntryPoint(CC, MF.getFunction().getName()); 1056 MD->setNumUsedVgprs(CC, CurrentProgramInfo.NumVGPRsForWavesPerEU); 1057 MD->setNumUsedSgprs(CC, CurrentProgramInfo.NumSGPRsForWavesPerEU); 1058 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 1059 MD->setRsrc1(CC, CurrentProgramInfo.ComputePGMRSrc1); 1060 MD->setRsrc2(CC, CurrentProgramInfo.ComputePGMRSrc2); 1061 } else { 1062 MD->setRsrc1(CC, S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 1063 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks)); 1064 if (CurrentProgramInfo.ScratchBlocks > 0) 1065 MD->setRsrc2(CC, S_00B84C_SCRATCH_EN(1)); 1066 } 1067 // ScratchSize is in bytes, 16 aligned. 1068 MD->setScratchSize(CC, alignTo(CurrentProgramInfo.ScratchSize, 16)); 1069 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1070 MD->setRsrc2(CC, S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks)); 1071 MD->setSpiPsInputEna(MFI->getPSInputEnable()); 1072 MD->setSpiPsInputAddr(MFI->getPSInputAddr()); 1073 } 1074 } 1075 1076 // This is supposed to be log2(Size) 1077 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) { 1078 switch (Size) { 1079 case 4: 1080 return AMD_ELEMENT_4_BYTES; 1081 case 8: 1082 return AMD_ELEMENT_8_BYTES; 1083 case 16: 1084 return AMD_ELEMENT_16_BYTES; 1085 default: 1086 llvm_unreachable("invalid private_element_size"); 1087 } 1088 } 1089 1090 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out, 1091 const SIProgramInfo &CurrentProgramInfo, 1092 const MachineFunction &MF) const { 1093 const Function &F = MF.getFunction(); 1094 assert(F.getCallingConv() == CallingConv::AMDGPU_KERNEL || 1095 F.getCallingConv() == CallingConv::SPIR_KERNEL); 1096 1097 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1098 const GCNSubtarget &STM = MF.getSubtarget<GCNSubtarget>(); 1099 1100 AMDGPU::initDefaultAMDKernelCodeT(Out, &STM); 1101 1102 Out.compute_pgm_resource_registers = 1103 CurrentProgramInfo.ComputePGMRSrc1 | 1104 (CurrentProgramInfo.ComputePGMRSrc2 << 32); 1105 Out.code_properties |= AMD_CODE_PROPERTY_IS_PTR64; 1106 1107 if (CurrentProgramInfo.DynamicCallStack) 1108 Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK; 1109 1110 AMD_HSA_BITS_SET(Out.code_properties, 1111 AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE, 1112 getElementByteSizeValue(STM.getMaxPrivateElementSize())); 1113 1114 if (MFI->hasPrivateSegmentBuffer()) { 1115 Out.code_properties |= 1116 AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 1117 } 1118 1119 if (MFI->hasDispatchPtr()) 1120 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1121 1122 if (MFI->hasQueuePtr()) 1123 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 1124 1125 if (MFI->hasKernargSegmentPtr()) 1126 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 1127 1128 if (MFI->hasDispatchID()) 1129 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 1130 1131 if (MFI->hasFlatScratchInit()) 1132 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 1133 1134 if (MFI->hasDispatchPtr()) 1135 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1136 1137 if (STM.isXNACKEnabled()) 1138 Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED; 1139 1140 unsigned MaxKernArgAlign; 1141 Out.kernarg_segment_byte_size = STM.getKernArgSegmentSize(F, MaxKernArgAlign); 1142 Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR; 1143 Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR; 1144 Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize; 1145 Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize; 1146 1147 // These alignment values are specified in powers of two, so alignment = 1148 // 2^n. The minimum alignment is 2^4 = 16. 1149 Out.kernarg_segment_alignment = std::max((size_t)4, 1150 countTrailingZeros(MaxKernArgAlign)); 1151 } 1152 1153 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1154 const char *ExtraCode, raw_ostream &O) { 1155 // First try the generic code, which knows about modifiers like 'c' and 'n'. 1156 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, ExtraCode, O)) 1157 return false; 1158 1159 if (ExtraCode && ExtraCode[0]) { 1160 if (ExtraCode[1] != 0) 1161 return true; // Unknown modifier. 1162 1163 switch (ExtraCode[0]) { 1164 case 'r': 1165 break; 1166 default: 1167 return true; 1168 } 1169 } 1170 1171 // TODO: Should be able to support other operand types like globals. 1172 const MachineOperand &MO = MI->getOperand(OpNo); 1173 if (MO.isReg()) { 1174 AMDGPUInstPrinter::printRegOperand(MO.getReg(), O, 1175 *MF->getSubtarget().getRegisterInfo()); 1176 return false; 1177 } 1178 1179 return true; 1180 } 1181