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