Revert 56176. All those instruction formats are still needed.
[oota-llvm.git] / lib / Target / ARM / ARMCodeEmitter.cpp
1 //===-- ARM/ARMCodeEmitter.cpp - Convert ARM 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 ARM machine instructions into
11 // relocatable machine code.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "arm-emitter"
16 #include "ARM.h"
17 #include "ARMAddressingModes.h"
18 #include "ARMInstrInfo.h"
19 #include "ARMRelocations.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "llvm/Function.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/CodeGen/MachineCodeEmitter.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 using namespace llvm;
32
33 STATISTIC(NumEmitted, "Number of machine instructions emitted");
34
35 namespace {
36   class VISIBILITY_HIDDEN ARMCodeEmitter : public MachineFunctionPass {
37     const ARMInstrInfo  *II;
38     const TargetData    *TD;
39     TargetMachine       &TM;
40     MachineCodeEmitter  &MCE;
41   public:
42     static char ID;
43     explicit ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce)
44       : MachineFunctionPass(&ID), II(0), TD(0), TM(tm),
45       MCE(mce) {}
46     ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce,
47             const ARMInstrInfo &ii, const TargetData &td)
48       : MachineFunctionPass(&ID), II(&ii), TD(&td), TM(tm),
49       MCE(mce) {}
50
51     bool runOnMachineFunction(MachineFunction &MF);
52
53     virtual const char *getPassName() const {
54       return "ARM Machine Code Emitter";
55     }
56
57     void emitInstruction(const MachineInstr &MI);
58
59   private:
60     unsigned getAddrModeNoneInstrBinary(const MachineInstr &MI,
61                                         const TargetInstrDesc &TID,
62                                         unsigned Binary);
63
64     unsigned getMachineSoRegOpValue(const MachineInstr &MI,
65                                     const TargetInstrDesc &TID,
66                                     unsigned OpIdx);
67
68     unsigned getAddrMode1SBit(const MachineInstr &MI,
69                               const TargetInstrDesc &TID) const;
70
71     unsigned getAddrMode1InstrBinary(const MachineInstr &MI,
72                                      const TargetInstrDesc &TID,
73                                      unsigned Binary);
74     unsigned getAddrMode2InstrBinary(const MachineInstr &MI,
75                                      const TargetInstrDesc &TID,
76                                      unsigned Binary);
77     unsigned getAddrMode3InstrBinary(const MachineInstr &MI,
78                                      const TargetInstrDesc &TID,
79                                      unsigned Binary);
80     unsigned getAddrMode4InstrBinary(const MachineInstr &MI,
81                                      const TargetInstrDesc &TID,
82                                      unsigned Binary);
83
84     /// getInstrBinary - Return binary encoding for the specified
85     /// machine instruction.
86     unsigned getInstrBinary(const MachineInstr &MI);
87
88     /// getBinaryCodeForInstr - This function, generated by the
89     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
90     /// machine instructions.
91     ///
92     unsigned getBinaryCodeForInstr(const MachineInstr &MI);
93
94     /// getMachineOpValue - Return binary encoding of operand. If the machine
95     /// operand requires relocation, record the relocation and return zero.
96     unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) {
97       return getMachineOpValue(MI, MI.getOperand(OpIdx));
98     }
99     unsigned getMachineOpValue(const MachineInstr &MI,
100                                const MachineOperand &MO);
101
102     /// getBaseOpcodeFor - Return the opcode value.
103     ///
104     unsigned getBaseOpcodeFor(const TargetInstrDesc &TID) const {
105       return (TID.TSFlags & ARMII::OpcodeMask) >> ARMII::OpcodeShift;
106     }
107
108     /// getShiftOp - Return the shift opcode (bit[6:5]) of the machine operand.
109     ///
110     unsigned getShiftOp(const MachineOperand &MO) const ;
111
112     /// Routines that handle operands which add machine relocations which are
113     /// fixed up by the JIT fixup stage.
114     void emitGlobalAddressForCall(GlobalValue *GV, bool DoesntNeedStub);
115     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
116     void emitConstPoolAddress(unsigned CPI, unsigned Reloc,
117                               int Disp = 0, unsigned PCAdj = 0 );
118     void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
119                               unsigned PCAdj = 0);
120     void emitGlobalConstant(const Constant *CV);
121     void emitMachineBasicBlock(MachineBasicBlock *BB);
122   };
123   char ARMCodeEmitter::ID = 0;
124 }
125
126 /// createARMCodeEmitterPass - Return a pass that emits the collected ARM code
127 /// to the specified MCE object.
128 FunctionPass *llvm::createARMCodeEmitterPass(ARMTargetMachine &TM,
129                                              MachineCodeEmitter &MCE) {
130   return new ARMCodeEmitter(TM, MCE);
131 }
132
133 bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
134   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
135           MF.getTarget().getRelocationModel() != Reloc::Static) &&
136          "JIT relocation model must be set to static or default!");
137   II = ((ARMTargetMachine&)MF.getTarget()).getInstrInfo();
138   TD = ((ARMTargetMachine&)MF.getTarget()).getTargetData();
139
140   do {
141     DOUT << "JITTing function '" << MF.getFunction()->getName() << "'\n";
142     MCE.startFunction(MF);
143     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
144          MBB != E; ++MBB) {
145       MCE.StartMachineBasicBlock(MBB);
146       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
147            I != E; ++I)
148         emitInstruction(*I);
149     }
150   } while (MCE.finishFunction(MF));
151
152   return false;
153 }
154
155 /// getShiftOp - Return the shift opcode (bit[6:5]) of the machine operand.
156 ///
157 unsigned ARMCodeEmitter::getShiftOp(const MachineOperand &MO) const {
158   switch (ARM_AM::getAM2ShiftOpc(MO.getImm())) {
159   default: assert(0 && "Unknown shift opc!");
160   case ARM_AM::asr: return 2;
161   case ARM_AM::lsl: return 0;
162   case ARM_AM::lsr: return 1;
163   case ARM_AM::ror:
164   case ARM_AM::rrx: return 3;
165   }
166   return 0;
167 }
168
169 /// getMachineOpValue - Return binary encoding of operand. If the machine
170 /// operand requires relocation, record the relocation and return zero.
171 unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
172                                            const MachineOperand &MO) {
173   if (MO.isRegister())
174     return ARMRegisterInfo::getRegisterNumbering(MO.getReg());
175   else if (MO.isImmediate())
176     return static_cast<unsigned>(MO.getImm());
177   else if (MO.isGlobalAddress())
178     emitGlobalAddressForCall(MO.getGlobal(), false);
179   else if (MO.isExternalSymbol())
180     emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_relative);
181   else if (MO.isConstantPoolIndex())
182     emitConstPoolAddress(MO.getIndex(), ARM::reloc_arm_relative);
183   else if (MO.isJumpTableIndex())
184     emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
185   else if (MO.isMachineBasicBlock())
186     emitMachineBasicBlock(MO.getMBB());
187
188   abort();
189   return 0;
190 }
191
192 /// emitGlobalAddressForCall - Emit the specified address to the code stream
193 /// assuming this is part of a function call, which is PC relative.
194 ///
195 void ARMCodeEmitter::emitGlobalAddressForCall(GlobalValue *GV,
196                                               bool DoesntNeedStub) {
197   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
198                                              ARM::reloc_arm_branch, GV, 0,
199                                              DoesntNeedStub));
200 }
201
202 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
203 /// be emitted to the current location in the function, and allow it to be PC
204 /// relative.
205 void ARMCodeEmitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
206   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
207                                                  Reloc, ES));
208 }
209
210 /// emitConstPoolAddress - Arrange for the address of an constant pool
211 /// to be emitted to the current location in the function, and allow it to be PC
212 /// relative.
213 void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
214                                           int Disp /* = 0 */,
215                                           unsigned PCAdj /* = 0 */) {
216   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
217                                                     Reloc, CPI, PCAdj));
218 }
219
220 /// emitJumpTableAddress - Arrange for the address of a jump table to
221 /// be emitted to the current location in the function, and allow it to be PC
222 /// relative.
223 void ARMCodeEmitter::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
224                                           unsigned PCAdj /* = 0 */) {
225   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
226                                                     Reloc, JTI, PCAdj));
227 }
228
229 /// emitMachineBasicBlock - Emit the specified address basic block.
230 void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB) {
231   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
232                                              ARM::reloc_arm_branch, BB));
233 }
234
235 void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
236   DOUT << MI;
237
238   NumEmitted++;  // Keep track of the # of mi's emitted
239   MCE.emitWordLE(getInstrBinary(MI));
240 }
241
242 unsigned ARMCodeEmitter::getAddrModeNoneInstrBinary(const MachineInstr &MI,
243                                                     const TargetInstrDesc &TID,
244                                                     unsigned Binary) {
245   switch (TID.TSFlags & ARMII::FormMask) {
246   default:
247     assert(0 && "Unknown instruction subtype!");
248     break;
249   case ARMII::Branch: {
250     // Set signed_immed_24 field
251     Binary |= getMachineOpValue(MI, 0);
252
253     // if it is a conditional branch, set cond field
254     if (TID.Opcode == ARM::Bcc) {
255       Binary &= 0x0FFFFFFF;                      // clear conditional field
256       Binary |= getMachineOpValue(MI, 1) << 28;  // set conditional field
257     }
258     break;
259   }
260   case ARMII::BranchMisc: {
261     // Set bit[19:8] to 0xFFF
262     Binary |= 0xfff << 8;
263     if (TID.Opcode == ARM::BX_RET)
264       Binary |= 0xe; // the return register is LR
265     else 
266       // otherwise, set the return register
267       Binary |= getMachineOpValue(MI, 0);
268     break;
269   }
270   }
271
272   return Binary;
273 }
274
275 unsigned ARMCodeEmitter::getMachineSoRegOpValue(const MachineInstr &MI,
276                                                 const TargetInstrDesc &TID,
277                                                 unsigned OpIdx) {
278   // Set last operand (register Rm)
279   unsigned Binary = getMachineOpValue(MI, OpIdx);
280
281   const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
282   const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
283   ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
284
285   // Encode the shift opcode.
286   unsigned SBits = 0;
287   unsigned Rs = MO1.getReg();
288   if (Rs) {
289     // Set shift operand (bit[7:4]).
290     // LSL - 0001
291     // LSR - 0011
292     // ASR - 0101
293     // ROR - 0111
294     // RRX - 0110 and bit[11:8] clear.
295     switch (SOpc) {
296     default: assert(0 && "Unknown shift opc!");
297     case ARM_AM::lsl: SBits = 0x1; break;
298     case ARM_AM::lsr: SBits = 0x3; break;
299     case ARM_AM::asr: SBits = 0x5; break;
300     case ARM_AM::ror: SBits = 0x7; break;
301     case ARM_AM::rrx: SBits = 0x6; break;
302     }
303   } else {
304     // Set shift operand (bit[6:4]).
305     // LSL - 000
306     // LSR - 010
307     // ASR - 100
308     // ROR - 110
309     switch (SOpc) {
310     default: assert(0 && "Unknown shift opc!");
311     case ARM_AM::lsl: SBits = 0x0; break;
312     case ARM_AM::lsr: SBits = 0x2; break;
313     case ARM_AM::asr: SBits = 0x4; break;
314     case ARM_AM::ror: SBits = 0x6; break;
315     }
316   }
317   Binary |= SBits << 4;
318   if (SOpc == ARM_AM::rrx)
319     return Binary;
320
321   // Encode the shift operation Rs or shift_imm (except rrx).
322   if (Rs) {
323     // Encode Rs bit[11:8].
324     assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
325     return Binary |
326       (ARMRegisterInfo::getRegisterNumbering(Rs) << ARMII::RegRsShift);
327   }
328
329   // Encode shift_imm bit[11:7].
330   return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
331 }
332
333 unsigned ARMCodeEmitter::getAddrMode1SBit(const MachineInstr &MI,
334                                           const TargetInstrDesc &TID) const {
335   for (unsigned i = MI.getNumOperands(), e = TID.getNumOperands(); i != e; --i){
336     const MachineOperand &MO = MI.getOperand(i-1);
337     if (MO.isRegister() && MO.isDef() && MO.getReg() == ARM::CPSR)
338       return 1 << ARMII::S_BitShift;
339   }
340   return 0;
341 }
342
343 unsigned ARMCodeEmitter::getAddrMode1InstrBinary(const MachineInstr &MI,
344                                                  const TargetInstrDesc &TID,
345                                                  unsigned Binary) {
346   unsigned Format = TID.TSFlags & ARMII::FormMask;
347   if (Format == ARMII::Pseudo)
348     abort(); // FIXME
349
350   // Encode S bit if MI modifies CPSR.
351   Binary |= getAddrMode1SBit(MI, TID);
352
353   // Encode register def if there is one.
354   unsigned NumDefs = TID.getNumDefs();
355   unsigned OpIdx = 0;
356   if (NumDefs) {
357     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdShift;
358     ++OpIdx;
359   }
360
361   // Encode first non-shifter register operand if ther is one.
362   bool isUnary = (Format == ARMII::DPRdMisc  ||
363                   Format == ARMII::DPRdIm    ||
364                   Format == ARMII::DPRdReg   ||
365                   Format == ARMII::DPRdSoReg ||
366                   Format == ARMII::DPRnIm    ||
367                   Format == ARMII::DPRnReg   ||
368                   Format == ARMII::DPRnSoReg);
369   if (!isUnary) {
370     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
371     ++OpIdx;
372   }
373
374   // Encode shifter operand.
375   if (TID.getNumOperands() - OpIdx > 1)
376     // Encode SoReg.
377     return Binary | getMachineSoRegOpValue(MI, TID, OpIdx);
378
379   const MachineOperand &MO = MI.getOperand(OpIdx);
380   if (MO.isRegister())
381     // Encode register Rm.
382     return Binary | getMachineOpValue(MI, NumDefs + 1);
383
384   // Encode so_imm.
385   // Set bit I(25) to identify this is the immediate form of <shifter_op>
386   Binary |= 1 << ARMII::I_BitShift;
387   unsigned SoImm = MO.getImm();
388   // Encode rotate_imm.
389   Binary |= ARM_AM::getSOImmValRot(SoImm) << ARMII::RotImmShift;
390   // Encode immed_8.
391   Binary |= ARM_AM::getSOImmVal(SoImm);
392   return Binary;
393 }
394
395 unsigned ARMCodeEmitter::getAddrMode2InstrBinary(const MachineInstr &MI,
396                                                  const TargetInstrDesc &TID,
397                                                  unsigned Binary) {
398   // Set first operand
399   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
400
401   // Set second operand
402   Binary |= getMachineOpValue(MI, 1) << ARMII::RegRnShift;
403
404   const MachineOperand &MO2 = MI.getOperand(2);
405   const MachineOperand &MO3 = MI.getOperand(3);
406
407   // Set bit U(23) according to signal of immed value (positive or negative).
408   Binary |= ((ARM_AM::getAM2Op(MO3.getImm()) == ARM_AM::add ? 1 : 0) <<
409             ARMII::U_BitShift);
410   if (!MO2.getReg()) { // is immediate
411     if (ARM_AM::getAM2Offset(MO3.getImm()))
412       // Set the value of offset_12 field
413       Binary |= ARM_AM::getAM2Offset(MO3.getImm());
414     return Binary;
415   }
416
417   // Set bit I(25), because this is not in immediate enconding.
418   Binary |= 1 << ARMII::I_BitShift;
419   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
420   // Set bit[3:0] to the corresponding Rm register
421   Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
422
423   // if this instr is in scaled register offset/index instruction, set
424   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
425   if (unsigned ShImm = ARM_AM::getAM2Offset(MO3.getImm())) {
426     Binary |= getShiftOp(MO3) << 5;  // shift
427     Binary |= ShImm           << 7;  // shift_immed
428   }
429
430   return Binary;
431 }
432
433 unsigned ARMCodeEmitter::getAddrMode3InstrBinary(const MachineInstr &MI,
434                                                  const TargetInstrDesc &TID,
435                                                  unsigned Binary) {
436   // Set first operand
437   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
438
439   // Set second operand
440   Binary |= getMachineOpValue(MI, 1) << ARMII::RegRnShift;
441
442   const MachineOperand &MO2 = MI.getOperand(2);
443   const MachineOperand &MO3 = MI.getOperand(3);
444
445   // Set bit U(23) according to signal of immed value (positive or negative)
446   Binary |= ((ARM_AM::getAM2Op(MO3.getImm()) == ARM_AM::add ? 1 : 0) <<
447              ARMII::U_BitShift);
448
449   // If this instr is in register offset/index encoding, set bit[3:0]
450   // to the corresponding Rm register.
451   if (MO2.getReg()) {
452     Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
453     return Binary;
454   }
455
456   // if this instr is in immediate offset/index encoding, set bit 22 to 1
457   if (unsigned ImmOffs = ARM_AM::getAM3Offset(MO3.getImm())) {
458     Binary |= 1 << 22;
459     // Set operands
460     Binary |= (ImmOffs >> 4) << 8;  // immedH
461     Binary |= (ImmOffs & ~0xF);     // immedL
462   }
463
464   return Binary;
465 }
466
467 unsigned ARMCodeEmitter::getAddrMode4InstrBinary(const MachineInstr &MI,
468                                                  const TargetInstrDesc &TID,
469                                                  unsigned Binary) {
470   // Set first operand
471   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
472
473   // Set addressing mode by modifying bits U(23) and P(24)
474   // IA - Increment after  - bit U = 1 and bit P = 0
475   // IB - Increment before - bit U = 1 and bit P = 1
476   // DA - Decrement after  - bit U = 0 and bit P = 0
477   // DB - Decrement before - bit U = 0 and bit P = 1
478   const MachineOperand &MO = MI.getOperand(1);
479   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO.getImm());
480   switch (Mode) {
481   default: assert(0 && "Unknown addressing sub-mode!");
482   case ARM_AM::da:                      break;
483   case ARM_AM::db: Binary |= 0x1 << 24; break;
484   case ARM_AM::ia: Binary |= 0x1 << 23; break;
485   case ARM_AM::ib: Binary |= 0x3 << 23; break;
486   }
487
488   // Set bit W(21)
489   if (ARM_AM::getAM4WBFlag(MO.getImm()))
490     Binary |= 0x1 << 21;
491
492   // Set registers
493   for (unsigned i = 4, e = MI.getNumOperands(); i != e; ++i) {
494     const MachineOperand &MO = MI.getOperand(i);
495     if (MO.isRegister() && MO.isImplicit())
496       continue;
497     unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
498     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
499            RegNum < 16);
500     Binary |= 0x1 << RegNum;
501   }
502
503   return Binary;
504 }
505
506 /// getInstrBinary - Return binary encoding for the specified
507 /// machine instruction.
508 unsigned ARMCodeEmitter::getInstrBinary(const MachineInstr &MI) {
509   // Part of binary is determined by TableGn.
510   unsigned Binary = getBinaryCodeForInstr(MI);
511
512   const TargetInstrDesc &TID = MI.getDesc();
513   switch (TID.TSFlags & ARMII::AddrModeMask) {
514   case ARMII::AddrModeNone:
515     return getAddrModeNoneInstrBinary(MI, TID, Binary);
516   case ARMII::AddrMode1:
517     return getAddrMode1InstrBinary(MI, TID, Binary);
518   case ARMII::AddrMode2:
519     return getAddrMode2InstrBinary(MI, TID, Binary);
520   case ARMII::AddrMode3:
521     return getAddrMode3InstrBinary(MI, TID, Binary);
522   case ARMII::AddrMode4:
523     return getAddrMode4InstrBinary(MI, TID, Binary);
524   }
525
526   abort();
527   return 0;
528 }
529
530 #include "ARMGenCodeEmitter.inc"