1 //===-- SIMCCodeEmitter.cpp - SI Code Emitter -----------------------------===//
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 /// The SI code emitter produces machine code that can be executed
11 /// directly on the GPU device.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "MCTargetDesc/AMDGPUFixupKinds.h"
16 #include "MCTargetDesc/AMDGPUMCCodeEmitter.h"
17 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
18 #include "SIDefines.h"
19 #include "Utils/AMDGPUBaseInfo.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCInstrInfo.h"
23 #include "llvm/MC/MCRegisterInfo.h"
24 
25 using namespace llvm;
26 
27 namespace {
28 
29 class SIMCCodeEmitter : public  AMDGPUMCCodeEmitter {
30   const MCRegisterInfo &MRI;
31 
32   /// Encode an fp or int literal
33   uint32_t getLitEncoding(const MCOperand &MO, const MCOperandInfo &OpInfo,
34                           const MCSubtargetInfo &STI) const;
35 
36 public:
37   SIMCCodeEmitter(const MCInstrInfo &mcii, const MCRegisterInfo &mri,
38                   MCContext &ctx)
39       : AMDGPUMCCodeEmitter(mcii), MRI(mri) {}
40   SIMCCodeEmitter(const SIMCCodeEmitter &) = delete;
41   SIMCCodeEmitter &operator=(const SIMCCodeEmitter &) = delete;
42 
43   /// Encode the instruction and write it to the OS.
44   void encodeInstruction(const MCInst &MI, raw_ostream &OS,
45                          SmallVectorImpl<MCFixup> &Fixups,
46                          const MCSubtargetInfo &STI) const override;
47 
48   /// \returns the encoding for an MCOperand.
49   uint64_t getMachineOpValue(const MCInst &MI, const MCOperand &MO,
50                              SmallVectorImpl<MCFixup> &Fixups,
51                              const MCSubtargetInfo &STI) const override;
52 
53   /// Use a fixup to encode the simm16 field for SOPP branch
54   ///        instructions.
55   unsigned getSOPPBrEncoding(const MCInst &MI, unsigned OpNo,
56                              SmallVectorImpl<MCFixup> &Fixups,
57                              const MCSubtargetInfo &STI) const override;
58 
59   unsigned getSMEMOffsetEncoding(const MCInst &MI, unsigned OpNo,
60                                  SmallVectorImpl<MCFixup> &Fixups,
61                                  const MCSubtargetInfo &STI) const override;
62 
63   unsigned getSDWASrcEncoding(const MCInst &MI, unsigned OpNo,
64                               SmallVectorImpl<MCFixup> &Fixups,
65                               const MCSubtargetInfo &STI) const override;
66 
67   unsigned getSDWAVopcDstEncoding(const MCInst &MI, unsigned OpNo,
68                                   SmallVectorImpl<MCFixup> &Fixups,
69                                   const MCSubtargetInfo &STI) const override;
70 
71   unsigned getAVOperandEncoding(const MCInst &MI, unsigned OpNo,
72                                 SmallVectorImpl<MCFixup> &Fixups,
73                                 const MCSubtargetInfo &STI) const override;
74 };
75 
76 } // end anonymous namespace
77 
78 MCCodeEmitter *llvm::createSIMCCodeEmitter(const MCInstrInfo &MCII,
79                                            const MCRegisterInfo &MRI,
80                                            MCContext &Ctx) {
81   return new SIMCCodeEmitter(MCII, MRI, Ctx);
82 }
83 
84 // Returns the encoding value to use if the given integer is an integer inline
85 // immediate value, or 0 if it is not.
86 template <typename IntTy>
87 static uint32_t getIntInlineImmEncoding(IntTy Imm) {
88   if (Imm >= 0 && Imm <= 64)
89     return 128 + Imm;
90 
91   if (Imm >= -16 && Imm <= -1)
92     return 192 + std::abs(Imm);
93 
94   return 0;
95 }
96 
97 static uint32_t getLit16IntEncoding(uint16_t Val, const MCSubtargetInfo &STI) {
98   uint16_t IntImm = getIntInlineImmEncoding(static_cast<int16_t>(Val));
99   return IntImm == 0 ? 255 : IntImm;
100 }
101 
102 static uint32_t getLit16Encoding(uint16_t Val, const MCSubtargetInfo &STI) {
103   uint16_t IntImm = getIntInlineImmEncoding(static_cast<int16_t>(Val));
104   if (IntImm != 0)
105     return IntImm;
106 
107   if (Val == 0x3800) // 0.5
108     return 240;
109 
110   if (Val == 0xB800) // -0.5
111     return 241;
112 
113   if (Val == 0x3C00) // 1.0
114     return 242;
115 
116   if (Val == 0xBC00) // -1.0
117     return 243;
118 
119   if (Val == 0x4000) // 2.0
120     return 244;
121 
122   if (Val == 0xC000) // -2.0
123     return 245;
124 
125   if (Val == 0x4400) // 4.0
126     return 246;
127 
128   if (Val == 0xC400) // -4.0
129     return 247;
130 
131   if (Val == 0x3118 && // 1.0 / (2.0 * pi)
132       STI.getFeatureBits()[AMDGPU::FeatureInv2PiInlineImm])
133     return 248;
134 
135   return 255;
136 }
137 
138 static uint32_t getLit32Encoding(uint32_t Val, const MCSubtargetInfo &STI) {
139   uint32_t IntImm = getIntInlineImmEncoding(static_cast<int32_t>(Val));
140   if (IntImm != 0)
141     return IntImm;
142 
143   if (Val == FloatToBits(0.5f))
144     return 240;
145 
146   if (Val == FloatToBits(-0.5f))
147     return 241;
148 
149   if (Val == FloatToBits(1.0f))
150     return 242;
151 
152   if (Val == FloatToBits(-1.0f))
153     return 243;
154 
155   if (Val == FloatToBits(2.0f))
156     return 244;
157 
158   if (Val == FloatToBits(-2.0f))
159     return 245;
160 
161   if (Val == FloatToBits(4.0f))
162     return 246;
163 
164   if (Val == FloatToBits(-4.0f))
165     return 247;
166 
167   if (Val == 0x3e22f983 && // 1.0 / (2.0 * pi)
168       STI.getFeatureBits()[AMDGPU::FeatureInv2PiInlineImm])
169     return 248;
170 
171   return 255;
172 }
173 
174 static uint32_t getLit64Encoding(uint64_t Val, const MCSubtargetInfo &STI) {
175   uint32_t IntImm = getIntInlineImmEncoding(static_cast<int64_t>(Val));
176   if (IntImm != 0)
177     return IntImm;
178 
179   if (Val == DoubleToBits(0.5))
180     return 240;
181 
182   if (Val == DoubleToBits(-0.5))
183     return 241;
184 
185   if (Val == DoubleToBits(1.0))
186     return 242;
187 
188   if (Val == DoubleToBits(-1.0))
189     return 243;
190 
191   if (Val == DoubleToBits(2.0))
192     return 244;
193 
194   if (Val == DoubleToBits(-2.0))
195     return 245;
196 
197   if (Val == DoubleToBits(4.0))
198     return 246;
199 
200   if (Val == DoubleToBits(-4.0))
201     return 247;
202 
203   if (Val == 0x3fc45f306dc9c882 && // 1.0 / (2.0 * pi)
204       STI.getFeatureBits()[AMDGPU::FeatureInv2PiInlineImm])
205     return 248;
206 
207   return 255;
208 }
209 
210 uint32_t SIMCCodeEmitter::getLitEncoding(const MCOperand &MO,
211                                          const MCOperandInfo &OpInfo,
212                                          const MCSubtargetInfo &STI) const {
213   int64_t Imm;
214   if (MO.isExpr()) {
215     const auto *C = dyn_cast<MCConstantExpr>(MO.getExpr());
216     if (!C)
217       return 255;
218 
219     Imm = C->getValue();
220   } else {
221 
222     assert(!MO.isDFPImm());
223 
224     if (!MO.isImm())
225       return ~0;
226 
227     Imm = MO.getImm();
228   }
229 
230   switch (OpInfo.OperandType) {
231   case AMDGPU::OPERAND_REG_IMM_INT32:
232   case AMDGPU::OPERAND_REG_IMM_FP32:
233   case AMDGPU::OPERAND_REG_INLINE_C_INT32:
234   case AMDGPU::OPERAND_REG_INLINE_C_FP32:
235   case AMDGPU::OPERAND_REG_INLINE_AC_INT32:
236   case AMDGPU::OPERAND_REG_INLINE_AC_FP32:
237     return getLit32Encoding(static_cast<uint32_t>(Imm), STI);
238 
239   case AMDGPU::OPERAND_REG_IMM_INT64:
240   case AMDGPU::OPERAND_REG_IMM_FP64:
241   case AMDGPU::OPERAND_REG_INLINE_C_INT64:
242   case AMDGPU::OPERAND_REG_INLINE_C_FP64:
243     return getLit64Encoding(static_cast<uint64_t>(Imm), STI);
244 
245   case AMDGPU::OPERAND_REG_IMM_INT16:
246   case AMDGPU::OPERAND_REG_INLINE_C_INT16:
247   case AMDGPU::OPERAND_REG_INLINE_AC_INT16:
248     return getLit16IntEncoding(static_cast<uint16_t>(Imm), STI);
249   case AMDGPU::OPERAND_REG_IMM_FP16:
250   case AMDGPU::OPERAND_REG_INLINE_C_FP16:
251   case AMDGPU::OPERAND_REG_INLINE_AC_FP16:
252     // FIXME Is this correct? What do inline immediates do on SI for f16 src
253     // which does not have f16 support?
254     return getLit16Encoding(static_cast<uint16_t>(Imm), STI);
255   case AMDGPU::OPERAND_REG_IMM_V2INT16:
256   case AMDGPU::OPERAND_REG_IMM_V2FP16: {
257     if (!isUInt<16>(Imm) && STI.getFeatureBits()[AMDGPU::FeatureVOP3Literal])
258       return getLit32Encoding(static_cast<uint32_t>(Imm), STI);
259     if (OpInfo.OperandType == AMDGPU::OPERAND_REG_IMM_V2FP16)
260       return getLit16Encoding(static_cast<uint16_t>(Imm), STI);
261     LLVM_FALLTHROUGH;
262   }
263   case AMDGPU::OPERAND_REG_INLINE_C_V2INT16:
264   case AMDGPU::OPERAND_REG_INLINE_AC_V2INT16:
265     return getLit16IntEncoding(static_cast<uint16_t>(Imm), STI);
266   case AMDGPU::OPERAND_REG_INLINE_C_V2FP16:
267   case AMDGPU::OPERAND_REG_INLINE_AC_V2FP16: {
268     uint16_t Lo16 = static_cast<uint16_t>(Imm);
269     uint32_t Encoding = getLit16Encoding(Lo16, STI);
270     return Encoding;
271   }
272   default:
273     llvm_unreachable("invalid operand size");
274   }
275 }
276 
277 void SIMCCodeEmitter::encodeInstruction(const MCInst &MI, raw_ostream &OS,
278                                        SmallVectorImpl<MCFixup> &Fixups,
279                                        const MCSubtargetInfo &STI) const {
280   verifyInstructionPredicates(MI,
281                               computeAvailableFeatures(STI.getFeatureBits()));
282 
283   uint64_t Encoding = getBinaryCodeForInstr(MI, Fixups, STI);
284   const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
285   unsigned bytes = Desc.getSize();
286 
287   switch (MI.getOpcode()) {
288   case AMDGPU::V_ACCVGPR_READ_B32_vi:
289   case AMDGPU::V_ACCVGPR_WRITE_B32_vi:
290     // Set unused op_sel_hi bits to 1.
291     // FIXME: This shall be done for all VOP3P but not MAI instructions with
292     // unused op_sel_hi bits if corresponding operands do not exist.
293     // accvgpr_read/write are different, however. These are VOP3P, MAI, have
294     // src0, but do not use op_sel.
295     Encoding |= (1ull << 14) | (1ull << 59) | (1ull << 60);
296     break;
297   default:
298     break;
299   }
300 
301   for (unsigned i = 0; i < bytes; i++) {
302     OS.write((uint8_t) ((Encoding >> (8 * i)) & 0xff));
303   }
304 
305   // NSA encoding.
306   if (AMDGPU::isGFX10Plus(STI) && Desc.TSFlags & SIInstrFlags::MIMG) {
307     int vaddr0 = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
308                                             AMDGPU::OpName::vaddr0);
309     int srsrc = AMDGPU::getNamedOperandIdx(MI.getOpcode(),
310                                            AMDGPU::OpName::srsrc);
311     assert(vaddr0 >= 0 && srsrc > vaddr0);
312     unsigned NumExtraAddrs = srsrc - vaddr0 - 1;
313     unsigned NumPadding = (-NumExtraAddrs) & 3;
314 
315     for (unsigned i = 0; i < NumExtraAddrs; ++i)
316       OS.write((uint8_t)getMachineOpValue(MI, MI.getOperand(vaddr0 + 1 + i),
317                                           Fixups, STI));
318     for (unsigned i = 0; i < NumPadding; ++i)
319       OS.write(0);
320   }
321 
322   if ((bytes > 8 && STI.getFeatureBits()[AMDGPU::FeatureVOP3Literal]) ||
323       (bytes > 4 && !STI.getFeatureBits()[AMDGPU::FeatureVOP3Literal]))
324     return;
325 
326   // Check for additional literals in SRC0/1/2 (Op 1/2/3)
327   for (unsigned i = 0, e = Desc.getNumOperands(); i < e; ++i) {
328 
329     // Check if this operand should be encoded as [SV]Src
330     if (!AMDGPU::isSISrcOperand(Desc, i))
331       continue;
332 
333     // Is this operand a literal immediate?
334     const MCOperand &Op = MI.getOperand(i);
335     if (getLitEncoding(Op, Desc.OpInfo[i], STI) != 255)
336       continue;
337 
338     // Yes! Encode it
339     int64_t Imm = 0;
340 
341     if (Op.isImm())
342       Imm = Op.getImm();
343     else if (Op.isExpr()) {
344       if (const auto *C = dyn_cast<MCConstantExpr>(Op.getExpr()))
345         Imm = C->getValue();
346 
347     } else if (!Op.isExpr()) // Exprs will be replaced with a fixup value.
348       llvm_unreachable("Must be immediate or expr");
349 
350     for (unsigned j = 0; j < 4; j++) {
351       OS.write((uint8_t) ((Imm >> (8 * j)) & 0xff));
352     }
353 
354     // Only one literal value allowed
355     break;
356   }
357 }
358 
359 unsigned SIMCCodeEmitter::getSOPPBrEncoding(const MCInst &MI, unsigned OpNo,
360                                             SmallVectorImpl<MCFixup> &Fixups,
361                                             const MCSubtargetInfo &STI) const {
362   const MCOperand &MO = MI.getOperand(OpNo);
363 
364   if (MO.isExpr()) {
365     const MCExpr *Expr = MO.getExpr();
366     MCFixupKind Kind = (MCFixupKind)AMDGPU::fixup_si_sopp_br;
367     Fixups.push_back(MCFixup::create(0, Expr, Kind, MI.getLoc()));
368     return 0;
369   }
370 
371   return getMachineOpValue(MI, MO, Fixups, STI);
372 }
373 
374 unsigned SIMCCodeEmitter::getSMEMOffsetEncoding(const MCInst &MI, unsigned OpNo,
375                                                 SmallVectorImpl<MCFixup> &Fixups,
376                                                 const MCSubtargetInfo &STI) const {
377   auto Offset = MI.getOperand(OpNo).getImm();
378   // VI only supports 20-bit unsigned offsets.
379   assert(!AMDGPU::isVI(STI) || isUInt<20>(Offset));
380   return Offset;
381 }
382 
383 unsigned
384 SIMCCodeEmitter::getSDWASrcEncoding(const MCInst &MI, unsigned OpNo,
385                                     SmallVectorImpl<MCFixup> &Fixups,
386                                     const MCSubtargetInfo &STI) const {
387   using namespace AMDGPU::SDWA;
388 
389   uint64_t RegEnc = 0;
390 
391   const MCOperand &MO = MI.getOperand(OpNo);
392 
393   if (MO.isReg()) {
394     unsigned Reg = MO.getReg();
395     RegEnc |= MRI.getEncodingValue(Reg);
396     RegEnc &= SDWA9EncValues::SRC_VGPR_MASK;
397     if (AMDGPU::isSGPR(AMDGPU::mc2PseudoReg(Reg), &MRI)) {
398       RegEnc |= SDWA9EncValues::SRC_SGPR_MASK;
399     }
400     return RegEnc;
401   } else {
402     const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
403     uint32_t Enc = getLitEncoding(MO, Desc.OpInfo[OpNo], STI);
404     if (Enc != ~0U && Enc != 255) {
405       return Enc | SDWA9EncValues::SRC_SGPR_MASK;
406     }
407   }
408 
409   llvm_unreachable("Unsupported operand kind");
410   return 0;
411 }
412 
413 unsigned
414 SIMCCodeEmitter::getSDWAVopcDstEncoding(const MCInst &MI, unsigned OpNo,
415                                         SmallVectorImpl<MCFixup> &Fixups,
416                                         const MCSubtargetInfo &STI) const {
417   using namespace AMDGPU::SDWA;
418 
419   uint64_t RegEnc = 0;
420 
421   const MCOperand &MO = MI.getOperand(OpNo);
422 
423   unsigned Reg = MO.getReg();
424   if (Reg != AMDGPU::VCC && Reg != AMDGPU::VCC_LO) {
425     RegEnc |= MRI.getEncodingValue(Reg);
426     RegEnc &= SDWA9EncValues::VOPC_DST_SGPR_MASK;
427     RegEnc |= SDWA9EncValues::VOPC_DST_VCC_MASK;
428   }
429   return RegEnc;
430 }
431 
432 unsigned
433 SIMCCodeEmitter::getAVOperandEncoding(const MCInst &MI, unsigned OpNo,
434                                       SmallVectorImpl<MCFixup> &Fixups,
435                                       const MCSubtargetInfo &STI) const {
436   unsigned Reg = MI.getOperand(OpNo).getReg();
437   uint64_t Enc = MRI.getEncodingValue(Reg);
438 
439   // VGPR and AGPR have the same encoding, but SrcA and SrcB operands of mfma
440   // instructions use acc[0:1] modifier bits to distinguish. These bits are
441   // encoded as a virtual 9th bit of the register for these operands.
442   if (MRI.getRegClass(AMDGPU::AGPR_32RegClassID).contains(Reg) ||
443       MRI.getRegClass(AMDGPU::AReg_64RegClassID).contains(Reg) ||
444       MRI.getRegClass(AMDGPU::AReg_96RegClassID).contains(Reg) ||
445       MRI.getRegClass(AMDGPU::AReg_128RegClassID).contains(Reg) ||
446       MRI.getRegClass(AMDGPU::AReg_160RegClassID).contains(Reg) ||
447       MRI.getRegClass(AMDGPU::AReg_192RegClassID).contains(Reg) ||
448       MRI.getRegClass(AMDGPU::AReg_256RegClassID).contains(Reg) ||
449       MRI.getRegClass(AMDGPU::AGPR_LO16RegClassID).contains(Reg))
450     Enc |= 512;
451 
452   return Enc;
453 }
454 
455 static bool needsPCRel(const MCExpr *Expr) {
456   switch (Expr->getKind()) {
457   case MCExpr::SymbolRef: {
458     auto *SE = cast<MCSymbolRefExpr>(Expr);
459     MCSymbolRefExpr::VariantKind Kind = SE->getKind();
460     return Kind != MCSymbolRefExpr::VK_AMDGPU_ABS32_LO &&
461            Kind != MCSymbolRefExpr::VK_AMDGPU_ABS32_HI;
462   }
463   case MCExpr::Binary: {
464     auto *BE = cast<MCBinaryExpr>(Expr);
465     if (BE->getOpcode() == MCBinaryExpr::Sub)
466       return false;
467     return needsPCRel(BE->getLHS()) || needsPCRel(BE->getRHS());
468   }
469   case MCExpr::Unary:
470     return needsPCRel(cast<MCUnaryExpr>(Expr)->getSubExpr());
471   case MCExpr::Target:
472   case MCExpr::Constant:
473     return false;
474   }
475   llvm_unreachable("invalid kind");
476 }
477 
478 uint64_t SIMCCodeEmitter::getMachineOpValue(const MCInst &MI,
479                                             const MCOperand &MO,
480                                        SmallVectorImpl<MCFixup> &Fixups,
481                                        const MCSubtargetInfo &STI) const {
482   if (MO.isReg())
483     return MRI.getEncodingValue(MO.getReg());
484 
485   if (MO.isExpr() && MO.getExpr()->getKind() != MCExpr::Constant) {
486     // FIXME: If this is expression is PCRel or not should not depend on what
487     // the expression looks like. Given that this is just a general expression,
488     // it should probably be FK_Data_4 and whatever is producing
489     //
490     //    s_add_u32 s2, s2, (extern_const_addrspace+16
491     //
492     // And expecting a PCRel should instead produce
493     //
494     // .Ltmp1:
495     //   s_add_u32 s2, s2, (extern_const_addrspace+16)-.Ltmp1
496     MCFixupKind Kind;
497     if (needsPCRel(MO.getExpr()))
498       Kind = FK_PCRel_4;
499     else
500       Kind = FK_Data_4;
501 
502     const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
503     uint32_t Offset = Desc.getSize();
504     assert(Offset == 4 || Offset == 8);
505 
506     Fixups.push_back(
507       MCFixup::create(Offset, MO.getExpr(), Kind, MI.getLoc()));
508   }
509 
510   // Figure out the operand number, needed for isSrcOperand check
511   unsigned OpNo = 0;
512   for (unsigned e = MI.getNumOperands(); OpNo < e; ++OpNo) {
513     if (&MO == &MI.getOperand(OpNo))
514       break;
515   }
516 
517   const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
518   if (AMDGPU::isSISrcOperand(Desc, OpNo)) {
519     uint32_t Enc = getLitEncoding(MO, Desc.OpInfo[OpNo], STI);
520     if (Enc != ~0U &&
521         (Enc != 255 || Desc.getSize() == 4 || Desc.getSize() == 8))
522       return Enc;
523 
524   } else if (MO.isImm())
525     return MO.getImm();
526 
527   llvm_unreachable("Encoding of this operand type is not supported yet.");
528   return 0;
529 }
530 
531 #define ENABLE_INSTR_PREDICATE_VERIFIER
532 #include "AMDGPUGenMCCodeEmitter.inc"
533