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