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