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