OSDN Git Service

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