Skip over two-address use operands.
[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 "jit"
16 #include "ARM.h"
17 #include "ARMAddressingModes.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMInstrInfo.h"
20 #include "ARMRelocations.h"
21 #include "ARMSubtarget.h"
22 #include "ARMTargetMachine.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Function.h"
26 #include "llvm/PassManager.h"
27 #include "llvm/CodeGen/MachineCodeEmitter.h"
28 #include "llvm/CodeGen/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/CodeGen/Passes.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/Debug.h"
36 #ifndef NDEBUG
37 #include <iomanip>
38 #endif
39 using namespace llvm;
40
41 STATISTIC(NumEmitted, "Number of machine instructions emitted");
42
43 namespace {
44   class VISIBILITY_HIDDEN ARMCodeEmitter : public MachineFunctionPass {
45     ARMJITInfo                *JTI;
46     const ARMInstrInfo        *II;
47     const TargetData          *TD;
48     TargetMachine             &TM;
49     MachineCodeEmitter        &MCE;
50     const std::vector<MachineConstantPoolEntry> *MCPEs;
51     const std::vector<MachineJumpTableEntry> *MJTEs;
52     bool IsPIC;
53
54   public:
55     static char ID;
56     explicit ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce)
57       : MachineFunctionPass(&ID), JTI(0), II(0), TD(0), TM(tm),
58       MCE(mce), MCPEs(0), MJTEs(0),
59       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
60     ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce,
61             const ARMInstrInfo &ii, const TargetData &td)
62       : MachineFunctionPass(&ID), JTI(0), II(&ii), TD(&td), TM(tm),
63       MCE(mce), MCPEs(0), MJTEs(0),
64       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
65
66     bool runOnMachineFunction(MachineFunction &MF);
67
68     virtual const char *getPassName() const {
69       return "ARM Machine Code Emitter";
70     }
71
72     void emitInstruction(const MachineInstr &MI);
73
74   private:
75
76     void emitWordLE(unsigned Binary);
77
78     void emitConstPoolInstruction(const MachineInstr &MI);
79
80     void emitMOVi2piecesInstruction(const MachineInstr &MI);
81
82     void emitLEApcrelJTInstruction(const MachineInstr &MI);
83
84     void addPCLabel(unsigned LabelID);
85
86     void emitPseudoInstruction(const MachineInstr &MI);
87
88     unsigned getMachineSoRegOpValue(const MachineInstr &MI,
89                                     const TargetInstrDesc &TID,
90                                     const MachineOperand &MO,
91                                     unsigned OpIdx);
92
93     unsigned getMachineSoImmOpValue(unsigned SoImm);
94
95     unsigned getAddrModeSBit(const MachineInstr &MI,
96                              const TargetInstrDesc &TID) const;
97
98     void emitDataProcessingInstruction(const MachineInstr &MI,
99                                        unsigned ImplicitRd = 0,
100                                        unsigned ImplicitRn = 0);
101
102     void emitLoadStoreInstruction(const MachineInstr &MI,
103                                   unsigned ImplicitRd = 0,
104                                   unsigned ImplicitRn = 0);
105
106     void emitMiscLoadStoreInstruction(const MachineInstr &MI,
107                                       unsigned ImplicitRn = 0);
108
109     void emitLoadStoreMultipleInstruction(const MachineInstr &MI);
110
111     void emitMulFrmInstruction(const MachineInstr &MI);
112
113     void emitExtendInstruction(const MachineInstr &MI);
114
115     void emitMiscArithInstruction(const MachineInstr &MI);
116
117     void emitBranchInstruction(const MachineInstr &MI);
118
119     void emitInlineJumpTable(unsigned JTIndex);
120
121     void emitMiscBranchInstruction(const MachineInstr &MI);
122
123     /// getBinaryCodeForInstr - This function, generated by the
124     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
125     /// machine instructions.
126     ///
127     unsigned getBinaryCodeForInstr(const MachineInstr &MI);
128
129     /// getMachineOpValue - Return binary encoding of operand. If the machine
130     /// operand requires relocation, record the relocation and return zero.
131     unsigned getMachineOpValue(const MachineInstr &MI,const MachineOperand &MO);
132     unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) {
133       return getMachineOpValue(MI, MI.getOperand(OpIdx));
134     }
135
136     /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
137     ///
138     unsigned getShiftOp(unsigned Imm) const ;
139
140     /// Routines that handle operands which add machine relocations which are
141     /// fixed up by the relocation stage.
142     void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
143                            bool NeedStub, intptr_t ACPV = 0);
144     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
145     void emitConstPoolAddress(unsigned CPI, unsigned Reloc);
146     void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc);
147     void emitMachineBasicBlock(MachineBasicBlock *BB, unsigned Reloc,
148                                intptr_t JTBase = 0);
149   };
150   char ARMCodeEmitter::ID = 0;
151 }
152
153 /// createARMCodeEmitterPass - Return a pass that emits the collected ARM code
154 /// to the specified MCE object.
155 FunctionPass *llvm::createARMCodeEmitterPass(ARMTargetMachine &TM,
156                                              MachineCodeEmitter &MCE) {
157   return new ARMCodeEmitter(TM, MCE);
158 }
159
160 bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
161   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
162           MF.getTarget().getRelocationModel() != Reloc::Static) &&
163          "JIT relocation model must be set to static or default!");
164   II = ((ARMTargetMachine&)MF.getTarget()).getInstrInfo();
165   TD = ((ARMTargetMachine&)MF.getTarget()).getTargetData();
166   JTI = ((ARMTargetMachine&)MF.getTarget()).getJITInfo();
167   MCPEs = &MF.getConstantPool()->getConstants();
168   MJTEs = &MF.getJumpTableInfo()->getJumpTables();
169   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
170   JTI->Initialize(MF);
171
172   do {
173     DOUT << "JITTing function '" << MF.getFunction()->getName() << "'\n";
174     MCE.startFunction(MF);
175     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
176          MBB != E; ++MBB) {
177       MCE.StartMachineBasicBlock(MBB);
178       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
179            I != E; ++I)
180         emitInstruction(*I);
181     }
182   } while (MCE.finishFunction(MF));
183
184   return false;
185 }
186
187 /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
188 ///
189 unsigned ARMCodeEmitter::getShiftOp(unsigned Imm) const {
190   switch (ARM_AM::getAM2ShiftOpc(Imm)) {
191   default: assert(0 && "Unknown shift opc!");
192   case ARM_AM::asr: return 2;
193   case ARM_AM::lsl: return 0;
194   case ARM_AM::lsr: return 1;
195   case ARM_AM::ror:
196   case ARM_AM::rrx: return 3;
197   }
198   return 0;
199 }
200
201 /// getMachineOpValue - Return binary encoding of operand. If the machine
202 /// operand requires relocation, record the relocation and return zero.
203 unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
204                                            const MachineOperand &MO) {
205   if (MO.isReg())
206     return ARMRegisterInfo::getRegisterNumbering(MO.getReg());
207   else if (MO.isImm())
208     return static_cast<unsigned>(MO.getImm());
209   else if (MO.isGlobal())
210     emitGlobalAddress(MO.getGlobal(), ARM::reloc_arm_branch, true);
211   else if (MO.isSymbol())
212     emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_relative);
213   else if (MO.isCPI())
214     emitConstPoolAddress(MO.getIndex(), ARM::reloc_arm_cp_entry);
215   else if (MO.isJTI())
216     emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
217   else if (MO.isMBB())
218     emitMachineBasicBlock(MO.getMBB(), ARM::reloc_arm_branch);
219   else {
220     cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
221     abort();
222   }
223   return 0;
224 }
225
226 /// emitGlobalAddress - Emit the specified address to the code stream.
227 ///
228 void ARMCodeEmitter::emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
229                                        bool NeedStub, intptr_t ACPV) {
230   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
231                                              Reloc, GV, ACPV, NeedStub));
232 }
233
234 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
235 /// be emitted to the current location in the function, and allow it to be PC
236 /// relative.
237 void ARMCodeEmitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
238   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
239                                                  Reloc, ES));
240 }
241
242 /// emitConstPoolAddress - Arrange for the address of an constant pool
243 /// to be emitted to the current location in the function, and allow it to be PC
244 /// relative.
245 void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc) {
246   // Tell JIT emitter we'll resolve the address.
247   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
248                                                     Reloc, CPI, 0, true));
249 }
250
251 /// emitJumpTableAddress - Arrange for the address of a jump table to
252 /// be emitted to the current location in the function, and allow it to be PC
253 /// relative.
254 void ARMCodeEmitter::emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) {
255   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
256                                                     Reloc, JTIndex, 0, true));
257 }
258
259 /// emitMachineBasicBlock - Emit the specified address basic block.
260 void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
261                                            unsigned Reloc, intptr_t JTBase) {
262   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
263                                              Reloc, BB, JTBase));
264 }
265
266 void ARMCodeEmitter::emitWordLE(unsigned Binary) {
267 #ifndef NDEBUG
268   DOUT << "  0x" << std::hex << std::setw(8) << std::setfill('0')
269        << Binary << std::dec << "\n";
270 #endif
271   MCE.emitWordLE(Binary);
272 }
273
274 void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
275   DOUT << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI;
276
277   NumEmitted++;  // Keep track of the # of mi's emitted
278   switch (MI.getDesc().TSFlags & ARMII::FormMask) {
279   default:
280     assert(0 && "Unhandled instruction encoding format!");
281     break;
282   case ARMII::Pseudo:
283     emitPseudoInstruction(MI);
284     break;
285   case ARMII::DPFrm:
286   case ARMII::DPSoRegFrm:
287     emitDataProcessingInstruction(MI);
288     break;
289   case ARMII::LdFrm:
290   case ARMII::StFrm:
291     emitLoadStoreInstruction(MI);
292     break;
293   case ARMII::LdMiscFrm:
294   case ARMII::StMiscFrm:
295     emitMiscLoadStoreInstruction(MI);
296     break;
297   case ARMII::LdMulFrm:
298   case ARMII::StMulFrm:
299     emitLoadStoreMultipleInstruction(MI);
300     break;
301   case ARMII::MulFrm:
302     emitMulFrmInstruction(MI);
303     break;
304   case ARMII::ExtFrm:
305     emitExtendInstruction(MI);
306     break;
307   case ARMII::ArithMiscFrm:
308     emitMiscArithInstruction(MI);
309     break;
310   case ARMII::BrFrm:
311     emitBranchInstruction(MI);
312     break;
313   case ARMII::BrMiscFrm:
314     emitMiscBranchInstruction(MI);
315     break;
316   }
317 }
318
319 void ARMCodeEmitter::emitConstPoolInstruction(const MachineInstr &MI) {
320   unsigned CPI = MI.getOperand(0).getImm();       // CP instruction index.
321   unsigned CPIndex = MI.getOperand(1).getIndex(); // Actual cp entry index.
322   const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
323   
324   // Remember the CONSTPOOL_ENTRY address for later relocation.
325   JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
326
327   // Emit constpool island entry. In most cases, the actual values will be
328   // resolved and relocated after code emission.
329   if (MCPE.isMachineConstantPoolEntry()) {
330     ARMConstantPoolValue *ACPV =
331       static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
332
333     DOUT << "  ** ARM constant pool #" << CPI << " @ "
334          << (void*)MCE.getCurrentPCValue() << " " << *ACPV << '\n';
335
336     GlobalValue *GV = ACPV->getGV();
337     if (GV) {
338       assert(!ACPV->isStub() && "Don't know how to deal this yet!");
339       if (ACPV->isNonLazyPointer())
340         MCE.addRelocation(MachineRelocation::getGVNonLazyPtr(
341                   MCE.getCurrentPCOffset(), ARM::reloc_arm_machine_cp_entry, GV,
342                   (intptr_t)ACPV, false));
343       else 
344         emitGlobalAddress(GV, ARM::reloc_arm_machine_cp_entry,
345                           ACPV->isStub(), (intptr_t)ACPV);
346      } else  {
347       assert(!ACPV->isNonLazyPointer() && "Don't know how to deal this yet!");
348       emitExternalSymbolAddress(ACPV->getSymbol(), ARM::reloc_arm_absolute);
349     }
350     emitWordLE(0);
351   } else {
352     Constant *CV = MCPE.Val.ConstVal;
353
354     DOUT << "  ** Constant pool #" << CPI << " @ "
355          << (void*)MCE.getCurrentPCValue() << " " << *CV << '\n';
356
357     if (GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
358       emitGlobalAddress(GV, ARM::reloc_arm_absolute, false);
359       emitWordLE(0);
360     } else {
361       assert(CV->getType()->isInteger() &&
362              "Not expecting non-integer constpool entries yet!");
363       const ConstantInt *CI = dyn_cast<ConstantInt>(CV);
364       uint32_t Val = *(uint32_t*)CI->getValue().getRawData();
365       emitWordLE(Val);
366     }
367   }
368 }
369
370 void ARMCodeEmitter::emitMOVi2piecesInstruction(const MachineInstr &MI) {
371   const MachineOperand &MO0 = MI.getOperand(0);
372   const MachineOperand &MO1 = MI.getOperand(1);
373   assert(MO1.isImm() && "Not a valid so_imm value!");
374   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO1.getImm());
375   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO1.getImm());
376
377   // Emit the 'mov' instruction.
378   unsigned Binary = 0xd << 21;  // mov: Insts{24-21} = 0b1101
379
380   // Set the conditional execution predicate.
381   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
382
383   // Encode Rd.
384   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
385
386   // Encode so_imm.
387   // Set bit I(25) to identify this is the immediate form of <shifter_op>
388   Binary |= 1 << ARMII::I_BitShift;
389   Binary |= getMachineSoImmOpValue(ARM_AM::getSOImmVal(V1));
390   emitWordLE(Binary);
391
392   // Now the 'orr' instruction.
393   Binary = 0xc << 21;  // orr: Insts{24-21} = 0b1100
394
395   // Set the conditional execution predicate.
396   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
397
398   // Encode Rd.
399   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
400
401   // Encode Rn.
402   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRnShift;
403
404   // Encode so_imm.
405   // Set bit I(25) to identify this is the immediate form of <shifter_op>
406   Binary |= 1 << ARMII::I_BitShift;
407   Binary |= getMachineSoImmOpValue(ARM_AM::getSOImmVal(V2));
408   emitWordLE(Binary);
409 }
410
411 void ARMCodeEmitter::emitLEApcrelJTInstruction(const MachineInstr &MI) {
412   // It's basically add r, pc, (LJTI - $+8)
413   
414   const TargetInstrDesc &TID = MI.getDesc();
415
416   // Emit the 'add' instruction.
417   unsigned Binary = 0x4 << 21;  // add: Insts{24-31} = 0b0100
418
419   // Set the conditional execution predicate
420   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
421
422   // Encode S bit if MI modifies CPSR.
423   Binary |= getAddrModeSBit(MI, TID);
424
425   // Encode Rd.
426   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
427
428   // Encode Rn which is PC.
429   Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::PC) << ARMII::RegRnShift;
430
431   // Encode the displacement.
432   // Set bit I(25) to identify this is the immediate form of <shifter_op>.
433   Binary |= 1 << ARMII::I_BitShift;
434   emitJumpTableAddress(MI.getOperand(1).getIndex(), ARM::reloc_arm_jt_base);
435
436   emitWordLE(Binary);
437 }
438
439 void ARMCodeEmitter::addPCLabel(unsigned LabelID) {
440   DOUT << "  ** LPC" << LabelID << " @ "
441        << (void*)MCE.getCurrentPCValue() << '\n';
442   JTI->addPCLabelAddr(LabelID, MCE.getCurrentPCValue());
443 }
444
445 void ARMCodeEmitter::emitPseudoInstruction(const MachineInstr &MI) {
446   unsigned Opcode = MI.getDesc().Opcode;
447   switch (Opcode) {
448   default:
449     abort(); // FIXME:
450   case ARM::CONSTPOOL_ENTRY:
451     emitConstPoolInstruction(MI);
452     break;
453   case ARM::PICADD: {
454     // Remember of the address of the PC label for relocation later.
455     addPCLabel(MI.getOperand(2).getImm());
456     // PICADD is just an add instruction that implicitly read pc.
457     emitDataProcessingInstruction(MI, 0, ARM::PC);
458     break;
459   }
460   case ARM::PICLDR:
461   case ARM::PICLDRB:
462   case ARM::PICSTR:
463   case ARM::PICSTRB: {
464     // Remember of the address of the PC label for relocation later.
465     addPCLabel(MI.getOperand(2).getImm());
466     // These are just load / store instructions that implicitly read pc.
467     emitLoadStoreInstruction(MI, 0, ARM::PC);
468     break;
469   }
470   case ARM::PICLDRH:
471   case ARM::PICLDRSH:
472   case ARM::PICLDRSB:
473   case ARM::PICSTRH: {
474     // Remember of the address of the PC label for relocation later.
475     addPCLabel(MI.getOperand(2).getImm());
476     // These are just load / store instructions that implicitly read pc.
477     emitMiscLoadStoreInstruction(MI, ARM::PC);
478     break;
479   }
480   case ARM::MOVi2pieces:
481     // Two instructions to materialize a constant.
482     emitMOVi2piecesInstruction(MI);
483     break;
484   case ARM::LEApcrelJT:
485     // Materialize jumptable address.
486     emitLEApcrelJTInstruction(MI);
487     break;
488   }
489 }
490
491
492 unsigned ARMCodeEmitter::getMachineSoRegOpValue(const MachineInstr &MI,
493                                                 const TargetInstrDesc &TID,
494                                                 const MachineOperand &MO,
495                                                 unsigned OpIdx) {
496   unsigned Binary = getMachineOpValue(MI, MO);
497
498   const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
499   const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
500   ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
501
502   // Encode the shift opcode.
503   unsigned SBits = 0;
504   unsigned Rs = MO1.getReg();
505   if (Rs) {
506     // Set shift operand (bit[7:4]).
507     // LSL - 0001
508     // LSR - 0011
509     // ASR - 0101
510     // ROR - 0111
511     // RRX - 0110 and bit[11:8] clear.
512     switch (SOpc) {
513     default: assert(0 && "Unknown shift opc!");
514     case ARM_AM::lsl: SBits = 0x1; break;
515     case ARM_AM::lsr: SBits = 0x3; break;
516     case ARM_AM::asr: SBits = 0x5; break;
517     case ARM_AM::ror: SBits = 0x7; break;
518     case ARM_AM::rrx: SBits = 0x6; break;
519     }
520   } else {
521     // Set shift operand (bit[6:4]).
522     // LSL - 000
523     // LSR - 010
524     // ASR - 100
525     // ROR - 110
526     switch (SOpc) {
527     default: assert(0 && "Unknown shift opc!");
528     case ARM_AM::lsl: SBits = 0x0; break;
529     case ARM_AM::lsr: SBits = 0x2; break;
530     case ARM_AM::asr: SBits = 0x4; break;
531     case ARM_AM::ror: SBits = 0x6; break;
532     }
533   }
534   Binary |= SBits << 4;
535   if (SOpc == ARM_AM::rrx)
536     return Binary;
537
538   // Encode the shift operation Rs or shift_imm (except rrx).
539   if (Rs) {
540     // Encode Rs bit[11:8].
541     assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
542     return Binary |
543       (ARMRegisterInfo::getRegisterNumbering(Rs) << ARMII::RegRsShift);
544   }
545
546   // Encode shift_imm bit[11:7].
547   return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
548 }
549
550 unsigned ARMCodeEmitter::getMachineSoImmOpValue(unsigned SoImm) {
551   // Encode rotate_imm.
552   unsigned Binary = (ARM_AM::getSOImmValRot(SoImm) >> 1)
553     << ARMII::SoRotImmShift;
554
555   // Encode immed_8.
556   Binary |= ARM_AM::getSOImmValImm(SoImm);
557   return Binary;
558 }
559
560 unsigned ARMCodeEmitter::getAddrModeSBit(const MachineInstr &MI,
561                                          const TargetInstrDesc &TID) const {
562   for (unsigned i = MI.getNumOperands(), e = TID.getNumOperands(); i != e; --i){
563     const MachineOperand &MO = MI.getOperand(i-1);
564     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)
565       return 1 << ARMII::S_BitShift;
566   }
567   return 0;
568 }
569
570 void ARMCodeEmitter::emitDataProcessingInstruction(const MachineInstr &MI,
571                                                    unsigned ImplicitRd,
572                                                    unsigned ImplicitRn) {
573   const TargetInstrDesc &TID = MI.getDesc();
574
575   // Part of binary is determined by TableGn.
576   unsigned Binary = getBinaryCodeForInstr(MI);
577
578   // Set the conditional execution predicate
579   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
580
581   // Encode S bit if MI modifies CPSR.
582   Binary |= getAddrModeSBit(MI, TID);
583
584   // Encode register def if there is one.
585   unsigned NumDefs = TID.getNumDefs();
586   unsigned OpIdx = 0;
587   if (NumDefs)
588     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
589   else if (ImplicitRd)
590     // Special handling for implicit use (e.g. PC).
591     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
592                << ARMII::RegRdShift);
593
594   // If this is a two-address operand, skip it. e.g. MOVCCr operand 1.
595   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
596     ++OpIdx;
597
598   // Encode first non-shifter register operand if there is one.
599   bool isUnary = TID.TSFlags & ARMII::UnaryDP;
600   if (!isUnary) {
601     if (ImplicitRn)
602       // Special handling for implicit use (e.g. PC).
603       Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
604                  << ARMII::RegRnShift);
605     else {
606       Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
607       ++OpIdx;
608     }
609   }
610
611   // Encode shifter operand.
612   const MachineOperand &MO = MI.getOperand(OpIdx);
613   if ((TID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
614     // Encode SoReg.
615     emitWordLE(Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx));
616     return;
617   }
618
619   if (MO.isReg()) {
620     // Encode register Rm.
621     emitWordLE(Binary | ARMRegisterInfo::getRegisterNumbering(MO.getReg()));
622     return;
623   }
624
625   // Encode so_imm.
626   // Set bit I(25) to identify this is the immediate form of <shifter_op>.
627   Binary |= 1 << ARMII::I_BitShift;
628   Binary |= getMachineSoImmOpValue(MO.getImm());
629
630   emitWordLE(Binary);
631 }
632
633 void ARMCodeEmitter::emitLoadStoreInstruction(const MachineInstr &MI,
634                                               unsigned ImplicitRd,
635                                               unsigned ImplicitRn) {
636   const TargetInstrDesc &TID = MI.getDesc();
637
638   // Part of binary is determined by TableGn.
639   unsigned Binary = getBinaryCodeForInstr(MI);
640
641   // Set the conditional execution predicate
642   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
643
644   // Set first operand
645   unsigned OpIdx = 0;
646   if (ImplicitRd)
647     // Special handling for implicit use (e.g. PC).
648     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
649                << ARMII::RegRdShift);
650   else
651     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
652
653   // Set second operand
654   if (ImplicitRn)
655     // Special handling for implicit use (e.g. PC).
656     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
657                << ARMII::RegRnShift);
658   else
659     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
660
661   // If this is a two-address operand, skip it. e.g. LDR_PRE.
662   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
663     ++OpIdx;
664
665   const MachineOperand &MO2 = MI.getOperand(OpIdx);
666   unsigned AM2Opc = (ImplicitRn == ARM::PC)
667     ? 0 : MI.getOperand(OpIdx+1).getImm();
668
669   // Set bit U(23) according to sign of immed value (positive or negative).
670   Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
671              ARMII::U_BitShift);
672   if (!MO2.getReg()) { // is immediate
673     if (ARM_AM::getAM2Offset(AM2Opc))
674       // Set the value of offset_12 field
675       Binary |= ARM_AM::getAM2Offset(AM2Opc);
676     emitWordLE(Binary);
677     return;
678   }
679
680   // Set bit I(25), because this is not in immediate enconding.
681   Binary |= 1 << ARMII::I_BitShift;
682   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
683   // Set bit[3:0] to the corresponding Rm register
684   Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
685
686   // if this instr is in scaled register offset/index instruction, set
687   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
688   if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
689     Binary |= getShiftOp(AM2Opc) << 5;  // shift
690     Binary |= ShImm              << 7;  // shift_immed
691   }
692
693   emitWordLE(Binary);
694 }
695
696 void ARMCodeEmitter::emitMiscLoadStoreInstruction(const MachineInstr &MI,
697                                                   unsigned ImplicitRn) {
698   const TargetInstrDesc &TID = MI.getDesc();
699
700   // Part of binary is determined by TableGn.
701   unsigned Binary = getBinaryCodeForInstr(MI);
702
703   // Set the conditional execution predicate
704   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
705
706   // Set first operand
707   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
708
709   // Set second operand
710   unsigned OpIdx = 1;
711   if (ImplicitRn)
712     // Special handling for implicit use (e.g. PC).
713     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
714                << ARMII::RegRnShift);
715   else
716     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
717
718   // If this is a two-address operand, skip it. e.g. LDRH_POST.
719   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
720     ++OpIdx;
721
722   const MachineOperand &MO2 = MI.getOperand(OpIdx);
723   unsigned AM3Opc = (ImplicitRn == ARM::PC)
724     ? 0 : MI.getOperand(OpIdx+1).getImm();
725
726   // Set bit U(23) according to sign of immed value (positive or negative)
727   Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
728              ARMII::U_BitShift);
729
730   // If this instr is in register offset/index encoding, set bit[3:0]
731   // to the corresponding Rm register.
732   if (MO2.getReg()) {
733     Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
734     emitWordLE(Binary);
735     return;
736   }
737
738   // This instr is in immediate offset/index encoding, set bit 22 to 1.
739   Binary |= 1 << ARMII::AM3_I_BitShift;
740   if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
741     // Set operands
742     Binary |= (ImmOffs >> 4) << 8;  // immedH
743     Binary |= (ImmOffs & ~0xF);     // immedL
744   }
745
746   emitWordLE(Binary);
747 }
748
749 void ARMCodeEmitter::emitLoadStoreMultipleInstruction(const MachineInstr &MI) {
750   // Part of binary is determined by TableGn.
751   unsigned Binary = getBinaryCodeForInstr(MI);
752
753   // Set the conditional execution predicate
754   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
755
756   // Set first operand
757   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
758
759   // Set addressing mode by modifying bits U(23) and P(24)
760   // IA - Increment after  - bit U = 1 and bit P = 0
761   // IB - Increment before - bit U = 1 and bit P = 1
762   // DA - Decrement after  - bit U = 0 and bit P = 0
763   // DB - Decrement before - bit U = 0 and bit P = 1
764   const MachineOperand &MO = MI.getOperand(1);
765   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO.getImm());
766   switch (Mode) {
767   default: assert(0 && "Unknown addressing sub-mode!");
768   case ARM_AM::da:                      break;
769   case ARM_AM::db: Binary |= 0x1 << ARMII::P_BitShift; break;
770   case ARM_AM::ia: Binary |= 0x1 << ARMII::U_BitShift; break;
771   case ARM_AM::ib: Binary |= 0x3 << ARMII::U_BitShift; break;
772   }
773
774   // Set bit W(21)
775   if (ARM_AM::getAM4WBFlag(MO.getImm()))
776     Binary |= 0x1 << ARMII::W_BitShift;
777
778   // Set registers
779   for (unsigned i = 4, e = MI.getNumOperands(); i != e; ++i) {
780     const MachineOperand &MO = MI.getOperand(i);
781     if (MO.isReg() && MO.isImplicit())
782       continue;
783     unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
784     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
785            RegNum < 16);
786     Binary |= 0x1 << RegNum;
787   }
788
789   emitWordLE(Binary);
790 }
791
792 void ARMCodeEmitter::emitMulFrmInstruction(const MachineInstr &MI) {
793   const TargetInstrDesc &TID = MI.getDesc();
794
795   // Part of binary is determined by TableGn.
796   unsigned Binary = getBinaryCodeForInstr(MI);
797
798   // Set the conditional execution predicate
799   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
800
801   // Encode S bit if MI modifies CPSR.
802   Binary |= getAddrModeSBit(MI, TID);
803
804   // 32x32->64bit operations have two destination registers. The number
805   // of register definitions will tell us if that's what we're dealing with.
806   unsigned OpIdx = 0;
807   if (TID.getNumDefs() == 2)
808     Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
809
810   // Encode Rd
811   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
812
813   // Encode Rm
814   Binary |= getMachineOpValue(MI, OpIdx++);
815
816   // Encode Rs
817   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
818
819   // Many multiple instructions (e.g. MLA) have three src operands. Encode
820   // it as Rn (for multiply, that's in the same offset as RdLo.
821   if (TID.getNumOperands() > OpIdx &&
822       !TID.OpInfo[OpIdx].isPredicate() &&
823       !TID.OpInfo[OpIdx].isOptionalDef())
824     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdLoShift;
825
826   emitWordLE(Binary);
827 }
828
829 void ARMCodeEmitter::emitExtendInstruction(const MachineInstr &MI) {
830   const TargetInstrDesc &TID = MI.getDesc();
831
832   // Part of binary is determined by TableGn.
833   unsigned Binary = getBinaryCodeForInstr(MI);
834
835   // Set the conditional execution predicate
836   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
837
838   unsigned OpIdx = 0;
839
840   // Encode Rd
841   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
842
843   const MachineOperand &MO1 = MI.getOperand(OpIdx++);
844   const MachineOperand &MO2 = MI.getOperand(OpIdx);
845   if (MO2.isReg()) {
846     // Two register operand form.
847     // Encode Rn.
848     Binary |= getMachineOpValue(MI, MO1) << ARMII::RegRnShift;
849
850     // Encode Rm.
851     Binary |= getMachineOpValue(MI, MO2);
852     ++OpIdx;
853   } else {
854     Binary |= getMachineOpValue(MI, MO1);
855   }
856
857   // Encode rot imm (0, 8, 16, or 24) if it has a rotate immediate operand.
858   if (MI.getOperand(OpIdx).isImm() &&
859       !TID.OpInfo[OpIdx].isPredicate() &&
860       !TID.OpInfo[OpIdx].isOptionalDef())
861     Binary |= (getMachineOpValue(MI, OpIdx) / 8) << ARMII::ExtRotImmShift;
862
863   emitWordLE(Binary);
864 }
865
866 void ARMCodeEmitter::emitMiscArithInstruction(const MachineInstr &MI) {
867   const TargetInstrDesc &TID = MI.getDesc();
868
869   // Part of binary is determined by TableGn.
870   unsigned Binary = getBinaryCodeForInstr(MI);
871
872   // Set the conditional execution predicate
873   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
874
875   unsigned OpIdx = 0;
876
877   // Encode Rd
878   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
879
880   const MachineOperand &MO = MI.getOperand(OpIdx++);
881   if (OpIdx == TID.getNumOperands() ||
882       TID.OpInfo[OpIdx].isPredicate() ||
883       TID.OpInfo[OpIdx].isOptionalDef()) {
884     // Encode Rm and it's done.
885     Binary |= getMachineOpValue(MI, MO);
886     emitWordLE(Binary);
887     return;
888   }
889
890   // Encode Rn.
891   Binary |= getMachineOpValue(MI, MO) << ARMII::RegRnShift;
892
893   // Encode Rm.
894   Binary |= getMachineOpValue(MI, OpIdx++);
895
896   // Encode shift_imm.
897   unsigned ShiftAmt = MI.getOperand(OpIdx).getImm();
898   assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
899   Binary |= ShiftAmt << ARMII::ShiftShift;
900   
901   emitWordLE(Binary);
902 }
903
904 void ARMCodeEmitter::emitBranchInstruction(const MachineInstr &MI) {
905   const TargetInstrDesc &TID = MI.getDesc();
906
907   if (TID.Opcode == ARM::TPsoft)
908     abort(); // FIXME
909
910   // Part of binary is determined by TableGn.
911   unsigned Binary = getBinaryCodeForInstr(MI);
912
913   // Set the conditional execution predicate
914   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
915
916   // Set signed_immed_24 field
917   Binary |= getMachineOpValue(MI, 0);
918
919   emitWordLE(Binary);
920 }
921
922 void ARMCodeEmitter::emitInlineJumpTable(unsigned JTIndex) {
923   // Remember the base address of the inline jump table.
924   intptr_t JTBase = MCE.getCurrentPCValue();
925   JTI->addJumpTableBaseAddr(JTIndex, JTBase);
926   DOUT << "  ** Jump Table #" << JTIndex << " @ " << (void*)JTBase << '\n';
927
928   // Now emit the jump table entries.
929   const std::vector<MachineBasicBlock*> &MBBs = (*MJTEs)[JTIndex].MBBs;
930   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
931     if (IsPIC)
932       // DestBB address - JT base.
933       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_pic_jt, JTBase);
934     else
935       // Absolute DestBB address.
936       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_absolute);
937     emitWordLE(0);
938   }
939 }
940
941 void ARMCodeEmitter::emitMiscBranchInstruction(const MachineInstr &MI) {
942   const TargetInstrDesc &TID = MI.getDesc();
943
944   // Handle jump tables.
945   if (TID.Opcode == ARM::BR_JTr || TID.Opcode == ARM::BR_JTadd) {
946     // First emit a ldr pc, [] instruction.
947     emitDataProcessingInstruction(MI, ARM::PC);
948
949     // Then emit the inline jump table.
950     unsigned JTIndex = (TID.Opcode == ARM::BR_JTr)
951       ? MI.getOperand(1).getIndex() : MI.getOperand(2).getIndex();
952     emitInlineJumpTable(JTIndex);
953     return;
954   } else if (TID.Opcode == ARM::BR_JTm) {
955     // First emit a ldr pc, [] instruction.
956     emitLoadStoreInstruction(MI, ARM::PC);
957
958     // Then emit the inline jump table.
959     emitInlineJumpTable(MI.getOperand(3).getIndex());
960     return;
961   }
962
963   // Part of binary is determined by TableGn.
964   unsigned Binary = getBinaryCodeForInstr(MI);
965
966   // Set the conditional execution predicate
967   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
968
969   if (TID.Opcode == ARM::BX_RET)
970     // The return register is LR.
971     Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::LR);
972   else 
973     // otherwise, set the return register
974     Binary |= getMachineOpValue(MI, 0);
975
976   emitWordLE(Binary);
977 }
978
979 #include "ARMGenCodeEmitter.inc"