1 //===-- PPCMCCodeEmitter.cpp - Convert PPC code to machine code -----------===//
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 // This file implements the PPCMCCodeEmitter class.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "MCTargetDesc/PPCFixupKinds.h"
14 #include "PPCInstrInfo.h"
15 #include "PPCMCCodeEmitter.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/MC/MCFixup.h"
20 #include "llvm/MC/MCInstrDesc.h"
21 #include "llvm/MC/MCRegisterInfo.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/EndianStream.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <cassert>
28 #include <cstdint>
29 
30 using namespace llvm;
31 
32 #define DEBUG_TYPE "mccodeemitter"
33 
34 STATISTIC(MCNumEmitted, "Number of MC instructions emitted");
35 
36 MCCodeEmitter *llvm::createPPCMCCodeEmitter(const MCInstrInfo &MCII,
37                                             const MCRegisterInfo &MRI,
38                                             MCContext &Ctx) {
39   return new PPCMCCodeEmitter(MCII, Ctx);
40 }
41 
42 unsigned PPCMCCodeEmitter::
43 getDirectBrEncoding(const MCInst &MI, unsigned OpNo,
44                     SmallVectorImpl<MCFixup> &Fixups,
45                     const MCSubtargetInfo &STI) const {
46   const MCOperand &MO = MI.getOperand(OpNo);
47 
48   if (MO.isReg() || MO.isImm())
49     return getMachineOpValue(MI, MO, Fixups, STI);
50   // Add a fixup for the branch target.
51   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
52                                    ((MI.getOpcode() == PPC::BL8_NOTOC ||
53                                      MI.getOpcode() == PPC::BL8_NOTOC_TLS)
54                                         ? (MCFixupKind)PPC::fixup_ppc_br24_notoc
55                                         : (MCFixupKind)PPC::fixup_ppc_br24)));
56   return 0;
57 }
58 
59 unsigned PPCMCCodeEmitter::getCondBrEncoding(const MCInst &MI, unsigned OpNo,
60                                      SmallVectorImpl<MCFixup> &Fixups,
61                                      const MCSubtargetInfo &STI) const {
62   const MCOperand &MO = MI.getOperand(OpNo);
63   if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
64 
65   // Add a fixup for the branch target.
66   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
67                                    (MCFixupKind)PPC::fixup_ppc_brcond14));
68   return 0;
69 }
70 
71 unsigned PPCMCCodeEmitter::
72 getAbsDirectBrEncoding(const MCInst &MI, unsigned OpNo,
73                        SmallVectorImpl<MCFixup> &Fixups,
74                        const MCSubtargetInfo &STI) const {
75   const MCOperand &MO = MI.getOperand(OpNo);
76   if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
77 
78   // Add a fixup for the branch target.
79   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
80                                    (MCFixupKind)PPC::fixup_ppc_br24abs));
81   return 0;
82 }
83 
84 unsigned PPCMCCodeEmitter::
85 getAbsCondBrEncoding(const MCInst &MI, unsigned OpNo,
86                      SmallVectorImpl<MCFixup> &Fixups,
87                      const MCSubtargetInfo &STI) const {
88   const MCOperand &MO = MI.getOperand(OpNo);
89   if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
90 
91   // Add a fixup for the branch target.
92   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
93                                    (MCFixupKind)PPC::fixup_ppc_brcond14abs));
94   return 0;
95 }
96 
97 unsigned PPCMCCodeEmitter::getImm16Encoding(const MCInst &MI, unsigned OpNo,
98                                        SmallVectorImpl<MCFixup> &Fixups,
99                                        const MCSubtargetInfo &STI) const {
100   const MCOperand &MO = MI.getOperand(OpNo);
101   if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
102 
103   // Add a fixup for the immediate field.
104   Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
105                                    (MCFixupKind)PPC::fixup_ppc_half16));
106   return 0;
107 }
108 
109 uint64_t PPCMCCodeEmitter::getImm34Encoding(const MCInst &MI, unsigned OpNo,
110                                             SmallVectorImpl<MCFixup> &Fixups,
111                                             const MCSubtargetInfo &STI,
112                                             MCFixupKind Fixup) const {
113   const MCOperand &MO = MI.getOperand(OpNo);
114   assert(!MO.isReg() && "Not expecting a register for this operand.");
115   if (MO.isImm())
116     return getMachineOpValue(MI, MO, Fixups, STI);
117 
118   // Add a fixup for the immediate field.
119   Fixups.push_back(MCFixup::create(0, MO.getExpr(), Fixup));
120   return 0;
121 }
122 
123 uint64_t
124 PPCMCCodeEmitter::getImm34EncodingNoPCRel(const MCInst &MI, unsigned OpNo,
125                                           SmallVectorImpl<MCFixup> &Fixups,
126                                           const MCSubtargetInfo &STI) const {
127   return getImm34Encoding(MI, OpNo, Fixups, STI,
128                           (MCFixupKind)PPC::fixup_ppc_imm34);
129 }
130 
131 uint64_t
132 PPCMCCodeEmitter::getImm34EncodingPCRel(const MCInst &MI, unsigned OpNo,
133                                         SmallVectorImpl<MCFixup> &Fixups,
134                                         const MCSubtargetInfo &STI) const {
135   return getImm34Encoding(MI, OpNo, Fixups, STI,
136                           (MCFixupKind)PPC::fixup_ppc_pcrel34);
137 }
138 
139 unsigned PPCMCCodeEmitter::getMemRIEncoding(const MCInst &MI, unsigned OpNo,
140                                             SmallVectorImpl<MCFixup> &Fixups,
141                                             const MCSubtargetInfo &STI) const {
142   // Encode (imm, reg) as a memri, which has the low 16-bits as the
143   // displacement and the next 5 bits as the register #.
144   assert(MI.getOperand(OpNo+1).isReg());
145   unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 16;
146 
147   const MCOperand &MO = MI.getOperand(OpNo);
148   if (MO.isImm())
149     return (getMachineOpValue(MI, MO, Fixups, STI) & 0xFFFF) | RegBits;
150 
151   // Add a fixup for the displacement field.
152   Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
153                                    (MCFixupKind)PPC::fixup_ppc_half16));
154   return RegBits;
155 }
156 
157 unsigned PPCMCCodeEmitter::getMemRIXEncoding(const MCInst &MI, unsigned OpNo,
158                                        SmallVectorImpl<MCFixup> &Fixups,
159                                        const MCSubtargetInfo &STI) const {
160   // Encode (imm, reg) as a memrix, which has the low 14-bits as the
161   // displacement and the next 5 bits as the register #.
162   assert(MI.getOperand(OpNo+1).isReg());
163   unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 14;
164 
165   const MCOperand &MO = MI.getOperand(OpNo);
166   if (MO.isImm())
167     return ((getMachineOpValue(MI, MO, Fixups, STI) >> 2) & 0x3FFF) | RegBits;
168 
169   // Add a fixup for the displacement field.
170   Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
171                                    (MCFixupKind)PPC::fixup_ppc_half16ds));
172   return RegBits;
173 }
174 
175 unsigned PPCMCCodeEmitter::getMemRIX16Encoding(const MCInst &MI, unsigned OpNo,
176                                        SmallVectorImpl<MCFixup> &Fixups,
177                                        const MCSubtargetInfo &STI) const {
178   // Encode (imm, reg) as a memrix16, which has the low 12-bits as the
179   // displacement and the next 5 bits as the register #.
180   assert(MI.getOperand(OpNo+1).isReg());
181   unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 12;
182 
183   const MCOperand &MO = MI.getOperand(OpNo);
184   if (MO.isImm()) {
185     assert(!(MO.getImm() % 16) &&
186            "Expecting an immediate that is a multiple of 16");
187     return ((getMachineOpValue(MI, MO, Fixups, STI) >> 4) & 0xFFF) | RegBits;
188   }
189 
190   // Otherwise add a fixup for the displacement field.
191   Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
192                                    (MCFixupKind)PPC::fixup_ppc_half16ds));
193   return RegBits;
194 }
195 
196 uint64_t
197 PPCMCCodeEmitter::getMemRI34PCRelEncoding(const MCInst &MI, unsigned OpNo,
198                                           SmallVectorImpl<MCFixup> &Fixups,
199                                           const MCSubtargetInfo &STI) const {
200   // Encode the PCRelative version of memri34: imm34(r0).
201   // In the PC relative version the register for the address must be zero.
202   // The 34 bit immediate can fall into one of three cases:
203   // 1) It is a relocation to be filled in by the linker represented as:
204   //    (MCExpr::SymbolRef)
205   // 2) It is a relocation + SignedOffset represented as:
206   //    (MCExpr::Binary(MCExpr::SymbolRef + MCExpr::Constant))
207   // 3) It is a known value at compile time.
208 
209   // Make sure that the register is a zero as expected.
210   assert(MI.getOperand(OpNo + 1).isImm() && "Expecting an immediate.");
211   uint64_t RegBits =
212     getMachineOpValue(MI, MI.getOperand(OpNo + 1), Fixups, STI) << 34;
213   assert(RegBits == 0 && "Operand must be 0.");
214 
215   // If this is not a MCExpr then we are in case 3) and we are dealing with
216   // a value known at compile time, not a relocation.
217   const MCOperand &MO = MI.getOperand(OpNo);
218   if (!MO.isExpr())
219     return ((getMachineOpValue(MI, MO, Fixups, STI)) & 0x3FFFFFFFFUL) | RegBits;
220 
221   // At this point in the function it is known that MO is of type MCExpr.
222   // Therefore we are dealing with either case 1) a symbol ref or
223   // case 2) a symbol ref plus a constant.
224   const MCExpr *Expr = MO.getExpr();
225   switch (Expr->getKind()) {
226   default:
227     llvm_unreachable("Unsupported MCExpr for getMemRI34PCRelEncoding.");
228   case MCExpr::SymbolRef: {
229     // Relocation alone.
230     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(Expr);
231     (void)SRE;
232     // Currently these are the only valid PCRelative Relocations.
233     assert((SRE->getKind() == MCSymbolRefExpr::VK_PCREL ||
234             SRE->getKind() == MCSymbolRefExpr::VK_PPC_GOT_PCREL ||
235             SRE->getKind() == MCSymbolRefExpr::VK_PPC_GOT_TLSGD_PCREL ||
236             SRE->getKind() == MCSymbolRefExpr::VK_PPC_GOT_TLSLD_PCREL ||
237             SRE->getKind() == MCSymbolRefExpr::VK_PPC_GOT_TPREL_PCREL) &&
238            "VariantKind must be VK_PCREL or VK_PPC_GOT_PCREL or "
239            "VK_PPC_GOT_TLSGD_PCREL or VK_PPC_GOT_TLSLD_PCREL or "
240            "VK_PPC_GOT_TPREL_PCREL.");
241     // Generate the fixup for the relocation.
242     Fixups.push_back(
243         MCFixup::create(0, Expr,
244                         static_cast<MCFixupKind>(PPC::fixup_ppc_pcrel34)));
245     // Put zero in the location of the immediate. The linker will fill in the
246     // correct value based on the relocation.
247     return 0;
248   }
249   case MCExpr::Binary: {
250     // Relocation plus some offset.
251     const MCBinaryExpr *BE = cast<MCBinaryExpr>(Expr);
252     assert(BE->getOpcode() == MCBinaryExpr::Add &&
253            "Binary expression opcode must be an add.");
254 
255     const MCExpr *LHS = BE->getLHS();
256     const MCExpr *RHS = BE->getRHS();
257 
258     // Need to check in both directions. Reloc+Offset and Offset+Reloc.
259     if (LHS->getKind() != MCExpr::SymbolRef)
260       std::swap(LHS, RHS);
261 
262     if (LHS->getKind() != MCExpr::SymbolRef ||
263         RHS->getKind() != MCExpr::Constant)
264       llvm_unreachable("Expecting to have one constant and one relocation.");
265 
266     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(LHS);
267     (void)SRE;
268     assert(isInt<34>(cast<MCConstantExpr>(RHS)->getValue()) &&
269            "Value must fit in 34 bits.");
270 
271     // Currently these are the only valid PCRelative Relocations.
272     assert((SRE->getKind() == MCSymbolRefExpr::VK_PCREL ||
273             SRE->getKind() == MCSymbolRefExpr::VK_PPC_GOT_PCREL) &&
274            "VariantKind must be VK_PCREL or VK_PPC_GOT_PCREL");
275     // Generate the fixup for the relocation.
276     Fixups.push_back(
277         MCFixup::create(0, Expr,
278                         static_cast<MCFixupKind>(PPC::fixup_ppc_pcrel34)));
279     // Put zero in the location of the immediate. The linker will fill in the
280     // correct value based on the relocation.
281     return 0;
282     }
283   }
284 }
285 
286 uint64_t
287 PPCMCCodeEmitter::getMemRI34Encoding(const MCInst &MI, unsigned OpNo,
288                                      SmallVectorImpl<MCFixup> &Fixups,
289                                      const MCSubtargetInfo &STI) const {
290   // Encode (imm, reg) as a memri34, which has the low 34-bits as the
291   // displacement and the next 5 bits as the register #.
292   assert(MI.getOperand(OpNo + 1).isReg() && "Expecting a register.");
293   uint64_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo + 1), Fixups, STI)
294                      << 34;
295   const MCOperand &MO = MI.getOperand(OpNo);
296   return ((getMachineOpValue(MI, MO, Fixups, STI)) & 0x3FFFFFFFFUL) | RegBits;
297 }
298 
299 unsigned PPCMCCodeEmitter::getSPE8DisEncoding(const MCInst &MI, unsigned OpNo,
300                                               SmallVectorImpl<MCFixup> &Fixups,
301                                               const MCSubtargetInfo &STI)
302                                               const {
303   // Encode (imm, reg) as a spe8dis, which has the low 5-bits of (imm / 8)
304   // as the displacement and the next 5 bits as the register #.
305   assert(MI.getOperand(OpNo+1).isReg());
306   uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
307 
308   const MCOperand &MO = MI.getOperand(OpNo);
309   assert(MO.isImm());
310   uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 3;
311   return reverseBits(Imm | RegBits) >> 22;
312 }
313 
314 unsigned PPCMCCodeEmitter::getSPE4DisEncoding(const MCInst &MI, unsigned OpNo,
315                                               SmallVectorImpl<MCFixup> &Fixups,
316                                               const MCSubtargetInfo &STI)
317                                               const {
318   // Encode (imm, reg) as a spe4dis, which has the low 5-bits of (imm / 4)
319   // as the displacement and the next 5 bits as the register #.
320   assert(MI.getOperand(OpNo+1).isReg());
321   uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
322 
323   const MCOperand &MO = MI.getOperand(OpNo);
324   assert(MO.isImm());
325   uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 2;
326   return reverseBits(Imm | RegBits) >> 22;
327 }
328 
329 unsigned PPCMCCodeEmitter::getSPE2DisEncoding(const MCInst &MI, unsigned OpNo,
330                                               SmallVectorImpl<MCFixup> &Fixups,
331                                               const MCSubtargetInfo &STI)
332                                               const {
333   // Encode (imm, reg) as a spe2dis, which has the low 5-bits of (imm / 2)
334   // as the displacement and the next 5 bits as the register #.
335   assert(MI.getOperand(OpNo+1).isReg());
336   uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
337 
338   const MCOperand &MO = MI.getOperand(OpNo);
339   assert(MO.isImm());
340   uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 1;
341   return reverseBits(Imm | RegBits) >> 22;
342 }
343 
344 unsigned PPCMCCodeEmitter::getTLSRegEncoding(const MCInst &MI, unsigned OpNo,
345                                        SmallVectorImpl<MCFixup> &Fixups,
346                                        const MCSubtargetInfo &STI) const {
347   const MCOperand &MO = MI.getOperand(OpNo);
348   if (MO.isReg()) return getMachineOpValue(MI, MO, Fixups, STI);
349 
350   // Add a fixup for the TLS register, which simply provides a relocation
351   // hint to the linker that this statement is part of a relocation sequence.
352   // Return the thread-pointer register's encoding. Add a one byte displacement
353   // if using PC relative memops.
354   const MCExpr *Expr = MO.getExpr();
355   const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(Expr);
356   bool IsPCRel = SRE->getKind() == MCSymbolRefExpr::VK_PPC_TLS_PCREL;
357   Fixups.push_back(MCFixup::create(IsPCRel ? 1 : 0, Expr,
358                                    (MCFixupKind)PPC::fixup_ppc_nofixup));
359   const Triple &TT = STI.getTargetTriple();
360   bool isPPC64 = TT.isPPC64();
361   return CTX.getRegisterInfo()->getEncodingValue(isPPC64 ? PPC::X13 : PPC::R2);
362 }
363 
364 unsigned PPCMCCodeEmitter::getTLSCallEncoding(const MCInst &MI, unsigned OpNo,
365                                        SmallVectorImpl<MCFixup> &Fixups,
366                                        const MCSubtargetInfo &STI) const {
367   // For special TLS calls, we need two fixups; one for the branch target
368   // (__tls_get_addr), which we create via getDirectBrEncoding as usual,
369   // and one for the TLSGD or TLSLD symbol, which is emitted here.
370   const MCOperand &MO = MI.getOperand(OpNo+1);
371   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
372                                    (MCFixupKind)PPC::fixup_ppc_nofixup));
373   return getDirectBrEncoding(MI, OpNo, Fixups, STI);
374 }
375 
376 unsigned PPCMCCodeEmitter::
377 get_crbitm_encoding(const MCInst &MI, unsigned OpNo,
378                     SmallVectorImpl<MCFixup> &Fixups,
379                     const MCSubtargetInfo &STI) const {
380   const MCOperand &MO = MI.getOperand(OpNo);
381   assert((MI.getOpcode() == PPC::MTOCRF || MI.getOpcode() == PPC::MTOCRF8 ||
382           MI.getOpcode() == PPC::MFOCRF || MI.getOpcode() == PPC::MFOCRF8) &&
383          (MO.getReg() >= PPC::CR0 && MO.getReg() <= PPC::CR7));
384   return 0x80 >> CTX.getRegisterInfo()->getEncodingValue(MO.getReg());
385 }
386 
387 // Get the index for this operand in this instruction. This is needed for
388 // computing the register number in PPCInstrInfo::getRegNumForOperand() for
389 // any instructions that use a different numbering scheme for registers in
390 // different operands.
391 static unsigned getOpIdxForMO(const MCInst &MI, const MCOperand &MO) {
392   for (unsigned i = 0; i < MI.getNumOperands(); i++) {
393     const MCOperand &Op = MI.getOperand(i);
394     if (&Op == &MO)
395       return i;
396   }
397   llvm_unreachable("This operand is not part of this instruction");
398   return ~0U; // Silence any warnings about no return.
399 }
400 
401 uint64_t PPCMCCodeEmitter::
402 getMachineOpValue(const MCInst &MI, const MCOperand &MO,
403                   SmallVectorImpl<MCFixup> &Fixups,
404                   const MCSubtargetInfo &STI) const {
405   if (MO.isReg()) {
406     // MTOCRF/MFOCRF should go through get_crbitm_encoding for the CR operand.
407     // The GPR operand should come through here though.
408     assert((MI.getOpcode() != PPC::MTOCRF && MI.getOpcode() != PPC::MTOCRF8 &&
409             MI.getOpcode() != PPC::MFOCRF && MI.getOpcode() != PPC::MFOCRF8) ||
410            MO.getReg() < PPC::CR0 || MO.getReg() > PPC::CR7);
411     unsigned OpNo = getOpIdxForMO(MI, MO);
412     unsigned Reg =
413       PPCInstrInfo::getRegNumForOperand(MCII.get(MI.getOpcode()),
414                                         MO.getReg(), OpNo);
415     return CTX.getRegisterInfo()->getEncodingValue(Reg);
416   }
417 
418   assert(MO.isImm() &&
419          "Relocation required in an instruction that we cannot encode!");
420   return MO.getImm();
421 }
422 
423 void PPCMCCodeEmitter::encodeInstruction(
424     const MCInst &MI, raw_ostream &OS, SmallVectorImpl<MCFixup> &Fixups,
425     const MCSubtargetInfo &STI) const {
426   verifyInstructionPredicates(MI,
427                               computeAvailableFeatures(STI.getFeatureBits()));
428 
429   uint64_t Bits = getBinaryCodeForInstr(MI, Fixups, STI);
430 
431   // Output the constant in big/little endian byte order.
432   unsigned Size = getInstSizeInBytes(MI);
433   support::endianness E = IsLittleEndian ? support::little : support::big;
434   switch (Size) {
435   case 0:
436     break;
437   case 4:
438     support::endian::write<uint32_t>(OS, Bits, E);
439     break;
440   case 8:
441     // If we emit a pair of instructions, the first one is
442     // always in the top 32 bits, even on little-endian.
443     support::endian::write<uint32_t>(OS, Bits >> 32, E);
444     support::endian::write<uint32_t>(OS, Bits, E);
445     break;
446   default:
447     llvm_unreachable("Invalid instruction size");
448   }
449 
450   ++MCNumEmitted; // Keep track of the # of mi's emitted.
451 }
452 
453 // Get the number of bytes used to encode the given MCInst.
454 unsigned PPCMCCodeEmitter::getInstSizeInBytes(const MCInst &MI) const {
455   unsigned Opcode = MI.getOpcode();
456   const MCInstrDesc &Desc = MCII.get(Opcode);
457   return Desc.getSize();
458 }
459 
460 bool PPCMCCodeEmitter::isPrefixedInstruction(const MCInst &MI) const {
461   unsigned Opcode = MI.getOpcode();
462   const PPCInstrInfo *InstrInfo = static_cast<const PPCInstrInfo*>(&MCII);
463   return InstrInfo->isPrefixed(Opcode);
464 }
465 
466 #define ENABLE_INSTR_PREDICATE_VERIFIER
467 #include "PPCGenMCCodeEmitter.inc"
468