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