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