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