MipsCodeEmitter.cpp revision 1aaf43c2a2ec0fd4c8dbfe56558237219c5f8af7
1//===-- Mips/MipsCodeEmitter.cpp - Convert Mips Code to Machine Code ------===//
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// This file contains the pass that transforms the Mips machine instructions
11// into relocatable machine code.
12//
13//===---------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "jit"
16#include "Mips.h"
17#include "MCTargetDesc/MipsBaseInfo.h"
18#include "MipsInstrInfo.h"
19#include "MipsRelocations.h"
20#include "MipsSubtarget.h"
21#include "MipsTargetMachine.h"
22#include "llvm/ADT/Statistic.h"
23#include "llvm/CodeGen/JITCodeEmitter.h"
24#include "llvm/CodeGen/MachineConstantPool.h"
25#include "llvm/CodeGen/MachineFunctionPass.h"
26#include "llvm/CodeGen/MachineInstr.h"
27#include "llvm/CodeGen/MachineJumpTableInfo.h"
28#include "llvm/CodeGen/MachineInstrBuilder.h"
29#include "llvm/CodeGen/MachineModuleInfo.h"
30#include "llvm/CodeGen/MachineOperand.h"
31#include "llvm/CodeGen/Passes.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DerivedTypes.h"
34#include "llvm/PassManager.h"
35#include "llvm/Support/Debug.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
38#ifndef NDEBUG
39#include <iomanip>
40#endif
41
42using namespace llvm;
43
44STATISTIC(NumEmitted, "Number of machine instructions emitted");
45
46namespace {
47
48class MipsCodeEmitter : public MachineFunctionPass {
49  MipsJITInfo *JTI;
50  const MipsInstrInfo *II;
51  const DataLayout *TD;
52  const MipsSubtarget *Subtarget;
53  TargetMachine &TM;
54  JITCodeEmitter &MCE;
55  const std::vector<MachineConstantPoolEntry> *MCPEs;
56  const std::vector<MachineJumpTableEntry> *MJTEs;
57  bool IsPIC;
58
59  void getAnalysisUsage(AnalysisUsage &AU) const {
60    AU.addRequired<MachineModuleInfo> ();
61    MachineFunctionPass::getAnalysisUsage(AU);
62  }
63
64  static char ID;
65
66public:
67  MipsCodeEmitter(TargetMachine &tm, JITCodeEmitter &mce)
68    : MachineFunctionPass(ID), JTI(0), II(0), TD(0),
69      TM(tm), MCE(mce), MCPEs(0), MJTEs(0),
70      IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
71
72  bool runOnMachineFunction(MachineFunction &MF);
73
74  virtual const char *getPassName() const {
75    return "Mips Machine Code Emitter";
76  }
77
78  /// getBinaryCodeForInstr - This function, generated by the
79  /// CodeEmitterGenerator using TableGen, produces the binary encoding for
80  /// machine instructions.
81  uint64_t getBinaryCodeForInstr(const MachineInstr &MI) const;
82
83  void emitInstruction(MachineBasicBlock::instr_iterator MI,
84                       MachineBasicBlock &MBB);
85
86private:
87
88  void emitWord(unsigned Word);
89
90  /// Routines that handle operands which add machine relocations which are
91  /// fixed up by the relocation stage.
92  void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
93                         bool MayNeedFarStub) const;
94  void emitExternalSymbolAddress(const char *ES, unsigned Reloc) const;
95  void emitConstPoolAddress(unsigned CPI, unsigned Reloc) const;
96  void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) const;
97  void emitMachineBasicBlock(MachineBasicBlock *BB, unsigned Reloc) const;
98
99  /// getMachineOpValue - Return binary encoding of operand. If the machine
100  /// operand requires relocation, record the relocation and return zero.
101  unsigned getMachineOpValue(const MachineInstr &MI,
102                             const MachineOperand &MO) const;
103
104  unsigned getRelocation(const MachineInstr &MI,
105                         const MachineOperand &MO) const;
106
107  unsigned getJumpTargetOpValue(const MachineInstr &MI, unsigned OpNo) const;
108  unsigned getJumpTargetOpValueMM(const MachineInstr &MI, unsigned OpNo) const;
109
110  unsigned getBranchTargetOpValue(const MachineInstr &MI, unsigned OpNo) const;
111  unsigned getMemEncoding(const MachineInstr &MI, unsigned OpNo) const;
112  unsigned getMemEncodingMMImm12(const MachineInstr &MI, unsigned OpNo) const;
113  unsigned getSizeExtEncoding(const MachineInstr &MI, unsigned OpNo) const;
114  unsigned getSizeInsEncoding(const MachineInstr &MI, unsigned OpNo) const;
115
116  void emitGlobalAddressUnaligned(const GlobalValue *GV, unsigned Reloc,
117                                  int Offset) const;
118
119  /// Expand pseudo instructions with accumulator register operands.
120  void expandACCInstr(MachineBasicBlock::instr_iterator MI,
121                      MachineBasicBlock &MBB, unsigned Opc) const;
122
123  /// \brief Expand pseudo instruction. Return true if MI was expanded.
124  bool expandPseudos(MachineBasicBlock::instr_iterator &MI,
125                     MachineBasicBlock &MBB) const;
126};
127}
128
129char MipsCodeEmitter::ID = 0;
130
131bool MipsCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
132  MipsTargetMachine &Target = static_cast<MipsTargetMachine &>(
133                                const_cast<TargetMachine &>(MF.getTarget()));
134
135  JTI = Target.getJITInfo();
136  II = Target.getInstrInfo();
137  TD = Target.getDataLayout();
138  Subtarget = &TM.getSubtarget<MipsSubtarget> ();
139  MCPEs = &MF.getConstantPool()->getConstants();
140  MJTEs = 0;
141  if (MF.getJumpTableInfo()) MJTEs = &MF.getJumpTableInfo()->getJumpTables();
142  JTI->Initialize(MF, IsPIC, Subtarget->isLittle());
143  MCE.setModuleInfo(&getAnalysis<MachineModuleInfo> ());
144
145  do {
146    DEBUG(errs() << "JITTing function '"
147        << MF.getName() << "'\n");
148    MCE.startFunction(MF);
149
150    for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
151        MBB != E; ++MBB){
152      MCE.StartMachineBasicBlock(MBB);
153      for (MachineBasicBlock::instr_iterator I = MBB->instr_begin(),
154           E = MBB->instr_end(); I != E;)
155        emitInstruction(*I++, *MBB);
156    }
157  } while (MCE.finishFunction(MF));
158
159  return false;
160}
161
162unsigned MipsCodeEmitter::getRelocation(const MachineInstr &MI,
163                                        const MachineOperand &MO) const {
164  // NOTE: This relocations are for static.
165  uint64_t TSFlags = MI.getDesc().TSFlags;
166  uint64_t Form = TSFlags & MipsII::FormMask;
167  if (Form == MipsII::FrmJ)
168    return Mips::reloc_mips_26;
169  if ((Form == MipsII::FrmI || Form == MipsII::FrmFI)
170       && MI.isBranch())
171    return Mips::reloc_mips_pc16;
172  if (Form == MipsII::FrmI && MI.getOpcode() == Mips::LUi)
173    return Mips::reloc_mips_hi;
174  return Mips::reloc_mips_lo;
175}
176
177unsigned MipsCodeEmitter::getJumpTargetOpValue(const MachineInstr &MI,
178                                               unsigned OpNo) const {
179  MachineOperand MO = MI.getOperand(OpNo);
180  if (MO.isGlobal())
181    emitGlobalAddress(MO.getGlobal(), getRelocation(MI, MO), true);
182  else if (MO.isSymbol())
183    emitExternalSymbolAddress(MO.getSymbolName(), getRelocation(MI, MO));
184  else if (MO.isMBB())
185    emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
186  else
187    llvm_unreachable("Unexpected jump target operand kind.");
188  return 0;
189}
190
191unsigned MipsCodeEmitter::getJumpTargetOpValueMM(const MachineInstr &MI,
192                                                 unsigned OpNo) const {
193  llvm_unreachable("Unimplemented function.");
194  return 0;
195}
196
197unsigned MipsCodeEmitter::getBranchTargetOpValue(const MachineInstr &MI,
198                                                 unsigned OpNo) const {
199  MachineOperand MO = MI.getOperand(OpNo);
200  emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
201  return 0;
202}
203
204unsigned MipsCodeEmitter::getMemEncoding(const MachineInstr &MI,
205                                         unsigned OpNo) const {
206  // Base register is encoded in bits 20-16, offset is encoded in bits 15-0.
207  assert(MI.getOperand(OpNo).isReg());
208  unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo)) << 16;
209  return (getMachineOpValue(MI, MI.getOperand(OpNo+1)) & 0xFFFF) | RegBits;
210}
211
212unsigned MipsCodeEmitter::getMemEncodingMMImm12(const MachineInstr &MI,
213                                                unsigned OpNo) const {
214  llvm_unreachable("Unimplemented function.");
215  return 0;
216}
217
218unsigned MipsCodeEmitter::getSizeExtEncoding(const MachineInstr &MI,
219                                             unsigned OpNo) const {
220  // size is encoded as size-1.
221  return getMachineOpValue(MI, MI.getOperand(OpNo)) - 1;
222}
223
224unsigned MipsCodeEmitter::getSizeInsEncoding(const MachineInstr &MI,
225                                             unsigned OpNo) const {
226  // size is encoded as pos+size-1.
227  return getMachineOpValue(MI, MI.getOperand(OpNo-1)) +
228         getMachineOpValue(MI, MI.getOperand(OpNo)) - 1;
229}
230
231/// getMachineOpValue - Return binary encoding of operand. If the machine
232/// operand requires relocation, record the relocation and return zero.
233unsigned MipsCodeEmitter::getMachineOpValue(const MachineInstr &MI,
234                                            const MachineOperand &MO) const {
235  if (MO.isReg())
236    return TM.getRegisterInfo()->getEncodingValue(MO.getReg());
237  else if (MO.isImm())
238    return static_cast<unsigned>(MO.getImm());
239  else if (MO.isGlobal())
240    emitGlobalAddress(MO.getGlobal(), getRelocation(MI, MO), true);
241  else if (MO.isSymbol())
242    emitExternalSymbolAddress(MO.getSymbolName(), getRelocation(MI, MO));
243  else if (MO.isCPI())
244    emitConstPoolAddress(MO.getIndex(), getRelocation(MI, MO));
245  else if (MO.isJTI())
246    emitJumpTableAddress(MO.getIndex(), getRelocation(MI, MO));
247  else if (MO.isMBB())
248    emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
249  else
250    llvm_unreachable("Unable to encode MachineOperand!");
251  return 0;
252}
253
254void MipsCodeEmitter::emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
255                                        bool MayNeedFarStub) const {
256  MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
257                                             const_cast<GlobalValue *>(GV), 0,
258                                             MayNeedFarStub));
259}
260
261void MipsCodeEmitter::emitGlobalAddressUnaligned(const GlobalValue *GV,
262                                           unsigned Reloc, int Offset) const {
263  MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
264                             const_cast<GlobalValue *>(GV), 0, false));
265  MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset() + Offset,
266                      Reloc, const_cast<GlobalValue *>(GV), 0, false));
267}
268
269void MipsCodeEmitter::
270emitExternalSymbolAddress(const char *ES, unsigned Reloc) const {
271  MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
272                                                 Reloc, ES, 0, 0));
273}
274
275void MipsCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc) const {
276  MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
277                                                    Reloc, CPI, 0, false));
278}
279
280void MipsCodeEmitter::
281emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) const {
282  MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
283                                                    Reloc, JTIndex, 0, false));
284}
285
286void MipsCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
287                                            unsigned Reloc) const {
288  MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
289                                             Reloc, BB));
290}
291
292void MipsCodeEmitter::emitInstruction(MachineBasicBlock::instr_iterator MI,
293                                      MachineBasicBlock &MBB) {
294  DEBUG(errs() << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << *MI);
295
296  // Expand pseudo instruction. Skip if MI was not expanded.
297  if (((MI->getDesc().TSFlags & MipsII::FormMask) == MipsII::Pseudo) &&
298      !expandPseudos(MI, MBB))
299    return;
300
301  MCE.processDebugLoc(MI->getDebugLoc(), true);
302
303  emitWord(getBinaryCodeForInstr(*MI));
304  ++NumEmitted;  // Keep track of the # of mi's emitted
305
306  MCE.processDebugLoc(MI->getDebugLoc(), false);
307}
308
309void MipsCodeEmitter::emitWord(unsigned Word) {
310  DEBUG(errs() << "  0x";
311        errs().write_hex(Word) << "\n");
312  if (Subtarget->isLittle())
313    MCE.emitWordLE(Word);
314  else
315    MCE.emitWordBE(Word);
316}
317
318void MipsCodeEmitter::expandACCInstr(MachineBasicBlock::instr_iterator MI,
319                                     MachineBasicBlock &MBB,
320                                     unsigned Opc) const {
321  // Expand "pseudomult $ac0, $t0, $t1" to "mult $t0, $t1".
322  BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Opc))
323    .addReg(MI->getOperand(1).getReg()).addReg(MI->getOperand(2).getReg());
324}
325
326bool MipsCodeEmitter::expandPseudos(MachineBasicBlock::instr_iterator &MI,
327                                    MachineBasicBlock &MBB) const {
328  switch (MI->getOpcode()) {
329  case Mips::NOP:
330    BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::SLL), Mips::ZERO)
331      .addReg(Mips::ZERO).addImm(0);
332    break;
333  case Mips::B:
334    BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::BEQ)).addReg(Mips::ZERO)
335      .addReg(Mips::ZERO).addOperand(MI->getOperand(0));
336    break;
337  case Mips::TRAP:
338    BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::BREAK)).addImm(0)
339      .addImm(0);
340    break;
341  case Mips::JALRPseudo:
342    BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::JALR), Mips::RA)
343      .addReg(MI->getOperand(0).getReg());
344    break;
345  case Mips::PseudoMULT:
346    expandACCInstr(MI, MBB, Mips::MULT);
347    break;
348  case Mips::PseudoMULTu:
349    expandACCInstr(MI, MBB, Mips::MULTu);
350    break;
351  case Mips::PseudoSDIV:
352    expandACCInstr(MI, MBB, Mips::SDIV);
353    break;
354  case Mips::PseudoUDIV:
355    expandACCInstr(MI, MBB, Mips::UDIV);
356    break;
357  case Mips::PseudoMADD:
358    expandACCInstr(MI, MBB, Mips::MADD);
359    break;
360  case Mips::PseudoMADDU:
361    expandACCInstr(MI, MBB, Mips::MADDU);
362    break;
363  case Mips::PseudoMSUB:
364    expandACCInstr(MI, MBB, Mips::MSUB);
365    break;
366  case Mips::PseudoMSUBU:
367    expandACCInstr(MI, MBB, Mips::MSUBU);
368    break;
369  default:
370    return false;
371  }
372
373  (MI--)->eraseFromBundle();
374  return true;
375}
376
377/// createMipsJITCodeEmitterPass - Return a pass that emits the collected Mips
378/// code to the specified MCE object.
379FunctionPass *llvm::createMipsJITCodeEmitterPass(MipsTargetMachine &TM,
380                                                 JITCodeEmitter &JCE) {
381  return new MipsCodeEmitter(TM, JCE);
382}
383
384#include "MipsGenCodeEmitter.inc"
385