Register the MachineModuleInfo for the ARM JIT, and update JITDwarfEmitter to
[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/JITCodeEmitter.h"
29 #include "llvm/CodeGen/ObjectCodeEmitter.h"
30 #include "llvm/CodeGen/MachineConstantPool.h"
31 #include "llvm/CodeGen/MachineFunctionPass.h"
32 #include "llvm/CodeGen/MachineInstr.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfo.h"
35 #include "llvm/CodeGen/Passes.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #ifndef NDEBUG
42 #include <iomanip>
43 #endif
44 using namespace llvm;
45
46 STATISTIC(NumEmitted, "Number of machine instructions emitted");
47
48 namespace {
49
50   class ARMCodeEmitter {
51   public:
52     /// getBinaryCodeForInstr - This function, generated by the
53     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
54     /// machine instructions.
55     unsigned getBinaryCodeForInstr(const MachineInstr &MI);
56   };
57
58   template<class CodeEmitter>
59   class VISIBILITY_HIDDEN Emitter : public MachineFunctionPass,
60                                     public ARMCodeEmitter {
61     ARMJITInfo                *JTI;
62     const ARMInstrInfo        *II;
63     const TargetData          *TD;
64     const ARMSubtarget        *Subtarget;
65     TargetMachine             &TM;
66     CodeEmitter               &MCE;
67     const std::vector<MachineConstantPoolEntry> *MCPEs;
68     const std::vector<MachineJumpTableEntry> *MJTEs;
69     bool IsPIC;
70
71     void getAnalysisUsage(AnalysisUsage &AU) const {
72       AU.addRequired<MachineModuleInfo>();
73       MachineFunctionPass::getAnalysisUsage(AU);
74     }
75
76   public:
77     static char ID;
78     explicit Emitter(TargetMachine &tm, CodeEmitter &mce)
79       : MachineFunctionPass(&ID), JTI(0), II(0), TD(0), TM(tm),
80       MCE(mce), MCPEs(0), MJTEs(0),
81       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
82     Emitter(TargetMachine &tm, CodeEmitter &mce,
83             const ARMInstrInfo &ii, const TargetData &td)
84       : MachineFunctionPass(&ID), JTI(0), II(&ii), TD(&td), TM(tm),
85       MCE(mce), MCPEs(0), MJTEs(0),
86       IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
87
88     bool runOnMachineFunction(MachineFunction &MF);
89
90     virtual const char *getPassName() const {
91       return "ARM Machine Code Emitter";
92     }
93
94     void emitInstruction(const MachineInstr &MI);
95
96   private:
97
98     void emitWordLE(unsigned Binary);
99
100     void emitDWordLE(uint64_t Binary);
101
102     void emitConstPoolInstruction(const MachineInstr &MI);
103
104     void emitMOVi2piecesInstruction(const MachineInstr &MI);
105
106     void emitLEApcrelJTInstruction(const MachineInstr &MI);
107
108     void emitPseudoMoveInstruction(const MachineInstr &MI);
109
110     void addPCLabel(unsigned LabelID);
111
112     void emitPseudoInstruction(const MachineInstr &MI);
113
114     unsigned getMachineSoRegOpValue(const MachineInstr &MI,
115                                     const TargetInstrDesc &TID,
116                                     const MachineOperand &MO,
117                                     unsigned OpIdx);
118
119     unsigned getMachineSoImmOpValue(unsigned SoImm);
120
121     unsigned getAddrModeSBit(const MachineInstr &MI,
122                              const TargetInstrDesc &TID) const;
123
124     void emitDataProcessingInstruction(const MachineInstr &MI,
125                                        unsigned ImplicitRd = 0,
126                                        unsigned ImplicitRn = 0);
127
128     void emitLoadStoreInstruction(const MachineInstr &MI,
129                                   unsigned ImplicitRd = 0,
130                                   unsigned ImplicitRn = 0);
131
132     void emitMiscLoadStoreInstruction(const MachineInstr &MI,
133                                       unsigned ImplicitRn = 0);
134
135     void emitLoadStoreMultipleInstruction(const MachineInstr &MI);
136
137     void emitMulFrmInstruction(const MachineInstr &MI);
138
139     void emitExtendInstruction(const MachineInstr &MI);
140
141     void emitMiscArithInstruction(const MachineInstr &MI);
142
143     void emitBranchInstruction(const MachineInstr &MI);
144
145     void emitInlineJumpTable(unsigned JTIndex);
146
147     void emitMiscBranchInstruction(const MachineInstr &MI);
148
149     void emitVFPArithInstruction(const MachineInstr &MI);
150
151     void emitVFPConversionInstruction(const MachineInstr &MI);
152
153     void emitVFPLoadStoreInstruction(const MachineInstr &MI);
154
155     void emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI);
156
157     void emitMiscInstruction(const MachineInstr &MI);
158
159     /// getMachineOpValue - Return binary encoding of operand. If the machine
160     /// operand requires relocation, record the relocation and return zero.
161     unsigned getMachineOpValue(const MachineInstr &MI,const MachineOperand &MO);
162     unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) {
163       return getMachineOpValue(MI, MI.getOperand(OpIdx));
164     }
165
166     /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
167     ///
168     unsigned getShiftOp(unsigned Imm) const ;
169
170     /// Routines that handle operands which add machine relocations which are
171     /// fixed up by the relocation stage.
172     void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
173                            bool NeedStub,  bool Indirect, intptr_t ACPV = 0);
174     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
175     void emitConstPoolAddress(unsigned CPI, unsigned Reloc);
176     void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc);
177     void emitMachineBasicBlock(MachineBasicBlock *BB, unsigned Reloc,
178                                intptr_t JTBase = 0);
179   };
180   template <class CodeEmitter>
181   char Emitter<CodeEmitter>::ID = 0;
182 }
183
184 /// createARMCodeEmitterPass - Return a pass that emits the collected ARM code
185 /// to the specified MCE object.
186
187 FunctionPass *llvm::createARMCodeEmitterPass(ARMBaseTargetMachine &TM,
188                                              MachineCodeEmitter &MCE) {
189   return new Emitter<MachineCodeEmitter>(TM, MCE);
190 }
191 FunctionPass *llvm::createARMJITCodeEmitterPass(ARMBaseTargetMachine &TM,
192                                                 JITCodeEmitter &JCE) {
193   return new Emitter<JITCodeEmitter>(TM, JCE);
194 }
195 FunctionPass *llvm::createARMObjectCodeEmitterPass(ARMBaseTargetMachine &TM,
196                                                    ObjectCodeEmitter &OCE) {
197   return new Emitter<ObjectCodeEmitter>(TM, OCE);
198 }
199
200 template<class CodeEmitter>
201 bool Emitter<CodeEmitter>::runOnMachineFunction(MachineFunction &MF) {
202   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
203           MF.getTarget().getRelocationModel() != Reloc::Static) &&
204          "JIT relocation model must be set to static or default!");
205   JTI = ((ARMTargetMachine&)MF.getTarget()).getJITInfo();
206   II = ((ARMTargetMachine&)MF.getTarget()).getInstrInfo();
207   TD = ((ARMTargetMachine&)MF.getTarget()).getTargetData();
208   Subtarget = &TM.getSubtarget<ARMSubtarget>();
209   MCPEs = &MF.getConstantPool()->getConstants();
210   MJTEs = &MF.getJumpTableInfo()->getJumpTables();
211   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
212   JTI->Initialize(MF, IsPIC);
213   MCE.setModuleInfo(&getAnalysis<MachineModuleInfo>());
214
215   do {
216     DEBUG(errs() << "JITTing function '"
217           << MF.getFunction()->getName() << "'\n");
218     MCE.startFunction(MF);
219     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
220          MBB != E; ++MBB) {
221       MCE.StartMachineBasicBlock(MBB);
222       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
223            I != E; ++I)
224         emitInstruction(*I);
225     }
226   } while (MCE.finishFunction(MF));
227
228   return false;
229 }
230
231 /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
232 ///
233 template<class CodeEmitter>
234 unsigned Emitter<CodeEmitter>::getShiftOp(unsigned Imm) const {
235   switch (ARM_AM::getAM2ShiftOpc(Imm)) {
236   default: llvm_unreachable("Unknown shift opc!");
237   case ARM_AM::asr: return 2;
238   case ARM_AM::lsl: return 0;
239   case ARM_AM::lsr: return 1;
240   case ARM_AM::ror:
241   case ARM_AM::rrx: return 3;
242   }
243   return 0;
244 }
245
246 /// getMachineOpValue - Return binary encoding of operand. If the machine
247 /// operand requires relocation, record the relocation and return zero.
248 template<class CodeEmitter>
249 unsigned Emitter<CodeEmitter>::getMachineOpValue(const MachineInstr &MI,
250                                                  const MachineOperand &MO) {
251   if (MO.isReg())
252     return ARMRegisterInfo::getRegisterNumbering(MO.getReg());
253   else if (MO.isImm())
254     return static_cast<unsigned>(MO.getImm());
255   else if (MO.isGlobal())
256     emitGlobalAddress(MO.getGlobal(), ARM::reloc_arm_branch, true, false);
257   else if (MO.isSymbol())
258     emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_branch);
259   else if (MO.isCPI()) {
260     const TargetInstrDesc &TID = MI.getDesc();
261     // For VFP load, the immediate offset is multiplied by 4.
262     unsigned Reloc =  ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPLdStFrm)
263       ? ARM::reloc_arm_vfp_cp_entry : ARM::reloc_arm_cp_entry;
264     emitConstPoolAddress(MO.getIndex(), Reloc);
265   } else if (MO.isJTI())
266     emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
267   else if (MO.isMBB())
268     emitMachineBasicBlock(MO.getMBB(), ARM::reloc_arm_branch);
269   else {
270 #ifndef NDEBUG
271     errs() << MO;
272 #endif
273     llvm_unreachable(0);
274   }
275   return 0;
276 }
277
278 /// emitGlobalAddress - Emit the specified address to the code stream.
279 ///
280 template<class CodeEmitter>
281 void Emitter<CodeEmitter>::emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
282                                              bool NeedStub, bool Indirect,
283                                              intptr_t ACPV) {
284   MachineRelocation MR = Indirect
285     ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
286                                            GV, ACPV, NeedStub)
287     : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
288                                GV, ACPV, NeedStub);
289   MCE.addRelocation(MR);
290 }
291
292 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
293 /// be emitted to the current location in the function, and allow it to be PC
294 /// relative.
295 template<class CodeEmitter>
296 void Emitter<CodeEmitter>::emitExternalSymbolAddress(const char *ES,
297                                                      unsigned Reloc) {
298   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
299                                                  Reloc, ES));
300 }
301
302 /// emitConstPoolAddress - Arrange for the address of an constant pool
303 /// to be emitted to the current location in the function, and allow it to be PC
304 /// relative.
305 template<class CodeEmitter>
306 void Emitter<CodeEmitter>::emitConstPoolAddress(unsigned CPI,
307                                                 unsigned Reloc) {
308   // Tell JIT emitter we'll resolve the address.
309   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
310                                                     Reloc, CPI, 0, true));
311 }
312
313 /// emitJumpTableAddress - Arrange for the address of a jump table to
314 /// be emitted to the current location in the function, and allow it to be PC
315 /// relative.
316 template<class CodeEmitter>
317 void Emitter<CodeEmitter>::emitJumpTableAddress(unsigned JTIndex,
318                                                 unsigned Reloc) {
319   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
320                                                     Reloc, JTIndex, 0, true));
321 }
322
323 /// emitMachineBasicBlock - Emit the specified address basic block.
324 template<class CodeEmitter>
325 void Emitter<CodeEmitter>::emitMachineBasicBlock(MachineBasicBlock *BB,
326                                               unsigned Reloc, intptr_t JTBase) {
327   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
328                                              Reloc, BB, JTBase));
329 }
330
331 template<class CodeEmitter>
332 void Emitter<CodeEmitter>::emitWordLE(unsigned Binary) {
333   DEBUG(errs() << "  0x";
334         errs().write_hex(Binary) << "\n");
335   MCE.emitWordLE(Binary);
336 }
337
338 template<class CodeEmitter>
339 void Emitter<CodeEmitter>::emitDWordLE(uint64_t Binary) {
340   DEBUG(errs() << "  0x";
341         errs().write_hex(Binary) << "\n");
342   MCE.emitDWordLE(Binary);
343 }
344
345 template<class CodeEmitter>
346 void Emitter<CodeEmitter>::emitInstruction(const MachineInstr &MI) {
347   DEBUG(errs() << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI);
348
349   MCE.processDebugLoc(MI.getDebugLoc());
350
351   NumEmitted++;  // Keep track of the # of mi's emitted
352   switch (MI.getDesc().TSFlags & ARMII::FormMask) {
353   default: {
354     llvm_unreachable("Unhandled instruction encoding format!");
355     break;
356   }
357   case ARMII::Pseudo:
358     emitPseudoInstruction(MI);
359     break;
360   case ARMII::DPFrm:
361   case ARMII::DPSoRegFrm:
362     emitDataProcessingInstruction(MI);
363     break;
364   case ARMII::LdFrm:
365   case ARMII::StFrm:
366     emitLoadStoreInstruction(MI);
367     break;
368   case ARMII::LdMiscFrm:
369   case ARMII::StMiscFrm:
370     emitMiscLoadStoreInstruction(MI);
371     break;
372   case ARMII::LdStMulFrm:
373     emitLoadStoreMultipleInstruction(MI);
374     break;
375   case ARMII::MulFrm:
376     emitMulFrmInstruction(MI);
377     break;
378   case ARMII::ExtFrm:
379     emitExtendInstruction(MI);
380     break;
381   case ARMII::ArithMiscFrm:
382     emitMiscArithInstruction(MI);
383     break;
384   case ARMII::BrFrm:
385     emitBranchInstruction(MI);
386     break;
387   case ARMII::BrMiscFrm:
388     emitMiscBranchInstruction(MI);
389     break;
390   // VFP instructions.
391   case ARMII::VFPUnaryFrm:
392   case ARMII::VFPBinaryFrm:
393     emitVFPArithInstruction(MI);
394     break;
395   case ARMII::VFPConv1Frm:
396   case ARMII::VFPConv2Frm:
397   case ARMII::VFPConv3Frm:
398   case ARMII::VFPConv4Frm:
399   case ARMII::VFPConv5Frm:
400     emitVFPConversionInstruction(MI);
401     break;
402   case ARMII::VFPLdStFrm:
403     emitVFPLoadStoreInstruction(MI);
404     break;
405   case ARMII::VFPLdStMulFrm:
406     emitVFPLoadStoreMultipleInstruction(MI);
407     break;
408   case ARMII::VFPMiscFrm:
409     emitMiscInstruction(MI);
410     break;
411   }
412 }
413
414 template<class CodeEmitter>
415 void Emitter<CodeEmitter>::emitConstPoolInstruction(const MachineInstr &MI) {
416   unsigned CPI = MI.getOperand(0).getImm();       // CP instruction index.
417   unsigned CPIndex = MI.getOperand(1).getIndex(); // Actual cp entry index.
418   const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
419
420   // Remember the CONSTPOOL_ENTRY address for later relocation.
421   JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
422
423   // Emit constpool island entry. In most cases, the actual values will be
424   // resolved and relocated after code emission.
425   if (MCPE.isMachineConstantPoolEntry()) {
426     ARMConstantPoolValue *ACPV =
427       static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
428
429     DEBUG(errs() << "  ** ARM constant pool #" << CPI << " @ "
430           << (void*)MCE.getCurrentPCValue() << " " << *ACPV << '\n');
431
432     GlobalValue *GV = ACPV->getGV();
433     if (GV) {
434       Reloc::Model RelocM = TM.getRelocationModel();
435       emitGlobalAddress(GV, ARM::reloc_arm_machine_cp_entry,
436                         isa<Function>(GV),
437                         Subtarget->GVIsIndirectSymbol(GV, RelocM),
438                         (intptr_t)ACPV);
439      } else  {
440       emitExternalSymbolAddress(ACPV->getSymbol(), ARM::reloc_arm_absolute);
441     }
442     emitWordLE(0);
443   } else {
444     Constant *CV = MCPE.Val.ConstVal;
445
446     DEBUG({
447         errs() << "  ** Constant pool #" << CPI << " @ "
448                << (void*)MCE.getCurrentPCValue() << " ";
449         if (const Function *F = dyn_cast<Function>(CV))
450           errs() << F->getName();
451         else
452           errs() << *CV;
453         errs() << '\n';
454       });
455
456     if (GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
457       emitGlobalAddress(GV, ARM::reloc_arm_absolute, isa<Function>(GV), false);
458       emitWordLE(0);
459     } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
460       uint32_t Val = *(uint32_t*)CI->getValue().getRawData();
461       emitWordLE(Val);
462     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
463       if (CFP->getType() == Type::getFloatTy(CFP->getContext()))
464         emitWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
465       else if (CFP->getType() == Type::getDoubleTy(CFP->getContext()))
466         emitDWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
467       else {
468         llvm_unreachable("Unable to handle this constantpool entry!");
469       }
470     } else {
471       llvm_unreachable("Unable to handle this constantpool entry!");
472     }
473   }
474 }
475
476 template<class CodeEmitter>
477 void Emitter<CodeEmitter>::emitMOVi2piecesInstruction(const MachineInstr &MI) {
478   const MachineOperand &MO0 = MI.getOperand(0);
479   const MachineOperand &MO1 = MI.getOperand(1);
480   assert(MO1.isImm() && ARM_AM::getSOImmVal(MO1.isImm()) != -1 &&
481                                             "Not a valid so_imm value!");
482   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO1.getImm());
483   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO1.getImm());
484
485   // Emit the 'mov' instruction.
486   unsigned Binary = 0xd << 21;  // mov: Insts{24-21} = 0b1101
487
488   // Set the conditional execution predicate.
489   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
490
491   // Encode Rd.
492   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
493
494   // Encode so_imm.
495   // Set bit I(25) to identify this is the immediate form of <shifter_op>
496   Binary |= 1 << ARMII::I_BitShift;
497   Binary |= getMachineSoImmOpValue(V1);
498   emitWordLE(Binary);
499
500   // Now the 'orr' instruction.
501   Binary = 0xc << 21;  // orr: Insts{24-21} = 0b1100
502
503   // Set the conditional execution predicate.
504   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
505
506   // Encode Rd.
507   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
508
509   // Encode Rn.
510   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRnShift;
511
512   // Encode so_imm.
513   // Set bit I(25) to identify this is the immediate form of <shifter_op>
514   Binary |= 1 << ARMII::I_BitShift;
515   Binary |= getMachineSoImmOpValue(V2);
516   emitWordLE(Binary);
517 }
518
519 template<class CodeEmitter>
520 void Emitter<CodeEmitter>::emitLEApcrelJTInstruction(const MachineInstr &MI) {
521   // It's basically add r, pc, (LJTI - $+8)
522
523   const TargetInstrDesc &TID = MI.getDesc();
524
525   // Emit the 'add' instruction.
526   unsigned Binary = 0x4 << 21;  // add: Insts{24-31} = 0b0100
527
528   // Set the conditional execution predicate
529   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
530
531   // Encode S bit if MI modifies CPSR.
532   Binary |= getAddrModeSBit(MI, TID);
533
534   // Encode Rd.
535   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
536
537   // Encode Rn which is PC.
538   Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::PC) << ARMII::RegRnShift;
539
540   // Encode the displacement.
541   Binary |= 1 << ARMII::I_BitShift;
542   emitJumpTableAddress(MI.getOperand(1).getIndex(), ARM::reloc_arm_jt_base);
543
544   emitWordLE(Binary);
545 }
546
547 template<class CodeEmitter>
548 void Emitter<CodeEmitter>::emitPseudoMoveInstruction(const MachineInstr &MI) {
549   unsigned Opcode = MI.getDesc().Opcode;
550
551   // Part of binary is determined by TableGn.
552   unsigned Binary = getBinaryCodeForInstr(MI);
553
554   // Set the conditional execution predicate
555   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
556
557   // Encode S bit if MI modifies CPSR.
558   if (Opcode == ARM::MOVsrl_flag || Opcode == ARM::MOVsra_flag)
559     Binary |= 1 << ARMII::S_BitShift;
560
561   // Encode register def if there is one.
562   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
563
564   // Encode the shift operation.
565   switch (Opcode) {
566   default: break;
567   case ARM::MOVrx:
568     // rrx
569     Binary |= 0x6 << 4;
570     break;
571   case ARM::MOVsrl_flag:
572     // lsr #1
573     Binary |= (0x2 << 4) | (1 << 7);
574     break;
575   case ARM::MOVsra_flag:
576     // asr #1
577     Binary |= (0x4 << 4) | (1 << 7);
578     break;
579   }
580
581   // Encode register Rm.
582   Binary |= getMachineOpValue(MI, 1);
583
584   emitWordLE(Binary);
585 }
586
587 template<class CodeEmitter>
588 void Emitter<CodeEmitter>::addPCLabel(unsigned LabelID) {
589   DEBUG(errs() << "  ** LPC" << LabelID << " @ "
590         << (void*)MCE.getCurrentPCValue() << '\n');
591   JTI->addPCLabelAddr(LabelID, MCE.getCurrentPCValue());
592 }
593
594 template<class CodeEmitter>
595 void Emitter<CodeEmitter>::emitPseudoInstruction(const MachineInstr &MI) {
596   unsigned Opcode = MI.getDesc().Opcode;
597   switch (Opcode) {
598   default:
599     llvm_unreachable("ARMCodeEmitter::emitPseudoInstruction");//FIXME:
600   case TargetInstrInfo::INLINEASM: {
601     // We allow inline assembler nodes with empty bodies - they can
602     // implicitly define registers, which is ok for JIT.
603     if (MI.getOperand(0).getSymbolName()[0]) {
604       llvm_report_error("JIT does not support inline asm!");
605     }
606     break;
607   }
608   case TargetInstrInfo::DBG_LABEL:
609   case TargetInstrInfo::EH_LABEL:
610     MCE.emitLabel(MI.getOperand(0).getImm());
611     break;
612   case TargetInstrInfo::IMPLICIT_DEF:
613   case ARM::DWARF_LOC:
614     // Do nothing.
615     break;
616   case ARM::CONSTPOOL_ENTRY:
617     emitConstPoolInstruction(MI);
618     break;
619   case ARM::PICADD: {
620     // Remember of the address of the PC label for relocation later.
621     addPCLabel(MI.getOperand(2).getImm());
622     // PICADD is just an add instruction that implicitly read pc.
623     emitDataProcessingInstruction(MI, 0, ARM::PC);
624     break;
625   }
626   case ARM::PICLDR:
627   case ARM::PICLDRB:
628   case ARM::PICSTR:
629   case ARM::PICSTRB: {
630     // Remember of the address of the PC label for relocation later.
631     addPCLabel(MI.getOperand(2).getImm());
632     // These are just load / store instructions that implicitly read pc.
633     emitLoadStoreInstruction(MI, 0, ARM::PC);
634     break;
635   }
636   case ARM::PICLDRH:
637   case ARM::PICLDRSH:
638   case ARM::PICLDRSB:
639   case ARM::PICSTRH: {
640     // Remember of the address of the PC label for relocation later.
641     addPCLabel(MI.getOperand(2).getImm());
642     // These are just load / store instructions that implicitly read pc.
643     emitMiscLoadStoreInstruction(MI, ARM::PC);
644     break;
645   }
646   case ARM::MOVi2pieces:
647     // Two instructions to materialize a constant.
648     emitMOVi2piecesInstruction(MI);
649     break;
650   case ARM::LEApcrelJT:
651     // Materialize jumptable address.
652     emitLEApcrelJTInstruction(MI);
653     break;
654   case ARM::MOVrx:
655   case ARM::MOVsrl_flag:
656   case ARM::MOVsra_flag:
657     emitPseudoMoveInstruction(MI);
658     break;
659   }
660 }
661
662 template<class CodeEmitter>
663 unsigned Emitter<CodeEmitter>::getMachineSoRegOpValue(
664                                                 const MachineInstr &MI,
665                                                 const TargetInstrDesc &TID,
666                                                 const MachineOperand &MO,
667                                                 unsigned OpIdx) {
668   unsigned Binary = getMachineOpValue(MI, MO);
669
670   const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
671   const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
672   ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
673
674   // Encode the shift opcode.
675   unsigned SBits = 0;
676   unsigned Rs = MO1.getReg();
677   if (Rs) {
678     // Set shift operand (bit[7:4]).
679     // LSL - 0001
680     // LSR - 0011
681     // ASR - 0101
682     // ROR - 0111
683     // RRX - 0110 and bit[11:8] clear.
684     switch (SOpc) {
685     default: llvm_unreachable("Unknown shift opc!");
686     case ARM_AM::lsl: SBits = 0x1; break;
687     case ARM_AM::lsr: SBits = 0x3; break;
688     case ARM_AM::asr: SBits = 0x5; break;
689     case ARM_AM::ror: SBits = 0x7; break;
690     case ARM_AM::rrx: SBits = 0x6; break;
691     }
692   } else {
693     // Set shift operand (bit[6:4]).
694     // LSL - 000
695     // LSR - 010
696     // ASR - 100
697     // ROR - 110
698     switch (SOpc) {
699     default: llvm_unreachable("Unknown shift opc!");
700     case ARM_AM::lsl: SBits = 0x0; break;
701     case ARM_AM::lsr: SBits = 0x2; break;
702     case ARM_AM::asr: SBits = 0x4; break;
703     case ARM_AM::ror: SBits = 0x6; break;
704     }
705   }
706   Binary |= SBits << 4;
707   if (SOpc == ARM_AM::rrx)
708     return Binary;
709
710   // Encode the shift operation Rs or shift_imm (except rrx).
711   if (Rs) {
712     // Encode Rs bit[11:8].
713     assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
714     return Binary |
715       (ARMRegisterInfo::getRegisterNumbering(Rs) << ARMII::RegRsShift);
716   }
717
718   // Encode shift_imm bit[11:7].
719   return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
720 }
721
722 template<class CodeEmitter>
723 unsigned Emitter<CodeEmitter>::getMachineSoImmOpValue(unsigned SoImm) {
724   int SoImmVal = ARM_AM::getSOImmVal(SoImm);
725   assert(SoImmVal != -1 && "Not a valid so_imm value!");
726
727   // Encode rotate_imm.
728   unsigned Binary = (ARM_AM::getSOImmValRot((unsigned)SoImmVal) >> 1)
729     << ARMII::SoRotImmShift;
730
731   // Encode immed_8.
732   Binary |= ARM_AM::getSOImmValImm((unsigned)SoImmVal);
733   return Binary;
734 }
735
736 template<class CodeEmitter>
737 unsigned Emitter<CodeEmitter>::getAddrModeSBit(const MachineInstr &MI,
738                                              const TargetInstrDesc &TID) const {
739   for (unsigned i = MI.getNumOperands(), e = TID.getNumOperands(); i != e; --i){
740     const MachineOperand &MO = MI.getOperand(i-1);
741     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)
742       return 1 << ARMII::S_BitShift;
743   }
744   return 0;
745 }
746
747 template<class CodeEmitter>
748 void Emitter<CodeEmitter>::emitDataProcessingInstruction(
749                                                    const MachineInstr &MI,
750                                                    unsigned ImplicitRd,
751                                                    unsigned ImplicitRn) {
752   const TargetInstrDesc &TID = MI.getDesc();
753
754   if (TID.Opcode == ARM::BFC) {
755     llvm_report_error("ARMv6t2 JIT is not yet supported.");
756   }
757
758   // Part of binary is determined by TableGn.
759   unsigned Binary = getBinaryCodeForInstr(MI);
760
761   // Set the conditional execution predicate
762   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
763
764   // Encode S bit if MI modifies CPSR.
765   Binary |= getAddrModeSBit(MI, TID);
766
767   // Encode register def if there is one.
768   unsigned NumDefs = TID.getNumDefs();
769   unsigned OpIdx = 0;
770   if (NumDefs)
771     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
772   else if (ImplicitRd)
773     // Special handling for implicit use (e.g. PC).
774     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
775                << ARMII::RegRdShift);
776
777   // If this is a two-address operand, skip it. e.g. MOVCCr operand 1.
778   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
779     ++OpIdx;
780
781   // Encode first non-shifter register operand if there is one.
782   bool isUnary = TID.TSFlags & ARMII::UnaryDP;
783   if (!isUnary) {
784     if (ImplicitRn)
785       // Special handling for implicit use (e.g. PC).
786       Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
787                  << ARMII::RegRnShift);
788     else {
789       Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
790       ++OpIdx;
791     }
792   }
793
794   // Encode shifter operand.
795   const MachineOperand &MO = MI.getOperand(OpIdx);
796   if ((TID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
797     // Encode SoReg.
798     emitWordLE(Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx));
799     return;
800   }
801
802   if (MO.isReg()) {
803     // Encode register Rm.
804     emitWordLE(Binary | ARMRegisterInfo::getRegisterNumbering(MO.getReg()));
805     return;
806   }
807
808   // Encode so_imm.
809   Binary |= getMachineSoImmOpValue((unsigned)MO.getImm());
810
811   emitWordLE(Binary);
812 }
813
814 template<class CodeEmitter>
815 void Emitter<CodeEmitter>::emitLoadStoreInstruction(
816                                               const MachineInstr &MI,
817                                               unsigned ImplicitRd,
818                                               unsigned ImplicitRn) {
819   const TargetInstrDesc &TID = MI.getDesc();
820   unsigned Form = TID.TSFlags & ARMII::FormMask;
821   bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
822
823   // Part of binary is determined by TableGn.
824   unsigned Binary = getBinaryCodeForInstr(MI);
825
826   // Set the conditional execution predicate
827   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
828
829   unsigned OpIdx = 0;
830
831   // Operand 0 of a pre- and post-indexed store is the address base
832   // writeback. Skip it.
833   bool Skipped = false;
834   if (IsPrePost && Form == ARMII::StFrm) {
835     ++OpIdx;
836     Skipped = true;
837   }
838
839   // Set first operand
840   if (ImplicitRd)
841     // Special handling for implicit use (e.g. PC).
842     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
843                << ARMII::RegRdShift);
844   else
845     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
846
847   // Set second operand
848   if (ImplicitRn)
849     // Special handling for implicit use (e.g. PC).
850     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
851                << ARMII::RegRnShift);
852   else
853     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
854
855   // If this is a two-address operand, skip it. e.g. LDR_PRE.
856   if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
857     ++OpIdx;
858
859   const MachineOperand &MO2 = MI.getOperand(OpIdx);
860   unsigned AM2Opc = (ImplicitRn == ARM::PC)
861     ? 0 : MI.getOperand(OpIdx+1).getImm();
862
863   // Set bit U(23) according to sign of immed value (positive or negative).
864   Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
865              ARMII::U_BitShift);
866   if (!MO2.getReg()) { // is immediate
867     if (ARM_AM::getAM2Offset(AM2Opc))
868       // Set the value of offset_12 field
869       Binary |= ARM_AM::getAM2Offset(AM2Opc);
870     emitWordLE(Binary);
871     return;
872   }
873
874   // Set bit I(25), because this is not in immediate enconding.
875   Binary |= 1 << ARMII::I_BitShift;
876   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
877   // Set bit[3:0] to the corresponding Rm register
878   Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
879
880   // If this instr is in scaled register offset/index instruction, set
881   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
882   if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
883     Binary |= getShiftOp(AM2Opc) << ARMII::ShiftImmShift;  // shift
884     Binary |= ShImm              << ARMII::ShiftShift;     // shift_immed
885   }
886
887   emitWordLE(Binary);
888 }
889
890 template<class CodeEmitter>
891 void Emitter<CodeEmitter>::emitMiscLoadStoreInstruction(const MachineInstr &MI,
892                                                         unsigned ImplicitRn) {
893   const TargetInstrDesc &TID = MI.getDesc();
894   unsigned Form = TID.TSFlags & ARMII::FormMask;
895   bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
896
897   // Part of binary is determined by TableGn.
898   unsigned Binary = getBinaryCodeForInstr(MI);
899
900   // Set the conditional execution predicate
901   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
902
903   unsigned OpIdx = 0;
904
905   // Operand 0 of a pre- and post-indexed store is the address base
906   // writeback. Skip it.
907   bool Skipped = false;
908   if (IsPrePost && Form == ARMII::StMiscFrm) {
909     ++OpIdx;
910     Skipped = true;
911   }
912
913   // Set first operand
914   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
915
916   // Skip LDRD and STRD's second operand.
917   if (TID.Opcode == ARM::LDRD || TID.Opcode == ARM::STRD)
918     ++OpIdx;
919
920   // Set second operand
921   if (ImplicitRn)
922     // Special handling for implicit use (e.g. PC).
923     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
924                << ARMII::RegRnShift);
925   else
926     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
927
928   // If this is a two-address operand, skip it. e.g. LDRH_POST.
929   if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
930     ++OpIdx;
931
932   const MachineOperand &MO2 = MI.getOperand(OpIdx);
933   unsigned AM3Opc = (ImplicitRn == ARM::PC)
934     ? 0 : MI.getOperand(OpIdx+1).getImm();
935
936   // Set bit U(23) according to sign of immed value (positive or negative)
937   Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
938              ARMII::U_BitShift);
939
940   // If this instr is in register offset/index encoding, set bit[3:0]
941   // to the corresponding Rm register.
942   if (MO2.getReg()) {
943     Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
944     emitWordLE(Binary);
945     return;
946   }
947
948   // This instr is in immediate offset/index encoding, set bit 22 to 1.
949   Binary |= 1 << ARMII::AM3_I_BitShift;
950   if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
951     // Set operands
952     Binary |= (ImmOffs >> 4) << ARMII::ImmHiShift;  // immedH
953     Binary |= (ImmOffs & 0xF);                      // immedL
954   }
955
956   emitWordLE(Binary);
957 }
958
959 static unsigned getAddrModeUPBits(unsigned Mode) {
960   unsigned Binary = 0;
961
962   // Set addressing mode by modifying bits U(23) and P(24)
963   // IA - Increment after  - bit U = 1 and bit P = 0
964   // IB - Increment before - bit U = 1 and bit P = 1
965   // DA - Decrement after  - bit U = 0 and bit P = 0
966   // DB - Decrement before - bit U = 0 and bit P = 1
967   switch (Mode) {
968   default: llvm_unreachable("Unknown addressing sub-mode!");
969   case ARM_AM::da:                                     break;
970   case ARM_AM::db: Binary |= 0x1 << ARMII::P_BitShift; break;
971   case ARM_AM::ia: Binary |= 0x1 << ARMII::U_BitShift; break;
972   case ARM_AM::ib: Binary |= 0x3 << ARMII::U_BitShift; break;
973   }
974
975   return Binary;
976 }
977
978 template<class CodeEmitter>
979 void Emitter<CodeEmitter>::emitLoadStoreMultipleInstruction(
980                                                        const MachineInstr &MI) {
981   // Part of binary is determined by TableGn.
982   unsigned Binary = getBinaryCodeForInstr(MI);
983
984   // Set the conditional execution predicate
985   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
986
987   // Set base address operand
988   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
989
990   // Set addressing mode by modifying bits U(23) and P(24)
991   const MachineOperand &MO = MI.getOperand(1);
992   Binary |= getAddrModeUPBits(ARM_AM::getAM4SubMode(MO.getImm()));
993
994   // Set bit W(21)
995   if (ARM_AM::getAM4WBFlag(MO.getImm()))
996     Binary |= 0x1 << ARMII::W_BitShift;
997
998   // Set registers
999   for (unsigned i = 4, e = MI.getNumOperands(); i != e; ++i) {
1000     const MachineOperand &MO = MI.getOperand(i);
1001     if (!MO.isReg() || MO.isImplicit())
1002       break;
1003     unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
1004     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
1005            RegNum < 16);
1006     Binary |= 0x1 << RegNum;
1007   }
1008
1009   emitWordLE(Binary);
1010 }
1011
1012 template<class CodeEmitter>
1013 void Emitter<CodeEmitter>::emitMulFrmInstruction(const MachineInstr &MI) {
1014   const TargetInstrDesc &TID = MI.getDesc();
1015
1016   // Part of binary is determined by TableGn.
1017   unsigned Binary = getBinaryCodeForInstr(MI);
1018
1019   // Set the conditional execution predicate
1020   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1021
1022   // Encode S bit if MI modifies CPSR.
1023   Binary |= getAddrModeSBit(MI, TID);
1024
1025   // 32x32->64bit operations have two destination registers. The number
1026   // of register definitions will tell us if that's what we're dealing with.
1027   unsigned OpIdx = 0;
1028   if (TID.getNumDefs() == 2)
1029     Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
1030
1031   // Encode Rd
1032   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
1033
1034   // Encode Rm
1035   Binary |= getMachineOpValue(MI, OpIdx++);
1036
1037   // Encode Rs
1038   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
1039
1040   // Many multiple instructions (e.g. MLA) have three src operands. Encode
1041   // it as Rn (for multiply, that's in the same offset as RdLo.
1042   if (TID.getNumOperands() > OpIdx &&
1043       !TID.OpInfo[OpIdx].isPredicate() &&
1044       !TID.OpInfo[OpIdx].isOptionalDef())
1045     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdLoShift;
1046
1047   emitWordLE(Binary);
1048 }
1049
1050 template<class CodeEmitter>
1051 void Emitter<CodeEmitter>::emitExtendInstruction(const MachineInstr &MI) {
1052   const TargetInstrDesc &TID = MI.getDesc();
1053
1054   // Part of binary is determined by TableGn.
1055   unsigned Binary = getBinaryCodeForInstr(MI);
1056
1057   // Set the conditional execution predicate
1058   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1059
1060   unsigned OpIdx = 0;
1061
1062   // Encode Rd
1063   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1064
1065   const MachineOperand &MO1 = MI.getOperand(OpIdx++);
1066   const MachineOperand &MO2 = MI.getOperand(OpIdx);
1067   if (MO2.isReg()) {
1068     // Two register operand form.
1069     // Encode Rn.
1070     Binary |= getMachineOpValue(MI, MO1) << ARMII::RegRnShift;
1071
1072     // Encode Rm.
1073     Binary |= getMachineOpValue(MI, MO2);
1074     ++OpIdx;
1075   } else {
1076     Binary |= getMachineOpValue(MI, MO1);
1077   }
1078
1079   // Encode rot imm (0, 8, 16, or 24) if it has a rotate immediate operand.
1080   if (MI.getOperand(OpIdx).isImm() &&
1081       !TID.OpInfo[OpIdx].isPredicate() &&
1082       !TID.OpInfo[OpIdx].isOptionalDef())
1083     Binary |= (getMachineOpValue(MI, OpIdx) / 8) << ARMII::ExtRotImmShift;
1084
1085   emitWordLE(Binary);
1086 }
1087
1088 template<class CodeEmitter>
1089 void Emitter<CodeEmitter>::emitMiscArithInstruction(const MachineInstr &MI) {
1090   const TargetInstrDesc &TID = MI.getDesc();
1091
1092   // Part of binary is determined by TableGn.
1093   unsigned Binary = getBinaryCodeForInstr(MI);
1094
1095   // Set the conditional execution predicate
1096   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1097
1098   unsigned OpIdx = 0;
1099
1100   // Encode Rd
1101   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1102
1103   const MachineOperand &MO = MI.getOperand(OpIdx++);
1104   if (OpIdx == TID.getNumOperands() ||
1105       TID.OpInfo[OpIdx].isPredicate() ||
1106       TID.OpInfo[OpIdx].isOptionalDef()) {
1107     // Encode Rm and it's done.
1108     Binary |= getMachineOpValue(MI, MO);
1109     emitWordLE(Binary);
1110     return;
1111   }
1112
1113   // Encode Rn.
1114   Binary |= getMachineOpValue(MI, MO) << ARMII::RegRnShift;
1115
1116   // Encode Rm.
1117   Binary |= getMachineOpValue(MI, OpIdx++);
1118
1119   // Encode shift_imm.
1120   unsigned ShiftAmt = MI.getOperand(OpIdx).getImm();
1121   assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
1122   Binary |= ShiftAmt << ARMII::ShiftShift;
1123
1124   emitWordLE(Binary);
1125 }
1126
1127 template<class CodeEmitter>
1128 void Emitter<CodeEmitter>::emitBranchInstruction(const MachineInstr &MI) {
1129   const TargetInstrDesc &TID = MI.getDesc();
1130
1131   if (TID.Opcode == ARM::TPsoft) {
1132     llvm_unreachable("ARM::TPsoft FIXME"); // FIXME
1133   }
1134
1135   // Part of binary is determined by TableGn.
1136   unsigned Binary = getBinaryCodeForInstr(MI);
1137
1138   // Set the conditional execution predicate
1139   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1140
1141   // Set signed_immed_24 field
1142   Binary |= getMachineOpValue(MI, 0);
1143
1144   emitWordLE(Binary);
1145 }
1146
1147 template<class CodeEmitter>
1148 void Emitter<CodeEmitter>::emitInlineJumpTable(unsigned JTIndex) {
1149   // Remember the base address of the inline jump table.
1150   uintptr_t JTBase = MCE.getCurrentPCValue();
1151   JTI->addJumpTableBaseAddr(JTIndex, JTBase);
1152   DEBUG(errs() << "  ** Jump Table #" << JTIndex << " @ " << (void*)JTBase
1153                << '\n');
1154
1155   // Now emit the jump table entries.
1156   const std::vector<MachineBasicBlock*> &MBBs = (*MJTEs)[JTIndex].MBBs;
1157   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
1158     if (IsPIC)
1159       // DestBB address - JT base.
1160       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_pic_jt, JTBase);
1161     else
1162       // Absolute DestBB address.
1163       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_absolute);
1164     emitWordLE(0);
1165   }
1166 }
1167
1168 template<class CodeEmitter>
1169 void Emitter<CodeEmitter>::emitMiscBranchInstruction(const MachineInstr &MI) {
1170   const TargetInstrDesc &TID = MI.getDesc();
1171
1172   // Handle jump tables.
1173   if (TID.Opcode == ARM::BR_JTr || TID.Opcode == ARM::BR_JTadd) {
1174     // First emit a ldr pc, [] instruction.
1175     emitDataProcessingInstruction(MI, ARM::PC);
1176
1177     // Then emit the inline jump table.
1178     unsigned JTIndex =
1179       (TID.Opcode == ARM::BR_JTr)
1180       ? MI.getOperand(1).getIndex() : MI.getOperand(2).getIndex();
1181     emitInlineJumpTable(JTIndex);
1182     return;
1183   } else if (TID.Opcode == ARM::BR_JTm) {
1184     // First emit a ldr pc, [] instruction.
1185     emitLoadStoreInstruction(MI, ARM::PC);
1186
1187     // Then emit the inline jump table.
1188     emitInlineJumpTable(MI.getOperand(3).getIndex());
1189     return;
1190   }
1191
1192   // Part of binary is determined by TableGn.
1193   unsigned Binary = getBinaryCodeForInstr(MI);
1194
1195   // Set the conditional execution predicate
1196   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1197
1198   if (TID.Opcode == ARM::BX_RET)
1199     // The return register is LR.
1200     Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::LR);
1201   else
1202     // otherwise, set the return register
1203     Binary |= getMachineOpValue(MI, 0);
1204
1205   emitWordLE(Binary);
1206 }
1207
1208 static unsigned encodeVFPRd(const MachineInstr &MI, unsigned OpIdx) {
1209   unsigned RegD = MI.getOperand(OpIdx).getReg();
1210   unsigned Binary = 0;
1211   bool isSPVFP = false;
1212   RegD = ARMRegisterInfo::getRegisterNumbering(RegD, &isSPVFP);
1213   if (!isSPVFP)
1214     Binary |=   RegD               << ARMII::RegRdShift;
1215   else {
1216     Binary |= ((RegD & 0x1E) >> 1) << ARMII::RegRdShift;
1217     Binary |=  (RegD & 0x01)       << ARMII::D_BitShift;
1218   }
1219   return Binary;
1220 }
1221
1222 static unsigned encodeVFPRn(const MachineInstr &MI, unsigned OpIdx) {
1223   unsigned RegN = MI.getOperand(OpIdx).getReg();
1224   unsigned Binary = 0;
1225   bool isSPVFP = false;
1226   RegN = ARMRegisterInfo::getRegisterNumbering(RegN, &isSPVFP);
1227   if (!isSPVFP)
1228     Binary |=   RegN               << ARMII::RegRnShift;
1229   else {
1230     Binary |= ((RegN & 0x1E) >> 1) << ARMII::RegRnShift;
1231     Binary |=  (RegN & 0x01)       << ARMII::N_BitShift;
1232   }
1233   return Binary;
1234 }
1235
1236 static unsigned encodeVFPRm(const MachineInstr &MI, unsigned OpIdx) {
1237   unsigned RegM = MI.getOperand(OpIdx).getReg();
1238   unsigned Binary = 0;
1239   bool isSPVFP = false;
1240   RegM = ARMRegisterInfo::getRegisterNumbering(RegM, &isSPVFP);
1241   if (!isSPVFP)
1242     Binary |=   RegM;
1243   else {
1244     Binary |= ((RegM & 0x1E) >> 1);
1245     Binary |=  (RegM & 0x01)       << ARMII::M_BitShift;
1246   }
1247   return Binary;
1248 }
1249
1250 template<class CodeEmitter>
1251 void Emitter<CodeEmitter>::emitVFPArithInstruction(const MachineInstr &MI) {
1252   const TargetInstrDesc &TID = MI.getDesc();
1253
1254   // Part of binary is determined by TableGn.
1255   unsigned Binary = getBinaryCodeForInstr(MI);
1256
1257   // Set the conditional execution predicate
1258   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1259
1260   unsigned OpIdx = 0;
1261   assert((Binary & ARMII::D_BitShift) == 0 &&
1262          (Binary & ARMII::N_BitShift) == 0 &&
1263          (Binary & ARMII::M_BitShift) == 0 && "VFP encoding bug!");
1264
1265   // Encode Dd / Sd.
1266   Binary |= encodeVFPRd(MI, OpIdx++);
1267
1268   // If this is a two-address operand, skip it, e.g. FMACD.
1269   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1270     ++OpIdx;
1271
1272   // Encode Dn / Sn.
1273   if ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPBinaryFrm)
1274     Binary |= encodeVFPRn(MI, OpIdx++);
1275
1276   if (OpIdx == TID.getNumOperands() ||
1277       TID.OpInfo[OpIdx].isPredicate() ||
1278       TID.OpInfo[OpIdx].isOptionalDef()) {
1279     // FCMPEZD etc. has only one operand.
1280     emitWordLE(Binary);
1281     return;
1282   }
1283
1284   // Encode Dm / Sm.
1285   Binary |= encodeVFPRm(MI, OpIdx);
1286
1287   emitWordLE(Binary);
1288 }
1289
1290 template<class CodeEmitter>
1291 void Emitter<CodeEmitter>::emitVFPConversionInstruction(
1292       const MachineInstr &MI) {
1293   const TargetInstrDesc &TID = MI.getDesc();
1294   unsigned Form = TID.TSFlags & ARMII::FormMask;
1295
1296   // Part of binary is determined by TableGn.
1297   unsigned Binary = getBinaryCodeForInstr(MI);
1298
1299   // Set the conditional execution predicate
1300   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1301
1302   switch (Form) {
1303   default: break;
1304   case ARMII::VFPConv1Frm:
1305   case ARMII::VFPConv2Frm:
1306   case ARMII::VFPConv3Frm:
1307     // Encode Dd / Sd.
1308     Binary |= encodeVFPRd(MI, 0);
1309     break;
1310   case ARMII::VFPConv4Frm:
1311     // Encode Dn / Sn.
1312     Binary |= encodeVFPRn(MI, 0);
1313     break;
1314   case ARMII::VFPConv5Frm:
1315     // Encode Dm / Sm.
1316     Binary |= encodeVFPRm(MI, 0);
1317     break;
1318   }
1319
1320   switch (Form) {
1321   default: break;
1322   case ARMII::VFPConv1Frm:
1323     // Encode Dm / Sm.
1324     Binary |= encodeVFPRm(MI, 1);
1325     break;
1326   case ARMII::VFPConv2Frm:
1327   case ARMII::VFPConv3Frm:
1328     // Encode Dn / Sn.
1329     Binary |= encodeVFPRn(MI, 1);
1330     break;
1331   case ARMII::VFPConv4Frm:
1332   case ARMII::VFPConv5Frm:
1333     // Encode Dd / Sd.
1334     Binary |= encodeVFPRd(MI, 1);
1335     break;
1336   }
1337
1338   if (Form == ARMII::VFPConv5Frm)
1339     // Encode Dn / Sn.
1340     Binary |= encodeVFPRn(MI, 2);
1341   else if (Form == ARMII::VFPConv3Frm)
1342     // Encode Dm / Sm.
1343     Binary |= encodeVFPRm(MI, 2);
1344
1345   emitWordLE(Binary);
1346 }
1347
1348 template<class CodeEmitter>
1349 void Emitter<CodeEmitter>::emitVFPLoadStoreInstruction(const MachineInstr &MI) {
1350   // Part of binary is determined by TableGn.
1351   unsigned Binary = getBinaryCodeForInstr(MI);
1352
1353   // Set the conditional execution predicate
1354   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1355
1356   unsigned OpIdx = 0;
1357
1358   // Encode Dd / Sd.
1359   Binary |= encodeVFPRd(MI, OpIdx++);
1360
1361   // Encode address base.
1362   const MachineOperand &Base = MI.getOperand(OpIdx++);
1363   Binary |= getMachineOpValue(MI, Base) << ARMII::RegRnShift;
1364
1365   // If there is a non-zero immediate offset, encode it.
1366   if (Base.isReg()) {
1367     const MachineOperand &Offset = MI.getOperand(OpIdx);
1368     if (unsigned ImmOffs = ARM_AM::getAM5Offset(Offset.getImm())) {
1369       if (ARM_AM::getAM5Op(Offset.getImm()) == ARM_AM::add)
1370         Binary |= 1 << ARMII::U_BitShift;
1371       Binary |= ImmOffs;
1372       emitWordLE(Binary);
1373       return;
1374     }
1375   }
1376
1377   // If immediate offset is omitted, default to +0.
1378   Binary |= 1 << ARMII::U_BitShift;
1379
1380   emitWordLE(Binary);
1381 }
1382
1383 template<class CodeEmitter>
1384 void Emitter<CodeEmitter>::emitVFPLoadStoreMultipleInstruction(
1385                                                        const MachineInstr &MI) {
1386   // Part of binary is determined by TableGn.
1387   unsigned Binary = getBinaryCodeForInstr(MI);
1388
1389   // Set the conditional execution predicate
1390   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1391
1392   // Set base address operand
1393   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
1394
1395   // Set addressing mode by modifying bits U(23) and P(24)
1396   const MachineOperand &MO = MI.getOperand(1);
1397   Binary |= getAddrModeUPBits(ARM_AM::getAM5SubMode(MO.getImm()));
1398
1399   // Set bit W(21)
1400   if (ARM_AM::getAM5WBFlag(MO.getImm()))
1401     Binary |= 0x1 << ARMII::W_BitShift;
1402
1403   // First register is encoded in Dd.
1404   Binary |= encodeVFPRd(MI, 4);
1405
1406   // Number of registers are encoded in offset field.
1407   unsigned NumRegs = 1;
1408   for (unsigned i = 5, e = MI.getNumOperands(); i != e; ++i) {
1409     const MachineOperand &MO = MI.getOperand(i);
1410     if (!MO.isReg() || MO.isImplicit())
1411       break;
1412     ++NumRegs;
1413   }
1414   Binary |= NumRegs * 2;
1415
1416   emitWordLE(Binary);
1417 }
1418
1419 template<class CodeEmitter>
1420 void Emitter<CodeEmitter>::emitMiscInstruction(const MachineInstr &MI) {
1421   // Part of binary is determined by TableGn.
1422   unsigned Binary = getBinaryCodeForInstr(MI);
1423
1424   // Set the conditional execution predicate
1425   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1426
1427   emitWordLE(Binary);
1428 }
1429
1430 #include "ARMGenCodeEmitter.inc"