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