Jump table JIT support. Work in progress.
[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 ImplicitRn = 0);
100
101     void emitLoadStoreInstruction(const MachineInstr &MI,
102                                   unsigned ImplicitRd = 0,
103                                   unsigned ImplicitRn = 0);
104
105     void emitMiscLoadStoreInstruction(const MachineInstr &MI,
106                                       unsigned ImplicitRn = 0);
107
108     void emitLoadStoreMultipleInstruction(const MachineInstr &MI);
109
110     void emitMulFrmInstruction(const MachineInstr &MI);
111
112     void emitExtendInstruction(const MachineInstr &MI);
113
114     void emitMiscArithInstruction(const MachineInstr &MI);
115
116     void emitBranchInstruction(const MachineInstr &MI);
117
118     void emitInlineJumpTable(unsigned JTIndex, intptr_t JTBase);
119
120     void emitMiscBranchInstruction(const MachineInstr &MI);
121
122     /// getBinaryCodeForInstr - This function, generated by the
123     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
124     /// machine instructions.
125     ///
126     unsigned getBinaryCodeForInstr(const MachineInstr &MI);
127
128     /// getMachineOpValue - Return binary encoding of operand. If the machine
129     /// operand requires relocation, record the relocation and return zero.
130     unsigned getMachineOpValue(const MachineInstr &MI,const MachineOperand &MO);
131     unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) {
132       return getMachineOpValue(MI, MI.getOperand(OpIdx));
133     }
134
135     /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
136     ///
137     unsigned getShiftOp(unsigned Imm) const ;
138
139     /// Routines that handle operands which add machine relocations which are
140     /// fixed up by the JIT fixup stage.
141     void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
142                            bool NeedStub);
143     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
144     void emitConstPoolAddress(unsigned CPI, unsigned Reloc,
145                               int Disp = 0, unsigned PCAdj = 0 );
146     void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc,
147                               unsigned PCAdj = 0);
148     void emitGlobalConstant(const Constant *CV);
149     void emitMachineBasicBlock(MachineBasicBlock *BB, unsigned Reloc);
150   };
151   char ARMCodeEmitter::ID = 0;
152 }
153
154 /// createARMCodeEmitterPass - Return a pass that emits the collected ARM code
155 /// to the specified MCE object.
156 FunctionPass *llvm::createARMCodeEmitterPass(ARMTargetMachine &TM,
157                                              MachineCodeEmitter &MCE) {
158   return new ARMCodeEmitter(TM, MCE);
159 }
160
161 bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
162   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
163           MF.getTarget().getRelocationModel() != Reloc::Static) &&
164          "JIT relocation model must be set to static or default!");
165   II = ((ARMTargetMachine&)MF.getTarget()).getInstrInfo();
166   TD = ((ARMTargetMachine&)MF.getTarget()).getTargetData();
167   JTI = ((ARMTargetMachine&)MF.getTarget()).getJITInfo();
168   MCPEs = &MF.getConstantPool()->getConstants();
169   MJTEs = &MF.getJumpTableInfo()->getJumpTables();
170   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
171   JTI->Initialize(MF);
172
173   do {
174     DOUT << "JITTing function '" << MF.getFunction()->getName() << "'\n";
175     MCE.startFunction(MF);
176     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
177          MBB != E; ++MBB) {
178       MCE.StartMachineBasicBlock(MBB);
179       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
180            I != E; ++I)
181         emitInstruction(*I);
182     }
183   } while (MCE.finishFunction(MF));
184
185   return false;
186 }
187
188 /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
189 ///
190 unsigned ARMCodeEmitter::getShiftOp(unsigned Imm) const {
191   switch (ARM_AM::getAM2ShiftOpc(Imm)) {
192   default: assert(0 && "Unknown shift opc!");
193   case ARM_AM::asr: return 2;
194   case ARM_AM::lsl: return 0;
195   case ARM_AM::lsr: return 1;
196   case ARM_AM::ror:
197   case ARM_AM::rrx: return 3;
198   }
199   return 0;
200 }
201
202 /// getMachineOpValue - Return binary encoding of operand. If the machine
203 /// operand requires relocation, record the relocation and return zero.
204 unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
205                                            const MachineOperand &MO) {
206   if (MO.isReg())
207     return ARMRegisterInfo::getRegisterNumbering(MO.getReg());
208   else if (MO.isImm())
209     return static_cast<unsigned>(MO.getImm());
210   else if (MO.isGlobal())
211     emitGlobalAddress(MO.getGlobal(), ARM::reloc_arm_branch, true);
212   else if (MO.isSymbol())
213     emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_relative);
214   else if (MO.isCPI())
215     emitConstPoolAddress(MO.getIndex(), ARM::reloc_arm_cp_entry);
216   else if (MO.isJTI())
217     emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
218   else if (MO.isMBB())
219     emitMachineBasicBlock(MO.getMBB(), ARM::reloc_arm_branch);
220   else {
221     cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
222     abort();
223   }
224   return 0;
225 }
226
227 /// emitGlobalAddress - Emit the specified address to the code stream.
228 ///
229 void ARMCodeEmitter::emitGlobalAddress(GlobalValue *GV,
230                                        unsigned Reloc, bool NeedStub) {
231   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
232                                              Reloc, GV, 0, NeedStub));
233 }
234
235 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
236 /// be emitted to the current location in the function, and allow it to be PC
237 /// relative.
238 void ARMCodeEmitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
239   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
240                                                  Reloc, ES));
241 }
242
243 /// emitConstPoolAddress - Arrange for the address of an constant pool
244 /// to be emitted to the current location in the function, and allow it to be PC
245 /// relative.
246 void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
247                                           int Disp /* = 0 */,
248                                           unsigned PCAdj /* = 0 */) {
249   // Tell JIT emitter we'll resolve the address.
250   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
251                                                     Reloc, CPI, PCAdj, true));
252 }
253
254 /// emitJumpTableAddress - Arrange for the address of a jump table to
255 /// be emitted to the current location in the function, and allow it to be PC
256 /// relative.
257 void ARMCodeEmitter::emitJumpTableAddress(unsigned JTIndex, unsigned Reloc,
258                                           unsigned PCAdj /* = 0 */) {
259   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
260                                                   Reloc, JTIndex, PCAdj, true));
261 }
262
263 /// emitMachineBasicBlock - Emit the specified address basic block.
264 void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
265                                            unsigned Reloc) {
266   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
267                                              Reloc, BB));
268 }
269
270 void ARMCodeEmitter::emitWordLE(unsigned Binary) {
271 #ifndef NDEBUG
272   DOUT << "  0x" << std::hex << std::setw(8) << std::setfill('0')
273        << Binary << std::dec << "\n";
274 #endif
275   MCE.emitWordLE(Binary);
276 }
277
278 void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
279   DOUT << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI;
280
281   NumEmitted++;  // Keep track of the # of mi's emitted
282   switch (MI.getDesc().TSFlags & ARMII::FormMask) {
283   default:
284     assert(0 && "Unhandled instruction encoding format!");
285     break;
286   case ARMII::Pseudo:
287     emitPseudoInstruction(MI);
288     break;
289   case ARMII::DPFrm:
290   case ARMII::DPSoRegFrm:
291     emitDataProcessingInstruction(MI);
292     break;
293   case ARMII::LdFrm:
294   case ARMII::StFrm:
295     emitLoadStoreInstruction(MI);
296     break;
297   case ARMII::LdMiscFrm:
298   case ARMII::StMiscFrm:
299     emitMiscLoadStoreInstruction(MI);
300     break;
301   case ARMII::LdMulFrm:
302   case ARMII::StMulFrm:
303     emitLoadStoreMultipleInstruction(MI);
304     break;
305   case ARMII::MulFrm:
306     emitMulFrmInstruction(MI);
307     break;
308   case ARMII::ExtFrm:
309     emitExtendInstruction(MI);
310     break;
311   case ARMII::ArithMiscFrm:
312     emitMiscArithInstruction(MI);
313     break;
314   case ARMII::BrFrm:
315     emitBranchInstruction(MI);
316     break;
317   case ARMII::BrMiscFrm:
318     emitMiscBranchInstruction(MI);
319     break;
320   }
321 }
322
323 void ARMCodeEmitter::emitConstPoolInstruction(const MachineInstr &MI) {
324   unsigned CPI = MI.getOperand(0).getImm();
325   unsigned CPIndex = MI.getOperand(1).getIndex();
326   const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
327   
328   // Remember the CONSTPOOL_ENTRY address for later relocation.
329   JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
330
331   // Emit constpool island entry. In most cases, the actual values will be
332   // resolved and relocated after code emission.
333   if (MCPE.isMachineConstantPoolEntry()) {
334     ARMConstantPoolValue *ACPV =
335       static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
336
337     DOUT << "  ** ARM constant pool #" << CPI << " @ "
338          << (void*)MCE.getCurrentPCValue() << " " << *ACPV << "\n";
339
340     GlobalValue *GV = ACPV->getGV();
341     if (GV) {
342       assert(!ACPV->isStub() && "Don't know how to deal this yet!");
343       MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
344                                                 ARM::reloc_arm_machine_cp_entry,
345                                                 GV, CPIndex, false));
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, 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 ImplicitRn) {
572   const TargetInstrDesc &TID = MI.getDesc();
573
574   // Part of binary is determined by TableGn.
575   unsigned Binary = getBinaryCodeForInstr(MI);
576
577   // Set the conditional execution predicate
578   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
579
580   // Encode S bit if MI modifies CPSR.
581   Binary |= getAddrModeSBit(MI, TID);
582
583   // Encode register def if there is one.
584   unsigned NumDefs = TID.getNumDefs();
585   unsigned OpIdx = 0;
586   if (NumDefs) {
587     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdShift;
588     ++OpIdx;
589   }
590
591   // If this is a two-address operand, skip it. e.g. MOVCCr operand 1.
592   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
593     ++OpIdx;
594
595   // Encode first non-shifter register operand if there is one.
596   bool isUnary = TID.TSFlags & ARMII::UnaryDP;
597   if (!isUnary) {
598     if (ImplicitRn)
599       // Special handling for implicit use (e.g. PC).
600       Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
601                  << ARMII::RegRnShift);
602     else {
603       Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
604       ++OpIdx;
605     }
606   }
607
608   // Encode shifter operand.
609   const MachineOperand &MO = MI.getOperand(OpIdx);
610   if ((TID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
611     // Encode SoReg.
612     emitWordLE(Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx));
613     return;
614   }
615
616   if (MO.isReg()) {
617     // Encode register Rm.
618     emitWordLE(Binary | ARMRegisterInfo::getRegisterNumbering(MO.getReg()));
619     return;
620   }
621
622   // Encode so_imm.
623   // Set bit I(25) to identify this is the immediate form of <shifter_op>.
624   Binary |= 1 << ARMII::I_BitShift;
625   Binary |= getMachineSoImmOpValue(MO.getImm());
626
627   emitWordLE(Binary);
628 }
629
630 void ARMCodeEmitter::emitLoadStoreInstruction(const MachineInstr &MI,
631                                               unsigned ImplicitRd,
632                                               unsigned ImplicitRn) {
633   // Part of binary is determined by TableGn.
634   unsigned Binary = getBinaryCodeForInstr(MI);
635
636   // Set the conditional execution predicate
637   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
638
639   // Set first operand
640   unsigned OpIdx = 0;
641   if (ImplicitRd)
642     // Special handling for implicit use (e.g. PC).
643     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
644                << ARMII::RegRdShift);
645   else
646     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
647
648   // Set second operand
649   if (ImplicitRn)
650     // Special handling for implicit use (e.g. PC).
651     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
652                << ARMII::RegRnShift);
653   else
654     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
655
656   const MachineOperand &MO2 = MI.getOperand(OpIdx);
657   unsigned AM2Opc = (ImplicitRn == ARM::PC)
658     ? 0 : MI.getOperand(OpIdx+1).getImm();
659
660   // Set bit U(23) according to sign of immed value (positive or negative).
661   Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
662              ARMII::U_BitShift);
663   if (!MO2.getReg()) { // is immediate
664     if (ARM_AM::getAM2Offset(AM2Opc))
665       // Set the value of offset_12 field
666       Binary |= ARM_AM::getAM2Offset(AM2Opc);
667     emitWordLE(Binary);
668     return;
669   }
670
671   // Set bit I(25), because this is not in immediate enconding.
672   Binary |= 1 << ARMII::I_BitShift;
673   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
674   // Set bit[3:0] to the corresponding Rm register
675   Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
676
677   // if this instr is in scaled register offset/index instruction, set
678   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
679   if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
680     Binary |= getShiftOp(AM2Opc) << 5;  // shift
681     Binary |= ShImm              << 7;  // shift_immed
682   }
683
684   emitWordLE(Binary);
685 }
686
687 void ARMCodeEmitter::emitMiscLoadStoreInstruction(const MachineInstr &MI,
688                                                   unsigned ImplicitRn) {
689   // Part of binary is determined by TableGn.
690   unsigned Binary = getBinaryCodeForInstr(MI);
691
692   // Set the conditional execution predicate
693   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
694
695   // Set first operand
696   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
697
698   // Set second operand
699   unsigned OpIdx = 1;
700   if (ImplicitRn)
701     // Special handling for implicit use (e.g. PC).
702     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
703                << ARMII::RegRnShift);
704   else
705     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
706
707   const MachineOperand &MO2 = MI.getOperand(OpIdx);
708   unsigned AM3Opc = (ImplicitRn == ARM::PC)
709     ? 0 : MI.getOperand(OpIdx+1).getImm();
710
711   // Set bit U(23) according to sign of immed value (positive or negative)
712   Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
713              ARMII::U_BitShift);
714
715   // If this instr is in register offset/index encoding, set bit[3:0]
716   // to the corresponding Rm register.
717   if (MO2.getReg()) {
718     Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
719     emitWordLE(Binary);
720     return;
721   }
722
723   // This instr is in immediate offset/index encoding, set bit 22 to 1.
724   Binary |= 1 << ARMII::AM3_I_BitShift;
725   if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
726     // Set operands
727     Binary |= (ImmOffs >> 4) << 8;  // immedH
728     Binary |= (ImmOffs & ~0xF);     // immedL
729   }
730
731   emitWordLE(Binary);
732 }
733
734 void ARMCodeEmitter::emitLoadStoreMultipleInstruction(const MachineInstr &MI) {
735   // Part of binary is determined by TableGn.
736   unsigned Binary = getBinaryCodeForInstr(MI);
737
738   // Set the conditional execution predicate
739   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
740
741   // Set first operand
742   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
743
744   // Set addressing mode by modifying bits U(23) and P(24)
745   // IA - Increment after  - bit U = 1 and bit P = 0
746   // IB - Increment before - bit U = 1 and bit P = 1
747   // DA - Decrement after  - bit U = 0 and bit P = 0
748   // DB - Decrement before - bit U = 0 and bit P = 1
749   const MachineOperand &MO = MI.getOperand(1);
750   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO.getImm());
751   switch (Mode) {
752   default: assert(0 && "Unknown addressing sub-mode!");
753   case ARM_AM::da:                      break;
754   case ARM_AM::db: Binary |= 0x1 << ARMII::P_BitShift; break;
755   case ARM_AM::ia: Binary |= 0x1 << ARMII::U_BitShift; break;
756   case ARM_AM::ib: Binary |= 0x3 << ARMII::U_BitShift; break;
757   }
758
759   // Set bit W(21)
760   if (ARM_AM::getAM4WBFlag(MO.getImm()))
761     Binary |= 0x1 << ARMII::W_BitShift;
762
763   // Set registers
764   for (unsigned i = 4, e = MI.getNumOperands(); i != e; ++i) {
765     const MachineOperand &MO = MI.getOperand(i);
766     if (MO.isReg() && MO.isImplicit())
767       continue;
768     unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
769     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
770            RegNum < 16);
771     Binary |= 0x1 << RegNum;
772   }
773
774   emitWordLE(Binary);
775 }
776
777 void ARMCodeEmitter::emitMulFrmInstruction(const MachineInstr &MI) {
778   const TargetInstrDesc &TID = MI.getDesc();
779
780   // Part of binary is determined by TableGn.
781   unsigned Binary = getBinaryCodeForInstr(MI);
782
783   // Set the conditional execution predicate
784   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
785
786   // Encode S bit if MI modifies CPSR.
787   Binary |= getAddrModeSBit(MI, TID);
788
789   // 32x32->64bit operations have two destination registers. The number
790   // of register definitions will tell us if that's what we're dealing with.
791   unsigned OpIdx = 0;
792   if (TID.getNumDefs() == 2)
793     Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
794
795   // Encode Rd
796   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
797
798   // Encode Rm
799   Binary |= getMachineOpValue(MI, OpIdx++);
800
801   // Encode Rs
802   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
803
804   // Many multiple instructions (e.g. MLA) have three src operands. Encode
805   // it as Rn (for multiply, that's in the same offset as RdLo.
806   if (TID.getNumOperands() > OpIdx &&
807       !TID.OpInfo[OpIdx].isPredicate() &&
808       !TID.OpInfo[OpIdx].isOptionalDef())
809     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdLoShift;
810
811   emitWordLE(Binary);
812 }
813
814 void ARMCodeEmitter::emitExtendInstruction(const MachineInstr &MI) {
815   const TargetInstrDesc &TID = MI.getDesc();
816
817   // Part of binary is determined by TableGn.
818   unsigned Binary = getBinaryCodeForInstr(MI);
819
820   // Set the conditional execution predicate
821   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
822
823   unsigned OpIdx = 0;
824
825   // Encode Rd
826   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
827
828   const MachineOperand &MO1 = MI.getOperand(OpIdx++);
829   const MachineOperand &MO2 = MI.getOperand(OpIdx);
830   if (MO2.isReg()) {
831     // Two register operand form.
832     // Encode Rn.
833     Binary |= getMachineOpValue(MI, MO1) << ARMII::RegRnShift;
834
835     // Encode Rm.
836     Binary |= getMachineOpValue(MI, MO2);
837     ++OpIdx;
838   } else {
839     Binary |= getMachineOpValue(MI, MO1);
840   }
841
842   // Encode rot imm (0, 8, 16, or 24) if it has a rotate immediate operand.
843   if (MI.getOperand(OpIdx).isImm() &&
844       !TID.OpInfo[OpIdx].isPredicate() &&
845       !TID.OpInfo[OpIdx].isOptionalDef())
846     Binary |= (getMachineOpValue(MI, OpIdx) / 8) << ARMII::ExtRotImmShift;
847
848   emitWordLE(Binary);
849 }
850
851 void ARMCodeEmitter::emitMiscArithInstruction(const MachineInstr &MI) {
852   const TargetInstrDesc &TID = MI.getDesc();
853
854   // Part of binary is determined by TableGn.
855   unsigned Binary = getBinaryCodeForInstr(MI);
856
857   // Set the conditional execution predicate
858   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
859
860   unsigned OpIdx = 0;
861
862   // Encode Rd
863   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
864
865   const MachineOperand &MO = MI.getOperand(OpIdx++);
866   if (OpIdx == TID.getNumOperands() ||
867       TID.OpInfo[OpIdx].isPredicate() ||
868       TID.OpInfo[OpIdx].isOptionalDef()) {
869     // Encode Rm and it's done.
870     Binary |= getMachineOpValue(MI, MO);
871     emitWordLE(Binary);
872     return;
873   }
874
875   // Encode Rn.
876   Binary |= getMachineOpValue(MI, MO) << ARMII::RegRnShift;
877
878   // Encode Rm.
879   Binary |= getMachineOpValue(MI, OpIdx++);
880
881   // Encode shift_imm.
882   unsigned ShiftAmt = MI.getOperand(OpIdx).getImm();
883   assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
884   Binary |= ShiftAmt << ARMII::ShiftShift;
885   
886   emitWordLE(Binary);
887 }
888
889 void ARMCodeEmitter::emitBranchInstruction(const MachineInstr &MI) {
890   const TargetInstrDesc &TID = MI.getDesc();
891
892   if (TID.Opcode == ARM::TPsoft)
893     abort(); // FIXME
894
895   // Part of binary is determined by TableGn.
896   unsigned Binary = getBinaryCodeForInstr(MI);
897
898   // Set the conditional execution predicate
899   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
900
901   // Set signed_immed_24 field
902   Binary |= getMachineOpValue(MI, 0);
903
904   emitWordLE(Binary);
905 }
906
907 void ARMCodeEmitter::emitInlineJumpTable(unsigned JTIndex, intptr_t JTBase) {
908   // Remember the base address of the inline jump table.
909   JTI->addJumpTableBaseAddr(JTIndex, MCE.getCurrentPCValue());
910
911   // Now emit the jump table entries.
912   const std::vector<MachineBasicBlock*> &MBBs = (*MJTEs)[JTIndex].MBBs;
913   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
914     if (IsPIC)
915       // DestBB address - JT base.
916       MCE.addRelocation(MachineRelocation::getBB(JTBase, ARM::reloc_arm_pic_jt,
917                                                  MBBs[i]));
918     else
919       // Absolute DestBB address.
920       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_absolute);
921     emitWordLE(0);
922   }
923 }
924
925 void ARMCodeEmitter::emitMiscBranchInstruction(const MachineInstr &MI) {
926   const TargetInstrDesc &TID = MI.getDesc();
927   if (TID.Opcode == ARM::BX ||
928       TID.Opcode == ARM::BR_JTr ||
929       TID.Opcode == ARM::BR_JTadd)
930     abort(); // FIXME
931
932   if (TID.Opcode == ARM::BR_JTm) {
933     // First emit a ldr pc, [] instruction.
934     emitLoadStoreInstruction(MI, ARM::PC);
935
936     // Then emit the inline jump table.
937     emitInlineJumpTable(MI.getOperand(3).getIndex(), MCE.getCurrentPCOffset());
938     return;
939   }
940
941   // Part of binary is determined by TableGn.
942   unsigned Binary = getBinaryCodeForInstr(MI);
943
944   // Set the conditional execution predicate
945   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
946
947   if (TID.Opcode == ARM::BX_RET)
948     // The return register is LR.
949     Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::LR);
950   else 
951     // otherwise, set the return register
952     Binary |= getMachineOpValue(MI, 0);
953
954   emitWordLE(Binary);
955 }
956
957 #include "ARMGenCodeEmitter.inc"