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