1 //===-- AMDGPUAsmPrinter.cpp - AMDGPU Assebly printer --------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 /// \file 11 /// 12 /// The AMDGPUAsmPrinter is used to print both assembly string and also binary 13 /// code. When passed an MCAsmStreamer it prints assembly and when passed 14 /// an MCObjectStreamer it outputs binary code. 15 // 16 //===----------------------------------------------------------------------===// 17 // 18 19 #include "AMDGPUAsmPrinter.h" 20 #include "AMDGPU.h" 21 #include "AMDGPUSubtarget.h" 22 #include "AMDGPUTargetMachine.h" 23 #include "InstPrinter/AMDGPUInstPrinter.h" 24 #include "MCTargetDesc/AMDGPUMCTargetDesc.h" 25 #include "MCTargetDesc/AMDGPUTargetStreamer.h" 26 #include "R600AsmPrinter.h" 27 #include "R600Defines.h" 28 #include "R600MachineFunctionInfo.h" 29 #include "R600RegisterInfo.h" 30 #include "SIDefines.h" 31 #include "SIInstrInfo.h" 32 #include "SIMachineFunctionInfo.h" 33 #include "SIRegisterInfo.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/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/TargetRegistry.h" 44 #include "llvm/Target/TargetLoweringObjectFile.h" 45 46 using namespace llvm; 47 using namespace llvm::AMDGPU; 48 49 // TODO: This should get the default rounding mode from the kernel. We just set 50 // the default here, but this could change if the OpenCL rounding mode pragmas 51 // are used. 52 // 53 // The denormal mode here should match what is reported by the OpenCL runtime 54 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but 55 // can also be override to flush with the -cl-denorms-are-zero compiler flag. 56 // 57 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double 58 // precision, and leaves single precision to flush all and does not report 59 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports 60 // CL_FP_DENORM for both. 61 // 62 // FIXME: It seems some instructions do not support single precision denormals 63 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32, 64 // and sin_f32, cos_f32 on most parts). 65 66 // We want to use these instructions, and using fp32 denormals also causes 67 // instructions to run at the double precision rate for the device so it's 68 // probably best to just report no single precision denormals. 69 static uint32_t getFPMode(const MachineFunction &F) { 70 const SISubtarget& ST = F.getSubtarget<SISubtarget>(); 71 // TODO: Is there any real use for the flush in only / flush out only modes? 72 73 uint32_t FP32Denormals = 74 ST.hasFP32Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT; 75 76 uint32_t FP64Denormals = 77 ST.hasFP64Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT; 78 79 return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) | 80 FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) | 81 FP_DENORM_MODE_SP(FP32Denormals) | 82 FP_DENORM_MODE_DP(FP64Denormals); 83 } 84 85 static AsmPrinter * 86 createAMDGPUAsmPrinterPass(TargetMachine &tm, 87 std::unique_ptr<MCStreamer> &&Streamer) { 88 return new AMDGPUAsmPrinter(tm, std::move(Streamer)); 89 } 90 91 extern "C" void LLVMInitializeAMDGPUAsmPrinter() { 92 TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(), 93 llvm::createR600AsmPrinterPass); 94 TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(), 95 createAMDGPUAsmPrinterPass); 96 } 97 98 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM, 99 std::unique_ptr<MCStreamer> Streamer) 100 : AsmPrinter(TM, std::move(Streamer)) { 101 AMDGPUASI = static_cast<AMDGPUTargetMachine*>(&TM)->getAMDGPUAS(); 102 } 103 104 StringRef AMDGPUAsmPrinter::getPassName() const { 105 return "AMDGPU Assembly Printer"; 106 } 107 108 const MCSubtargetInfo* AMDGPUAsmPrinter::getSTI() const { 109 return TM.getMCSubtargetInfo(); 110 } 111 112 AMDGPUTargetStreamer* AMDGPUAsmPrinter::getTargetStreamer() const { 113 if (!OutStreamer) 114 return nullptr; 115 return static_cast<AMDGPUTargetStreamer*>(OutStreamer->getTargetStreamer()); 116 } 117 118 void AMDGPUAsmPrinter::EmitStartOfAsmFile(Module &M) { 119 if (IsaInfo::hasCodeObjectV3(getSTI()) && 120 TM.getTargetTriple().getOS() == Triple::AMDHSA) 121 return; 122 123 if (TM.getTargetTriple().getOS() != Triple::AMDHSA && 124 TM.getTargetTriple().getOS() != Triple::AMDPAL) 125 return; 126 127 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) 128 HSAMetadataStream.begin(M); 129 130 if (TM.getTargetTriple().getOS() == Triple::AMDPAL) 131 readPALMetadata(M); 132 133 // HSA emits NT_AMDGPU_HSA_CODE_OBJECT_VERSION for code objects v2. 134 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) 135 getTargetStreamer()->EmitDirectiveHSACodeObjectVersion(2, 1); 136 137 // HSA and PAL emit NT_AMDGPU_HSA_ISA for code objects v2. 138 IsaInfo::IsaVersion ISA = IsaInfo::getIsaVersion(getSTI()->getFeatureBits()); 139 getTargetStreamer()->EmitDirectiveHSACodeObjectISA( 140 ISA.Major, ISA.Minor, ISA.Stepping, "AMD", "AMDGPU"); 141 } 142 143 void AMDGPUAsmPrinter::EmitEndOfAsmFile(Module &M) { 144 // TODO: Add metadata to code object v3. 145 if (IsaInfo::hasCodeObjectV3(getSTI()) && 146 TM.getTargetTriple().getOS() == Triple::AMDHSA) 147 return; 148 149 // Following code requires TargetStreamer to be present. 150 if (!getTargetStreamer()) 151 return; 152 153 // Emit ISA Version (NT_AMD_AMDGPU_ISA). 154 std::string ISAVersionString; 155 raw_string_ostream ISAVersionStream(ISAVersionString); 156 IsaInfo::streamIsaVersion(getSTI(), ISAVersionStream); 157 getTargetStreamer()->EmitISAVersion(ISAVersionStream.str()); 158 159 // Emit HSA Metadata (NT_AMD_AMDGPU_HSA_METADATA). 160 if (TM.getTargetTriple().getOS() == Triple::AMDHSA) { 161 HSAMetadataStream.end(); 162 getTargetStreamer()->EmitHSAMetadata(HSAMetadataStream.getHSAMetadata()); 163 } 164 165 // Emit PAL Metadata (NT_AMD_AMDGPU_PAL_METADATA). 166 if (TM.getTargetTriple().getOS() == Triple::AMDPAL) { 167 // Copy the PAL metadata from the map where we collected it into a vector, 168 // then write it as a .note. 169 PALMD::Metadata PALMetadataVector; 170 for (auto i : PALMetadataMap) { 171 PALMetadataVector.push_back(i.first); 172 PALMetadataVector.push_back(i.second); 173 } 174 getTargetStreamer()->EmitPALMetadata(PALMetadataVector); 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 if (IsaInfo::hasCodeObjectV3(getSTI()) && 197 TM.getTargetTriple().getOS() == Triple::AMDHSA) 198 return; 199 200 const AMDGPUSubtarget &STM = MF->getSubtarget<AMDGPUSubtarget>(); 201 amd_kernel_code_t KernelCode; 202 if (STM.isAmdCodeObjectV2(MF->getFunction())) { 203 getAmdKernelCode(KernelCode, CurrentProgramInfo, *MF); 204 getTargetStreamer()->EmitAMDKernelCodeT(KernelCode); 205 } 206 207 if (TM.getTargetTriple().getOS() != Triple::AMDHSA) 208 return; 209 210 HSAMetadataStream.emitKernel(MF->getFunction(), 211 getHSACodeProps(*MF, CurrentProgramInfo), 212 getHSADebugProps(*MF, CurrentProgramInfo)); 213 } 214 215 void AMDGPUAsmPrinter::EmitFunctionBodyEnd() { 216 const SIMachineFunctionInfo &MFI = *MF->getInfo<SIMachineFunctionInfo>(); 217 if (!MFI.isEntryFunction()) 218 return; 219 if (!IsaInfo::hasCodeObjectV3(getSTI()) || 220 TM.getTargetTriple().getOS() != Triple::AMDHSA) 221 return; 222 223 auto &Streamer = getTargetStreamer()->getStreamer(); 224 auto &Context = Streamer.getContext(); 225 auto &ObjectFileInfo = *Context.getObjectFileInfo(); 226 auto &ReadOnlySection = *ObjectFileInfo.getReadOnlySection(); 227 228 Streamer.PushSection(); 229 Streamer.SwitchSection(&ReadOnlySection); 230 231 // CP microcode requires the kernel descriptor to be allocated on 64 byte 232 // alignment. 233 Streamer.EmitValueToAlignment(64, 0, 1, 0); 234 if (ReadOnlySection.getAlignment() < 64) 235 ReadOnlySection.setAlignment(64); 236 237 SmallString<128> KernelName; 238 getNameWithPrefix(KernelName, &MF->getFunction()); 239 getTargetStreamer()->EmitAmdhsaKernelDescriptor( 240 KernelName, getAmdhsaKernelDescriptor(*MF, CurrentProgramInfo)); 241 242 Streamer.PopSection(); 243 } 244 245 void AMDGPUAsmPrinter::EmitFunctionEntryLabel() { 246 if (IsaInfo::hasCodeObjectV3(getSTI()) && 247 TM.getTargetTriple().getOS() == Triple::AMDHSA) { 248 AsmPrinter::EmitFunctionEntryLabel(); 249 return; 250 } 251 252 const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>(); 253 const AMDGPUSubtarget &STM = MF->getSubtarget<AMDGPUSubtarget>(); 254 if (MFI->isEntryFunction() && STM.isAmdCodeObjectV2(MF->getFunction())) { 255 SmallString<128> SymbolName; 256 getNameWithPrefix(SymbolName, &MF->getFunction()), 257 getTargetStreamer()->EmitAMDGPUSymbolType( 258 SymbolName, ELF::STT_AMDGPU_HSA_KERNEL); 259 } 260 const AMDGPUSubtarget &STI = MF->getSubtarget<AMDGPUSubtarget>(); 261 if (STI.dumpCode()) { 262 // Disassemble function name label to text. 263 DisasmLines.push_back(MF->getName().str() + ":"); 264 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size()); 265 HexLines.push_back(""); 266 } 267 268 AsmPrinter::EmitFunctionEntryLabel(); 269 } 270 271 void AMDGPUAsmPrinter::EmitBasicBlockStart(const MachineBasicBlock &MBB) const { 272 const AMDGPUSubtarget &STI = MBB.getParent()->getSubtarget<AMDGPUSubtarget>(); 273 if (STI.dumpCode() && !isBlockOnlyReachableByFallthrough(&MBB)) { 274 // Write a line for the basic block label if it is not only fallthrough. 275 DisasmLines.push_back( 276 (Twine("BB") + Twine(getFunctionNumber()) 277 + "_" + Twine(MBB.getNumber()) + ":").str()); 278 DisasmLineMaxLen = std::max(DisasmLineMaxLen, DisasmLines.back().size()); 279 HexLines.push_back(""); 280 } 281 AsmPrinter::EmitBasicBlockStart(MBB); 282 } 283 284 void AMDGPUAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) { 285 286 // Group segment variables aren't emitted in HSA. 287 if (AMDGPU::isGroupSegment(GV)) 288 return; 289 290 AsmPrinter::EmitGlobalVariable(GV); 291 } 292 293 bool AMDGPUAsmPrinter::doFinalization(Module &M) { 294 CallGraphResourceInfo.clear(); 295 return AsmPrinter::doFinalization(M); 296 } 297 298 // For the amdpal OS type, read the amdgpu.pal.metadata supplied by the 299 // frontend into our PALMetadataMap, ready for per-function modification. It 300 // is a NamedMD containing an MDTuple containing a number of MDNodes each of 301 // which is an integer value, and each two integer values forms a key=value 302 // pair that we store as PALMetadataMap[key]=value in the map. 303 void AMDGPUAsmPrinter::readPALMetadata(Module &M) { 304 auto NamedMD = M.getNamedMetadata("amdgpu.pal.metadata"); 305 if (!NamedMD || !NamedMD->getNumOperands()) 306 return; 307 auto Tuple = dyn_cast<MDTuple>(NamedMD->getOperand(0)); 308 if (!Tuple) 309 return; 310 for (unsigned I = 0, E = Tuple->getNumOperands() & -2; I != E; I += 2) { 311 auto Key = mdconst::dyn_extract<ConstantInt>(Tuple->getOperand(I)); 312 auto Val = mdconst::dyn_extract<ConstantInt>(Tuple->getOperand(I + 1)); 313 if (!Key || !Val) 314 continue; 315 PALMetadataMap[Key->getZExtValue()] = Val->getZExtValue(); 316 } 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 if (MFI.hasGridWorkgroupCountX()) { 364 KernelCodeProperties |= 365 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_X; 366 } 367 if (MFI.hasGridWorkgroupCountY()) { 368 KernelCodeProperties |= 369 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Y; 370 } 371 if (MFI.hasGridWorkgroupCountZ()) { 372 KernelCodeProperties |= 373 amdhsa::KERNEL_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Z; 374 } 375 376 return KernelCodeProperties; 377 } 378 379 amdhsa::kernel_descriptor_t AMDGPUAsmPrinter::getAmdhsaKernelDescriptor( 380 const MachineFunction &MF, 381 const SIProgramInfo &PI) const { 382 amdhsa::kernel_descriptor_t KernelDescriptor; 383 memset(&KernelDescriptor, 0x0, sizeof(KernelDescriptor)); 384 385 assert(isUInt<32>(PI.ScratchSize)); 386 assert(isUInt<32>(PI.ComputePGMRSrc1)); 387 assert(isUInt<32>(PI.ComputePGMRSrc2)); 388 389 KernelDescriptor.group_segment_fixed_size = PI.LDSSize; 390 KernelDescriptor.private_segment_fixed_size = PI.ScratchSize; 391 KernelDescriptor.compute_pgm_rsrc1 = PI.ComputePGMRSrc1; 392 KernelDescriptor.compute_pgm_rsrc2 = PI.ComputePGMRSrc2; 393 KernelDescriptor.kernel_code_properties = getAmdhsaKernelCodeProperties(MF); 394 395 return KernelDescriptor; 396 } 397 398 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) { 399 CurrentProgramInfo = SIProgramInfo(); 400 401 const AMDGPUMachineFunction *MFI = MF.getInfo<AMDGPUMachineFunction>(); 402 403 // The starting address of all shader programs must be 256 bytes aligned. 404 // Regular functions just need the basic required instruction alignment. 405 MF.setAlignment(MFI->isEntryFunction() ? 8 : 2); 406 407 SetupMachineFunction(MF); 408 409 const AMDGPUSubtarget &STM = MF.getSubtarget<AMDGPUSubtarget>(); 410 MCContext &Context = getObjFileLowering().getContext(); 411 // FIXME: This should be an explicit check for Mesa. 412 if (!STM.isAmdHsaOS() && !STM.isAmdPalOS()) { 413 MCSectionELF *ConfigSection = 414 Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0); 415 OutStreamer->SwitchSection(ConfigSection); 416 } 417 418 if (MFI->isEntryFunction()) { 419 getSIProgramInfo(CurrentProgramInfo, MF); 420 } else { 421 auto I = CallGraphResourceInfo.insert( 422 std::make_pair(&MF.getFunction(), SIFunctionResourceInfo())); 423 SIFunctionResourceInfo &Info = I.first->second; 424 assert(I.second && "should only be called once per function"); 425 Info = analyzeResourceUsage(MF); 426 } 427 428 if (STM.isAmdPalOS()) 429 EmitPALMetadata(MF, CurrentProgramInfo); 430 else if (!STM.isAmdHsaOS()) { 431 EmitProgramInfoSI(MF, CurrentProgramInfo); 432 } 433 434 DisasmLines.clear(); 435 HexLines.clear(); 436 DisasmLineMaxLen = 0; 437 438 EmitFunctionBody(); 439 440 if (isVerbose()) { 441 MCSectionELF *CommentSection = 442 Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0); 443 OutStreamer->SwitchSection(CommentSection); 444 445 if (!MFI->isEntryFunction()) { 446 OutStreamer->emitRawComment(" Function info:", false); 447 SIFunctionResourceInfo &Info = CallGraphResourceInfo[&MF.getFunction()]; 448 emitCommonFunctionComments( 449 Info.NumVGPR, 450 Info.getTotalNumSGPRs(MF.getSubtarget<SISubtarget>()), 451 Info.PrivateSegmentSize, 452 getFunctionCodeSize(MF), MFI); 453 return false; 454 } 455 456 OutStreamer->emitRawComment(" Kernel info:", false); 457 emitCommonFunctionComments(CurrentProgramInfo.NumVGPR, 458 CurrentProgramInfo.NumSGPR, 459 CurrentProgramInfo.ScratchSize, 460 getFunctionCodeSize(MF), MFI); 461 462 OutStreamer->emitRawComment( 463 " FloatMode: " + Twine(CurrentProgramInfo.FloatMode), false); 464 OutStreamer->emitRawComment( 465 " IeeeMode: " + Twine(CurrentProgramInfo.IEEEMode), false); 466 OutStreamer->emitRawComment( 467 " LDSByteSize: " + Twine(CurrentProgramInfo.LDSSize) + 468 " bytes/workgroup (compile time only)", false); 469 470 OutStreamer->emitRawComment( 471 " SGPRBlocks: " + Twine(CurrentProgramInfo.SGPRBlocks), false); 472 OutStreamer->emitRawComment( 473 " VGPRBlocks: " + Twine(CurrentProgramInfo.VGPRBlocks), false); 474 475 OutStreamer->emitRawComment( 476 " NumSGPRsForWavesPerEU: " + 477 Twine(CurrentProgramInfo.NumSGPRsForWavesPerEU), false); 478 OutStreamer->emitRawComment( 479 " NumVGPRsForWavesPerEU: " + 480 Twine(CurrentProgramInfo.NumVGPRsForWavesPerEU), false); 481 482 OutStreamer->emitRawComment( 483 " ReservedVGPRFirst: " + Twine(CurrentProgramInfo.ReservedVGPRFirst), 484 false); 485 OutStreamer->emitRawComment( 486 " ReservedVGPRCount: " + Twine(CurrentProgramInfo.ReservedVGPRCount), 487 false); 488 489 OutStreamer->emitRawComment( 490 " WaveLimiterHint : " + Twine(MFI->needsWaveLimiter()), false); 491 492 if (MF.getSubtarget<SISubtarget>().debuggerEmitPrologue()) { 493 OutStreamer->emitRawComment( 494 " DebuggerWavefrontPrivateSegmentOffsetSGPR: s" + 495 Twine(CurrentProgramInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR), false); 496 OutStreamer->emitRawComment( 497 " DebuggerPrivateSegmentBufferSGPR: s" + 498 Twine(CurrentProgramInfo.DebuggerPrivateSegmentBufferSGPR), false); 499 } 500 501 OutStreamer->emitRawComment( 502 " COMPUTE_PGM_RSRC2:USER_SGPR: " + 503 Twine(G_00B84C_USER_SGPR(CurrentProgramInfo.ComputePGMRSrc2)), false); 504 OutStreamer->emitRawComment( 505 " COMPUTE_PGM_RSRC2:TRAP_HANDLER: " + 506 Twine(G_00B84C_TRAP_HANDLER(CurrentProgramInfo.ComputePGMRSrc2)), false); 507 OutStreamer->emitRawComment( 508 " COMPUTE_PGM_RSRC2:TGID_X_EN: " + 509 Twine(G_00B84C_TGID_X_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 510 OutStreamer->emitRawComment( 511 " COMPUTE_PGM_RSRC2:TGID_Y_EN: " + 512 Twine(G_00B84C_TGID_Y_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 513 OutStreamer->emitRawComment( 514 " COMPUTE_PGM_RSRC2:TGID_Z_EN: " + 515 Twine(G_00B84C_TGID_Z_EN(CurrentProgramInfo.ComputePGMRSrc2)), false); 516 OutStreamer->emitRawComment( 517 " COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " + 518 Twine(G_00B84C_TIDIG_COMP_CNT(CurrentProgramInfo.ComputePGMRSrc2)), 519 false); 520 } 521 522 if (STM.dumpCode()) { 523 524 OutStreamer->SwitchSection( 525 Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0)); 526 527 for (size_t i = 0; i < DisasmLines.size(); ++i) { 528 std::string Comment = "\n"; 529 if (!HexLines[i].empty()) { 530 Comment = std::string(DisasmLineMaxLen - DisasmLines[i].size(), ' '); 531 Comment += " ; " + HexLines[i] + "\n"; 532 } 533 534 OutStreamer->EmitBytes(StringRef(DisasmLines[i])); 535 OutStreamer->EmitBytes(StringRef(Comment)); 536 } 537 } 538 539 return false; 540 } 541 542 uint64_t AMDGPUAsmPrinter::getFunctionCodeSize(const MachineFunction &MF) const { 543 const SISubtarget &STM = MF.getSubtarget<SISubtarget>(); 544 const SIInstrInfo *TII = STM.getInstrInfo(); 545 546 uint64_t CodeSize = 0; 547 548 for (const MachineBasicBlock &MBB : MF) { 549 for (const MachineInstr &MI : MBB) { 550 // TODO: CodeSize should account for multiple functions. 551 552 // TODO: Should we count size of debug info? 553 if (MI.isDebugInstr()) 554 continue; 555 556 CodeSize += TII->getInstSizeInBytes(MI); 557 } 558 } 559 560 return CodeSize; 561 } 562 563 static bool hasAnyNonFlatUseOfReg(const MachineRegisterInfo &MRI, 564 const SIInstrInfo &TII, 565 unsigned Reg) { 566 for (const MachineOperand &UseOp : MRI.reg_operands(Reg)) { 567 if (!UseOp.isImplicit() || !TII.isFLAT(*UseOp.getParent())) 568 return true; 569 } 570 571 return false; 572 } 573 574 static unsigned getNumExtraSGPRs(const SISubtarget &ST, 575 bool VCCUsed, 576 bool FlatScrUsed) { 577 unsigned ExtraSGPRs = 0; 578 if (VCCUsed) 579 ExtraSGPRs = 2; 580 581 if (ST.getGeneration() < SISubtarget::VOLCANIC_ISLANDS) { 582 if (FlatScrUsed) 583 ExtraSGPRs = 4; 584 } else { 585 if (ST.isXNACKEnabled()) 586 ExtraSGPRs = 4; 587 588 if (FlatScrUsed) 589 ExtraSGPRs = 6; 590 } 591 592 return ExtraSGPRs; 593 } 594 595 int32_t AMDGPUAsmPrinter::SIFunctionResourceInfo::getTotalNumSGPRs( 596 const SISubtarget &ST) const { 597 return NumExplicitSGPR + getNumExtraSGPRs(ST, UsesVCC, UsesFlatScratch); 598 } 599 600 AMDGPUAsmPrinter::SIFunctionResourceInfo AMDGPUAsmPrinter::analyzeResourceUsage( 601 const MachineFunction &MF) const { 602 SIFunctionResourceInfo Info; 603 604 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 605 const SISubtarget &ST = MF.getSubtarget<SISubtarget>(); 606 const MachineFrameInfo &FrameInfo = MF.getFrameInfo(); 607 const MachineRegisterInfo &MRI = MF.getRegInfo(); 608 const SIInstrInfo *TII = ST.getInstrInfo(); 609 const SIRegisterInfo &TRI = TII->getRegisterInfo(); 610 611 Info.UsesFlatScratch = MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_LO) || 612 MRI.isPhysRegUsed(AMDGPU::FLAT_SCR_HI); 613 614 // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat 615 // instructions aren't used to access the scratch buffer. Inline assembly may 616 // need it though. 617 // 618 // If we only have implicit uses of flat_scr on flat instructions, it is not 619 // really needed. 620 if (Info.UsesFlatScratch && !MFI->hasFlatScratchInit() && 621 (!hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR) && 622 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_LO) && 623 !hasAnyNonFlatUseOfReg(MRI, *TII, AMDGPU::FLAT_SCR_HI))) { 624 Info.UsesFlatScratch = false; 625 } 626 627 Info.HasDynamicallySizedStack = FrameInfo.hasVarSizedObjects(); 628 Info.PrivateSegmentSize = FrameInfo.getStackSize(); 629 if (MFI->isStackRealigned()) 630 Info.PrivateSegmentSize += FrameInfo.getMaxAlignment(); 631 632 633 Info.UsesVCC = MRI.isPhysRegUsed(AMDGPU::VCC_LO) || 634 MRI.isPhysRegUsed(AMDGPU::VCC_HI); 635 636 // If there are no calls, MachineRegisterInfo can tell us the used register 637 // count easily. 638 // A tail call isn't considered a call for MachineFrameInfo's purposes. 639 if (!FrameInfo.hasCalls() && !FrameInfo.hasTailCall()) { 640 MCPhysReg HighestVGPRReg = AMDGPU::NoRegister; 641 for (MCPhysReg Reg : reverse(AMDGPU::VGPR_32RegClass.getRegisters())) { 642 if (MRI.isPhysRegUsed(Reg)) { 643 HighestVGPRReg = Reg; 644 break; 645 } 646 } 647 648 MCPhysReg HighestSGPRReg = AMDGPU::NoRegister; 649 for (MCPhysReg Reg : reverse(AMDGPU::SGPR_32RegClass.getRegisters())) { 650 if (MRI.isPhysRegUsed(Reg)) { 651 HighestSGPRReg = Reg; 652 break; 653 } 654 } 655 656 // We found the maximum register index. They start at 0, so add one to get the 657 // number of registers. 658 Info.NumVGPR = HighestVGPRReg == AMDGPU::NoRegister ? 0 : 659 TRI.getHWRegIndex(HighestVGPRReg) + 1; 660 Info.NumExplicitSGPR = HighestSGPRReg == AMDGPU::NoRegister ? 0 : 661 TRI.getHWRegIndex(HighestSGPRReg) + 1; 662 663 return Info; 664 } 665 666 int32_t MaxVGPR = -1; 667 int32_t MaxSGPR = -1; 668 uint64_t CalleeFrameSize = 0; 669 670 for (const MachineBasicBlock &MBB : MF) { 671 for (const MachineInstr &MI : MBB) { 672 // TODO: Check regmasks? Do they occur anywhere except calls? 673 for (const MachineOperand &MO : MI.operands()) { 674 unsigned Width = 0; 675 bool IsSGPR = false; 676 677 if (!MO.isReg()) 678 continue; 679 680 unsigned Reg = MO.getReg(); 681 switch (Reg) { 682 case AMDGPU::EXEC: 683 case AMDGPU::EXEC_LO: 684 case AMDGPU::EXEC_HI: 685 case AMDGPU::SCC: 686 case AMDGPU::M0: 687 case AMDGPU::SRC_SHARED_BASE: 688 case AMDGPU::SRC_SHARED_LIMIT: 689 case AMDGPU::SRC_PRIVATE_BASE: 690 case AMDGPU::SRC_PRIVATE_LIMIT: 691 continue; 692 693 case AMDGPU::NoRegister: 694 assert(MI.isDebugInstr()); 695 continue; 696 697 case AMDGPU::VCC: 698 case AMDGPU::VCC_LO: 699 case AMDGPU::VCC_HI: 700 Info.UsesVCC = true; 701 continue; 702 703 case AMDGPU::FLAT_SCR: 704 case AMDGPU::FLAT_SCR_LO: 705 case AMDGPU::FLAT_SCR_HI: 706 continue; 707 708 case AMDGPU::XNACK_MASK: 709 case AMDGPU::XNACK_MASK_LO: 710 case AMDGPU::XNACK_MASK_HI: 711 llvm_unreachable("xnack_mask registers should not be used"); 712 713 case AMDGPU::TBA: 714 case AMDGPU::TBA_LO: 715 case AMDGPU::TBA_HI: 716 case AMDGPU::TMA: 717 case AMDGPU::TMA_LO: 718 case AMDGPU::TMA_HI: 719 llvm_unreachable("trap handler registers should not be used"); 720 721 default: 722 break; 723 } 724 725 if (AMDGPU::SReg_32RegClass.contains(Reg)) { 726 assert(!AMDGPU::TTMP_32RegClass.contains(Reg) && 727 "trap handler registers should not be used"); 728 IsSGPR = true; 729 Width = 1; 730 } else if (AMDGPU::VGPR_32RegClass.contains(Reg)) { 731 IsSGPR = false; 732 Width = 1; 733 } else if (AMDGPU::SReg_64RegClass.contains(Reg)) { 734 assert(!AMDGPU::TTMP_64RegClass.contains(Reg) && 735 "trap handler registers should not be used"); 736 IsSGPR = true; 737 Width = 2; 738 } else if (AMDGPU::VReg_64RegClass.contains(Reg)) { 739 IsSGPR = false; 740 Width = 2; 741 } else if (AMDGPU::VReg_96RegClass.contains(Reg)) { 742 IsSGPR = false; 743 Width = 3; 744 } else if (AMDGPU::SReg_128RegClass.contains(Reg)) { 745 assert(!AMDGPU::TTMP_128RegClass.contains(Reg) && 746 "trap handler registers should not be used"); 747 IsSGPR = true; 748 Width = 4; 749 } else if (AMDGPU::VReg_128RegClass.contains(Reg)) { 750 IsSGPR = false; 751 Width = 4; 752 } else if (AMDGPU::SReg_256RegClass.contains(Reg)) { 753 assert(!AMDGPU::TTMP_256RegClass.contains(Reg) && 754 "trap handler registers should not be used"); 755 IsSGPR = true; 756 Width = 8; 757 } else if (AMDGPU::VReg_256RegClass.contains(Reg)) { 758 IsSGPR = false; 759 Width = 8; 760 } else if (AMDGPU::SReg_512RegClass.contains(Reg)) { 761 assert(!AMDGPU::TTMP_512RegClass.contains(Reg) && 762 "trap handler registers should not be used"); 763 IsSGPR = true; 764 Width = 16; 765 } else if (AMDGPU::VReg_512RegClass.contains(Reg)) { 766 IsSGPR = false; 767 Width = 16; 768 } else { 769 llvm_unreachable("Unknown register class"); 770 } 771 unsigned HWReg = TRI.getHWRegIndex(Reg); 772 int MaxUsed = HWReg + Width - 1; 773 if (IsSGPR) { 774 MaxSGPR = MaxUsed > MaxSGPR ? MaxUsed : MaxSGPR; 775 } else { 776 MaxVGPR = MaxUsed > MaxVGPR ? MaxUsed : MaxVGPR; 777 } 778 } 779 780 if (MI.isCall()) { 781 // Pseudo used just to encode the underlying global. Is there a better 782 // way to track this? 783 784 const MachineOperand *CalleeOp 785 = TII->getNamedOperand(MI, AMDGPU::OpName::callee); 786 const Function *Callee = cast<Function>(CalleeOp->getGlobal()); 787 if (Callee->isDeclaration()) { 788 // If this is a call to an external function, we can't do much. Make 789 // conservative guesses. 790 791 // 48 SGPRs - vcc, - flat_scr, -xnack 792 int MaxSGPRGuess = 47 - getNumExtraSGPRs(ST, true, 793 ST.hasFlatAddressSpace()); 794 MaxSGPR = std::max(MaxSGPR, MaxSGPRGuess); 795 MaxVGPR = std::max(MaxVGPR, 23); 796 797 CalleeFrameSize = std::max(CalleeFrameSize, UINT64_C(16384)); 798 Info.UsesVCC = true; 799 Info.UsesFlatScratch = ST.hasFlatAddressSpace(); 800 Info.HasDynamicallySizedStack = true; 801 } else { 802 // We force CodeGen to run in SCC order, so the callee's register 803 // usage etc. should be the cumulative usage of all callees. 804 auto I = CallGraphResourceInfo.find(Callee); 805 assert(I != CallGraphResourceInfo.end() && 806 "callee should have been handled before caller"); 807 808 MaxSGPR = std::max(I->second.NumExplicitSGPR - 1, MaxSGPR); 809 MaxVGPR = std::max(I->second.NumVGPR - 1, MaxVGPR); 810 CalleeFrameSize 811 = std::max(I->second.PrivateSegmentSize, CalleeFrameSize); 812 Info.UsesVCC |= I->second.UsesVCC; 813 Info.UsesFlatScratch |= I->second.UsesFlatScratch; 814 Info.HasDynamicallySizedStack |= I->second.HasDynamicallySizedStack; 815 Info.HasRecursion |= I->second.HasRecursion; 816 } 817 818 if (!Callee->doesNotRecurse()) 819 Info.HasRecursion = true; 820 } 821 } 822 } 823 824 Info.NumExplicitSGPR = MaxSGPR + 1; 825 Info.NumVGPR = MaxVGPR + 1; 826 Info.PrivateSegmentSize += CalleeFrameSize; 827 828 return Info; 829 } 830 831 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo, 832 const MachineFunction &MF) { 833 SIFunctionResourceInfo Info = analyzeResourceUsage(MF); 834 835 ProgInfo.NumVGPR = Info.NumVGPR; 836 ProgInfo.NumSGPR = Info.NumExplicitSGPR; 837 ProgInfo.ScratchSize = Info.PrivateSegmentSize; 838 ProgInfo.VCCUsed = Info.UsesVCC; 839 ProgInfo.FlatUsed = Info.UsesFlatScratch; 840 ProgInfo.DynamicCallStack = Info.HasDynamicallySizedStack || Info.HasRecursion; 841 842 if (!isUInt<32>(ProgInfo.ScratchSize)) { 843 DiagnosticInfoStackSize DiagStackSize(MF.getFunction(), 844 ProgInfo.ScratchSize, DS_Error); 845 MF.getFunction().getContext().diagnose(DiagStackSize); 846 } 847 848 const SISubtarget &STM = MF.getSubtarget<SISubtarget>(); 849 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 850 const SIInstrInfo *TII = STM.getInstrInfo(); 851 const SIRegisterInfo *RI = &TII->getRegisterInfo(); 852 853 unsigned ExtraSGPRs = getNumExtraSGPRs(STM, 854 ProgInfo.VCCUsed, 855 ProgInfo.FlatUsed); 856 unsigned ExtraVGPRs = STM.getReservedNumVGPRs(MF); 857 858 // Check the addressable register limit before we add ExtraSGPRs. 859 if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS && 860 !STM.hasSGPRInitBug()) { 861 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 862 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 863 // This can happen due to a compiler bug or when using inline asm. 864 LLVMContext &Ctx = MF.getFunction().getContext(); 865 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 866 "addressable scalar registers", 867 ProgInfo.NumSGPR, DS_Error, 868 DK_ResourceLimit, 869 MaxAddressableNumSGPRs); 870 Ctx.diagnose(Diag); 871 ProgInfo.NumSGPR = MaxAddressableNumSGPRs - 1; 872 } 873 } 874 875 // Account for extra SGPRs and VGPRs reserved for debugger use. 876 ProgInfo.NumSGPR += ExtraSGPRs; 877 ProgInfo.NumVGPR += ExtraVGPRs; 878 879 // Ensure there are enough SGPRs and VGPRs for wave dispatch, where wave 880 // dispatch registers are function args. 881 unsigned WaveDispatchNumSGPR = 0, WaveDispatchNumVGPR = 0; 882 for (auto &Arg : MF.getFunction().args()) { 883 unsigned NumRegs = (Arg.getType()->getPrimitiveSizeInBits() + 31) / 32; 884 if (Arg.hasAttribute(Attribute::InReg)) 885 WaveDispatchNumSGPR += NumRegs; 886 else 887 WaveDispatchNumVGPR += NumRegs; 888 } 889 ProgInfo.NumSGPR = std::max(ProgInfo.NumSGPR, WaveDispatchNumSGPR); 890 ProgInfo.NumVGPR = std::max(ProgInfo.NumVGPR, WaveDispatchNumVGPR); 891 892 // Adjust number of registers used to meet default/requested minimum/maximum 893 // number of waves per execution unit request. 894 ProgInfo.NumSGPRsForWavesPerEU = std::max( 895 std::max(ProgInfo.NumSGPR, 1u), STM.getMinNumSGPRs(MFI->getMaxWavesPerEU())); 896 ProgInfo.NumVGPRsForWavesPerEU = std::max( 897 std::max(ProgInfo.NumVGPR, 1u), STM.getMinNumVGPRs(MFI->getMaxWavesPerEU())); 898 899 if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS || 900 STM.hasSGPRInitBug()) { 901 unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs(); 902 if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) { 903 // This can happen due to a compiler bug or when using inline asm to use 904 // the registers which are usually reserved for vcc etc. 905 LLVMContext &Ctx = MF.getFunction().getContext(); 906 DiagnosticInfoResourceLimit Diag(MF.getFunction(), 907 "scalar registers", 908 ProgInfo.NumSGPR, DS_Error, 909 DK_ResourceLimit, 910 MaxAddressableNumSGPRs); 911 Ctx.diagnose(Diag); 912 ProgInfo.NumSGPR = MaxAddressableNumSGPRs; 913 ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs; 914 } 915 } 916 917 if (STM.hasSGPRInitBug()) { 918 ProgInfo.NumSGPR = 919 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 920 ProgInfo.NumSGPRsForWavesPerEU = 921 AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG; 922 } 923 924 if (MFI->getNumUserSGPRs() > STM.getMaxNumUserSGPRs()) { 925 LLVMContext &Ctx = MF.getFunction().getContext(); 926 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "user SGPRs", 927 MFI->getNumUserSGPRs(), DS_Error); 928 Ctx.diagnose(Diag); 929 } 930 931 if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) { 932 LLVMContext &Ctx = MF.getFunction().getContext(); 933 DiagnosticInfoResourceLimit Diag(MF.getFunction(), "local memory", 934 MFI->getLDSSize(), DS_Error); 935 Ctx.diagnose(Diag); 936 } 937 938 // SGPRBlocks is actual number of SGPR blocks minus 1. 939 ProgInfo.SGPRBlocks = alignTo(ProgInfo.NumSGPRsForWavesPerEU, 940 STM.getSGPREncodingGranule()); 941 ProgInfo.SGPRBlocks = ProgInfo.SGPRBlocks / STM.getSGPREncodingGranule() - 1; 942 943 // VGPRBlocks is actual number of VGPR blocks minus 1. 944 ProgInfo.VGPRBlocks = alignTo(ProgInfo.NumVGPRsForWavesPerEU, 945 STM.getVGPREncodingGranule()); 946 ProgInfo.VGPRBlocks = ProgInfo.VGPRBlocks / STM.getVGPREncodingGranule() - 1; 947 948 // Record first reserved VGPR and number of reserved VGPRs. 949 ProgInfo.ReservedVGPRFirst = STM.debuggerReserveRegs() ? ProgInfo.NumVGPR : 0; 950 ProgInfo.ReservedVGPRCount = STM.getReservedNumVGPRs(MF); 951 952 // Update DebuggerWavefrontPrivateSegmentOffsetSGPR and 953 // DebuggerPrivateSegmentBufferSGPR fields if "amdgpu-debugger-emit-prologue" 954 // attribute was requested. 955 if (STM.debuggerEmitPrologue()) { 956 ProgInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR = 957 RI->getHWRegIndex(MFI->getScratchWaveOffsetReg()); 958 ProgInfo.DebuggerPrivateSegmentBufferSGPR = 959 RI->getHWRegIndex(MFI->getScratchRSrcReg()); 960 } 961 962 // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode 963 // register. 964 ProgInfo.FloatMode = getFPMode(MF); 965 966 ProgInfo.IEEEMode = STM.enableIEEEBit(MF); 967 968 // Make clamp modifier on NaN input returns 0. 969 ProgInfo.DX10Clamp = STM.enableDX10Clamp(); 970 971 unsigned LDSAlignShift; 972 if (STM.getGeneration() < SISubtarget::SEA_ISLANDS) { 973 // LDS is allocated in 64 dword blocks. 974 LDSAlignShift = 8; 975 } else { 976 // LDS is allocated in 128 dword blocks. 977 LDSAlignShift = 9; 978 } 979 980 unsigned LDSSpillSize = 981 MFI->getLDSWaveSpillSize() * MFI->getMaxFlatWorkGroupSize(); 982 983 ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize; 984 ProgInfo.LDSBlocks = 985 alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift; 986 987 // Scratch is allocated in 256 dword blocks. 988 unsigned ScratchAlignShift = 10; 989 // We need to program the hardware with the amount of scratch memory that 990 // is used by the entire wave. ProgInfo.ScratchSize is the amount of 991 // scratch memory used per thread. 992 ProgInfo.ScratchBlocks = 993 alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(), 994 1ULL << ScratchAlignShift) >> 995 ScratchAlignShift; 996 997 ProgInfo.ComputePGMRSrc1 = 998 S_00B848_VGPRS(ProgInfo.VGPRBlocks) | 999 S_00B848_SGPRS(ProgInfo.SGPRBlocks) | 1000 S_00B848_PRIORITY(ProgInfo.Priority) | 1001 S_00B848_FLOAT_MODE(ProgInfo.FloatMode) | 1002 S_00B848_PRIV(ProgInfo.Priv) | 1003 S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) | 1004 S_00B848_DEBUG_MODE(ProgInfo.DebugMode) | 1005 S_00B848_IEEE_MODE(ProgInfo.IEEEMode); 1006 1007 // 0 = X, 1 = XY, 2 = XYZ 1008 unsigned TIDIGCompCnt = 0; 1009 if (MFI->hasWorkItemIDZ()) 1010 TIDIGCompCnt = 2; 1011 else if (MFI->hasWorkItemIDY()) 1012 TIDIGCompCnt = 1; 1013 1014 ProgInfo.ComputePGMRSrc2 = 1015 S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) | 1016 S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) | 1017 // For AMDHSA, TRAP_HANDLER must be zero, as it is populated by the CP. 1018 S_00B84C_TRAP_HANDLER(STM.isAmdHsaOS() ? 0 : STM.isTrapHandlerEnabled()) | 1019 S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) | 1020 S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) | 1021 S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) | 1022 S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) | 1023 S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) | 1024 S_00B84C_EXCP_EN_MSB(0) | 1025 // For AMDHSA, LDS_SIZE must be zero, as it is populated by the CP. 1026 S_00B84C_LDS_SIZE(STM.isAmdHsaOS() ? 0 : ProgInfo.LDSBlocks) | 1027 S_00B84C_EXCP_EN(0); 1028 } 1029 1030 static unsigned getRsrcReg(CallingConv::ID CallConv) { 1031 switch (CallConv) { 1032 default: LLVM_FALLTHROUGH; 1033 case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1; 1034 case CallingConv::AMDGPU_LS: return R_00B528_SPI_SHADER_PGM_RSRC1_LS; 1035 case CallingConv::AMDGPU_HS: return R_00B428_SPI_SHADER_PGM_RSRC1_HS; 1036 case CallingConv::AMDGPU_ES: return R_00B328_SPI_SHADER_PGM_RSRC1_ES; 1037 case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS; 1038 case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS; 1039 case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS; 1040 } 1041 } 1042 1043 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF, 1044 const SIProgramInfo &CurrentProgramInfo) { 1045 const SISubtarget &STM = MF.getSubtarget<SISubtarget>(); 1046 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1047 unsigned RsrcReg = getRsrcReg(MF.getFunction().getCallingConv()); 1048 1049 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 1050 OutStreamer->EmitIntValue(R_00B848_COMPUTE_PGM_RSRC1, 4); 1051 1052 OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc1, 4); 1053 1054 OutStreamer->EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4); 1055 OutStreamer->EmitIntValue(CurrentProgramInfo.ComputePGMRSrc2, 4); 1056 1057 OutStreamer->EmitIntValue(R_00B860_COMPUTE_TMPRING_SIZE, 4); 1058 OutStreamer->EmitIntValue(S_00B860_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 1059 1060 // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 = 1061 // 0" comment but I don't see a corresponding field in the register spec. 1062 } else { 1063 OutStreamer->EmitIntValue(RsrcReg, 4); 1064 OutStreamer->EmitIntValue(S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 1065 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks), 4); 1066 if (STM.isVGPRSpillingEnabled(MF.getFunction())) { 1067 OutStreamer->EmitIntValue(R_0286E8_SPI_TMPRING_SIZE, 4); 1068 OutStreamer->EmitIntValue(S_0286E8_WAVESIZE(CurrentProgramInfo.ScratchBlocks), 4); 1069 } 1070 } 1071 1072 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1073 OutStreamer->EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4); 1074 OutStreamer->EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks), 4); 1075 OutStreamer->EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4); 1076 OutStreamer->EmitIntValue(MFI->getPSInputEnable(), 4); 1077 OutStreamer->EmitIntValue(R_0286D0_SPI_PS_INPUT_ADDR, 4); 1078 OutStreamer->EmitIntValue(MFI->getPSInputAddr(), 4); 1079 } 1080 1081 OutStreamer->EmitIntValue(R_SPILLED_SGPRS, 4); 1082 OutStreamer->EmitIntValue(MFI->getNumSpilledSGPRs(), 4); 1083 OutStreamer->EmitIntValue(R_SPILLED_VGPRS, 4); 1084 OutStreamer->EmitIntValue(MFI->getNumSpilledVGPRs(), 4); 1085 } 1086 1087 // This is the equivalent of EmitProgramInfoSI above, but for when the OS type 1088 // is AMDPAL. It stores each compute/SPI register setting and other PAL 1089 // metadata items into the PALMetadataMap, combining with any provided by the 1090 // frontend as LLVM metadata. Once all functions are written, PALMetadataMap is 1091 // then written as a single block in the .note section. 1092 void AMDGPUAsmPrinter::EmitPALMetadata(const MachineFunction &MF, 1093 const SIProgramInfo &CurrentProgramInfo) { 1094 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1095 // Given the calling convention, calculate the register number for rsrc1. In 1096 // principle the register number could change in future hardware, but we know 1097 // it is the same for gfx6-9 (except that LS and ES don't exist on gfx9), so 1098 // we can use the same fixed value that .AMDGPU.config has for Mesa. Note 1099 // that we use a register number rather than a byte offset, so we need to 1100 // divide by 4. 1101 unsigned Rsrc1Reg = getRsrcReg(MF.getFunction().getCallingConv()) / 4; 1102 unsigned Rsrc2Reg = Rsrc1Reg + 1; 1103 // Also calculate the PAL metadata key for *S_SCRATCH_SIZE. It can be used 1104 // with a constant offset to access any non-register shader-specific PAL 1105 // metadata key. 1106 unsigned ScratchSizeKey = PALMD::Key::CS_SCRATCH_SIZE; 1107 switch (MF.getFunction().getCallingConv()) { 1108 case CallingConv::AMDGPU_PS: 1109 ScratchSizeKey = PALMD::Key::PS_SCRATCH_SIZE; 1110 break; 1111 case CallingConv::AMDGPU_VS: 1112 ScratchSizeKey = PALMD::Key::VS_SCRATCH_SIZE; 1113 break; 1114 case CallingConv::AMDGPU_GS: 1115 ScratchSizeKey = PALMD::Key::GS_SCRATCH_SIZE; 1116 break; 1117 case CallingConv::AMDGPU_ES: 1118 ScratchSizeKey = PALMD::Key::ES_SCRATCH_SIZE; 1119 break; 1120 case CallingConv::AMDGPU_HS: 1121 ScratchSizeKey = PALMD::Key::HS_SCRATCH_SIZE; 1122 break; 1123 case CallingConv::AMDGPU_LS: 1124 ScratchSizeKey = PALMD::Key::LS_SCRATCH_SIZE; 1125 break; 1126 } 1127 unsigned NumUsedVgprsKey = ScratchSizeKey + 1128 PALMD::Key::VS_NUM_USED_VGPRS - PALMD::Key::VS_SCRATCH_SIZE; 1129 unsigned NumUsedSgprsKey = ScratchSizeKey + 1130 PALMD::Key::VS_NUM_USED_SGPRS - PALMD::Key::VS_SCRATCH_SIZE; 1131 PALMetadataMap[NumUsedVgprsKey] = CurrentProgramInfo.NumVGPRsForWavesPerEU; 1132 PALMetadataMap[NumUsedSgprsKey] = CurrentProgramInfo.NumSGPRsForWavesPerEU; 1133 if (AMDGPU::isCompute(MF.getFunction().getCallingConv())) { 1134 PALMetadataMap[Rsrc1Reg] |= CurrentProgramInfo.ComputePGMRSrc1; 1135 PALMetadataMap[Rsrc2Reg] |= CurrentProgramInfo.ComputePGMRSrc2; 1136 // ScratchSize is in bytes, 16 aligned. 1137 PALMetadataMap[ScratchSizeKey] |= 1138 alignTo(CurrentProgramInfo.ScratchSize, 16); 1139 } else { 1140 PALMetadataMap[Rsrc1Reg] |= S_00B028_VGPRS(CurrentProgramInfo.VGPRBlocks) | 1141 S_00B028_SGPRS(CurrentProgramInfo.SGPRBlocks); 1142 if (CurrentProgramInfo.ScratchBlocks > 0) 1143 PALMetadataMap[Rsrc2Reg] |= S_00B84C_SCRATCH_EN(1); 1144 // ScratchSize is in bytes, 16 aligned. 1145 PALMetadataMap[ScratchSizeKey] |= 1146 alignTo(CurrentProgramInfo.ScratchSize, 16); 1147 } 1148 if (MF.getFunction().getCallingConv() == CallingConv::AMDGPU_PS) { 1149 PALMetadataMap[Rsrc2Reg] |= 1150 S_00B02C_EXTRA_LDS_SIZE(CurrentProgramInfo.LDSBlocks); 1151 PALMetadataMap[R_0286CC_SPI_PS_INPUT_ENA / 4] |= MFI->getPSInputEnable(); 1152 PALMetadataMap[R_0286D0_SPI_PS_INPUT_ADDR / 4] |= MFI->getPSInputAddr(); 1153 } 1154 } 1155 1156 // This is supposed to be log2(Size) 1157 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) { 1158 switch (Size) { 1159 case 4: 1160 return AMD_ELEMENT_4_BYTES; 1161 case 8: 1162 return AMD_ELEMENT_8_BYTES; 1163 case 16: 1164 return AMD_ELEMENT_16_BYTES; 1165 default: 1166 llvm_unreachable("invalid private_element_size"); 1167 } 1168 } 1169 1170 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out, 1171 const SIProgramInfo &CurrentProgramInfo, 1172 const MachineFunction &MF) const { 1173 const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>(); 1174 const SISubtarget &STM = MF.getSubtarget<SISubtarget>(); 1175 1176 AMDGPU::initDefaultAMDKernelCodeT(Out, STM.getFeatureBits()); 1177 1178 Out.compute_pgm_resource_registers = 1179 CurrentProgramInfo.ComputePGMRSrc1 | 1180 (CurrentProgramInfo.ComputePGMRSrc2 << 32); 1181 Out.code_properties = AMD_CODE_PROPERTY_IS_PTR64; 1182 1183 if (CurrentProgramInfo.DynamicCallStack) 1184 Out.code_properties |= AMD_CODE_PROPERTY_IS_DYNAMIC_CALLSTACK; 1185 1186 AMD_HSA_BITS_SET(Out.code_properties, 1187 AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE, 1188 getElementByteSizeValue(STM.getMaxPrivateElementSize())); 1189 1190 if (MFI->hasPrivateSegmentBuffer()) { 1191 Out.code_properties |= 1192 AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER; 1193 } 1194 1195 if (MFI->hasDispatchPtr()) 1196 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1197 1198 if (MFI->hasQueuePtr()) 1199 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR; 1200 1201 if (MFI->hasKernargSegmentPtr()) 1202 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR; 1203 1204 if (MFI->hasDispatchID()) 1205 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID; 1206 1207 if (MFI->hasFlatScratchInit()) 1208 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT; 1209 1210 if (MFI->hasGridWorkgroupCountX()) { 1211 Out.code_properties |= 1212 AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_X; 1213 } 1214 1215 if (MFI->hasGridWorkgroupCountY()) { 1216 Out.code_properties |= 1217 AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Y; 1218 } 1219 1220 if (MFI->hasGridWorkgroupCountZ()) { 1221 Out.code_properties |= 1222 AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Z; 1223 } 1224 1225 if (MFI->hasDispatchPtr()) 1226 Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR; 1227 1228 if (STM.debuggerSupported()) 1229 Out.code_properties |= AMD_CODE_PROPERTY_IS_DEBUG_SUPPORTED; 1230 1231 if (STM.isXNACKEnabled()) 1232 Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED; 1233 1234 // FIXME: Should use getKernArgSize 1235 Out.kernarg_segment_byte_size = 1236 STM.getKernArgSegmentSize(MF.getFunction(), MFI->getABIArgOffset()); 1237 Out.wavefront_sgpr_count = CurrentProgramInfo.NumSGPR; 1238 Out.workitem_vgpr_count = CurrentProgramInfo.NumVGPR; 1239 Out.workitem_private_segment_byte_size = CurrentProgramInfo.ScratchSize; 1240 Out.workgroup_group_segment_byte_size = CurrentProgramInfo.LDSSize; 1241 Out.reserved_vgpr_first = CurrentProgramInfo.ReservedVGPRFirst; 1242 Out.reserved_vgpr_count = CurrentProgramInfo.ReservedVGPRCount; 1243 1244 // These alignment values are specified in powers of two, so alignment = 1245 // 2^n. The minimum alignment is 2^4 = 16. 1246 Out.kernarg_segment_alignment = std::max((size_t)4, 1247 countTrailingZeros(MFI->getMaxKernArgAlign())); 1248 1249 if (STM.debuggerEmitPrologue()) { 1250 Out.debug_wavefront_private_segment_offset_sgpr = 1251 CurrentProgramInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR; 1252 Out.debug_private_segment_buffer_sgpr = 1253 CurrentProgramInfo.DebuggerPrivateSegmentBufferSGPR; 1254 } 1255 } 1256 1257 AMDGPU::HSAMD::Kernel::CodeProps::Metadata AMDGPUAsmPrinter::getHSACodeProps( 1258 const MachineFunction &MF, 1259 const SIProgramInfo &ProgramInfo) const { 1260 const SISubtarget &STM = MF.getSubtarget<SISubtarget>(); 1261 const SIMachineFunctionInfo &MFI = *MF.getInfo<SIMachineFunctionInfo>(); 1262 HSAMD::Kernel::CodeProps::Metadata HSACodeProps; 1263 1264 HSACodeProps.mKernargSegmentSize = 1265 STM.getKernArgSegmentSize(MF.getFunction(), MFI.getABIArgOffset()); 1266 HSACodeProps.mGroupSegmentFixedSize = ProgramInfo.LDSSize; 1267 HSACodeProps.mPrivateSegmentFixedSize = ProgramInfo.ScratchSize; 1268 HSACodeProps.mKernargSegmentAlign = 1269 std::max(uint32_t(4), MFI.getMaxKernArgAlign()); 1270 HSACodeProps.mWavefrontSize = STM.getWavefrontSize(); 1271 HSACodeProps.mNumSGPRs = CurrentProgramInfo.NumSGPR; 1272 HSACodeProps.mNumVGPRs = CurrentProgramInfo.NumVGPR; 1273 HSACodeProps.mMaxFlatWorkGroupSize = MFI.getMaxFlatWorkGroupSize(); 1274 HSACodeProps.mIsDynamicCallStack = ProgramInfo.DynamicCallStack; 1275 HSACodeProps.mIsXNACKEnabled = STM.isXNACKEnabled(); 1276 HSACodeProps.mNumSpilledSGPRs = MFI.getNumSpilledSGPRs(); 1277 HSACodeProps.mNumSpilledVGPRs = MFI.getNumSpilledVGPRs(); 1278 1279 return HSACodeProps; 1280 } 1281 1282 AMDGPU::HSAMD::Kernel::DebugProps::Metadata AMDGPUAsmPrinter::getHSADebugProps( 1283 const MachineFunction &MF, 1284 const SIProgramInfo &ProgramInfo) const { 1285 const SISubtarget &STM = MF.getSubtarget<SISubtarget>(); 1286 HSAMD::Kernel::DebugProps::Metadata HSADebugProps; 1287 1288 if (!STM.debuggerSupported()) 1289 return HSADebugProps; 1290 1291 HSADebugProps.mDebuggerABIVersion.push_back(1); 1292 HSADebugProps.mDebuggerABIVersion.push_back(0); 1293 HSADebugProps.mReservedNumVGPRs = ProgramInfo.ReservedVGPRCount; 1294 HSADebugProps.mReservedFirstVGPR = ProgramInfo.ReservedVGPRFirst; 1295 1296 if (STM.debuggerEmitPrologue()) { 1297 HSADebugProps.mPrivateSegmentBufferSGPR = 1298 ProgramInfo.DebuggerPrivateSegmentBufferSGPR; 1299 HSADebugProps.mWavefrontPrivateSegmentOffsetSGPR = 1300 ProgramInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR; 1301 } 1302 1303 return HSADebugProps; 1304 } 1305 1306 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 1307 unsigned AsmVariant, 1308 const char *ExtraCode, raw_ostream &O) { 1309 // First try the generic code, which knows about modifiers like 'c' and 'n'. 1310 if (!AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O)) 1311 return false; 1312 1313 if (ExtraCode && ExtraCode[0]) { 1314 if (ExtraCode[1] != 0) 1315 return true; // Unknown modifier. 1316 1317 switch (ExtraCode[0]) { 1318 case 'r': 1319 break; 1320 default: 1321 return true; 1322 } 1323 } 1324 1325 // TODO: Should be able to support other operand types like globals. 1326 const MachineOperand &MO = MI->getOperand(OpNo); 1327 if (MO.isReg()) { 1328 AMDGPUInstPrinter::printRegOperand(MO.getReg(), O, 1329 *MF->getSubtarget().getRegisterInfo()); 1330 return false; 1331 } 1332 1333 return true; 1334 } 1335