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 "MCTargetDesc/AMDGPUTargetStreamer.h"
21 #include "InstPrinter/AMDGPUInstPrinter.h"
22 #include "Utils/AMDGPUBaseInfo.h"
23 #include "AMDGPU.h"
24 #include "AMDGPUSubtarget.h"
25 #include "R600Defines.h"
26 #include "R600MachineFunctionInfo.h"
27 #include "R600RegisterInfo.h"
28 #include "SIDefines.h"
29 #include "SIMachineFunctionInfo.h"
30 #include "SIInstrInfo.h"
31 #include "SIRegisterInfo.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/IR/DiagnosticInfo.h"
34 #include "llvm/MC/MCContext.h"
35 #include "llvm/MC/MCSectionELF.h"
36 #include "llvm/MC/MCStreamer.h"
37 #include "llvm/Support/ELF.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Target/TargetLoweringObjectFile.h"
41 
42 using namespace llvm;
43 
44 // TODO: This should get the default rounding mode from the kernel. We just set
45 // the default here, but this could change if the OpenCL rounding mode pragmas
46 // are used.
47 //
48 // The denormal mode here should match what is reported by the OpenCL runtime
49 // for the CL_FP_DENORM bit from CL_DEVICE_{HALF|SINGLE|DOUBLE}_FP_CONFIG, but
50 // can also be override to flush with the -cl-denorms-are-zero compiler flag.
51 //
52 // AMD OpenCL only sets flush none and reports CL_FP_DENORM for double
53 // precision, and leaves single precision to flush all and does not report
54 // CL_FP_DENORM for CL_DEVICE_SINGLE_FP_CONFIG. Mesa's OpenCL currently reports
55 // CL_FP_DENORM for both.
56 //
57 // FIXME: It seems some instructions do not support single precision denormals
58 // regardless of the mode (exp_*_f32, rcp_*_f32, rsq_*_f32, rsq_*f32, sqrt_f32,
59 // and sin_f32, cos_f32 on most parts).
60 
61 // We want to use these instructions, and using fp32 denormals also causes
62 // instructions to run at the double precision rate for the device so it's
63 // probably best to just report no single precision denormals.
64 static uint32_t getFPMode(const MachineFunction &F) {
65   const SISubtarget& ST = F.getSubtarget<SISubtarget>();
66   // TODO: Is there any real use for the flush in only / flush out only modes?
67 
68   uint32_t FP32Denormals =
69     ST.hasFP32Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT;
70 
71   uint32_t FP64Denormals =
72     ST.hasFP64Denormals() ? FP_DENORM_FLUSH_NONE : FP_DENORM_FLUSH_IN_FLUSH_OUT;
73 
74   return FP_ROUND_MODE_SP(FP_ROUND_ROUND_TO_NEAREST) |
75          FP_ROUND_MODE_DP(FP_ROUND_ROUND_TO_NEAREST) |
76          FP_DENORM_MODE_SP(FP32Denormals) |
77          FP_DENORM_MODE_DP(FP64Denormals);
78 }
79 
80 static AsmPrinter *
81 createAMDGPUAsmPrinterPass(TargetMachine &tm,
82                            std::unique_ptr<MCStreamer> &&Streamer) {
83   return new AMDGPUAsmPrinter(tm, std::move(Streamer));
84 }
85 
86 extern "C" void LLVMInitializeAMDGPUAsmPrinter() {
87   TargetRegistry::RegisterAsmPrinter(getTheAMDGPUTarget(),
88                                      createAMDGPUAsmPrinterPass);
89   TargetRegistry::RegisterAsmPrinter(getTheGCNTarget(),
90                                      createAMDGPUAsmPrinterPass);
91 }
92 
93 AMDGPUAsmPrinter::AMDGPUAsmPrinter(TargetMachine &TM,
94                                    std::unique_ptr<MCStreamer> Streamer)
95   : AsmPrinter(TM, std::move(Streamer)) {}
96 
97 StringRef AMDGPUAsmPrinter::getPassName() const {
98   return "AMDGPU Assembly Printer";
99 }
100 
101 const MCSubtargetInfo* AMDGPUAsmPrinter::getSTI() const {
102   return TM.getMCSubtargetInfo();
103 }
104 
105 AMDGPUTargetStreamer& AMDGPUAsmPrinter::getTargetStreamer() const {
106   return static_cast<AMDGPUTargetStreamer&>(*OutStreamer->getTargetStreamer());
107 }
108 
109 void AMDGPUAsmPrinter::EmitStartOfAsmFile(Module &M) {
110   if (TM.getTargetTriple().getOS() != Triple::AMDHSA)
111     return;
112 
113   AMDGPU::IsaInfo::IsaVersion ISA =
114       AMDGPU::IsaInfo::getIsaVersion(getSTI()->getFeatureBits());
115 
116   getTargetStreamer().EmitDirectiveHSACodeObjectVersion(2, 1);
117   getTargetStreamer().EmitDirectiveHSACodeObjectISA(
118       ISA.Major, ISA.Minor, ISA.Stepping, "AMD", "AMDGPU");
119   getTargetStreamer().EmitStartOfCodeObjectMetadata(M);
120 }
121 
122 void AMDGPUAsmPrinter::EmitEndOfAsmFile(Module &M) {
123   if (TM.getTargetTriple().getOS() != Triple::AMDHSA)
124     return;
125 
126   getTargetStreamer().EmitEndOfCodeObjectMetadata();
127 }
128 
129 bool AMDGPUAsmPrinter::isBlockOnlyReachableByFallthrough(
130   const MachineBasicBlock *MBB) const {
131   if (!AsmPrinter::isBlockOnlyReachableByFallthrough(MBB))
132     return false;
133 
134   if (MBB->empty())
135     return true;
136 
137   // If this is a block implementing a long branch, an expression relative to
138   // the start of the block is needed.  to the start of the block.
139   // XXX - Is there a smarter way to check this?
140   return (MBB->back().getOpcode() != AMDGPU::S_SETPC_B64);
141 }
142 
143 void AMDGPUAsmPrinter::EmitFunctionBodyStart() {
144   const AMDGPUSubtarget &STM = MF->getSubtarget<AMDGPUSubtarget>();
145   SIProgramInfo KernelInfo;
146   amd_kernel_code_t KernelCode;
147   if (STM.isAmdCodeObjectV2(*MF)) {
148     getSIProgramInfo(KernelInfo, *MF);
149     getAmdKernelCode(KernelCode, KernelInfo, *MF);
150 
151     OutStreamer->SwitchSection(getObjFileLowering().getTextSection());
152     getTargetStreamer().EmitAMDKernelCodeT(KernelCode);
153   }
154 
155   if (TM.getTargetTriple().getOS() != Triple::AMDHSA)
156     return;
157   getTargetStreamer().EmitKernelCodeObjectMetadata(*MF->getFunction(),
158                                                    KernelCode);
159 }
160 
161 void AMDGPUAsmPrinter::EmitFunctionEntryLabel() {
162   const SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
163   const AMDGPUSubtarget &STM = MF->getSubtarget<AMDGPUSubtarget>();
164   if (MFI->isKernel() && STM.isAmdCodeObjectV2(*MF)) {
165     SmallString<128> SymbolName;
166     getNameWithPrefix(SymbolName, MF->getFunction()),
167     getTargetStreamer().EmitAMDGPUSymbolType(
168         SymbolName, ELF::STT_AMDGPU_HSA_KERNEL);
169   }
170 
171   AsmPrinter::EmitFunctionEntryLabel();
172 }
173 
174 void AMDGPUAsmPrinter::EmitGlobalVariable(const GlobalVariable *GV) {
175 
176   // Group segment variables aren't emitted in HSA.
177   if (AMDGPU::isGroupSegment(GV))
178     return;
179 
180   AsmPrinter::EmitGlobalVariable(GV);
181 }
182 
183 bool AMDGPUAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
184 
185   // The starting address of all shader programs must be 256 bytes aligned.
186   MF.setAlignment(8);
187 
188   SetupMachineFunction(MF);
189 
190   const AMDGPUSubtarget &STM = MF.getSubtarget<AMDGPUSubtarget>();
191   MCContext &Context = getObjFileLowering().getContext();
192   if (!STM.isAmdHsaOS()) {
193     MCSectionELF *ConfigSection =
194         Context.getELFSection(".AMDGPU.config", ELF::SHT_PROGBITS, 0);
195     OutStreamer->SwitchSection(ConfigSection);
196   }
197 
198   SIProgramInfo KernelInfo;
199   if (STM.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
200     getSIProgramInfo(KernelInfo, MF);
201     if (!STM.isAmdHsaOS()) {
202       EmitProgramInfoSI(MF, KernelInfo);
203     }
204   } else {
205     EmitProgramInfoR600(MF);
206   }
207 
208   DisasmLines.clear();
209   HexLines.clear();
210   DisasmLineMaxLen = 0;
211 
212   EmitFunctionBody();
213 
214   if (isVerbose()) {
215     MCSectionELF *CommentSection =
216         Context.getELFSection(".AMDGPU.csdata", ELF::SHT_PROGBITS, 0);
217     OutStreamer->SwitchSection(CommentSection);
218 
219     if (STM.getGeneration() >= AMDGPUSubtarget::SOUTHERN_ISLANDS) {
220       OutStreamer->emitRawComment(" Kernel info:", false);
221       OutStreamer->emitRawComment(" codeLenInByte = " + Twine(KernelInfo.CodeLen),
222                                   false);
223       OutStreamer->emitRawComment(" NumSgprs: " + Twine(KernelInfo.NumSGPR),
224                                   false);
225       OutStreamer->emitRawComment(" NumVgprs: " + Twine(KernelInfo.NumVGPR),
226                                   false);
227       OutStreamer->emitRawComment(" FloatMode: " + Twine(KernelInfo.FloatMode),
228                                   false);
229       OutStreamer->emitRawComment(" IeeeMode: " + Twine(KernelInfo.IEEEMode),
230                                   false);
231       OutStreamer->emitRawComment(" ScratchSize: " + Twine(KernelInfo.ScratchSize),
232                                   false);
233       OutStreamer->emitRawComment(" LDSByteSize: " + Twine(KernelInfo.LDSSize) +
234                                   " bytes/workgroup (compile time only)", false);
235 
236       OutStreamer->emitRawComment(" SGPRBlocks: " +
237                                   Twine(KernelInfo.SGPRBlocks), false);
238       OutStreamer->emitRawComment(" VGPRBlocks: " +
239                                   Twine(KernelInfo.VGPRBlocks), false);
240 
241       OutStreamer->emitRawComment(" NumSGPRsForWavesPerEU: " +
242                                   Twine(KernelInfo.NumSGPRsForWavesPerEU), false);
243       OutStreamer->emitRawComment(" NumVGPRsForWavesPerEU: " +
244                                   Twine(KernelInfo.NumVGPRsForWavesPerEU), false);
245 
246       OutStreamer->emitRawComment(" ReservedVGPRFirst: " + Twine(KernelInfo.ReservedVGPRFirst),
247                                   false);
248       OutStreamer->emitRawComment(" ReservedVGPRCount: " + Twine(KernelInfo.ReservedVGPRCount),
249                                   false);
250 
251       if (MF.getSubtarget<SISubtarget>().debuggerEmitPrologue()) {
252         OutStreamer->emitRawComment(" DebuggerWavefrontPrivateSegmentOffsetSGPR: s" +
253                                     Twine(KernelInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR), false);
254         OutStreamer->emitRawComment(" DebuggerPrivateSegmentBufferSGPR: s" +
255                                     Twine(KernelInfo.DebuggerPrivateSegmentBufferSGPR), false);
256       }
257 
258       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:USER_SGPR: " +
259                                   Twine(G_00B84C_USER_SGPR(KernelInfo.ComputePGMRSrc2)),
260                                   false);
261       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TRAP_HANDLER: " +
262                                   Twine(G_00B84C_TRAP_HANDLER(KernelInfo.ComputePGMRSrc2)),
263                                   false);
264       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_X_EN: " +
265                                   Twine(G_00B84C_TGID_X_EN(KernelInfo.ComputePGMRSrc2)),
266                                   false);
267       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_Y_EN: " +
268                                   Twine(G_00B84C_TGID_Y_EN(KernelInfo.ComputePGMRSrc2)),
269                                   false);
270       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TGID_Z_EN: " +
271                                   Twine(G_00B84C_TGID_Z_EN(KernelInfo.ComputePGMRSrc2)),
272                                   false);
273       OutStreamer->emitRawComment(" COMPUTE_PGM_RSRC2:TIDIG_COMP_CNT: " +
274                                   Twine(G_00B84C_TIDIG_COMP_CNT(KernelInfo.ComputePGMRSrc2)),
275                                   false);
276 
277     } else {
278       R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
279       OutStreamer->emitRawComment(
280         Twine("SQ_PGM_RESOURCES:STACK_SIZE = " + Twine(MFI->CFStackSize)));
281     }
282   }
283 
284   if (STM.dumpCode()) {
285 
286     OutStreamer->SwitchSection(
287         Context.getELFSection(".AMDGPU.disasm", ELF::SHT_NOTE, 0));
288 
289     for (size_t i = 0; i < DisasmLines.size(); ++i) {
290       std::string Comment(DisasmLineMaxLen - DisasmLines[i].size(), ' ');
291       Comment += " ; " + HexLines[i] + "\n";
292 
293       OutStreamer->EmitBytes(StringRef(DisasmLines[i]));
294       OutStreamer->EmitBytes(StringRef(Comment));
295     }
296   }
297 
298   return false;
299 }
300 
301 void AMDGPUAsmPrinter::EmitProgramInfoR600(const MachineFunction &MF) {
302   unsigned MaxGPR = 0;
303   bool killPixel = false;
304   const R600Subtarget &STM = MF.getSubtarget<R600Subtarget>();
305   const R600RegisterInfo *RI = STM.getRegisterInfo();
306   const R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
307 
308   for (const MachineBasicBlock &MBB : MF) {
309     for (const MachineInstr &MI : MBB) {
310       if (MI.getOpcode() == AMDGPU::KILLGT)
311         killPixel = true;
312       unsigned numOperands = MI.getNumOperands();
313       for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
314         const MachineOperand &MO = MI.getOperand(op_idx);
315         if (!MO.isReg())
316           continue;
317         unsigned HWReg = RI->getEncodingValue(MO.getReg()) & 0xff;
318 
319         // Register with value > 127 aren't GPR
320         if (HWReg > 127)
321           continue;
322         MaxGPR = std::max(MaxGPR, HWReg);
323       }
324     }
325   }
326 
327   unsigned RsrcReg;
328   if (STM.getGeneration() >= R600Subtarget::EVERGREEN) {
329     // Evergreen / Northern Islands
330     switch (MF.getFunction()->getCallingConv()) {
331     default: LLVM_FALLTHROUGH;
332     case CallingConv::AMDGPU_CS: RsrcReg = R_0288D4_SQ_PGM_RESOURCES_LS; break;
333     case CallingConv::AMDGPU_GS: RsrcReg = R_028878_SQ_PGM_RESOURCES_GS; break;
334     case CallingConv::AMDGPU_PS: RsrcReg = R_028844_SQ_PGM_RESOURCES_PS; break;
335     case CallingConv::AMDGPU_VS: RsrcReg = R_028860_SQ_PGM_RESOURCES_VS; break;
336     }
337   } else {
338     // R600 / R700
339     switch (MF.getFunction()->getCallingConv()) {
340     default: LLVM_FALLTHROUGH;
341     case CallingConv::AMDGPU_GS: LLVM_FALLTHROUGH;
342     case CallingConv::AMDGPU_CS: LLVM_FALLTHROUGH;
343     case CallingConv::AMDGPU_VS: RsrcReg = R_028868_SQ_PGM_RESOURCES_VS; break;
344     case CallingConv::AMDGPU_PS: RsrcReg = R_028850_SQ_PGM_RESOURCES_PS; break;
345     }
346   }
347 
348   OutStreamer->EmitIntValue(RsrcReg, 4);
349   OutStreamer->EmitIntValue(S_NUM_GPRS(MaxGPR + 1) |
350                            S_STACK_SIZE(MFI->CFStackSize), 4);
351   OutStreamer->EmitIntValue(R_02880C_DB_SHADER_CONTROL, 4);
352   OutStreamer->EmitIntValue(S_02880C_KILL_ENABLE(killPixel), 4);
353 
354   if (AMDGPU::isCompute(MF.getFunction()->getCallingConv())) {
355     OutStreamer->EmitIntValue(R_0288E8_SQ_LDS_ALLOC, 4);
356     OutStreamer->EmitIntValue(alignTo(MFI->getLDSSize(), 4) >> 2, 4);
357   }
358 }
359 
360 void AMDGPUAsmPrinter::getSIProgramInfo(SIProgramInfo &ProgInfo,
361                                         const MachineFunction &MF) const {
362   const SISubtarget &STM = MF.getSubtarget<SISubtarget>();
363   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
364   uint64_t CodeSize = 0;
365   unsigned MaxSGPR = 0;
366   unsigned MaxVGPR = 0;
367   bool VCCUsed = false;
368   bool FlatUsed = false;
369   const SIRegisterInfo *RI = STM.getRegisterInfo();
370   const SIInstrInfo *TII = STM.getInstrInfo();
371 
372   for (const MachineBasicBlock &MBB : MF) {
373     for (const MachineInstr &MI : MBB) {
374       // TODO: CodeSize should account for multiple functions.
375 
376       // TODO: Should we count size of debug info?
377       if (MI.isDebugValue())
378         continue;
379 
380       if (isVerbose())
381         CodeSize += TII->getInstSizeInBytes(MI);
382 
383       unsigned numOperands = MI.getNumOperands();
384       for (unsigned op_idx = 0; op_idx < numOperands; op_idx++) {
385         const MachineOperand &MO = MI.getOperand(op_idx);
386         unsigned width = 0;
387         bool isSGPR = false;
388 
389         if (!MO.isReg())
390           continue;
391 
392         unsigned reg = MO.getReg();
393         switch (reg) {
394         case AMDGPU::EXEC:
395         case AMDGPU::EXEC_LO:
396         case AMDGPU::EXEC_HI:
397         case AMDGPU::SCC:
398         case AMDGPU::M0:
399         case AMDGPU::SRC_SHARED_BASE:
400         case AMDGPU::SRC_SHARED_LIMIT:
401         case AMDGPU::SRC_PRIVATE_BASE:
402         case AMDGPU::SRC_PRIVATE_LIMIT:
403           continue;
404 
405         case AMDGPU::VCC:
406         case AMDGPU::VCC_LO:
407         case AMDGPU::VCC_HI:
408           VCCUsed = true;
409           continue;
410 
411         case AMDGPU::FLAT_SCR:
412         case AMDGPU::FLAT_SCR_LO:
413         case AMDGPU::FLAT_SCR_HI:
414           // Even if FLAT_SCRATCH is implicitly used, it has no effect if flat
415           // instructions aren't used to access the scratch buffer.
416           if (MFI->hasFlatScratchInit())
417             FlatUsed = true;
418           continue;
419 
420         case AMDGPU::TBA:
421         case AMDGPU::TBA_LO:
422         case AMDGPU::TBA_HI:
423         case AMDGPU::TMA:
424         case AMDGPU::TMA_LO:
425         case AMDGPU::TMA_HI:
426           llvm_unreachable("trap handler registers should not be used");
427 
428         default:
429           break;
430         }
431 
432         if (AMDGPU::SReg_32RegClass.contains(reg)) {
433           assert(!AMDGPU::TTMP_32RegClass.contains(reg) &&
434                  "trap handler registers should not be used");
435           isSGPR = true;
436           width = 1;
437         } else if (AMDGPU::VGPR_32RegClass.contains(reg)) {
438           isSGPR = false;
439           width = 1;
440         } else if (AMDGPU::SReg_64RegClass.contains(reg)) {
441           assert(!AMDGPU::TTMP_64RegClass.contains(reg) &&
442                  "trap handler registers should not be used");
443           isSGPR = true;
444           width = 2;
445         } else if (AMDGPU::VReg_64RegClass.contains(reg)) {
446           isSGPR = false;
447           width = 2;
448         } else if (AMDGPU::VReg_96RegClass.contains(reg)) {
449           isSGPR = false;
450           width = 3;
451         } else if (AMDGPU::SReg_128RegClass.contains(reg)) {
452           isSGPR = true;
453           width = 4;
454         } else if (AMDGPU::VReg_128RegClass.contains(reg)) {
455           isSGPR = false;
456           width = 4;
457         } else if (AMDGPU::SReg_256RegClass.contains(reg)) {
458           isSGPR = true;
459           width = 8;
460         } else if (AMDGPU::VReg_256RegClass.contains(reg)) {
461           isSGPR = false;
462           width = 8;
463         } else if (AMDGPU::SReg_512RegClass.contains(reg)) {
464           isSGPR = true;
465           width = 16;
466         } else if (AMDGPU::VReg_512RegClass.contains(reg)) {
467           isSGPR = false;
468           width = 16;
469         } else {
470           llvm_unreachable("Unknown register class");
471         }
472         unsigned hwReg = RI->getEncodingValue(reg) & 0xff;
473         unsigned maxUsed = hwReg + width - 1;
474         if (isSGPR) {
475           MaxSGPR = maxUsed > MaxSGPR ? maxUsed : MaxSGPR;
476         } else {
477           MaxVGPR = maxUsed > MaxVGPR ? maxUsed : MaxVGPR;
478         }
479       }
480     }
481   }
482 
483   unsigned ExtraSGPRs = 0;
484 
485   if (VCCUsed)
486     ExtraSGPRs = 2;
487 
488   if (STM.getGeneration() < SISubtarget::VOLCANIC_ISLANDS) {
489     if (FlatUsed)
490       ExtraSGPRs = 4;
491   } else {
492     if (STM.isXNACKEnabled())
493       ExtraSGPRs = 4;
494 
495     if (FlatUsed)
496       ExtraSGPRs = 6;
497   }
498 
499   unsigned ExtraVGPRs = STM.getReservedNumVGPRs(MF);
500 
501   // Check the addressable register limit before we add ExtraSGPRs.
502   if (STM.getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS &&
503       !STM.hasSGPRInitBug()) {
504     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
505     if (MaxSGPR + 1 > MaxAddressableNumSGPRs) {
506       // This can happen due to a compiler bug or when using inline asm.
507       LLVMContext &Ctx = MF.getFunction()->getContext();
508       DiagnosticInfoResourceLimit Diag(*MF.getFunction(),
509                                        "addressable scalar registers",
510                                        MaxSGPR + 1, DS_Error,
511                                        DK_ResourceLimit,
512                                        MaxAddressableNumSGPRs);
513       Ctx.diagnose(Diag);
514       MaxSGPR = MaxAddressableNumSGPRs - 1;
515     }
516   }
517 
518   // Account for extra SGPRs and VGPRs reserved for debugger use.
519   MaxSGPR += ExtraSGPRs;
520   MaxVGPR += ExtraVGPRs;
521 
522   // We found the maximum register index. They start at 0, so add one to get the
523   // number of registers.
524   ProgInfo.NumSGPR = MaxSGPR + 1;
525   ProgInfo.NumVGPR = MaxVGPR + 1;
526 
527   // Adjust number of registers used to meet default/requested minimum/maximum
528   // number of waves per execution unit request.
529   ProgInfo.NumSGPRsForWavesPerEU = std::max(
530     ProgInfo.NumSGPR, STM.getMinNumSGPRs(MFI->getMaxWavesPerEU()));
531   ProgInfo.NumVGPRsForWavesPerEU = std::max(
532     ProgInfo.NumVGPR, STM.getMinNumVGPRs(MFI->getMaxWavesPerEU()));
533 
534   if (STM.getGeneration() <= AMDGPUSubtarget::SEA_ISLANDS ||
535       STM.hasSGPRInitBug()) {
536     unsigned MaxAddressableNumSGPRs = STM.getAddressableNumSGPRs();
537     if (ProgInfo.NumSGPR > MaxAddressableNumSGPRs) {
538       // This can happen due to a compiler bug or when using inline asm to use
539       // the registers which are usually reserved for vcc etc.
540       LLVMContext &Ctx = MF.getFunction()->getContext();
541       DiagnosticInfoResourceLimit Diag(*MF.getFunction(),
542                                        "scalar registers",
543                                        ProgInfo.NumSGPR, DS_Error,
544                                        DK_ResourceLimit,
545                                        MaxAddressableNumSGPRs);
546       Ctx.diagnose(Diag);
547       ProgInfo.NumSGPR = MaxAddressableNumSGPRs;
548       ProgInfo.NumSGPRsForWavesPerEU = MaxAddressableNumSGPRs;
549     }
550   }
551 
552   if (STM.hasSGPRInitBug()) {
553     ProgInfo.NumSGPR =
554         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
555     ProgInfo.NumSGPRsForWavesPerEU =
556         AMDGPU::IsaInfo::FIXED_NUM_SGPRS_FOR_INIT_BUG;
557   }
558 
559   if (MFI->NumUserSGPRs > STM.getMaxNumUserSGPRs()) {
560     LLVMContext &Ctx = MF.getFunction()->getContext();
561     DiagnosticInfoResourceLimit Diag(*MF.getFunction(), "user SGPRs",
562                                      MFI->NumUserSGPRs, DS_Error);
563     Ctx.diagnose(Diag);
564   }
565 
566   if (MFI->getLDSSize() > static_cast<unsigned>(STM.getLocalMemorySize())) {
567     LLVMContext &Ctx = MF.getFunction()->getContext();
568     DiagnosticInfoResourceLimit Diag(*MF.getFunction(), "local memory",
569                                      MFI->getLDSSize(), DS_Error);
570     Ctx.diagnose(Diag);
571   }
572 
573   // SGPRBlocks is actual number of SGPR blocks minus 1.
574   ProgInfo.SGPRBlocks = alignTo(ProgInfo.NumSGPRsForWavesPerEU,
575                                 STM.getSGPREncodingGranule());
576   ProgInfo.SGPRBlocks = ProgInfo.SGPRBlocks / STM.getSGPREncodingGranule() - 1;
577 
578   // VGPRBlocks is actual number of VGPR blocks minus 1.
579   ProgInfo.VGPRBlocks = alignTo(ProgInfo.NumVGPRsForWavesPerEU,
580                                 STM.getVGPREncodingGranule());
581   ProgInfo.VGPRBlocks = ProgInfo.VGPRBlocks / STM.getVGPREncodingGranule() - 1;
582 
583   // Record first reserved VGPR and number of reserved VGPRs.
584   ProgInfo.ReservedVGPRFirst = STM.debuggerReserveRegs() ? MaxVGPR + 1 : 0;
585   ProgInfo.ReservedVGPRCount = STM.getReservedNumVGPRs(MF);
586 
587   // Update DebuggerWavefrontPrivateSegmentOffsetSGPR and
588   // DebuggerPrivateSegmentBufferSGPR fields if "amdgpu-debugger-emit-prologue"
589   // attribute was requested.
590   if (STM.debuggerEmitPrologue()) {
591     ProgInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR =
592       RI->getHWRegIndex(MFI->getScratchWaveOffsetReg());
593     ProgInfo.DebuggerPrivateSegmentBufferSGPR =
594       RI->getHWRegIndex(MFI->getScratchRSrcReg());
595   }
596 
597   // Set the value to initialize FP_ROUND and FP_DENORM parts of the mode
598   // register.
599   ProgInfo.FloatMode = getFPMode(MF);
600 
601   ProgInfo.IEEEMode = STM.enableIEEEBit(MF);
602 
603   // Make clamp modifier on NaN input returns 0.
604   ProgInfo.DX10Clamp = STM.enableDX10Clamp();
605 
606   const MachineFrameInfo &FrameInfo = MF.getFrameInfo();
607   ProgInfo.ScratchSize = FrameInfo.getStackSize();
608 
609   ProgInfo.FlatUsed = FlatUsed;
610   ProgInfo.VCCUsed = VCCUsed;
611   ProgInfo.CodeLen = CodeSize;
612 
613   unsigned LDSAlignShift;
614   if (STM.getGeneration() < SISubtarget::SEA_ISLANDS) {
615     // LDS is allocated in 64 dword blocks.
616     LDSAlignShift = 8;
617   } else {
618     // LDS is allocated in 128 dword blocks.
619     LDSAlignShift = 9;
620   }
621 
622   unsigned LDSSpillSize =
623     MFI->LDSWaveSpillSize * MFI->getMaxFlatWorkGroupSize();
624 
625   ProgInfo.LDSSize = MFI->getLDSSize() + LDSSpillSize;
626   ProgInfo.LDSBlocks =
627       alignTo(ProgInfo.LDSSize, 1ULL << LDSAlignShift) >> LDSAlignShift;
628 
629   // Scratch is allocated in 256 dword blocks.
630   unsigned ScratchAlignShift = 10;
631   // We need to program the hardware with the amount of scratch memory that
632   // is used by the entire wave.  ProgInfo.ScratchSize is the amount of
633   // scratch memory used per thread.
634   ProgInfo.ScratchBlocks =
635       alignTo(ProgInfo.ScratchSize * STM.getWavefrontSize(),
636               1ULL << ScratchAlignShift) >>
637       ScratchAlignShift;
638 
639   ProgInfo.ComputePGMRSrc1 =
640       S_00B848_VGPRS(ProgInfo.VGPRBlocks) |
641       S_00B848_SGPRS(ProgInfo.SGPRBlocks) |
642       S_00B848_PRIORITY(ProgInfo.Priority) |
643       S_00B848_FLOAT_MODE(ProgInfo.FloatMode) |
644       S_00B848_PRIV(ProgInfo.Priv) |
645       S_00B848_DX10_CLAMP(ProgInfo.DX10Clamp) |
646       S_00B848_DEBUG_MODE(ProgInfo.DebugMode) |
647       S_00B848_IEEE_MODE(ProgInfo.IEEEMode);
648 
649   // 0 = X, 1 = XY, 2 = XYZ
650   unsigned TIDIGCompCnt = 0;
651   if (MFI->hasWorkItemIDZ())
652     TIDIGCompCnt = 2;
653   else if (MFI->hasWorkItemIDY())
654     TIDIGCompCnt = 1;
655 
656   ProgInfo.ComputePGMRSrc2 =
657       S_00B84C_SCRATCH_EN(ProgInfo.ScratchBlocks > 0) |
658       S_00B84C_USER_SGPR(MFI->getNumUserSGPRs()) |
659       S_00B84C_TRAP_HANDLER(STM.isTrapHandlerEnabled()) |
660       S_00B84C_TGID_X_EN(MFI->hasWorkGroupIDX()) |
661       S_00B84C_TGID_Y_EN(MFI->hasWorkGroupIDY()) |
662       S_00B84C_TGID_Z_EN(MFI->hasWorkGroupIDZ()) |
663       S_00B84C_TG_SIZE_EN(MFI->hasWorkGroupInfo()) |
664       S_00B84C_TIDIG_COMP_CNT(TIDIGCompCnt) |
665       S_00B84C_EXCP_EN_MSB(0) |
666       S_00B84C_LDS_SIZE(ProgInfo.LDSBlocks) |
667       S_00B84C_EXCP_EN(0);
668 }
669 
670 static unsigned getRsrcReg(CallingConv::ID CallConv) {
671   switch (CallConv) {
672   default: LLVM_FALLTHROUGH;
673   case CallingConv::AMDGPU_CS: return R_00B848_COMPUTE_PGM_RSRC1;
674   case CallingConv::AMDGPU_GS: return R_00B228_SPI_SHADER_PGM_RSRC1_GS;
675   case CallingConv::AMDGPU_PS: return R_00B028_SPI_SHADER_PGM_RSRC1_PS;
676   case CallingConv::AMDGPU_VS: return R_00B128_SPI_SHADER_PGM_RSRC1_VS;
677   }
678 }
679 
680 void AMDGPUAsmPrinter::EmitProgramInfoSI(const MachineFunction &MF,
681                                          const SIProgramInfo &KernelInfo) {
682   const SISubtarget &STM = MF.getSubtarget<SISubtarget>();
683   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
684   unsigned RsrcReg = getRsrcReg(MF.getFunction()->getCallingConv());
685 
686   if (AMDGPU::isCompute(MF.getFunction()->getCallingConv())) {
687     OutStreamer->EmitIntValue(R_00B848_COMPUTE_PGM_RSRC1, 4);
688 
689     OutStreamer->EmitIntValue(KernelInfo.ComputePGMRSrc1, 4);
690 
691     OutStreamer->EmitIntValue(R_00B84C_COMPUTE_PGM_RSRC2, 4);
692     OutStreamer->EmitIntValue(KernelInfo.ComputePGMRSrc2, 4);
693 
694     OutStreamer->EmitIntValue(R_00B860_COMPUTE_TMPRING_SIZE, 4);
695     OutStreamer->EmitIntValue(S_00B860_WAVESIZE(KernelInfo.ScratchBlocks), 4);
696 
697     // TODO: Should probably note flat usage somewhere. SC emits a "FlatPtr32 =
698     // 0" comment but I don't see a corresponding field in the register spec.
699   } else {
700     OutStreamer->EmitIntValue(RsrcReg, 4);
701     OutStreamer->EmitIntValue(S_00B028_VGPRS(KernelInfo.VGPRBlocks) |
702                               S_00B028_SGPRS(KernelInfo.SGPRBlocks), 4);
703     if (STM.isVGPRSpillingEnabled(*MF.getFunction())) {
704       OutStreamer->EmitIntValue(R_0286E8_SPI_TMPRING_SIZE, 4);
705       OutStreamer->EmitIntValue(S_0286E8_WAVESIZE(KernelInfo.ScratchBlocks), 4);
706     }
707   }
708 
709   if (MF.getFunction()->getCallingConv() == CallingConv::AMDGPU_PS) {
710     OutStreamer->EmitIntValue(R_00B02C_SPI_SHADER_PGM_RSRC2_PS, 4);
711     OutStreamer->EmitIntValue(S_00B02C_EXTRA_LDS_SIZE(KernelInfo.LDSBlocks), 4);
712     OutStreamer->EmitIntValue(R_0286CC_SPI_PS_INPUT_ENA, 4);
713     OutStreamer->EmitIntValue(MFI->PSInputEna, 4);
714     OutStreamer->EmitIntValue(R_0286D0_SPI_PS_INPUT_ADDR, 4);
715     OutStreamer->EmitIntValue(MFI->getPSInputAddr(), 4);
716   }
717 
718   OutStreamer->EmitIntValue(R_SPILLED_SGPRS, 4);
719   OutStreamer->EmitIntValue(MFI->getNumSpilledSGPRs(), 4);
720   OutStreamer->EmitIntValue(R_SPILLED_VGPRS, 4);
721   OutStreamer->EmitIntValue(MFI->getNumSpilledVGPRs(), 4);
722 }
723 
724 // This is supposed to be log2(Size)
725 static amd_element_byte_size_t getElementByteSizeValue(unsigned Size) {
726   switch (Size) {
727   case 4:
728     return AMD_ELEMENT_4_BYTES;
729   case 8:
730     return AMD_ELEMENT_8_BYTES;
731   case 16:
732     return AMD_ELEMENT_16_BYTES;
733   default:
734     llvm_unreachable("invalid private_element_size");
735   }
736 }
737 
738 void AMDGPUAsmPrinter::getAmdKernelCode(amd_kernel_code_t &Out,
739                                         const SIProgramInfo &KernelInfo,
740                                         const MachineFunction &MF) const {
741   const SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
742   const SISubtarget &STM = MF.getSubtarget<SISubtarget>();
743 
744   AMDGPU::initDefaultAMDKernelCodeT(Out, STM.getFeatureBits());
745 
746   Out.compute_pgm_resource_registers =
747       KernelInfo.ComputePGMRSrc1 |
748       (KernelInfo.ComputePGMRSrc2 << 32);
749   Out.code_properties = AMD_CODE_PROPERTY_IS_PTR64;
750 
751   AMD_HSA_BITS_SET(Out.code_properties,
752                    AMD_CODE_PROPERTY_PRIVATE_ELEMENT_SIZE,
753                    getElementByteSizeValue(STM.getMaxPrivateElementSize()));
754 
755   if (MFI->hasPrivateSegmentBuffer()) {
756     Out.code_properties |=
757       AMD_CODE_PROPERTY_ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER;
758   }
759 
760   if (MFI->hasDispatchPtr())
761     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
762 
763   if (MFI->hasQueuePtr())
764     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_QUEUE_PTR;
765 
766   if (MFI->hasKernargSegmentPtr())
767     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_KERNARG_SEGMENT_PTR;
768 
769   if (MFI->hasDispatchID())
770     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_ID;
771 
772   if (MFI->hasFlatScratchInit())
773     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_FLAT_SCRATCH_INIT;
774 
775   if (MFI->hasGridWorkgroupCountX()) {
776     Out.code_properties |=
777       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_X;
778   }
779 
780   if (MFI->hasGridWorkgroupCountY()) {
781     Out.code_properties |=
782       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Y;
783   }
784 
785   if (MFI->hasGridWorkgroupCountZ()) {
786     Out.code_properties |=
787       AMD_CODE_PROPERTY_ENABLE_SGPR_GRID_WORKGROUP_COUNT_Z;
788   }
789 
790   if (MFI->hasDispatchPtr())
791     Out.code_properties |= AMD_CODE_PROPERTY_ENABLE_SGPR_DISPATCH_PTR;
792 
793   if (STM.debuggerSupported())
794     Out.code_properties |= AMD_CODE_PROPERTY_IS_DEBUG_SUPPORTED;
795 
796   if (STM.isXNACKEnabled())
797     Out.code_properties |= AMD_CODE_PROPERTY_IS_XNACK_SUPPORTED;
798 
799   // FIXME: Should use getKernArgSize
800   Out.kernarg_segment_byte_size =
801     STM.getKernArgSegmentSize(MF, MFI->getABIArgOffset());
802   Out.wavefront_sgpr_count = KernelInfo.NumSGPR;
803   Out.workitem_vgpr_count = KernelInfo.NumVGPR;
804   Out.workitem_private_segment_byte_size = KernelInfo.ScratchSize;
805   Out.workgroup_group_segment_byte_size = KernelInfo.LDSSize;
806   Out.reserved_vgpr_first = KernelInfo.ReservedVGPRFirst;
807   Out.reserved_vgpr_count = KernelInfo.ReservedVGPRCount;
808 
809   // These alignment values are specified in powers of two, so alignment =
810   // 2^n.  The minimum alignment is 2^4 = 16.
811   Out.kernarg_segment_alignment = std::max((size_t)4,
812       countTrailingZeros(MFI->getMaxKernArgAlign()));
813 
814   if (STM.debuggerEmitPrologue()) {
815     Out.debug_wavefront_private_segment_offset_sgpr =
816       KernelInfo.DebuggerWavefrontPrivateSegmentOffsetSGPR;
817     Out.debug_private_segment_buffer_sgpr =
818       KernelInfo.DebuggerPrivateSegmentBufferSGPR;
819   }
820 }
821 
822 bool AMDGPUAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
823                                        unsigned AsmVariant,
824                                        const char *ExtraCode, raw_ostream &O) {
825   if (ExtraCode && ExtraCode[0]) {
826     if (ExtraCode[1] != 0)
827       return true; // Unknown modifier.
828 
829     switch (ExtraCode[0]) {
830     default:
831       // See if this is a generic print operand
832       return AsmPrinter::PrintAsmOperand(MI, OpNo, AsmVariant, ExtraCode, O);
833     case 'r':
834       break;
835     }
836   }
837 
838   AMDGPUInstPrinter::printRegOperand(MI->getOperand(OpNo).getReg(), O,
839                    *TM.getSubtargetImpl(*MF->getFunction())->getRegisterInfo());
840   return false;
841 }
842