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