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   if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
48 
49   // Add a fixup for the branch target.
50   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
51                                    ((MI.getOpcode() == PPC::BL8_NOTOC)
52                                         ? (MCFixupKind)PPC::fixup_ppc_br24_notoc
53                                         : (MCFixupKind)PPC::fixup_ppc_br24)));
54   return 0;
55 }
56 
57 unsigned PPCMCCodeEmitter::getCondBrEncoding(const MCInst &MI, unsigned OpNo,
58                                      SmallVectorImpl<MCFixup> &Fixups,
59                                      const MCSubtargetInfo &STI) const {
60   const MCOperand &MO = MI.getOperand(OpNo);
61   if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
62 
63   // Add a fixup for the branch target.
64   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
65                                    (MCFixupKind)PPC::fixup_ppc_brcond14));
66   return 0;
67 }
68 
69 unsigned PPCMCCodeEmitter::
70 getAbsDirectBrEncoding(const MCInst &MI, unsigned OpNo,
71                        SmallVectorImpl<MCFixup> &Fixups,
72                        const MCSubtargetInfo &STI) const {
73   const MCOperand &MO = MI.getOperand(OpNo);
74   if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
75 
76   // Add a fixup for the branch target.
77   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
78                                    (MCFixupKind)PPC::fixup_ppc_br24abs));
79   return 0;
80 }
81 
82 unsigned PPCMCCodeEmitter::
83 getAbsCondBrEncoding(const MCInst &MI, unsigned OpNo,
84                      SmallVectorImpl<MCFixup> &Fixups,
85                      const MCSubtargetInfo &STI) const {
86   const MCOperand &MO = MI.getOperand(OpNo);
87   if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
88 
89   // Add a fixup for the branch target.
90   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
91                                    (MCFixupKind)PPC::fixup_ppc_brcond14abs));
92   return 0;
93 }
94 
95 unsigned PPCMCCodeEmitter::getImm16Encoding(const MCInst &MI, unsigned OpNo,
96                                        SmallVectorImpl<MCFixup> &Fixups,
97                                        const MCSubtargetInfo &STI) const {
98   const MCOperand &MO = MI.getOperand(OpNo);
99   if (MO.isReg() || MO.isImm()) return getMachineOpValue(MI, MO, Fixups, STI);
100 
101   // Add a fixup for the immediate field.
102   Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
103                                    (MCFixupKind)PPC::fixup_ppc_half16));
104   return 0;
105 }
106 
107 uint64_t
108 PPCMCCodeEmitter::getImm34Encoding(const MCInst &MI, unsigned OpNo,
109                                    SmallVectorImpl<MCFixup> &Fixups,
110                                    const MCSubtargetInfo &STI) const {
111   const MCOperand &MO = MI.getOperand(OpNo);
112   if (MO.isReg() || MO.isImm())
113     return getMachineOpValue(MI, MO, Fixups, STI);
114 
115   // Add a fixup for the immediate field.
116   Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 1, MO.getExpr(),
117                                    (MCFixupKind)PPC::fixup_ppc_pcrel34));
118   return 0;
119 }
120 
121 unsigned PPCMCCodeEmitter::getMemRIEncoding(const MCInst &MI, unsigned OpNo,
122                                             SmallVectorImpl<MCFixup> &Fixups,
123                                             const MCSubtargetInfo &STI) const {
124   // Encode (imm, reg) as a memri, which has the low 16-bits as the
125   // displacement and the next 5 bits as the register #.
126   assert(MI.getOperand(OpNo+1).isReg());
127   unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 16;
128 
129   const MCOperand &MO = MI.getOperand(OpNo);
130   if (MO.isImm())
131     return (getMachineOpValue(MI, MO, Fixups, STI) & 0xFFFF) | RegBits;
132 
133   // Add a fixup for the displacement field.
134   Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
135                                    (MCFixupKind)PPC::fixup_ppc_half16));
136   return RegBits;
137 }
138 
139 unsigned PPCMCCodeEmitter::getMemRIXEncoding(const MCInst &MI, unsigned OpNo,
140                                        SmallVectorImpl<MCFixup> &Fixups,
141                                        const MCSubtargetInfo &STI) const {
142   // Encode (imm, reg) as a memrix, which has the low 14-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) << 14;
146 
147   const MCOperand &MO = MI.getOperand(OpNo);
148   if (MO.isImm())
149     return ((getMachineOpValue(MI, MO, Fixups, STI) >> 2) & 0x3FFF) | 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_half16ds));
154   return RegBits;
155 }
156 
157 unsigned PPCMCCodeEmitter::getMemRIX16Encoding(const MCInst &MI, unsigned OpNo,
158                                        SmallVectorImpl<MCFixup> &Fixups,
159                                        const MCSubtargetInfo &STI) const {
160   // Encode (imm, reg) as a memrix16, which has the low 12-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) << 12;
164 
165   const MCOperand &MO = MI.getOperand(OpNo);
166   if (MO.isImm()) {
167     assert(!(MO.getImm() % 16) &&
168            "Expecting an immediate that is a multiple of 16");
169     return ((getMachineOpValue(MI, MO, Fixups, STI) >> 4) & 0xFFF) | RegBits;
170   }
171 
172   // Otherwise add a fixup for the displacement field.
173   Fixups.push_back(MCFixup::create(IsLittleEndian? 0 : 2, MO.getExpr(),
174                                    (MCFixupKind)PPC::fixup_ppc_half16ds));
175   return RegBits;
176 }
177 
178 uint64_t
179 PPCMCCodeEmitter::getMemRI34PCRelEncoding(const MCInst &MI, unsigned OpNo,
180                                           SmallVectorImpl<MCFixup> &Fixups,
181                                           const MCSubtargetInfo &STI) const {
182   // Encode (imm, reg) as a memri34, which has the low 34-bits as the
183   // displacement and the next 5 bits as an immediate 0.
184   assert(MI.getOperand(OpNo + 1).isImm() && "Expecting an immediate.");
185   uint64_t RegBits =
186     getMachineOpValue(MI, MI.getOperand(OpNo + 1), Fixups, STI) << 34;
187 
188   if (RegBits != 0)
189     report_fatal_error("Operand must be 0");
190 
191   const MCOperand &MO = MI.getOperand(OpNo);
192   if (MO.isExpr()) {
193     const MCExpr *Expr = MO.getExpr();
194     const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(Expr);
195     (void)SRE;
196     assert((SRE->getKind() == MCSymbolRefExpr::VK_PCREL ||
197             SRE->getKind() == MCSymbolRefExpr::VK_PPC_GOT_PCREL) &&
198            "VariantKind must be VK_PCREL or VK_PPC_GOT_PCREL");
199     Fixups.push_back(
200         MCFixup::create(IsLittleEndian ? 0 : 1, Expr,
201                         static_cast<MCFixupKind>(PPC::fixup_ppc_pcrel34)));
202     return 0;
203   }
204   return ((getMachineOpValue(MI, MO, Fixups, STI)) & 0x3FFFFFFFFUL) | RegBits;
205 }
206 
207 uint64_t
208 PPCMCCodeEmitter::getMemRI34Encoding(const MCInst &MI, unsigned OpNo,
209                                      SmallVectorImpl<MCFixup> &Fixups,
210                                      const MCSubtargetInfo &STI) const {
211   // Encode (imm, reg) as a memri34, which has the low 34-bits as the
212   // displacement and the next 5 bits as the register #.
213   assert(MI.getOperand(OpNo + 1).isReg() && "Expecting a register.");
214   uint64_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo + 1), Fixups, STI)
215                      << 34;
216   const MCOperand &MO = MI.getOperand(OpNo);
217   return ((getMachineOpValue(MI, MO, Fixups, STI)) & 0x3FFFFFFFFUL) | RegBits;
218 }
219 
220 unsigned PPCMCCodeEmitter::getSPE8DisEncoding(const MCInst &MI, unsigned OpNo,
221                                               SmallVectorImpl<MCFixup> &Fixups,
222                                               const MCSubtargetInfo &STI)
223                                               const {
224   // Encode (imm, reg) as a spe8dis, which has the low 5-bits of (imm / 8)
225   // as the displacement and the next 5 bits as the register #.
226   assert(MI.getOperand(OpNo+1).isReg());
227   uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
228 
229   const MCOperand &MO = MI.getOperand(OpNo);
230   assert(MO.isImm());
231   uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 3;
232   return reverseBits(Imm | RegBits) >> 22;
233 }
234 
235 unsigned PPCMCCodeEmitter::getSPE4DisEncoding(const MCInst &MI, unsigned OpNo,
236                                               SmallVectorImpl<MCFixup> &Fixups,
237                                               const MCSubtargetInfo &STI)
238                                               const {
239   // Encode (imm, reg) as a spe4dis, which has the low 5-bits of (imm / 4)
240   // as the displacement and the next 5 bits as the register #.
241   assert(MI.getOperand(OpNo+1).isReg());
242   uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
243 
244   const MCOperand &MO = MI.getOperand(OpNo);
245   assert(MO.isImm());
246   uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 2;
247   return reverseBits(Imm | RegBits) >> 22;
248 }
249 
250 unsigned PPCMCCodeEmitter::getSPE2DisEncoding(const MCInst &MI, unsigned OpNo,
251                                               SmallVectorImpl<MCFixup> &Fixups,
252                                               const MCSubtargetInfo &STI)
253                                               const {
254   // Encode (imm, reg) as a spe2dis, which has the low 5-bits of (imm / 2)
255   // as the displacement and the next 5 bits as the register #.
256   assert(MI.getOperand(OpNo+1).isReg());
257   uint32_t RegBits = getMachineOpValue(MI, MI.getOperand(OpNo+1), Fixups, STI) << 5;
258 
259   const MCOperand &MO = MI.getOperand(OpNo);
260   assert(MO.isImm());
261   uint32_t Imm = getMachineOpValue(MI, MO, Fixups, STI) >> 1;
262   return reverseBits(Imm | RegBits) >> 22;
263 }
264 
265 unsigned PPCMCCodeEmitter::getTLSRegEncoding(const MCInst &MI, unsigned OpNo,
266                                        SmallVectorImpl<MCFixup> &Fixups,
267                                        const MCSubtargetInfo &STI) const {
268   const MCOperand &MO = MI.getOperand(OpNo);
269   if (MO.isReg()) return getMachineOpValue(MI, MO, Fixups, STI);
270 
271   // Add a fixup for the TLS register, which simply provides a relocation
272   // hint to the linker that this statement is part of a relocation sequence.
273   // Return the thread-pointer register's encoding.
274   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
275                                    (MCFixupKind)PPC::fixup_ppc_nofixup));
276   const Triple &TT = STI.getTargetTriple();
277   bool isPPC64 = TT.isPPC64();
278   return CTX.getRegisterInfo()->getEncodingValue(isPPC64 ? PPC::X13 : PPC::R2);
279 }
280 
281 unsigned PPCMCCodeEmitter::getTLSCallEncoding(const MCInst &MI, unsigned OpNo,
282                                        SmallVectorImpl<MCFixup> &Fixups,
283                                        const MCSubtargetInfo &STI) const {
284   // For special TLS calls, we need two fixups; one for the branch target
285   // (__tls_get_addr), which we create via getDirectBrEncoding as usual,
286   // and one for the TLSGD or TLSLD symbol, which is emitted here.
287   const MCOperand &MO = MI.getOperand(OpNo+1);
288   Fixups.push_back(MCFixup::create(0, MO.getExpr(),
289                                    (MCFixupKind)PPC::fixup_ppc_nofixup));
290   return getDirectBrEncoding(MI, OpNo, Fixups, STI);
291 }
292 
293 unsigned PPCMCCodeEmitter::
294 get_crbitm_encoding(const MCInst &MI, unsigned OpNo,
295                     SmallVectorImpl<MCFixup> &Fixups,
296                     const MCSubtargetInfo &STI) const {
297   const MCOperand &MO = MI.getOperand(OpNo);
298   assert((MI.getOpcode() == PPC::MTOCRF || MI.getOpcode() == PPC::MTOCRF8 ||
299           MI.getOpcode() == PPC::MFOCRF || MI.getOpcode() == PPC::MFOCRF8) &&
300          (MO.getReg() >= PPC::CR0 && MO.getReg() <= PPC::CR7));
301   return 0x80 >> CTX.getRegisterInfo()->getEncodingValue(MO.getReg());
302 }
303 
304 // Get the index for this operand in this instruction. This is needed for
305 // computing the register number in PPCInstrInfo::getRegNumForOperand() for
306 // any instructions that use a different numbering scheme for registers in
307 // different operands.
308 static unsigned getOpIdxForMO(const MCInst &MI, const MCOperand &MO) {
309   for (unsigned i = 0; i < MI.getNumOperands(); i++) {
310     const MCOperand &Op = MI.getOperand(i);
311     if (&Op == &MO)
312       return i;
313   }
314   llvm_unreachable("This operand is not part of this instruction");
315   return ~0U; // Silence any warnings about no return.
316 }
317 
318 uint64_t PPCMCCodeEmitter::
319 getMachineOpValue(const MCInst &MI, const MCOperand &MO,
320                   SmallVectorImpl<MCFixup> &Fixups,
321                   const MCSubtargetInfo &STI) const {
322   if (MO.isReg()) {
323     // MTOCRF/MFOCRF should go through get_crbitm_encoding for the CR operand.
324     // The GPR operand should come through here though.
325     assert((MI.getOpcode() != PPC::MTOCRF && MI.getOpcode() != PPC::MTOCRF8 &&
326             MI.getOpcode() != PPC::MFOCRF && MI.getOpcode() != PPC::MFOCRF8) ||
327            MO.getReg() < PPC::CR0 || MO.getReg() > PPC::CR7);
328     unsigned OpNo = getOpIdxForMO(MI, MO);
329     unsigned Reg =
330       PPCInstrInfo::getRegNumForOperand(MCII.get(MI.getOpcode()),
331                                         MO.getReg(), OpNo);
332     return CTX.getRegisterInfo()->getEncodingValue(Reg);
333   }
334 
335   assert(MO.isImm() &&
336          "Relocation required in an instruction that we cannot encode!");
337   return MO.getImm();
338 }
339 
340 void PPCMCCodeEmitter::encodeInstruction(
341     const MCInst &MI, raw_ostream &OS, SmallVectorImpl<MCFixup> &Fixups,
342     const MCSubtargetInfo &STI) const {
343   verifyInstructionPredicates(MI,
344                               computeAvailableFeatures(STI.getFeatureBits()));
345 
346   uint64_t Bits = getBinaryCodeForInstr(MI, Fixups, STI);
347 
348   // Output the constant in big/little endian byte order.
349   unsigned Size = getInstSizeInBytes(MI);
350   support::endianness E = IsLittleEndian ? support::little : support::big;
351   switch (Size) {
352   case 0:
353     break;
354   case 4:
355     support::endian::write<uint32_t>(OS, Bits, E);
356     break;
357   case 8:
358     // If we emit a pair of instructions, the first one is
359     // always in the top 32 bits, even on little-endian.
360     support::endian::write<uint32_t>(OS, Bits >> 32, E);
361     support::endian::write<uint32_t>(OS, Bits, E);
362     break;
363   default:
364     llvm_unreachable("Invalid instruction size");
365   }
366 
367   ++MCNumEmitted; // Keep track of the # of mi's emitted.
368 }
369 
370 // Get the number of bytes used to encode the given MCInst.
371 unsigned PPCMCCodeEmitter::getInstSizeInBytes(const MCInst &MI) const {
372   unsigned Opcode = MI.getOpcode();
373   const MCInstrDesc &Desc = MCII.get(Opcode);
374   return Desc.getSize();
375 }
376 
377 bool PPCMCCodeEmitter::isPrefixedInstruction(const MCInst &MI) const {
378   unsigned Opcode = MI.getOpcode();
379   const PPCInstrInfo *InstrInfo = static_cast<const PPCInstrInfo*>(&MCII);
380   return InstrInfo->isPrefixed(Opcode);
381 }
382 
383 #define ENABLE_INSTR_PREDICATE_VERIFIER
384 #include "PPCGenMCCodeEmitter.inc"
385