76f604d660341ba57d74b44f0c58956abf008347
[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 #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
42 using namespace llvm;
43
44 STATISTIC(NumEmitted, "Number of machine instructions emitted");
45
46 namespace {
47
48 class 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
66 public:
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
86 private:
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   unsigned getBranchTargetOpValueMM(const MachineInstr &MI,
110                                     unsigned OpNo) const;
111
112   unsigned getBranchTargetOpValue(const MachineInstr &MI, unsigned OpNo) const;
113   unsigned getMemEncoding(const MachineInstr &MI, unsigned OpNo) const;
114   unsigned getMemEncodingMMImm12(const MachineInstr &MI, unsigned OpNo) const;
115   unsigned getMSAMemEncoding(const MachineInstr &MI, unsigned OpNo) const;
116   unsigned getSizeExtEncoding(const MachineInstr &MI, unsigned OpNo) const;
117   unsigned getSizeInsEncoding(const MachineInstr &MI, unsigned OpNo) const;
118   unsigned getLSAImmEncoding(const MachineInstr &MI, unsigned OpNo) const;
119
120   void emitGlobalAddressUnaligned(const GlobalValue *GV, unsigned Reloc,
121                                   int Offset) const;
122
123   /// Expand pseudo instructions with accumulator register operands.
124   void expandACCInstr(MachineBasicBlock::instr_iterator MI,
125                       MachineBasicBlock &MBB, unsigned Opc) const;
126
127   /// \brief Expand pseudo instruction. Return true if MI was expanded.
128   bool expandPseudos(MachineBasicBlock::instr_iterator &MI,
129                      MachineBasicBlock &MBB) const;
130 };
131 }
132
133 char MipsCodeEmitter::ID = 0;
134
135 bool MipsCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
136   MipsTargetMachine &Target = static_cast<MipsTargetMachine &>(
137                                 const_cast<TargetMachine &>(MF.getTarget()));
138
139   JTI = Target.getJITInfo();
140   II = Target.getInstrInfo();
141   TD = Target.getDataLayout();
142   Subtarget = &TM.getSubtarget<MipsSubtarget> ();
143   MCPEs = &MF.getConstantPool()->getConstants();
144   MJTEs = 0;
145   if (MF.getJumpTableInfo()) MJTEs = &MF.getJumpTableInfo()->getJumpTables();
146   JTI->Initialize(MF, IsPIC, Subtarget->isLittle());
147   MCE.setModuleInfo(&getAnalysis<MachineModuleInfo> ());
148
149   do {
150     DEBUG(errs() << "JITTing function '"
151         << MF.getName() << "'\n");
152     MCE.startFunction(MF);
153
154     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
155         MBB != E; ++MBB){
156       MCE.StartMachineBasicBlock(MBB);
157       for (MachineBasicBlock::instr_iterator I = MBB->instr_begin(),
158            E = MBB->instr_end(); I != E;)
159         emitInstruction(*I++, *MBB);
160     }
161   } while (MCE.finishFunction(MF));
162
163   return false;
164 }
165
166 unsigned MipsCodeEmitter::getRelocation(const MachineInstr &MI,
167                                         const MachineOperand &MO) const {
168   // NOTE: This relocations are for static.
169   uint64_t TSFlags = MI.getDesc().TSFlags;
170   uint64_t Form = TSFlags & MipsII::FormMask;
171   if (Form == MipsII::FrmJ)
172     return Mips::reloc_mips_26;
173   if ((Form == MipsII::FrmI || Form == MipsII::FrmFI)
174        && MI.isBranch())
175     return Mips::reloc_mips_pc16;
176   if (Form == MipsII::FrmI && MI.getOpcode() == Mips::LUi)
177     return Mips::reloc_mips_hi;
178   return Mips::reloc_mips_lo;
179 }
180
181 unsigned MipsCodeEmitter::getJumpTargetOpValue(const MachineInstr &MI,
182                                                unsigned OpNo) const {
183   MachineOperand MO = MI.getOperand(OpNo);
184   if (MO.isGlobal())
185     emitGlobalAddress(MO.getGlobal(), getRelocation(MI, MO), true);
186   else if (MO.isSymbol())
187     emitExternalSymbolAddress(MO.getSymbolName(), getRelocation(MI, MO));
188   else if (MO.isMBB())
189     emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
190   else
191     llvm_unreachable("Unexpected jump target operand kind.");
192   return 0;
193 }
194
195 unsigned MipsCodeEmitter::getJumpTargetOpValueMM(const MachineInstr &MI,
196                                                  unsigned OpNo) const {
197   llvm_unreachable("Unimplemented function.");
198   return 0;
199 }
200
201 unsigned MipsCodeEmitter::getBranchTargetOpValueMM(const MachineInstr &MI,
202                                                    unsigned OpNo) const {
203   llvm_unreachable("Unimplemented function.");
204   return 0;
205 }
206
207 unsigned MipsCodeEmitter::getBranchTargetOpValue(const MachineInstr &MI,
208                                                  unsigned OpNo) const {
209   MachineOperand MO = MI.getOperand(OpNo);
210   emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
211   return 0;
212 }
213
214 unsigned MipsCodeEmitter::getMemEncoding(const MachineInstr &MI,
215                                          unsigned OpNo) const {
216   // Base register is encoded in bits 20-16, offset is encoded in bits 15-0.
217   assert(MI.getOperand(OpNo).isReg());
218   unsigned RegBits = getMachineOpValue(MI, MI.getOperand(OpNo)) << 16;
219   return (getMachineOpValue(MI, MI.getOperand(OpNo+1)) & 0xFFFF) | RegBits;
220 }
221
222 unsigned MipsCodeEmitter::getMemEncodingMMImm12(const MachineInstr &MI,
223                                                 unsigned OpNo) const {
224   llvm_unreachable("Unimplemented function.");
225   return 0;
226 }
227
228 unsigned MipsCodeEmitter::getMSAMemEncoding(const MachineInstr &MI,
229                                             unsigned OpNo) const {
230   llvm_unreachable("Unimplemented function.");
231   return 0;
232 }
233
234 unsigned MipsCodeEmitter::getSizeExtEncoding(const MachineInstr &MI,
235                                              unsigned OpNo) const {
236   // size is encoded as size-1.
237   return getMachineOpValue(MI, MI.getOperand(OpNo)) - 1;
238 }
239
240 unsigned MipsCodeEmitter::getSizeInsEncoding(const MachineInstr &MI,
241                                              unsigned OpNo) const {
242   // size is encoded as pos+size-1.
243   return getMachineOpValue(MI, MI.getOperand(OpNo-1)) +
244          getMachineOpValue(MI, MI.getOperand(OpNo)) - 1;
245 }
246
247 unsigned MipsCodeEmitter::getLSAImmEncoding(const MachineInstr &MI,
248                                             unsigned OpNo) const {
249   llvm_unreachable("Unimplemented function.");
250   return 0;
251 }
252
253 /// getMachineOpValue - Return binary encoding of operand. If the machine
254 /// operand requires relocation, record the relocation and return zero.
255 unsigned MipsCodeEmitter::getMachineOpValue(const MachineInstr &MI,
256                                             const MachineOperand &MO) const {
257   if (MO.isReg())
258     return TM.getRegisterInfo()->getEncodingValue(MO.getReg());
259   else if (MO.isImm())
260     return static_cast<unsigned>(MO.getImm());
261   else if (MO.isGlobal())
262     emitGlobalAddress(MO.getGlobal(), getRelocation(MI, MO), true);
263   else if (MO.isSymbol())
264     emitExternalSymbolAddress(MO.getSymbolName(), getRelocation(MI, MO));
265   else if (MO.isCPI())
266     emitConstPoolAddress(MO.getIndex(), getRelocation(MI, MO));
267   else if (MO.isJTI())
268     emitJumpTableAddress(MO.getIndex(), getRelocation(MI, MO));
269   else if (MO.isMBB())
270     emitMachineBasicBlock(MO.getMBB(), getRelocation(MI, MO));
271   else
272     llvm_unreachable("Unable to encode MachineOperand!");
273   return 0;
274 }
275
276 void MipsCodeEmitter::emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
277                                         bool MayNeedFarStub) const {
278   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
279                                              const_cast<GlobalValue *>(GV), 0,
280                                              MayNeedFarStub));
281 }
282
283 void MipsCodeEmitter::emitGlobalAddressUnaligned(const GlobalValue *GV,
284                                            unsigned Reloc, int Offset) const {
285   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
286                              const_cast<GlobalValue *>(GV), 0, false));
287   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset() + Offset,
288                       Reloc, const_cast<GlobalValue *>(GV), 0, false));
289 }
290
291 void MipsCodeEmitter::
292 emitExternalSymbolAddress(const char *ES, unsigned Reloc) const {
293   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
294                                                  Reloc, ES, 0, 0));
295 }
296
297 void MipsCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc) const {
298   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
299                                                     Reloc, CPI, 0, false));
300 }
301
302 void MipsCodeEmitter::
303 emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) const {
304   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
305                                                     Reloc, JTIndex, 0, false));
306 }
307
308 void MipsCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
309                                             unsigned Reloc) const {
310   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
311                                              Reloc, BB));
312 }
313
314 void MipsCodeEmitter::emitInstruction(MachineBasicBlock::instr_iterator MI,
315                                       MachineBasicBlock &MBB) {
316   DEBUG(errs() << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << *MI);
317
318   // Expand pseudo instruction. Skip if MI was not expanded.
319   if (((MI->getDesc().TSFlags & MipsII::FormMask) == MipsII::Pseudo) &&
320       !expandPseudos(MI, MBB))
321     return;
322
323   MCE.processDebugLoc(MI->getDebugLoc(), true);
324
325   emitWord(getBinaryCodeForInstr(*MI));
326   ++NumEmitted;  // Keep track of the # of mi's emitted
327
328   MCE.processDebugLoc(MI->getDebugLoc(), false);
329 }
330
331 void MipsCodeEmitter::emitWord(unsigned Word) {
332   DEBUG(errs() << "  0x";
333         errs().write_hex(Word) << "\n");
334   if (Subtarget->isLittle())
335     MCE.emitWordLE(Word);
336   else
337     MCE.emitWordBE(Word);
338 }
339
340 void MipsCodeEmitter::expandACCInstr(MachineBasicBlock::instr_iterator MI,
341                                      MachineBasicBlock &MBB,
342                                      unsigned Opc) const {
343   // Expand "pseudomult $ac0, $t0, $t1" to "mult $t0, $t1".
344   BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Opc))
345     .addReg(MI->getOperand(1).getReg()).addReg(MI->getOperand(2).getReg());
346 }
347
348 bool MipsCodeEmitter::expandPseudos(MachineBasicBlock::instr_iterator &MI,
349                                     MachineBasicBlock &MBB) const {
350   switch (MI->getOpcode()) {
351   case Mips::NOP:
352     BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::SLL), Mips::ZERO)
353       .addReg(Mips::ZERO).addImm(0);
354     break;
355   case Mips::B:
356     BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::BEQ)).addReg(Mips::ZERO)
357       .addReg(Mips::ZERO).addOperand(MI->getOperand(0));
358     break;
359   case Mips::TRAP:
360     BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::BREAK)).addImm(0)
361       .addImm(0);
362     break;
363   case Mips::JALRPseudo:
364     BuildMI(MBB, &*MI, MI->getDebugLoc(), II->get(Mips::JALR), Mips::RA)
365       .addReg(MI->getOperand(0).getReg());
366     break;
367   case Mips::PseudoMULT:
368     expandACCInstr(MI, MBB, Mips::MULT);
369     break;
370   case Mips::PseudoMULTu:
371     expandACCInstr(MI, MBB, Mips::MULTu);
372     break;
373   case Mips::PseudoSDIV:
374     expandACCInstr(MI, MBB, Mips::SDIV);
375     break;
376   case Mips::PseudoUDIV:
377     expandACCInstr(MI, MBB, Mips::UDIV);
378     break;
379   case Mips::PseudoMADD:
380     expandACCInstr(MI, MBB, Mips::MADD);
381     break;
382   case Mips::PseudoMADDU:
383     expandACCInstr(MI, MBB, Mips::MADDU);
384     break;
385   case Mips::PseudoMSUB:
386     expandACCInstr(MI, MBB, Mips::MSUB);
387     break;
388   case Mips::PseudoMSUBU:
389     expandACCInstr(MI, MBB, Mips::MSUBU);
390     break;
391   default:
392     return false;
393   }
394
395   (MI--)->eraseFromBundle();
396   return true;
397 }
398
399 /// createMipsJITCodeEmitterPass - Return a pass that emits the collected Mips
400 /// code to the specified MCE object.
401 FunctionPass *llvm::createMipsJITCodeEmitterPass(MipsTargetMachine &TM,
402                                                  JITCodeEmitter &JCE) {
403   return new MipsCodeEmitter(TM, JCE);
404 }
405
406 #include "MipsGenCodeEmitter.inc"