Whitespeace
[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/JITCodeEmitter.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/MachineModuleInfo.h"
33 #include "llvm/CodeGen/Passes.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #ifndef NDEBUG
39 #include <iomanip>
40 #endif
41 using namespace llvm;
42
43 STATISTIC(NumEmitted, "Number of machine instructions emitted");
44
45 namespace {
46
47   class ARMCodeEmitter : public MachineFunctionPass {
48     ARMJITInfo                *JTI;
49     const ARMInstrInfo        *II;
50     const TargetData          *TD;
51     const ARMSubtarget        *Subtarget;
52     TargetMachine             &TM;
53     JITCodeEmitter            &MCE;
54     MachineModuleInfo *MMI;
55     const std::vector<MachineConstantPoolEntry> *MCPEs;
56     const std::vector<MachineJumpTableEntry> *MJTEs;
57     bool IsPIC;
58     bool IsThumb;
59
60     void getAnalysisUsage(AnalysisUsage &AU) const {
61       AU.addRequired<MachineModuleInfo>();
62       MachineFunctionPass::getAnalysisUsage(AU);
63     }
64
65     static char ID;
66   public:
67     ARMCodeEmitter(TargetMachine &tm, JITCodeEmitter &mce)
68       : MachineFunctionPass(ID), JTI(0),
69         II((const ARMInstrInfo *)tm.getInstrInfo()),
70         TD(tm.getTargetData()), TM(tm),
71         MCE(mce), MCPEs(0), MJTEs(0),
72         IsPIC(TM.getRelocationModel() == Reloc::PIC_), IsThumb(false) {}
73
74     /// getBinaryCodeForInstr - This function, generated by the
75     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
76     /// machine instructions.
77     unsigned getBinaryCodeForInstr(const MachineInstr &MI) const;
78
79     bool runOnMachineFunction(MachineFunction &MF);
80
81     virtual const char *getPassName() const {
82       return "ARM Machine Code Emitter";
83     }
84
85     void emitInstruction(const MachineInstr &MI);
86
87   private:
88
89     void emitWordLE(unsigned Binary);
90     void emitDWordLE(uint64_t Binary);
91     void emitConstPoolInstruction(const MachineInstr &MI);
92     void emitMOVi32immInstruction(const MachineInstr &MI);
93     void emitMOVi2piecesInstruction(const MachineInstr &MI);
94     void emitLEApcrelJTInstruction(const MachineInstr &MI);
95     void emitPseudoMoveInstruction(const MachineInstr &MI);
96     void addPCLabel(unsigned LabelID);
97     void emitPseudoInstruction(const MachineInstr &MI);
98     unsigned getMachineSoRegOpValue(const MachineInstr &MI,
99                                     const TargetInstrDesc &TID,
100                                     const MachineOperand &MO,
101                                     unsigned OpIdx);
102
103     unsigned getMachineSoImmOpValue(unsigned SoImm);
104     unsigned getAddrMode6RegisterOperand(const MachineInstr &MI);
105     
106     unsigned getAddrModeSBit(const MachineInstr &MI,
107                              const TargetInstrDesc &TID) const;
108
109     void emitDataProcessingInstruction(const MachineInstr &MI,
110                                        unsigned ImplicitRd = 0,
111                                        unsigned ImplicitRn = 0);
112
113     void emitLoadStoreInstruction(const MachineInstr &MI,
114                                   unsigned ImplicitRd = 0,
115                                   unsigned ImplicitRn = 0);
116
117     void emitMiscLoadStoreInstruction(const MachineInstr &MI,
118                                       unsigned ImplicitRn = 0);
119
120     void emitLoadStoreMultipleInstruction(const MachineInstr &MI);
121
122     void emitMulFrmInstruction(const MachineInstr &MI);
123
124     void emitExtendInstruction(const MachineInstr &MI);
125
126     void emitMiscArithInstruction(const MachineInstr &MI);
127
128     void emitSaturateInstruction(const MachineInstr &MI);
129
130     void emitBranchInstruction(const MachineInstr &MI);
131
132     void emitInlineJumpTable(unsigned JTIndex);
133
134     void emitMiscBranchInstruction(const MachineInstr &MI);
135
136     void emitVFPArithInstruction(const MachineInstr &MI);
137
138     void emitVFPConversionInstruction(const MachineInstr &MI);
139
140     void emitVFPLoadStoreInstruction(const MachineInstr &MI);
141
142     void emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI);
143
144     void emitNEONLaneInstruction(const MachineInstr &MI);
145     void emitNEONDupInstruction(const MachineInstr &MI);
146     void emitNEON1RegModImmInstruction(const MachineInstr &MI);
147     void emitNEON2RegInstruction(const MachineInstr &MI);
148     void emitNEON3RegInstruction(const MachineInstr &MI);
149
150     /// getMachineOpValue - Return binary encoding of operand. If the machine
151     /// operand requires relocation, record the relocation and return zero.
152     unsigned getMachineOpValue(const MachineInstr &MI,
153                                const MachineOperand &MO) const;
154     unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) const {
155       return getMachineOpValue(MI, MI.getOperand(OpIdx));
156     }
157
158     // FIXME: The legacy JIT ARMCodeEmitter doesn't rely on the the
159     //  TableGen'erated getBinaryCodeForInstr() function to encode any
160     //  operand values, instead querying getMachineOpValue() directly for
161     //  each operand it needs to encode. Thus, any of the new encoder
162     //  helper functions can simply return 0 as the values the return
163     //  are already handled elsewhere. They are placeholders to allow this
164     //  encoder to continue to function until the MC encoder is sufficiently
165     //  far along that this one can be eliminated entirely.
166     unsigned getCCOutOpValue(const MachineInstr &MI, unsigned Op)
167       const { return 0; }
168     unsigned getSOImmOpValue(const MachineInstr &MI, unsigned Op)
169       const { return 0; }
170     unsigned getSORegOpValue(const MachineInstr &MI, unsigned Op)
171       const { return 0; }
172     unsigned getRotImmOpValue(const MachineInstr &MI, unsigned Op)
173       const { return 0; }
174     unsigned getImmMinusOneOpValue(const MachineInstr &MI, unsigned Op)
175       const { return 0; }
176     unsigned getAddrMode6RegisterOperand(const MachineInstr &MI, unsigned Op)
177       const { return 0; }
178     unsigned getBitfieldInvertedMaskOpValue(const MachineInstr &MI,
179                                             unsigned Op) const { return 0; }
180     unsigned getAddrModeImm12OpValue(const MachineInstr &MI, unsigned Op)
181       const {
182         // {17-13} = reg
183         // {12}    = (U)nsigned (add == '1', sub == '0')
184         // {11-0}  = imm12
185         const MachineOperand &MO  = MI.getOperand(Op);
186         const MachineOperand &MO1 = MI.getOperand(Op + 1);
187         if (!MO.isReg()) {
188           emitConstPoolAddress(MO.getIndex(), ARM::reloc_arm_cp_entry);
189           return 0;
190         }
191         unsigned Reg = getARMRegisterNumbering(MO.getReg());
192         int32_t Imm12 = MO1.getImm();
193         uint32_t Binary;
194         Binary = Imm12 & 0xfff;
195         if (Imm12 >= 0)
196           Binary |= (1 << 12);
197         Binary |= (Reg << 13);
198         return Binary;
199       }
200     unsigned getNEONVcvtImm32OpValue(const MachineInstr &MI, unsigned Op)
201       const { return 0; }
202
203     unsigned getRegisterListOpValue(const MachineInstr &MI, unsigned Op)
204       const { return 0; }
205
206     /// getMovi32Value - Return binary encoding of operand for movw/movt. If the
207     /// machine operand requires relocation, record the relocation and return
208     /// zero.
209     unsigned getMovi32Value(const MachineInstr &MI,const MachineOperand &MO,
210                             unsigned Reloc);
211
212     /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
213     ///
214     unsigned getShiftOp(unsigned Imm) const ;
215
216     /// Routines that handle operands which add machine relocations which are
217     /// fixed up by the relocation stage.
218     void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
219                            bool MayNeedFarStub,  bool Indirect,
220                            intptr_t ACPV = 0) const;
221     void emitExternalSymbolAddress(const char *ES, unsigned Reloc) const;
222     void emitConstPoolAddress(unsigned CPI, unsigned Reloc) const;
223     void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) const;
224     void emitMachineBasicBlock(MachineBasicBlock *BB, unsigned Reloc,
225                                intptr_t JTBase = 0) const;
226   };
227 }
228
229 char ARMCodeEmitter::ID = 0;
230
231 /// createARMJITCodeEmitterPass - Return a pass that emits the collected ARM
232 /// code to the specified MCE object.
233 FunctionPass *llvm::createARMJITCodeEmitterPass(ARMBaseTargetMachine &TM,
234                                                 JITCodeEmitter &JCE) {
235   return new ARMCodeEmitter(TM, JCE);
236 }
237
238 bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
239   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
240           MF.getTarget().getRelocationModel() != Reloc::Static) &&
241          "JIT relocation model must be set to static or default!");
242   JTI = ((ARMTargetMachine &)MF.getTarget()).getJITInfo();
243   II = ((const ARMTargetMachine &)MF.getTarget()).getInstrInfo();
244   TD = ((const ARMTargetMachine &)MF.getTarget()).getTargetData();
245   Subtarget = &TM.getSubtarget<ARMSubtarget>();
246   MCPEs = &MF.getConstantPool()->getConstants();
247   MJTEs = 0;
248   if (MF.getJumpTableInfo()) MJTEs = &MF.getJumpTableInfo()->getJumpTables();
249   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
250   IsThumb = MF.getInfo<ARMFunctionInfo>()->isThumbFunction();
251   JTI->Initialize(MF, IsPIC);
252   MMI = &getAnalysis<MachineModuleInfo>();
253   MCE.setModuleInfo(MMI);
254
255   do {
256     DEBUG(errs() << "JITTing function '"
257           << MF.getFunction()->getName() << "'\n");
258     MCE.startFunction(MF);
259     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
260          MBB != E; ++MBB) {
261       MCE.StartMachineBasicBlock(MBB);
262       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
263            I != E; ++I)
264         emitInstruction(*I);
265     }
266   } while (MCE.finishFunction(MF));
267
268   return false;
269 }
270
271 /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
272 ///
273 unsigned ARMCodeEmitter::getShiftOp(unsigned Imm) const {
274   switch (ARM_AM::getAM2ShiftOpc(Imm)) {
275   default: llvm_unreachable("Unknown shift opc!");
276   case ARM_AM::asr: return 2;
277   case ARM_AM::lsl: return 0;
278   case ARM_AM::lsr: return 1;
279   case ARM_AM::ror:
280   case ARM_AM::rrx: return 3;
281   }
282   return 0;
283 }
284
285 /// getMovi32Value - Return binary encoding of operand for movw/movt. If the
286 /// machine operand requires relocation, record the relocation and return zero.
287 unsigned ARMCodeEmitter::getMovi32Value(const MachineInstr &MI,
288                                         const MachineOperand &MO,
289                                         unsigned Reloc) {
290   assert(((Reloc == ARM::reloc_arm_movt) || (Reloc == ARM::reloc_arm_movw))
291       && "Relocation to this function should be for movt or movw");
292
293   if (MO.isImm())
294     return static_cast<unsigned>(MO.getImm());
295   else if (MO.isGlobal())
296     emitGlobalAddress(MO.getGlobal(), Reloc, true, false);
297   else if (MO.isSymbol())
298     emitExternalSymbolAddress(MO.getSymbolName(), Reloc);
299   else if (MO.isMBB())
300     emitMachineBasicBlock(MO.getMBB(), Reloc);
301   else {
302 #ifndef NDEBUG
303     errs() << MO;
304 #endif
305     llvm_unreachable("Unsupported operand type for movw/movt");
306   }
307   return 0;
308 }
309
310 /// getMachineOpValue - Return binary encoding of operand. If the machine
311 /// operand requires relocation, record the relocation and return zero.
312 unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
313                                            const MachineOperand &MO) const {
314   if (MO.isReg())
315     return getARMRegisterNumbering(MO.getReg());
316   else if (MO.isImm())
317     return static_cast<unsigned>(MO.getImm());
318   else if (MO.isGlobal())
319     emitGlobalAddress(MO.getGlobal(), ARM::reloc_arm_branch, true, false);
320   else if (MO.isSymbol())
321     emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_branch);
322   else if (MO.isCPI()) {
323     const TargetInstrDesc &TID = MI.getDesc();
324     // For VFP load, the immediate offset is multiplied by 4.
325     unsigned Reloc =  ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPLdStFrm)
326       ? ARM::reloc_arm_vfp_cp_entry : ARM::reloc_arm_cp_entry;
327     emitConstPoolAddress(MO.getIndex(), Reloc);
328   } else if (MO.isJTI())
329     emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
330   else if (MO.isMBB())
331     emitMachineBasicBlock(MO.getMBB(), ARM::reloc_arm_branch);
332   else {
333 #ifndef NDEBUG
334     errs() << MO;
335 #endif
336     llvm_unreachable(0);
337   }
338   return 0;
339 }
340
341 /// emitGlobalAddress - Emit the specified address to the code stream.
342 ///
343 void ARMCodeEmitter::emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
344                                        bool MayNeedFarStub, bool Indirect,
345                                        intptr_t ACPV) const {
346   MachineRelocation MR = Indirect
347     ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
348                                            const_cast<GlobalValue *>(GV),
349                                            ACPV, MayNeedFarStub)
350     : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
351                                const_cast<GlobalValue *>(GV), ACPV,
352                                MayNeedFarStub);
353   MCE.addRelocation(MR);
354 }
355
356 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
357 /// be emitted to the current location in the function, and allow it to be PC
358 /// relative.
359 void ARMCodeEmitter::
360 emitExternalSymbolAddress(const char *ES, unsigned Reloc) const {
361   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
362                                                  Reloc, ES));
363 }
364
365 /// emitConstPoolAddress - Arrange for the address of an constant pool
366 /// to be emitted to the current location in the function, and allow it to be PC
367 /// relative.
368 void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc) const {
369   // Tell JIT emitter we'll resolve the address.
370   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
371                                                     Reloc, CPI, 0, true));
372 }
373
374 /// emitJumpTableAddress - Arrange for the address of a jump table to
375 /// be emitted to the current location in the function, and allow it to be PC
376 /// relative.
377 void ARMCodeEmitter::
378 emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) const {
379   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
380                                                     Reloc, JTIndex, 0, true));
381 }
382
383 /// emitMachineBasicBlock - Emit the specified address basic block.
384 void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
385                                            unsigned Reloc,
386                                            intptr_t JTBase) const {
387   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
388                                              Reloc, BB, JTBase));
389 }
390
391 void ARMCodeEmitter::emitWordLE(unsigned Binary) {
392   DEBUG(errs() << "  0x";
393         errs().write_hex(Binary) << "\n");
394   MCE.emitWordLE(Binary);
395 }
396
397 void ARMCodeEmitter::emitDWordLE(uint64_t Binary) {
398   DEBUG(errs() << "  0x";
399         errs().write_hex(Binary) << "\n");
400   MCE.emitDWordLE(Binary);
401 }
402
403 void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
404   DEBUG(errs() << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI);
405
406   MCE.processDebugLoc(MI.getDebugLoc(), true);
407
408   ++NumEmitted;  // Keep track of the # of mi's emitted
409   switch (MI.getDesc().TSFlags & ARMII::FormMask) {
410   default: {
411     llvm_unreachable("Unhandled instruction encoding format!");
412     break;
413   }
414   case ARMII::Pseudo:
415     emitPseudoInstruction(MI);
416     break;
417   case ARMII::DPFrm:
418   case ARMII::DPSoRegFrm:
419     emitDataProcessingInstruction(MI);
420     break;
421   case ARMII::LdFrm:
422   case ARMII::StFrm:
423     emitLoadStoreInstruction(MI);
424     break;
425   case ARMII::LdMiscFrm:
426   case ARMII::StMiscFrm:
427     emitMiscLoadStoreInstruction(MI);
428     break;
429   case ARMII::LdStMulFrm:
430     emitLoadStoreMultipleInstruction(MI);
431     break;
432   case ARMII::MulFrm:
433     emitMulFrmInstruction(MI);
434     break;
435   case ARMII::ExtFrm:
436     emitExtendInstruction(MI);
437     break;
438   case ARMII::ArithMiscFrm:
439     emitMiscArithInstruction(MI);
440     break;
441   case ARMII::SatFrm:
442     emitSaturateInstruction(MI);
443     break;
444   case ARMII::BrFrm:
445     emitBranchInstruction(MI);
446     break;
447   case ARMII::BrMiscFrm:
448     emitMiscBranchInstruction(MI);
449     break;
450   // VFP instructions.
451   case ARMII::VFPUnaryFrm:
452   case ARMII::VFPBinaryFrm:
453     emitVFPArithInstruction(MI);
454     break;
455   case ARMII::VFPConv1Frm:
456   case ARMII::VFPConv2Frm:
457   case ARMII::VFPConv3Frm:
458   case ARMII::VFPConv4Frm:
459   case ARMII::VFPConv5Frm:
460     emitVFPConversionInstruction(MI);
461     break;
462   case ARMII::VFPLdStFrm:
463     emitVFPLoadStoreInstruction(MI);
464     break;
465   case ARMII::VFPLdStMulFrm:
466     emitVFPLoadStoreMultipleInstruction(MI);
467     break;
468
469   // NEON instructions.
470   case ARMII::NGetLnFrm:
471   case ARMII::NSetLnFrm:
472     emitNEONLaneInstruction(MI);
473     break;
474   case ARMII::NDupFrm:
475     emitNEONDupInstruction(MI);
476     break;
477   case ARMII::N1RegModImmFrm:
478     emitNEON1RegModImmInstruction(MI);
479     break;
480   case ARMII::N2RegFrm:
481     emitNEON2RegInstruction(MI);
482     break;
483   case ARMII::N3RegFrm:
484     emitNEON3RegInstruction(MI);
485     break;
486   }
487   MCE.processDebugLoc(MI.getDebugLoc(), false);
488 }
489
490 void ARMCodeEmitter::emitConstPoolInstruction(const MachineInstr &MI) {
491   unsigned CPI = MI.getOperand(0).getImm();       // CP instruction index.
492   unsigned CPIndex = MI.getOperand(1).getIndex(); // Actual cp entry index.
493   const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
494
495   // Remember the CONSTPOOL_ENTRY address for later relocation.
496   JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
497
498   // Emit constpool island entry. In most cases, the actual values will be
499   // resolved and relocated after code emission.
500   if (MCPE.isMachineConstantPoolEntry()) {
501     ARMConstantPoolValue *ACPV =
502       static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
503
504     DEBUG(errs() << "  ** ARM constant pool #" << CPI << " @ "
505           << (void*)MCE.getCurrentPCValue() << " " << *ACPV << '\n');
506
507     assert(ACPV->isGlobalValue() && "unsupported constant pool value");
508     const GlobalValue *GV = ACPV->getGV();
509     if (GV) {
510       Reloc::Model RelocM = TM.getRelocationModel();
511       emitGlobalAddress(GV, ARM::reloc_arm_machine_cp_entry,
512                         isa<Function>(GV),
513                         Subtarget->GVIsIndirectSymbol(GV, RelocM),
514                         (intptr_t)ACPV);
515      } else  {
516       emitExternalSymbolAddress(ACPV->getSymbol(), ARM::reloc_arm_absolute);
517     }
518     emitWordLE(0);
519   } else {
520     const Constant *CV = MCPE.Val.ConstVal;
521
522     DEBUG({
523         errs() << "  ** Constant pool #" << CPI << " @ "
524                << (void*)MCE.getCurrentPCValue() << " ";
525         if (const Function *F = dyn_cast<Function>(CV))
526           errs() << F->getName();
527         else
528           errs() << *CV;
529         errs() << '\n';
530       });
531
532     if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
533       emitGlobalAddress(GV, ARM::reloc_arm_absolute, isa<Function>(GV), false);
534       emitWordLE(0);
535     } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
536       uint32_t Val = uint32_t(*CI->getValue().getRawData());
537       emitWordLE(Val);
538     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
539       if (CFP->getType()->isFloatTy())
540         emitWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
541       else if (CFP->getType()->isDoubleTy())
542         emitDWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
543       else {
544         llvm_unreachable("Unable to handle this constantpool entry!");
545       }
546     } else {
547       llvm_unreachable("Unable to handle this constantpool entry!");
548     }
549   }
550 }
551
552 void ARMCodeEmitter::emitMOVi32immInstruction(const MachineInstr &MI) {
553   const MachineOperand &MO0 = MI.getOperand(0);
554   const MachineOperand &MO1 = MI.getOperand(1);
555
556   // Emit the 'movw' instruction.
557   unsigned Binary = 0x30 << 20;  // mov: Insts{27-20} = 0b00110000
558
559   unsigned Lo16 = getMovi32Value(MI, MO1, ARM::reloc_arm_movw) & 0xFFFF;
560
561   // Set the conditional execution predicate.
562   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
563
564   // Encode Rd.
565   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
566
567   // Encode imm16 as imm4:imm12
568   Binary |= Lo16 & 0xFFF; // Insts{11-0} = imm12
569   Binary |= ((Lo16 >> 12) & 0xF) << 16; // Insts{19-16} = imm4
570   emitWordLE(Binary);
571
572   unsigned Hi16 = getMovi32Value(MI, MO1, ARM::reloc_arm_movt) >> 16;
573   // Emit the 'movt' instruction.
574   Binary = 0x34 << 20; // movt: Insts{27-20} = 0b00110100
575
576   // Set the conditional execution predicate.
577   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
578
579   // Encode Rd.
580   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
581
582   // Encode imm16 as imm4:imm1, same as movw above.
583   Binary |= Hi16 & 0xFFF;
584   Binary |= ((Hi16 >> 12) & 0xF) << 16;
585   emitWordLE(Binary);
586 }
587
588 void ARMCodeEmitter::emitMOVi2piecesInstruction(const MachineInstr &MI) {
589   const MachineOperand &MO0 = MI.getOperand(0);
590   const MachineOperand &MO1 = MI.getOperand(1);
591   assert(MO1.isImm() && ARM_AM::isSOImmTwoPartVal(MO1.getImm()) &&
592                                                   "Not a valid so_imm value!");
593   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO1.getImm());
594   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO1.getImm());
595
596   // Emit the 'mov' instruction.
597   unsigned Binary = 0xd << 21;  // mov: Insts{24-21} = 0b1101
598
599   // Set the conditional execution predicate.
600   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
601
602   // Encode Rd.
603   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
604
605   // Encode so_imm.
606   // Set bit I(25) to identify this is the immediate form of <shifter_op>
607   Binary |= 1 << ARMII::I_BitShift;
608   Binary |= getMachineSoImmOpValue(V1);
609   emitWordLE(Binary);
610
611   // Now the 'orr' instruction.
612   Binary = 0xc << 21;  // orr: Insts{24-21} = 0b1100
613
614   // Set the conditional execution predicate.
615   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
616
617   // Encode Rd.
618   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
619
620   // Encode Rn.
621   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRnShift;
622
623   // Encode so_imm.
624   // Set bit I(25) to identify this is the immediate form of <shifter_op>
625   Binary |= 1 << ARMII::I_BitShift;
626   Binary |= getMachineSoImmOpValue(V2);
627   emitWordLE(Binary);
628 }
629
630 void ARMCodeEmitter::emitLEApcrelJTInstruction(const MachineInstr &MI) {
631   // It's basically add r, pc, (LJTI - $+8)
632
633   const TargetInstrDesc &TID = MI.getDesc();
634
635   // Emit the 'add' instruction.
636   unsigned Binary = 0x4 << 21;  // add: Insts{24-31} = 0b0100
637
638   // Set the conditional execution predicate
639   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
640
641   // Encode S bit if MI modifies CPSR.
642   Binary |= getAddrModeSBit(MI, TID);
643
644   // Encode Rd.
645   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
646
647   // Encode Rn which is PC.
648   Binary |= getARMRegisterNumbering(ARM::PC) << ARMII::RegRnShift;
649
650   // Encode the displacement.
651   Binary |= 1 << ARMII::I_BitShift;
652   emitJumpTableAddress(MI.getOperand(1).getIndex(), ARM::reloc_arm_jt_base);
653
654   emitWordLE(Binary);
655 }
656
657 void ARMCodeEmitter::emitPseudoMoveInstruction(const MachineInstr &MI) {
658   unsigned Opcode = MI.getDesc().Opcode;
659
660   // Part of binary is determined by TableGn.
661   unsigned Binary = getBinaryCodeForInstr(MI);
662
663   // Set the conditional execution predicate
664   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
665
666   // Encode S bit if MI modifies CPSR.
667   if (Opcode == ARM::MOVsrl_flag || Opcode == ARM::MOVsra_flag)
668     Binary |= 1 << ARMII::S_BitShift;
669
670   // Encode register def if there is one.
671   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
672
673   // Encode the shift operation.
674   switch (Opcode) {
675   default: break;
676   case ARM::RRX:
677     // rrx
678     Binary |= 0x6 << 4;
679     break;
680   case ARM::MOVsrl_flag:
681     // lsr #1
682     Binary |= (0x2 << 4) | (1 << 7);
683     break;
684   case ARM::MOVsra_flag:
685     // asr #1
686     Binary |= (0x4 << 4) | (1 << 7);
687     break;
688   }
689
690   // Encode register Rm.
691   Binary |= getMachineOpValue(MI, 1);
692
693   emitWordLE(Binary);
694 }
695
696 void ARMCodeEmitter::addPCLabel(unsigned LabelID) {
697   DEBUG(errs() << "  ** LPC" << LabelID << " @ "
698         << (void*)MCE.getCurrentPCValue() << '\n');
699   JTI->addPCLabelAddr(LabelID, MCE.getCurrentPCValue());
700 }
701
702 void ARMCodeEmitter::emitPseudoInstruction(const MachineInstr &MI) {
703   unsigned Opcode = MI.getDesc().Opcode;
704   switch (Opcode) {
705   default:
706     llvm_unreachable("ARMCodeEmitter::emitPseudoInstruction");
707   case ARM::BX:
708   case ARM::BMOVPCRX:
709   case ARM::BXr9:
710   case ARM::BMOVPCRXr9: {
711     // First emit mov lr, pc
712     unsigned Binary = 0x01a0e00f;
713     Binary |= II->getPredicate(&MI) << ARMII::CondShift;
714     emitWordLE(Binary);
715
716     // and then emit the branch.
717     emitMiscBranchInstruction(MI);
718     break;
719   }
720   case TargetOpcode::INLINEASM: {
721     // We allow inline assembler nodes with empty bodies - they can
722     // implicitly define registers, which is ok for JIT.
723     if (MI.getOperand(0).getSymbolName()[0]) {
724       report_fatal_error("JIT does not support inline asm!");
725     }
726     break;
727   }
728   case TargetOpcode::PROLOG_LABEL:
729   case TargetOpcode::EH_LABEL:
730     MCE.emitLabel(MI.getOperand(0).getMCSymbol());
731     break;
732   case TargetOpcode::IMPLICIT_DEF:
733   case TargetOpcode::KILL:
734     // Do nothing.
735     break;
736   case ARM::CONSTPOOL_ENTRY:
737     emitConstPoolInstruction(MI);
738     break;
739   case ARM::PICADD: {
740     // Remember of the address of the PC label for relocation later.
741     addPCLabel(MI.getOperand(2).getImm());
742     // PICADD is just an add instruction that implicitly read pc.
743     emitDataProcessingInstruction(MI, 0, ARM::PC);
744     break;
745   }
746   case ARM::PICLDR:
747   case ARM::PICLDRB:
748   case ARM::PICSTR:
749   case ARM::PICSTRB: {
750     // Remember of the address of the PC label for relocation later.
751     addPCLabel(MI.getOperand(2).getImm());
752     // These are just load / store instructions that implicitly read pc.
753     emitLoadStoreInstruction(MI, 0, ARM::PC);
754     break;
755   }
756   case ARM::PICLDRH:
757   case ARM::PICLDRSH:
758   case ARM::PICLDRSB:
759   case ARM::PICSTRH: {
760     // Remember of the address of the PC label for relocation later.
761     addPCLabel(MI.getOperand(2).getImm());
762     // These are just load / store instructions that implicitly read pc.
763     emitMiscLoadStoreInstruction(MI, ARM::PC);
764     break;
765   }
766
767   case ARM::MOVi32imm:
768     emitMOVi32immInstruction(MI);
769     break;
770
771   case ARM::MOVi2pieces:
772     // Two instructions to materialize a constant.
773     emitMOVi2piecesInstruction(MI);
774     break;
775   case ARM::LEApcrelJT:
776     // Materialize jumptable address.
777     emitLEApcrelJTInstruction(MI);
778     break;
779   case ARM::RRX:
780   case ARM::MOVsrl_flag:
781   case ARM::MOVsra_flag:
782     emitPseudoMoveInstruction(MI);
783     break;
784   }
785 }
786
787 unsigned ARMCodeEmitter::getMachineSoRegOpValue(const MachineInstr &MI,
788                                                 const TargetInstrDesc &TID,
789                                                 const MachineOperand &MO,
790                                                 unsigned OpIdx) {
791   unsigned Binary = getMachineOpValue(MI, MO);
792
793   const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
794   const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
795   ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
796
797   // Encode the shift opcode.
798   unsigned SBits = 0;
799   unsigned Rs = MO1.getReg();
800   if (Rs) {
801     // Set shift operand (bit[7:4]).
802     // LSL - 0001
803     // LSR - 0011
804     // ASR - 0101
805     // ROR - 0111
806     // RRX - 0110 and bit[11:8] clear.
807     switch (SOpc) {
808     default: llvm_unreachable("Unknown shift opc!");
809     case ARM_AM::lsl: SBits = 0x1; break;
810     case ARM_AM::lsr: SBits = 0x3; break;
811     case ARM_AM::asr: SBits = 0x5; break;
812     case ARM_AM::ror: SBits = 0x7; break;
813     case ARM_AM::rrx: SBits = 0x6; break;
814     }
815   } else {
816     // Set shift operand (bit[6:4]).
817     // LSL - 000
818     // LSR - 010
819     // ASR - 100
820     // ROR - 110
821     switch (SOpc) {
822     default: llvm_unreachable("Unknown shift opc!");
823     case ARM_AM::lsl: SBits = 0x0; break;
824     case ARM_AM::lsr: SBits = 0x2; break;
825     case ARM_AM::asr: SBits = 0x4; break;
826     case ARM_AM::ror: SBits = 0x6; break;
827     }
828   }
829   Binary |= SBits << 4;
830   if (SOpc == ARM_AM::rrx)
831     return Binary;
832
833   // Encode the shift operation Rs or shift_imm (except rrx).
834   if (Rs) {
835     // Encode Rs bit[11:8].
836     assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
837     return Binary | (getARMRegisterNumbering(Rs) << ARMII::RegRsShift);
838   }
839
840   // Encode shift_imm bit[11:7].
841   return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
842 }
843
844 unsigned ARMCodeEmitter::getMachineSoImmOpValue(unsigned SoImm) {
845   int SoImmVal = ARM_AM::getSOImmVal(SoImm);
846   assert(SoImmVal != -1 && "Not a valid so_imm value!");
847
848   // Encode rotate_imm.
849   unsigned Binary = (ARM_AM::getSOImmValRot((unsigned)SoImmVal) >> 1)
850     << ARMII::SoRotImmShift;
851
852   // Encode immed_8.
853   Binary |= ARM_AM::getSOImmValImm((unsigned)SoImmVal);
854   return Binary;
855 }
856
857 unsigned ARMCodeEmitter::getAddrModeSBit(const MachineInstr &MI,
858                                          const TargetInstrDesc &TID) const {
859   for (unsigned i = MI.getNumOperands(), e = TID.getNumOperands(); i != e; --i){
860     const MachineOperand &MO = MI.getOperand(i-1);
861     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)
862       return 1 << ARMII::S_BitShift;
863   }
864   return 0;
865 }
866
867 void ARMCodeEmitter::emitDataProcessingInstruction(const MachineInstr &MI,
868                                                    unsigned ImplicitRd,
869                                                    unsigned ImplicitRn) {
870   const TargetInstrDesc &TID = MI.getDesc();
871
872   // Part of binary is determined by TableGn.
873   unsigned Binary = getBinaryCodeForInstr(MI);
874
875   // Set the conditional execution predicate
876   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
877
878   // Encode S bit if MI modifies CPSR.
879   Binary |= getAddrModeSBit(MI, TID);
880
881   // Encode register def if there is one.
882   unsigned NumDefs = TID.getNumDefs();
883   unsigned OpIdx = 0;
884   if (NumDefs)
885     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
886   else if (ImplicitRd)
887     // Special handling for implicit use (e.g. PC).
888     Binary |= (getARMRegisterNumbering(ImplicitRd) << ARMII::RegRdShift);
889
890   if (TID.Opcode == ARM::MOVi16) {
891       // Get immediate from MI.
892       unsigned Lo16 = getMovi32Value(MI, MI.getOperand(OpIdx),
893                       ARM::reloc_arm_movw);
894       // Encode imm which is the same as in emitMOVi32immInstruction().
895       Binary |= Lo16 & 0xFFF;
896       Binary |= ((Lo16 >> 12) & 0xF) << 16;
897       emitWordLE(Binary);
898       return;
899   } else if(TID.Opcode == ARM::MOVTi16) {
900       unsigned Hi16 = (getMovi32Value(MI, MI.getOperand(OpIdx),
901                        ARM::reloc_arm_movt) >> 16);
902       Binary |= Hi16 & 0xFFF;
903       Binary |= ((Hi16 >> 12) & 0xF) << 16;
904       emitWordLE(Binary);
905       return;
906   } else if ((TID.Opcode == ARM::BFC) || (TID.Opcode == ARM::BFI)) {
907       uint32_t v = ~MI.getOperand(2).getImm();
908       int32_t lsb = CountTrailingZeros_32(v);
909       int32_t msb = (32 - CountLeadingZeros_32(v)) - 1;
910       // Instr{20-16} = msb, Instr{11-7} = lsb
911       Binary |= (msb & 0x1F) << 16;
912       Binary |= (lsb & 0x1F) << 7;
913       emitWordLE(Binary);
914       return;
915   } else if ((TID.Opcode == ARM::UBFX) || (TID.Opcode == ARM::SBFX)) {
916       // Encode Rn in Instr{0-3}
917       Binary |= getMachineOpValue(MI, OpIdx++);
918
919       uint32_t lsb = MI.getOperand(OpIdx++).getImm();
920       uint32_t widthm1 = MI.getOperand(OpIdx++).getImm() - 1;
921
922       // Instr{20-16} = widthm1, Instr{11-7} = lsb
923       Binary |= (widthm1 & 0x1F) << 16;
924       Binary |= (lsb & 0x1F) << 7;
925       emitWordLE(Binary);
926       return;
927   }
928
929   // If this is a two-address operand, skip it. e.g. MOVCCr operand 1.
930   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
931     ++OpIdx;
932
933   // Encode first non-shifter register operand if there is one.
934   bool isUnary = TID.TSFlags & ARMII::UnaryDP;
935   if (!isUnary) {
936     if (ImplicitRn)
937       // Special handling for implicit use (e.g. PC).
938       Binary |= (getARMRegisterNumbering(ImplicitRn) << ARMII::RegRnShift);
939     else {
940       Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
941       ++OpIdx;
942     }
943   }
944
945   // Encode shifter operand.
946   const MachineOperand &MO = MI.getOperand(OpIdx);
947   if ((TID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
948     // Encode SoReg.
949     emitWordLE(Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx));
950     return;
951   }
952
953   if (MO.isReg()) {
954     // Encode register Rm.
955     emitWordLE(Binary | getARMRegisterNumbering(MO.getReg()));
956     return;
957   }
958
959   // Encode so_imm.
960   Binary |= getMachineSoImmOpValue((unsigned)MO.getImm());
961
962   emitWordLE(Binary);
963 }
964
965 void ARMCodeEmitter::emitLoadStoreInstruction(const MachineInstr &MI,
966                                               unsigned ImplicitRd,
967                                               unsigned ImplicitRn) {
968   const TargetInstrDesc &TID = MI.getDesc();
969   unsigned Form = TID.TSFlags & ARMII::FormMask;
970   bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
971
972   // Part of binary is determined by TableGn.
973   unsigned Binary = getBinaryCodeForInstr(MI);
974
975   // If this is an LDRi12, STRi12 or LDRcp, nothing more needs be done.
976   if (MI.getOpcode() == ARM::LDRi12 || MI.getOpcode() == ARM::LDRcp ||
977       MI.getOpcode() == ARM::STRi12) {
978     emitWordLE(Binary);
979     return;
980   }
981
982   // Set the conditional execution predicate
983   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
984
985   unsigned OpIdx = 0;
986
987   // Operand 0 of a pre- and post-indexed store is the address base
988   // writeback. Skip it.
989   bool Skipped = false;
990   if (IsPrePost && Form == ARMII::StFrm) {
991     ++OpIdx;
992     Skipped = true;
993   }
994
995   // Set first operand
996   if (ImplicitRd)
997     // Special handling for implicit use (e.g. PC).
998     Binary |= (getARMRegisterNumbering(ImplicitRd) << ARMII::RegRdShift);
999   else
1000     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1001
1002   // Set second operand
1003   if (ImplicitRn)
1004     // Special handling for implicit use (e.g. PC).
1005     Binary |= (getARMRegisterNumbering(ImplicitRn) << ARMII::RegRnShift);
1006   else
1007     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1008
1009   // If this is a two-address operand, skip it. e.g. LDR_PRE.
1010   if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1011     ++OpIdx;
1012
1013   const MachineOperand &MO2 = MI.getOperand(OpIdx);
1014   unsigned AM2Opc = (ImplicitRn == ARM::PC)
1015     ? 0 : MI.getOperand(OpIdx+1).getImm();
1016
1017   // Set bit U(23) according to sign of immed value (positive or negative).
1018   Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
1019              ARMII::U_BitShift);
1020   if (!MO2.getReg()) { // is immediate
1021     if (ARM_AM::getAM2Offset(AM2Opc))
1022       // Set the value of offset_12 field
1023       Binary |= ARM_AM::getAM2Offset(AM2Opc);
1024     emitWordLE(Binary);
1025     return;
1026   }
1027
1028   // Set bit I(25), because this is not in immediate encoding.
1029   Binary |= 1 << ARMII::I_BitShift;
1030   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
1031   // Set bit[3:0] to the corresponding Rm register
1032   Binary |= getARMRegisterNumbering(MO2.getReg());
1033
1034   // If this instr is in scaled register offset/index instruction, set
1035   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
1036   if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
1037     Binary |= getShiftOp(AM2Opc) << ARMII::ShiftImmShift;  // shift
1038     Binary |= ShImm              << ARMII::ShiftShift;     // shift_immed
1039   }
1040
1041   emitWordLE(Binary);
1042 }
1043
1044 void ARMCodeEmitter::emitMiscLoadStoreInstruction(const MachineInstr &MI,
1045                                                   unsigned ImplicitRn) {
1046   const TargetInstrDesc &TID = MI.getDesc();
1047   unsigned Form = TID.TSFlags & ARMII::FormMask;
1048   bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
1049
1050   // Part of binary is determined by TableGn.
1051   unsigned Binary = getBinaryCodeForInstr(MI);
1052
1053   // Set the conditional execution predicate
1054   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1055
1056   unsigned OpIdx = 0;
1057
1058   // Operand 0 of a pre- and post-indexed store is the address base
1059   // writeback. Skip it.
1060   bool Skipped = false;
1061   if (IsPrePost && Form == ARMII::StMiscFrm) {
1062     ++OpIdx;
1063     Skipped = true;
1064   }
1065
1066   // Set first operand
1067   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1068
1069   // Skip LDRD and STRD's second operand.
1070   if (TID.Opcode == ARM::LDRD || TID.Opcode == ARM::STRD)
1071     ++OpIdx;
1072
1073   // Set second operand
1074   if (ImplicitRn)
1075     // Special handling for implicit use (e.g. PC).
1076     Binary |= (getARMRegisterNumbering(ImplicitRn) << ARMII::RegRnShift);
1077   else
1078     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1079
1080   // If this is a two-address operand, skip it. e.g. LDRH_POST.
1081   if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1082     ++OpIdx;
1083
1084   const MachineOperand &MO2 = MI.getOperand(OpIdx);
1085   unsigned AM3Opc = (ImplicitRn == ARM::PC)
1086     ? 0 : MI.getOperand(OpIdx+1).getImm();
1087
1088   // Set bit U(23) according to sign of immed value (positive or negative)
1089   Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
1090              ARMII::U_BitShift);
1091
1092   // If this instr is in register offset/index encoding, set bit[3:0]
1093   // to the corresponding Rm register.
1094   if (MO2.getReg()) {
1095     Binary |= getARMRegisterNumbering(MO2.getReg());
1096     emitWordLE(Binary);
1097     return;
1098   }
1099
1100   // This instr is in immediate offset/index encoding, set bit 22 to 1.
1101   Binary |= 1 << ARMII::AM3_I_BitShift;
1102   if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
1103     // Set operands
1104     Binary |= (ImmOffs >> 4) << ARMII::ImmHiShift;  // immedH
1105     Binary |= (ImmOffs & 0xF);                      // immedL
1106   }
1107
1108   emitWordLE(Binary);
1109 }
1110
1111 static unsigned getAddrModeUPBits(unsigned Mode) {
1112   unsigned Binary = 0;
1113
1114   // Set addressing mode by modifying bits U(23) and P(24)
1115   // IA - Increment after  - bit U = 1 and bit P = 0
1116   // IB - Increment before - bit U = 1 and bit P = 1
1117   // DA - Decrement after  - bit U = 0 and bit P = 0
1118   // DB - Decrement before - bit U = 0 and bit P = 1
1119   switch (Mode) {
1120   default: llvm_unreachable("Unknown addressing sub-mode!");
1121   case ARM_AM::da:                                     break;
1122   case ARM_AM::db: Binary |= 0x1 << ARMII::P_BitShift; break;
1123   case ARM_AM::ia: Binary |= 0x1 << ARMII::U_BitShift; break;
1124   case ARM_AM::ib: Binary |= 0x3 << ARMII::U_BitShift; break;
1125   }
1126
1127   return Binary;
1128 }
1129
1130 void ARMCodeEmitter::emitLoadStoreMultipleInstruction(const MachineInstr &MI) {
1131   const TargetInstrDesc &TID = MI.getDesc();
1132   bool IsUpdating = (TID.TSFlags & ARMII::IndexModeMask) != 0;
1133
1134   // Part of binary is determined by TableGn.
1135   unsigned Binary = getBinaryCodeForInstr(MI);
1136
1137   // Set the conditional execution predicate
1138   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1139
1140   // Skip operand 0 of an instruction with base register update.
1141   unsigned OpIdx = 0;
1142   if (IsUpdating)
1143     ++OpIdx;
1144
1145   // Set base address operand
1146   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1147
1148   // Set addressing mode by modifying bits U(23) and P(24)
1149   const MachineOperand &MO = MI.getOperand(OpIdx++);
1150   Binary |= getAddrModeUPBits(ARM_AM::getAM4SubMode(MO.getImm()));
1151
1152   // Set bit W(21)
1153   if (IsUpdating)
1154     Binary |= 0x1 << ARMII::W_BitShift;
1155
1156   // Set registers
1157   for (unsigned i = OpIdx+2, e = MI.getNumOperands(); i != e; ++i) {
1158     const MachineOperand &MO = MI.getOperand(i);
1159     if (!MO.isReg() || MO.isImplicit())
1160       break;
1161     unsigned RegNum = getARMRegisterNumbering(MO.getReg());
1162     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
1163            RegNum < 16);
1164     Binary |= 0x1 << RegNum;
1165   }
1166
1167   emitWordLE(Binary);
1168 }
1169
1170 void ARMCodeEmitter::emitMulFrmInstruction(const MachineInstr &MI) {
1171   const TargetInstrDesc &TID = MI.getDesc();
1172
1173   // Part of binary is determined by TableGn.
1174   unsigned Binary = getBinaryCodeForInstr(MI);
1175
1176   // Set the conditional execution predicate
1177   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1178
1179   // Encode S bit if MI modifies CPSR.
1180   Binary |= getAddrModeSBit(MI, TID);
1181
1182   // 32x32->64bit operations have two destination registers. The number
1183   // of register definitions will tell us if that's what we're dealing with.
1184   unsigned OpIdx = 0;
1185   if (TID.getNumDefs() == 2)
1186     Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
1187
1188   // Encode Rd
1189   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
1190
1191   // Encode Rm
1192   Binary |= getMachineOpValue(MI, OpIdx++);
1193
1194   // Encode Rs
1195   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
1196
1197   // Many multiple instructions (e.g. MLA) have three src operands. Encode
1198   // it as Rn (for multiply, that's in the same offset as RdLo.
1199   if (TID.getNumOperands() > OpIdx &&
1200       !TID.OpInfo[OpIdx].isPredicate() &&
1201       !TID.OpInfo[OpIdx].isOptionalDef())
1202     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdLoShift;
1203
1204   emitWordLE(Binary);
1205 }
1206
1207 void ARMCodeEmitter::emitExtendInstruction(const MachineInstr &MI) {
1208   const TargetInstrDesc &TID = MI.getDesc();
1209
1210   // Part of binary is determined by TableGn.
1211   unsigned Binary = getBinaryCodeForInstr(MI);
1212
1213   // Set the conditional execution predicate
1214   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1215
1216   unsigned OpIdx = 0;
1217
1218   // Encode Rd
1219   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1220
1221   const MachineOperand &MO1 = MI.getOperand(OpIdx++);
1222   const MachineOperand &MO2 = MI.getOperand(OpIdx);
1223   if (MO2.isReg()) {
1224     // Two register operand form.
1225     // Encode Rn.
1226     Binary |= getMachineOpValue(MI, MO1) << ARMII::RegRnShift;
1227
1228     // Encode Rm.
1229     Binary |= getMachineOpValue(MI, MO2);
1230     ++OpIdx;
1231   } else {
1232     Binary |= getMachineOpValue(MI, MO1);
1233   }
1234
1235   // Encode rot imm (0, 8, 16, or 24) if it has a rotate immediate operand.
1236   if (MI.getOperand(OpIdx).isImm() &&
1237       !TID.OpInfo[OpIdx].isPredicate() &&
1238       !TID.OpInfo[OpIdx].isOptionalDef())
1239     Binary |= (getMachineOpValue(MI, OpIdx) / 8) << ARMII::ExtRotImmShift;
1240
1241   emitWordLE(Binary);
1242 }
1243
1244 void ARMCodeEmitter::emitMiscArithInstruction(const MachineInstr &MI) {
1245   const TargetInstrDesc &TID = MI.getDesc();
1246
1247   // Part of binary is determined by TableGn.
1248   unsigned Binary = getBinaryCodeForInstr(MI);
1249
1250   // Set the conditional execution predicate
1251   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1252
1253   unsigned OpIdx = 0;
1254
1255   // Encode Rd
1256   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1257
1258   const MachineOperand &MO = MI.getOperand(OpIdx++);
1259   if (OpIdx == TID.getNumOperands() ||
1260       TID.OpInfo[OpIdx].isPredicate() ||
1261       TID.OpInfo[OpIdx].isOptionalDef()) {
1262     // Encode Rm and it's done.
1263     Binary |= getMachineOpValue(MI, MO);
1264     emitWordLE(Binary);
1265     return;
1266   }
1267
1268   // Encode Rn.
1269   Binary |= getMachineOpValue(MI, MO) << ARMII::RegRnShift;
1270
1271   // Encode Rm.
1272   Binary |= getMachineOpValue(MI, OpIdx++);
1273
1274   // Encode shift_imm.
1275   unsigned ShiftAmt = MI.getOperand(OpIdx).getImm();
1276   if (TID.Opcode == ARM::PKHTB) {
1277     assert(ShiftAmt != 0 && "PKHTB shift_imm is 0!");
1278     if (ShiftAmt == 32)
1279       ShiftAmt = 0;
1280   }
1281   assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
1282   Binary |= ShiftAmt << ARMII::ShiftShift;
1283
1284   emitWordLE(Binary);
1285 }
1286
1287 void ARMCodeEmitter::emitSaturateInstruction(const MachineInstr &MI) {
1288   const TargetInstrDesc &TID = MI.getDesc();
1289
1290   // Part of binary is determined by TableGen.
1291   unsigned Binary = getBinaryCodeForInstr(MI);
1292
1293   // Set the conditional execution predicate
1294   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1295
1296   // Encode Rd
1297   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
1298
1299   // Encode saturate bit position.
1300   unsigned Pos = MI.getOperand(1).getImm();
1301   if (TID.Opcode == ARM::SSAT || TID.Opcode == ARM::SSAT16)
1302     Pos -= 1;
1303   assert((Pos < 16 || (Pos < 32 &&
1304                        TID.Opcode != ARM::SSAT16 &&
1305                        TID.Opcode != ARM::USAT16)) &&
1306          "saturate bit position out of range");
1307   Binary |= Pos << 16;
1308
1309   // Encode Rm
1310   Binary |= getMachineOpValue(MI, 2);
1311
1312   // Encode shift_imm.
1313   if (TID.getNumOperands() == 4) {
1314     unsigned ShiftOp = MI.getOperand(3).getImm();
1315     ARM_AM::ShiftOpc Opc = ARM_AM::getSORegShOp(ShiftOp);
1316     if (Opc == ARM_AM::asr)
1317       Binary |= (1 << 6);
1318     unsigned ShiftAmt = MI.getOperand(3).getImm();
1319     if (ShiftAmt == 32 && Opc == ARM_AM::asr)
1320       ShiftAmt = 0;
1321     assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
1322     Binary |= ShiftAmt << ARMII::ShiftShift;
1323   }
1324
1325   emitWordLE(Binary);
1326 }
1327
1328 void ARMCodeEmitter::emitBranchInstruction(const MachineInstr &MI) {
1329   const TargetInstrDesc &TID = MI.getDesc();
1330
1331   if (TID.Opcode == ARM::TPsoft) {
1332     llvm_unreachable("ARM::TPsoft FIXME"); // FIXME
1333   }
1334
1335   // Part of binary is determined by TableGn.
1336   unsigned Binary = getBinaryCodeForInstr(MI);
1337
1338   // Set the conditional execution predicate
1339   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1340
1341   // Set signed_immed_24 field
1342   Binary |= getMachineOpValue(MI, 0);
1343
1344   emitWordLE(Binary);
1345 }
1346
1347 void ARMCodeEmitter::emitInlineJumpTable(unsigned JTIndex) {
1348   // Remember the base address of the inline jump table.
1349   uintptr_t JTBase = MCE.getCurrentPCValue();
1350   JTI->addJumpTableBaseAddr(JTIndex, JTBase);
1351   DEBUG(errs() << "  ** Jump Table #" << JTIndex << " @ " << (void*)JTBase
1352                << '\n');
1353
1354   // Now emit the jump table entries.
1355   const std::vector<MachineBasicBlock*> &MBBs = (*MJTEs)[JTIndex].MBBs;
1356   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
1357     if (IsPIC)
1358       // DestBB address - JT base.
1359       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_pic_jt, JTBase);
1360     else
1361       // Absolute DestBB address.
1362       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_absolute);
1363     emitWordLE(0);
1364   }
1365 }
1366
1367 void ARMCodeEmitter::emitMiscBranchInstruction(const MachineInstr &MI) {
1368   const TargetInstrDesc &TID = MI.getDesc();
1369
1370   // Handle jump tables.
1371   if (TID.Opcode == ARM::BR_JTr || TID.Opcode == ARM::BR_JTadd) {
1372     // First emit a ldr pc, [] instruction.
1373     emitDataProcessingInstruction(MI, ARM::PC);
1374
1375     // Then emit the inline jump table.
1376     unsigned JTIndex =
1377       (TID.Opcode == ARM::BR_JTr)
1378       ? MI.getOperand(1).getIndex() : MI.getOperand(2).getIndex();
1379     emitInlineJumpTable(JTIndex);
1380     return;
1381   } else if (TID.Opcode == ARM::BR_JTm) {
1382     // First emit a ldr pc, [] instruction.
1383     emitLoadStoreInstruction(MI, ARM::PC);
1384
1385     // Then emit the inline jump table.
1386     emitInlineJumpTable(MI.getOperand(3).getIndex());
1387     return;
1388   }
1389
1390   // Part of binary is determined by TableGn.
1391   unsigned Binary = getBinaryCodeForInstr(MI);
1392
1393   // Set the conditional execution predicate
1394   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1395
1396   if (TID.Opcode == ARM::BX_RET || TID.Opcode == ARM::MOVPCLR)
1397     // The return register is LR.
1398     Binary |= getARMRegisterNumbering(ARM::LR);
1399   else
1400     // otherwise, set the return register
1401     Binary |= getMachineOpValue(MI, 0);
1402
1403   emitWordLE(Binary);
1404 }
1405
1406 static unsigned encodeVFPRd(const MachineInstr &MI, unsigned OpIdx) {
1407   unsigned RegD = MI.getOperand(OpIdx).getReg();
1408   unsigned Binary = 0;
1409   bool isSPVFP = ARM::SPRRegisterClass->contains(RegD);
1410   RegD = getARMRegisterNumbering(RegD);
1411   if (!isSPVFP)
1412     Binary |=   RegD               << ARMII::RegRdShift;
1413   else {
1414     Binary |= ((RegD & 0x1E) >> 1) << ARMII::RegRdShift;
1415     Binary |=  (RegD & 0x01)       << ARMII::D_BitShift;
1416   }
1417   return Binary;
1418 }
1419
1420 static unsigned encodeVFPRn(const MachineInstr &MI, unsigned OpIdx) {
1421   unsigned RegN = MI.getOperand(OpIdx).getReg();
1422   unsigned Binary = 0;
1423   bool isSPVFP = ARM::SPRRegisterClass->contains(RegN);
1424   RegN = getARMRegisterNumbering(RegN);
1425   if (!isSPVFP)
1426     Binary |=   RegN               << ARMII::RegRnShift;
1427   else {
1428     Binary |= ((RegN & 0x1E) >> 1) << ARMII::RegRnShift;
1429     Binary |=  (RegN & 0x01)       << ARMII::N_BitShift;
1430   }
1431   return Binary;
1432 }
1433
1434 static unsigned encodeVFPRm(const MachineInstr &MI, unsigned OpIdx) {
1435   unsigned RegM = MI.getOperand(OpIdx).getReg();
1436   unsigned Binary = 0;
1437   bool isSPVFP = ARM::SPRRegisterClass->contains(RegM);
1438   RegM = getARMRegisterNumbering(RegM);
1439   if (!isSPVFP)
1440     Binary |=   RegM;
1441   else {
1442     Binary |= ((RegM & 0x1E) >> 1);
1443     Binary |=  (RegM & 0x01)       << ARMII::M_BitShift;
1444   }
1445   return Binary;
1446 }
1447
1448 void ARMCodeEmitter::emitVFPArithInstruction(const MachineInstr &MI) {
1449   const TargetInstrDesc &TID = MI.getDesc();
1450
1451   // Part of binary is determined by TableGn.
1452   unsigned Binary = getBinaryCodeForInstr(MI);
1453
1454   // Set the conditional execution predicate
1455   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1456
1457   unsigned OpIdx = 0;
1458   assert((Binary & ARMII::D_BitShift) == 0 &&
1459          (Binary & ARMII::N_BitShift) == 0 &&
1460          (Binary & ARMII::M_BitShift) == 0 && "VFP encoding bug!");
1461
1462   // Encode Dd / Sd.
1463   Binary |= encodeVFPRd(MI, OpIdx++);
1464
1465   // If this is a two-address operand, skip it, e.g. FMACD.
1466   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1467     ++OpIdx;
1468
1469   // Encode Dn / Sn.
1470   if ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPBinaryFrm)
1471     Binary |= encodeVFPRn(MI, OpIdx++);
1472
1473   if (OpIdx == TID.getNumOperands() ||
1474       TID.OpInfo[OpIdx].isPredicate() ||
1475       TID.OpInfo[OpIdx].isOptionalDef()) {
1476     // FCMPEZD etc. has only one operand.
1477     emitWordLE(Binary);
1478     return;
1479   }
1480
1481   // Encode Dm / Sm.
1482   Binary |= encodeVFPRm(MI, OpIdx);
1483
1484   emitWordLE(Binary);
1485 }
1486
1487 void ARMCodeEmitter::emitVFPConversionInstruction(const MachineInstr &MI) {
1488   const TargetInstrDesc &TID = MI.getDesc();
1489   unsigned Form = TID.TSFlags & ARMII::FormMask;
1490
1491   // Part of binary is determined by TableGn.
1492   unsigned Binary = getBinaryCodeForInstr(MI);
1493
1494   // Set the conditional execution predicate
1495   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1496
1497   switch (Form) {
1498   default: break;
1499   case ARMII::VFPConv1Frm:
1500   case ARMII::VFPConv2Frm:
1501   case ARMII::VFPConv3Frm:
1502     // Encode Dd / Sd.
1503     Binary |= encodeVFPRd(MI, 0);
1504     break;
1505   case ARMII::VFPConv4Frm:
1506     // Encode Dn / Sn.
1507     Binary |= encodeVFPRn(MI, 0);
1508     break;
1509   case ARMII::VFPConv5Frm:
1510     // Encode Dm / Sm.
1511     Binary |= encodeVFPRm(MI, 0);
1512     break;
1513   }
1514
1515   switch (Form) {
1516   default: break;
1517   case ARMII::VFPConv1Frm:
1518     // Encode Dm / Sm.
1519     Binary |= encodeVFPRm(MI, 1);
1520     break;
1521   case ARMII::VFPConv2Frm:
1522   case ARMII::VFPConv3Frm:
1523     // Encode Dn / Sn.
1524     Binary |= encodeVFPRn(MI, 1);
1525     break;
1526   case ARMII::VFPConv4Frm:
1527   case ARMII::VFPConv5Frm:
1528     // Encode Dd / Sd.
1529     Binary |= encodeVFPRd(MI, 1);
1530     break;
1531   }
1532
1533   if (Form == ARMII::VFPConv5Frm)
1534     // Encode Dn / Sn.
1535     Binary |= encodeVFPRn(MI, 2);
1536   else if (Form == ARMII::VFPConv3Frm)
1537     // Encode Dm / Sm.
1538     Binary |= encodeVFPRm(MI, 2);
1539
1540   emitWordLE(Binary);
1541 }
1542
1543 void ARMCodeEmitter::emitVFPLoadStoreInstruction(const MachineInstr &MI) {
1544   // Part of binary is determined by TableGn.
1545   unsigned Binary = getBinaryCodeForInstr(MI);
1546
1547   // Set the conditional execution predicate
1548   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1549
1550   unsigned OpIdx = 0;
1551
1552   // Encode Dd / Sd.
1553   Binary |= encodeVFPRd(MI, OpIdx++);
1554
1555   // Encode address base.
1556   const MachineOperand &Base = MI.getOperand(OpIdx++);
1557   Binary |= getMachineOpValue(MI, Base) << ARMII::RegRnShift;
1558
1559   // If there is a non-zero immediate offset, encode it.
1560   if (Base.isReg()) {
1561     const MachineOperand &Offset = MI.getOperand(OpIdx);
1562     if (unsigned ImmOffs = ARM_AM::getAM5Offset(Offset.getImm())) {
1563       if (ARM_AM::getAM5Op(Offset.getImm()) == ARM_AM::add)
1564         Binary |= 1 << ARMII::U_BitShift;
1565       Binary |= ImmOffs;
1566       emitWordLE(Binary);
1567       return;
1568     }
1569   }
1570
1571   // If immediate offset is omitted, default to +0.
1572   Binary |= 1 << ARMII::U_BitShift;
1573
1574   emitWordLE(Binary);
1575 }
1576
1577 void
1578 ARMCodeEmitter::emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI) {
1579   const TargetInstrDesc &TID = MI.getDesc();
1580   bool IsUpdating = (TID.TSFlags & ARMII::IndexModeMask) != 0;
1581
1582   // Part of binary is determined by TableGn.
1583   unsigned Binary = getBinaryCodeForInstr(MI);
1584
1585   // Set the conditional execution predicate
1586   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1587
1588   // Skip operand 0 of an instruction with base register update.
1589   unsigned OpIdx = 0;
1590   if (IsUpdating)
1591     ++OpIdx;
1592
1593   // Set base address operand
1594   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1595
1596   // Set addressing mode by modifying bits U(23) and P(24)
1597   const MachineOperand &MO = MI.getOperand(OpIdx++);
1598   Binary |= getAddrModeUPBits(ARM_AM::getAM4SubMode(MO.getImm()));
1599
1600   // Set bit W(21)
1601   if (IsUpdating)
1602     Binary |= 0x1 << ARMII::W_BitShift;
1603
1604   // First register is encoded in Dd.
1605   Binary |= encodeVFPRd(MI, OpIdx+2);
1606
1607   // Count the number of registers.
1608   unsigned NumRegs = 1;
1609   for (unsigned i = OpIdx+3, e = MI.getNumOperands(); i != e; ++i) {
1610     const MachineOperand &MO = MI.getOperand(i);
1611     if (!MO.isReg() || MO.isImplicit())
1612       break;
1613     ++NumRegs;
1614   }
1615   // Bit 8 will be set if <list> is consecutive 64-bit registers (e.g., D0)
1616   // Otherwise, it will be 0, in the case of 32-bit registers.
1617   if(Binary & 0x100)
1618     Binary |= NumRegs * 2;
1619   else
1620     Binary |= NumRegs;
1621
1622   emitWordLE(Binary);
1623 }
1624
1625 static unsigned encodeNEONRd(const MachineInstr &MI, unsigned OpIdx) {
1626   unsigned RegD = MI.getOperand(OpIdx).getReg();
1627   unsigned Binary = 0;
1628   RegD = getARMRegisterNumbering(RegD);
1629   Binary |= (RegD & 0xf) << ARMII::RegRdShift;
1630   Binary |= ((RegD >> 4) & 1) << ARMII::D_BitShift;
1631   return Binary;
1632 }
1633
1634 static unsigned encodeNEONRn(const MachineInstr &MI, unsigned OpIdx) {
1635   unsigned RegN = MI.getOperand(OpIdx).getReg();
1636   unsigned Binary = 0;
1637   RegN = getARMRegisterNumbering(RegN);
1638   Binary |= (RegN & 0xf) << ARMII::RegRnShift;
1639   Binary |= ((RegN >> 4) & 1) << ARMII::N_BitShift;
1640   return Binary;
1641 }
1642
1643 static unsigned encodeNEONRm(const MachineInstr &MI, unsigned OpIdx) {
1644   unsigned RegM = MI.getOperand(OpIdx).getReg();
1645   unsigned Binary = 0;
1646   RegM = getARMRegisterNumbering(RegM);
1647   Binary |= (RegM & 0xf);
1648   Binary |= ((RegM >> 4) & 1) << ARMII::M_BitShift;
1649   return Binary;
1650 }
1651
1652 /// convertNEONDataProcToThumb - Convert the ARM mode encoding for a NEON
1653 /// data-processing instruction to the corresponding Thumb encoding.
1654 static unsigned convertNEONDataProcToThumb(unsigned Binary) {
1655   assert((Binary & 0xfe000000) == 0xf2000000 &&
1656          "not an ARM NEON data-processing instruction");
1657   unsigned UBit = (Binary >> 24) & 1;
1658   return 0xef000000 | (UBit << 28) | (Binary & 0xffffff);
1659 }
1660
1661 void ARMCodeEmitter::emitNEONLaneInstruction(const MachineInstr &MI) {
1662   unsigned Binary = getBinaryCodeForInstr(MI);
1663
1664   unsigned RegTOpIdx, RegNOpIdx, LnOpIdx;
1665   const TargetInstrDesc &TID = MI.getDesc();
1666   if ((TID.TSFlags & ARMII::FormMask) == ARMII::NGetLnFrm) {
1667     RegTOpIdx = 0;
1668     RegNOpIdx = 1;
1669     LnOpIdx = 2;
1670   } else { // ARMII::NSetLnFrm
1671     RegTOpIdx = 2;
1672     RegNOpIdx = 0;
1673     LnOpIdx = 3;
1674   }
1675
1676   // Set the conditional execution predicate
1677   Binary |= (IsThumb ? ARMCC::AL : II->getPredicate(&MI)) << ARMII::CondShift;
1678
1679   unsigned RegT = MI.getOperand(RegTOpIdx).getReg();
1680   RegT = getARMRegisterNumbering(RegT);
1681   Binary |= (RegT << ARMII::RegRdShift);
1682   Binary |= encodeNEONRn(MI, RegNOpIdx);
1683
1684   unsigned LaneShift;
1685   if ((Binary & (1 << 22)) != 0)
1686     LaneShift = 0; // 8-bit elements
1687   else if ((Binary & (1 << 5)) != 0)
1688     LaneShift = 1; // 16-bit elements
1689   else
1690     LaneShift = 2; // 32-bit elements
1691
1692   unsigned Lane = MI.getOperand(LnOpIdx).getImm() << LaneShift;
1693   unsigned Opc1 = Lane >> 2;
1694   unsigned Opc2 = Lane & 3;
1695   assert((Opc1 & 3) == 0 && "out-of-range lane number operand");
1696   Binary |= (Opc1 << 21);
1697   Binary |= (Opc2 << 5);
1698
1699   emitWordLE(Binary);
1700 }
1701
1702 void ARMCodeEmitter::emitNEONDupInstruction(const MachineInstr &MI) {
1703   unsigned Binary = getBinaryCodeForInstr(MI);
1704
1705   // Set the conditional execution predicate
1706   Binary |= (IsThumb ? ARMCC::AL : II->getPredicate(&MI)) << ARMII::CondShift;
1707
1708   unsigned RegT = MI.getOperand(1).getReg();
1709   RegT = getARMRegisterNumbering(RegT);
1710   Binary |= (RegT << ARMII::RegRdShift);
1711   Binary |= encodeNEONRn(MI, 0);
1712   emitWordLE(Binary);
1713 }
1714
1715 void ARMCodeEmitter::emitNEON1RegModImmInstruction(const MachineInstr &MI) {
1716   unsigned Binary = getBinaryCodeForInstr(MI);
1717   // Destination register is encoded in Dd.
1718   Binary |= encodeNEONRd(MI, 0);
1719   // Immediate fields: Op, Cmode, I, Imm3, Imm4
1720   unsigned Imm = MI.getOperand(1).getImm();
1721   unsigned Op = (Imm >> 12) & 1;
1722   unsigned Cmode = (Imm >> 8) & 0xf;
1723   unsigned I = (Imm >> 7) & 1;
1724   unsigned Imm3 = (Imm >> 4) & 0x7;
1725   unsigned Imm4 = Imm & 0xf;
1726   Binary |= (I << 24) | (Imm3 << 16) | (Cmode << 8) | (Op << 5) | Imm4;
1727   if (IsThumb)
1728     Binary = convertNEONDataProcToThumb(Binary);
1729   emitWordLE(Binary);
1730 }
1731
1732 void ARMCodeEmitter::emitNEON2RegInstruction(const MachineInstr &MI) {
1733   const TargetInstrDesc &TID = MI.getDesc();
1734   unsigned Binary = getBinaryCodeForInstr(MI);
1735   // Destination register is encoded in Dd; source register in Dm.
1736   unsigned OpIdx = 0;
1737   Binary |= encodeNEONRd(MI, OpIdx++);
1738   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1739     ++OpIdx;
1740   Binary |= encodeNEONRm(MI, OpIdx);
1741   if (IsThumb)
1742     Binary = convertNEONDataProcToThumb(Binary);
1743   // FIXME: This does not handle VDUPfdf or VDUPfqf.
1744   emitWordLE(Binary);
1745 }
1746
1747 void ARMCodeEmitter::emitNEON3RegInstruction(const MachineInstr &MI) {
1748   const TargetInstrDesc &TID = MI.getDesc();
1749   unsigned Binary = getBinaryCodeForInstr(MI);
1750   // Destination register is encoded in Dd; source registers in Dn and Dm.
1751   unsigned OpIdx = 0;
1752   Binary |= encodeNEONRd(MI, OpIdx++);
1753   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1754     ++OpIdx;
1755   Binary |= encodeNEONRn(MI, OpIdx++);
1756   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1757     ++OpIdx;
1758   Binary |= encodeNEONRm(MI, OpIdx);
1759   if (IsThumb)
1760     Binary = convertNEONDataProcToThumb(Binary);
1761   // FIXME: This does not handle VMOVDneon or VMOVQ.
1762   emitWordLE(Binary);
1763 }
1764
1765 #include "ARMGenCodeEmitter.inc"