ARMCodeEmitter.cpp revision 2491664d4979d33da2b90fc471cab2287c863e59
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
59    void getAnalysisUsage(AnalysisUsage &AU) const {
60      AU.addRequired<MachineModuleInfo>();
61      MachineFunctionPass::getAnalysisUsage(AU);
62    }
63
64    static char ID;
65  public:
66    ARMCodeEmitter(TargetMachine &tm, JITCodeEmitter &mce)
67      : MachineFunctionPass(&ID), JTI(0),
68        II((const ARMInstrInfo *)tm.getInstrInfo()),
69        TD(tm.getTargetData()), TM(tm),
70    MCE(mce), MCPEs(0), MJTEs(0),
71    IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
72
73    /// getBinaryCodeForInstr - This function, generated by the
74    /// CodeEmitterGenerator using TableGen, produces the binary encoding for
75    /// machine instructions.
76    unsigned getBinaryCodeForInstr(const MachineInstr &MI);
77
78    bool runOnMachineFunction(MachineFunction &MF);
79
80    virtual const char *getPassName() const {
81      return "ARM Machine Code Emitter";
82    }
83
84    void emitInstruction(const MachineInstr &MI);
85
86  private:
87
88    void emitWordLE(unsigned Binary);
89    void emitDWordLE(uint64_t Binary);
90    void emitConstPoolInstruction(const MachineInstr &MI);
91    void emitMOVi2piecesInstruction(const MachineInstr &MI);
92    void emitLEApcrelJTInstruction(const MachineInstr &MI);
93    void emitPseudoMoveInstruction(const MachineInstr &MI);
94    void addPCLabel(unsigned LabelID);
95    void emitPseudoInstruction(const MachineInstr &MI);
96    unsigned getMachineSoRegOpValue(const MachineInstr &MI,
97                                    const TargetInstrDesc &TID,
98                                    const MachineOperand &MO,
99                                    unsigned OpIdx);
100
101    unsigned getMachineSoImmOpValue(unsigned SoImm);
102
103    unsigned getAddrModeSBit(const MachineInstr &MI,
104                             const TargetInstrDesc &TID) const;
105
106    void emitDataProcessingInstruction(const MachineInstr &MI,
107                                       unsigned ImplicitRd = 0,
108                                       unsigned ImplicitRn = 0);
109
110    void emitLoadStoreInstruction(const MachineInstr &MI,
111                                  unsigned ImplicitRd = 0,
112                                  unsigned ImplicitRn = 0);
113
114    void emitMiscLoadStoreInstruction(const MachineInstr &MI,
115                                      unsigned ImplicitRn = 0);
116
117    void emitLoadStoreMultipleInstruction(const MachineInstr &MI);
118
119    void emitMulFrmInstruction(const MachineInstr &MI);
120
121    void emitExtendInstruction(const MachineInstr &MI);
122
123    void emitMiscArithInstruction(const MachineInstr &MI);
124
125    void emitBranchInstruction(const MachineInstr &MI);
126
127    void emitInlineJumpTable(unsigned JTIndex);
128
129    void emitMiscBranchInstruction(const MachineInstr &MI);
130
131    void emitVFPArithInstruction(const MachineInstr &MI);
132
133    void emitVFPConversionInstruction(const MachineInstr &MI);
134
135    void emitVFPLoadStoreInstruction(const MachineInstr &MI);
136
137    void emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI);
138
139    void emitMiscInstruction(const MachineInstr &MI);
140
141    /// getMachineOpValue - Return binary encoding of operand. If the machine
142    /// operand requires relocation, record the relocation and return zero.
143    unsigned getMachineOpValue(const MachineInstr &MI,const MachineOperand &MO);
144    unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) {
145      return getMachineOpValue(MI, MI.getOperand(OpIdx));
146    }
147
148    /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
149    ///
150    unsigned getShiftOp(unsigned Imm) const ;
151
152    /// Routines that handle operands which add machine relocations which are
153    /// fixed up by the relocation stage.
154    void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
155                           bool MayNeedFarStub,  bool Indirect,
156                           intptr_t ACPV = 0);
157    void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
158    void emitConstPoolAddress(unsigned CPI, unsigned Reloc);
159    void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc);
160    void emitMachineBasicBlock(MachineBasicBlock *BB, unsigned Reloc,
161                               intptr_t JTBase = 0);
162  };
163}
164
165char ARMCodeEmitter::ID = 0;
166
167/// createARMJITCodeEmitterPass - Return a pass that emits the collected ARM
168/// code to the specified MCE object.
169FunctionPass *llvm::createARMJITCodeEmitterPass(ARMBaseTargetMachine &TM,
170                                                JITCodeEmitter &JCE) {
171  return new ARMCodeEmitter(TM, JCE);
172}
173
174bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
175  assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
176          MF.getTarget().getRelocationModel() != Reloc::Static) &&
177         "JIT relocation model must be set to static or default!");
178  JTI = ((ARMTargetMachine &)MF.getTarget()).getJITInfo();
179  II = ((const ARMTargetMachine &)MF.getTarget()).getInstrInfo();
180  TD = ((const ARMTargetMachine &)MF.getTarget()).getTargetData();
181  Subtarget = &TM.getSubtarget<ARMSubtarget>();
182  MCPEs = &MF.getConstantPool()->getConstants();
183  MJTEs = 0;
184  if (MF.getJumpTableInfo()) MJTEs = &MF.getJumpTableInfo()->getJumpTables();
185  IsPIC = TM.getRelocationModel() == Reloc::PIC_;
186  JTI->Initialize(MF, IsPIC);
187  MMI = &getAnalysis<MachineModuleInfo>();
188  MCE.setModuleInfo(MMI);
189
190  do {
191    DEBUG(errs() << "JITTing function '"
192          << MF.getFunction()->getName() << "'\n");
193    MCE.startFunction(MF);
194    for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
195         MBB != E; ++MBB) {
196      MCE.StartMachineBasicBlock(MBB);
197      for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
198           I != E; ++I)
199        emitInstruction(*I);
200    }
201  } while (MCE.finishFunction(MF));
202
203  return false;
204}
205
206/// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
207///
208unsigned ARMCodeEmitter::getShiftOp(unsigned Imm) const {
209  switch (ARM_AM::getAM2ShiftOpc(Imm)) {
210  default: llvm_unreachable("Unknown shift opc!");
211  case ARM_AM::asr: return 2;
212  case ARM_AM::lsl: return 0;
213  case ARM_AM::lsr: return 1;
214  case ARM_AM::ror:
215  case ARM_AM::rrx: return 3;
216  }
217  return 0;
218}
219
220/// getMachineOpValue - Return binary encoding of operand. If the machine
221/// operand requires relocation, record the relocation and return zero.
222unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
223                                           const MachineOperand &MO) {
224  if (MO.isReg())
225    return ARMRegisterInfo::getRegisterNumbering(MO.getReg());
226  else if (MO.isImm())
227    return static_cast<unsigned>(MO.getImm());
228  else if (MO.isGlobal())
229    emitGlobalAddress(MO.getGlobal(), ARM::reloc_arm_branch, true, false);
230  else if (MO.isSymbol())
231    emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_branch);
232  else if (MO.isCPI()) {
233    const TargetInstrDesc &TID = MI.getDesc();
234    // For VFP load, the immediate offset is multiplied by 4.
235    unsigned Reloc =  ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPLdStFrm)
236      ? ARM::reloc_arm_vfp_cp_entry : ARM::reloc_arm_cp_entry;
237    emitConstPoolAddress(MO.getIndex(), Reloc);
238  } else if (MO.isJTI())
239    emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
240  else if (MO.isMBB())
241    emitMachineBasicBlock(MO.getMBB(), ARM::reloc_arm_branch);
242  else {
243#ifndef NDEBUG
244    errs() << MO;
245#endif
246    llvm_unreachable(0);
247  }
248  return 0;
249}
250
251/// emitGlobalAddress - Emit the specified address to the code stream.
252///
253void ARMCodeEmitter::emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
254                                       bool MayNeedFarStub, bool Indirect,
255                                       intptr_t ACPV) {
256  MachineRelocation MR = Indirect
257    ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
258                                           const_cast<GlobalValue *>(GV),
259                                           ACPV, MayNeedFarStub)
260    : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
261                               const_cast<GlobalValue *>(GV), ACPV,
262                               MayNeedFarStub);
263  MCE.addRelocation(MR);
264}
265
266/// emitExternalSymbolAddress - Arrange for the address of an external symbol to
267/// be emitted to the current location in the function, and allow it to be PC
268/// relative.
269void ARMCodeEmitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
270  MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
271                                                 Reloc, ES));
272}
273
274/// emitConstPoolAddress - Arrange for the address of an constant pool
275/// to be emitted to the current location in the function, and allow it to be PC
276/// relative.
277void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc) {
278  // Tell JIT emitter we'll resolve the address.
279  MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
280                                                    Reloc, CPI, 0, true));
281}
282
283/// emitJumpTableAddress - Arrange for the address of a jump table to
284/// be emitted to the current location in the function, and allow it to be PC
285/// relative.
286void ARMCodeEmitter::emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) {
287  MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
288                                                    Reloc, JTIndex, 0, true));
289}
290
291/// emitMachineBasicBlock - Emit the specified address basic block.
292void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
293                                           unsigned Reloc, intptr_t JTBase) {
294  MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
295                                             Reloc, BB, JTBase));
296}
297
298void ARMCodeEmitter::emitWordLE(unsigned Binary) {
299  DEBUG(errs() << "  0x";
300        errs().write_hex(Binary) << "\n");
301  MCE.emitWordLE(Binary);
302}
303
304void ARMCodeEmitter::emitDWordLE(uint64_t Binary) {
305  DEBUG(errs() << "  0x";
306        errs().write_hex(Binary) << "\n");
307  MCE.emitDWordLE(Binary);
308}
309
310void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
311  DEBUG(errs() << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI);
312
313  MCE.processDebugLoc(MI.getDebugLoc(), true);
314
315  NumEmitted++;  // Keep track of the # of mi's emitted
316  switch (MI.getDesc().TSFlags & ARMII::FormMask) {
317  default: {
318    llvm_unreachable("Unhandled instruction encoding format!");
319    break;
320  }
321  case ARMII::Pseudo:
322    emitPseudoInstruction(MI);
323    break;
324  case ARMII::DPFrm:
325  case ARMII::DPSoRegFrm:
326    emitDataProcessingInstruction(MI);
327    break;
328  case ARMII::LdFrm:
329  case ARMII::StFrm:
330    emitLoadStoreInstruction(MI);
331    break;
332  case ARMII::LdMiscFrm:
333  case ARMII::StMiscFrm:
334    emitMiscLoadStoreInstruction(MI);
335    break;
336  case ARMII::LdStMulFrm:
337    emitLoadStoreMultipleInstruction(MI);
338    break;
339  case ARMII::MulFrm:
340    emitMulFrmInstruction(MI);
341    break;
342  case ARMII::ExtFrm:
343    emitExtendInstruction(MI);
344    break;
345  case ARMII::ArithMiscFrm:
346    emitMiscArithInstruction(MI);
347    break;
348  case ARMII::BrFrm:
349    emitBranchInstruction(MI);
350    break;
351  case ARMII::BrMiscFrm:
352    emitMiscBranchInstruction(MI);
353    break;
354  // VFP instructions.
355  case ARMII::VFPUnaryFrm:
356  case ARMII::VFPBinaryFrm:
357    emitVFPArithInstruction(MI);
358    break;
359  case ARMII::VFPConv1Frm:
360  case ARMII::VFPConv2Frm:
361  case ARMII::VFPConv3Frm:
362  case ARMII::VFPConv4Frm:
363  case ARMII::VFPConv5Frm:
364    emitVFPConversionInstruction(MI);
365    break;
366  case ARMII::VFPLdStFrm:
367    emitVFPLoadStoreInstruction(MI);
368    break;
369  case ARMII::VFPLdStMulFrm:
370    emitVFPLoadStoreMultipleInstruction(MI);
371    break;
372  case ARMII::VFPMiscFrm:
373    emitMiscInstruction(MI);
374    break;
375  }
376  MCE.processDebugLoc(MI.getDebugLoc(), false);
377}
378
379void ARMCodeEmitter::emitConstPoolInstruction(const MachineInstr &MI) {
380  unsigned CPI = MI.getOperand(0).getImm();       // CP instruction index.
381  unsigned CPIndex = MI.getOperand(1).getIndex(); // Actual cp entry index.
382  const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
383
384  // Remember the CONSTPOOL_ENTRY address for later relocation.
385  JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
386
387  // Emit constpool island entry. In most cases, the actual values will be
388  // resolved and relocated after code emission.
389  if (MCPE.isMachineConstantPoolEntry()) {
390    ARMConstantPoolValue *ACPV =
391      static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
392
393    DEBUG(errs() << "  ** ARM constant pool #" << CPI << " @ "
394          << (void*)MCE.getCurrentPCValue() << " " << *ACPV << '\n');
395
396    assert(ACPV->isGlobalValue() && "unsupported constant pool value");
397    const GlobalValue *GV = ACPV->getGV();
398    if (GV) {
399      Reloc::Model RelocM = TM.getRelocationModel();
400      emitGlobalAddress(GV, ARM::reloc_arm_machine_cp_entry,
401                        isa<Function>(GV),
402                        Subtarget->GVIsIndirectSymbol(GV, RelocM),
403                        (intptr_t)ACPV);
404     } else  {
405      emitExternalSymbolAddress(ACPV->getSymbol(), ARM::reloc_arm_absolute);
406    }
407    emitWordLE(0);
408  } else {
409    const Constant *CV = MCPE.Val.ConstVal;
410
411    DEBUG({
412        errs() << "  ** Constant pool #" << CPI << " @ "
413               << (void*)MCE.getCurrentPCValue() << " ";
414        if (const Function *F = dyn_cast<Function>(CV))
415          errs() << F->getName();
416        else
417          errs() << *CV;
418        errs() << '\n';
419      });
420
421    if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
422      emitGlobalAddress(GV, ARM::reloc_arm_absolute, isa<Function>(GV), false);
423      emitWordLE(0);
424    } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
425      uint32_t Val = *(uint32_t*)CI->getValue().getRawData();
426      emitWordLE(Val);
427    } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
428      if (CFP->getType()->isFloatTy())
429        emitWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
430      else if (CFP->getType()->isDoubleTy())
431        emitDWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
432      else {
433        llvm_unreachable("Unable to handle this constantpool entry!");
434      }
435    } else {
436      llvm_unreachable("Unable to handle this constantpool entry!");
437    }
438  }
439}
440
441void ARMCodeEmitter::emitMOVi2piecesInstruction(const MachineInstr &MI) {
442  const MachineOperand &MO0 = MI.getOperand(0);
443  const MachineOperand &MO1 = MI.getOperand(1);
444  assert(MO1.isImm() && ARM_AM::isSOImmTwoPartVal(MO1.getImm()) &&
445                                                  "Not a valid so_imm value!");
446  unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO1.getImm());
447  unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO1.getImm());
448
449  // Emit the 'mov' instruction.
450  unsigned Binary = 0xd << 21;  // mov: Insts{24-21} = 0b1101
451
452  // Set the conditional execution predicate.
453  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
454
455  // Encode Rd.
456  Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
457
458  // Encode so_imm.
459  // Set bit I(25) to identify this is the immediate form of <shifter_op>
460  Binary |= 1 << ARMII::I_BitShift;
461  Binary |= getMachineSoImmOpValue(V1);
462  emitWordLE(Binary);
463
464  // Now the 'orr' instruction.
465  Binary = 0xc << 21;  // orr: Insts{24-21} = 0b1100
466
467  // Set the conditional execution predicate.
468  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
469
470  // Encode Rd.
471  Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
472
473  // Encode Rn.
474  Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRnShift;
475
476  // Encode so_imm.
477  // Set bit I(25) to identify this is the immediate form of <shifter_op>
478  Binary |= 1 << ARMII::I_BitShift;
479  Binary |= getMachineSoImmOpValue(V2);
480  emitWordLE(Binary);
481}
482
483void ARMCodeEmitter::emitLEApcrelJTInstruction(const MachineInstr &MI) {
484  // It's basically add r, pc, (LJTI - $+8)
485
486  const TargetInstrDesc &TID = MI.getDesc();
487
488  // Emit the 'add' instruction.
489  unsigned Binary = 0x4 << 21;  // add: Insts{24-31} = 0b0100
490
491  // Set the conditional execution predicate
492  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
493
494  // Encode S bit if MI modifies CPSR.
495  Binary |= getAddrModeSBit(MI, TID);
496
497  // Encode Rd.
498  Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
499
500  // Encode Rn which is PC.
501  Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::PC) << ARMII::RegRnShift;
502
503  // Encode the displacement.
504  Binary |= 1 << ARMII::I_BitShift;
505  emitJumpTableAddress(MI.getOperand(1).getIndex(), ARM::reloc_arm_jt_base);
506
507  emitWordLE(Binary);
508}
509
510void ARMCodeEmitter::emitPseudoMoveInstruction(const MachineInstr &MI) {
511  unsigned Opcode = MI.getDesc().Opcode;
512
513  // Part of binary is determined by TableGn.
514  unsigned Binary = getBinaryCodeForInstr(MI);
515
516  // Set the conditional execution predicate
517  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
518
519  // Encode S bit if MI modifies CPSR.
520  if (Opcode == ARM::MOVsrl_flag || Opcode == ARM::MOVsra_flag)
521    Binary |= 1 << ARMII::S_BitShift;
522
523  // Encode register def if there is one.
524  Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
525
526  // Encode the shift operation.
527  switch (Opcode) {
528  default: break;
529  case ARM::MOVrx:
530    // rrx
531    Binary |= 0x6 << 4;
532    break;
533  case ARM::MOVsrl_flag:
534    // lsr #1
535    Binary |= (0x2 << 4) | (1 << 7);
536    break;
537  case ARM::MOVsra_flag:
538    // asr #1
539    Binary |= (0x4 << 4) | (1 << 7);
540    break;
541  }
542
543  // Encode register Rm.
544  Binary |= getMachineOpValue(MI, 1);
545
546  emitWordLE(Binary);
547}
548
549void ARMCodeEmitter::addPCLabel(unsigned LabelID) {
550  DEBUG(errs() << "  ** LPC" << LabelID << " @ "
551        << (void*)MCE.getCurrentPCValue() << '\n');
552  JTI->addPCLabelAddr(LabelID, MCE.getCurrentPCValue());
553}
554
555void ARMCodeEmitter::emitPseudoInstruction(const MachineInstr &MI) {
556  unsigned Opcode = MI.getDesc().Opcode;
557  switch (Opcode) {
558  default:
559    llvm_unreachable("ARMCodeEmitter::emitPseudoInstruction");
560  // FIXME: Add support for MOVimm32.
561  case TargetOpcode::INLINEASM: {
562    // We allow inline assembler nodes with empty bodies - they can
563    // implicitly define registers, which is ok for JIT.
564    if (MI.getOperand(0).getSymbolName()[0]) {
565      report_fatal_error("JIT does not support inline asm!");
566    }
567    break;
568  }
569  case TargetOpcode::DBG_LABEL:
570  case TargetOpcode::EH_LABEL:
571    MCE.emitLabel(MI.getOperand(0).getMCSymbol());
572    break;
573  case TargetOpcode::IMPLICIT_DEF:
574  case TargetOpcode::KILL:
575    // Do nothing.
576    break;
577  case ARM::CONSTPOOL_ENTRY:
578    emitConstPoolInstruction(MI);
579    break;
580  case ARM::PICADD: {
581    // Remember of the address of the PC label for relocation later.
582    addPCLabel(MI.getOperand(2).getImm());
583    // PICADD is just an add instruction that implicitly read pc.
584    emitDataProcessingInstruction(MI, 0, ARM::PC);
585    break;
586  }
587  case ARM::PICLDR:
588  case ARM::PICLDRB:
589  case ARM::PICSTR:
590  case ARM::PICSTRB: {
591    // Remember of the address of the PC label for relocation later.
592    addPCLabel(MI.getOperand(2).getImm());
593    // These are just load / store instructions that implicitly read pc.
594    emitLoadStoreInstruction(MI, 0, ARM::PC);
595    break;
596  }
597  case ARM::PICLDRH:
598  case ARM::PICLDRSH:
599  case ARM::PICLDRSB:
600  case ARM::PICSTRH: {
601    // Remember of the address of the PC label for relocation later.
602    addPCLabel(MI.getOperand(2).getImm());
603    // These are just load / store instructions that implicitly read pc.
604    emitMiscLoadStoreInstruction(MI, ARM::PC);
605    break;
606  }
607  case ARM::MOVi2pieces:
608    // Two instructions to materialize a constant.
609    emitMOVi2piecesInstruction(MI);
610    break;
611  case ARM::LEApcrelJT:
612    // Materialize jumptable address.
613    emitLEApcrelJTInstruction(MI);
614    break;
615  case ARM::MOVrx:
616  case ARM::MOVsrl_flag:
617  case ARM::MOVsra_flag:
618    emitPseudoMoveInstruction(MI);
619    break;
620  }
621}
622
623unsigned ARMCodeEmitter::getMachineSoRegOpValue(const MachineInstr &MI,
624                                                const TargetInstrDesc &TID,
625                                                const MachineOperand &MO,
626                                                unsigned OpIdx) {
627  unsigned Binary = getMachineOpValue(MI, MO);
628
629  const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
630  const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
631  ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
632
633  // Encode the shift opcode.
634  unsigned SBits = 0;
635  unsigned Rs = MO1.getReg();
636  if (Rs) {
637    // Set shift operand (bit[7:4]).
638    // LSL - 0001
639    // LSR - 0011
640    // ASR - 0101
641    // ROR - 0111
642    // RRX - 0110 and bit[11:8] clear.
643    switch (SOpc) {
644    default: llvm_unreachable("Unknown shift opc!");
645    case ARM_AM::lsl: SBits = 0x1; break;
646    case ARM_AM::lsr: SBits = 0x3; break;
647    case ARM_AM::asr: SBits = 0x5; break;
648    case ARM_AM::ror: SBits = 0x7; break;
649    case ARM_AM::rrx: SBits = 0x6; break;
650    }
651  } else {
652    // Set shift operand (bit[6:4]).
653    // LSL - 000
654    // LSR - 010
655    // ASR - 100
656    // ROR - 110
657    switch (SOpc) {
658    default: llvm_unreachable("Unknown shift opc!");
659    case ARM_AM::lsl: SBits = 0x0; break;
660    case ARM_AM::lsr: SBits = 0x2; break;
661    case ARM_AM::asr: SBits = 0x4; break;
662    case ARM_AM::ror: SBits = 0x6; break;
663    }
664  }
665  Binary |= SBits << 4;
666  if (SOpc == ARM_AM::rrx)
667    return Binary;
668
669  // Encode the shift operation Rs or shift_imm (except rrx).
670  if (Rs) {
671    // Encode Rs bit[11:8].
672    assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
673    return Binary |
674      (ARMRegisterInfo::getRegisterNumbering(Rs) << ARMII::RegRsShift);
675  }
676
677  // Encode shift_imm bit[11:7].
678  return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
679}
680
681unsigned ARMCodeEmitter::getMachineSoImmOpValue(unsigned SoImm) {
682  int SoImmVal = ARM_AM::getSOImmVal(SoImm);
683  assert(SoImmVal != -1 && "Not a valid so_imm value!");
684
685  // Encode rotate_imm.
686  unsigned Binary = (ARM_AM::getSOImmValRot((unsigned)SoImmVal) >> 1)
687    << ARMII::SoRotImmShift;
688
689  // Encode immed_8.
690  Binary |= ARM_AM::getSOImmValImm((unsigned)SoImmVal);
691  return Binary;
692}
693
694unsigned ARMCodeEmitter::getAddrModeSBit(const MachineInstr &MI,
695                                         const TargetInstrDesc &TID) const {
696  for (unsigned i = MI.getNumOperands(), e = TID.getNumOperands(); i != e; --i){
697    const MachineOperand &MO = MI.getOperand(i-1);
698    if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)
699      return 1 << ARMII::S_BitShift;
700  }
701  return 0;
702}
703
704void ARMCodeEmitter::emitDataProcessingInstruction(const MachineInstr &MI,
705                                                   unsigned ImplicitRd,
706                                                   unsigned ImplicitRn) {
707  const TargetInstrDesc &TID = MI.getDesc();
708
709  if (TID.Opcode == ARM::BFC) {
710    report_fatal_error("ARMv6t2 JIT is not yet supported.");
711  }
712
713  // Part of binary is determined by TableGn.
714  unsigned Binary = getBinaryCodeForInstr(MI);
715
716  // Set the conditional execution predicate
717  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
718
719  // Encode S bit if MI modifies CPSR.
720  Binary |= getAddrModeSBit(MI, TID);
721
722  // Encode register def if there is one.
723  unsigned NumDefs = TID.getNumDefs();
724  unsigned OpIdx = 0;
725  if (NumDefs)
726    Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
727  else if (ImplicitRd)
728    // Special handling for implicit use (e.g. PC).
729    Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
730               << ARMII::RegRdShift);
731
732  // If this is a two-address operand, skip it. e.g. MOVCCr operand 1.
733  if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
734    ++OpIdx;
735
736  // Encode first non-shifter register operand if there is one.
737  bool isUnary = TID.TSFlags & ARMII::UnaryDP;
738  if (!isUnary) {
739    if (ImplicitRn)
740      // Special handling for implicit use (e.g. PC).
741      Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
742                 << ARMII::RegRnShift);
743    else {
744      Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
745      ++OpIdx;
746    }
747  }
748
749  // Encode shifter operand.
750  const MachineOperand &MO = MI.getOperand(OpIdx);
751  if ((TID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
752    // Encode SoReg.
753    emitWordLE(Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx));
754    return;
755  }
756
757  if (MO.isReg()) {
758    // Encode register Rm.
759    emitWordLE(Binary | ARMRegisterInfo::getRegisterNumbering(MO.getReg()));
760    return;
761  }
762
763  // Encode so_imm.
764  Binary |= getMachineSoImmOpValue((unsigned)MO.getImm());
765
766  emitWordLE(Binary);
767}
768
769void ARMCodeEmitter::emitLoadStoreInstruction(const MachineInstr &MI,
770                                              unsigned ImplicitRd,
771                                              unsigned ImplicitRn) {
772  const TargetInstrDesc &TID = MI.getDesc();
773  unsigned Form = TID.TSFlags & ARMII::FormMask;
774  bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
775
776  // Part of binary is determined by TableGn.
777  unsigned Binary = getBinaryCodeForInstr(MI);
778
779  // Set the conditional execution predicate
780  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
781
782  unsigned OpIdx = 0;
783
784  // Operand 0 of a pre- and post-indexed store is the address base
785  // writeback. Skip it.
786  bool Skipped = false;
787  if (IsPrePost && Form == ARMII::StFrm) {
788    ++OpIdx;
789    Skipped = true;
790  }
791
792  // Set first operand
793  if (ImplicitRd)
794    // Special handling for implicit use (e.g. PC).
795    Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
796               << ARMII::RegRdShift);
797  else
798    Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
799
800  // Set second operand
801  if (ImplicitRn)
802    // Special handling for implicit use (e.g. PC).
803    Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
804               << ARMII::RegRnShift);
805  else
806    Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
807
808  // If this is a two-address operand, skip it. e.g. LDR_PRE.
809  if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
810    ++OpIdx;
811
812  const MachineOperand &MO2 = MI.getOperand(OpIdx);
813  unsigned AM2Opc = (ImplicitRn == ARM::PC)
814    ? 0 : MI.getOperand(OpIdx+1).getImm();
815
816  // Set bit U(23) according to sign of immed value (positive or negative).
817  Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
818             ARMII::U_BitShift);
819  if (!MO2.getReg()) { // is immediate
820    if (ARM_AM::getAM2Offset(AM2Opc))
821      // Set the value of offset_12 field
822      Binary |= ARM_AM::getAM2Offset(AM2Opc);
823    emitWordLE(Binary);
824    return;
825  }
826
827  // Set bit I(25), because this is not in immediate enconding.
828  Binary |= 1 << ARMII::I_BitShift;
829  assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
830  // Set bit[3:0] to the corresponding Rm register
831  Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
832
833  // If this instr is in scaled register offset/index instruction, set
834  // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
835  if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
836    Binary |= getShiftOp(AM2Opc) << ARMII::ShiftImmShift;  // shift
837    Binary |= ShImm              << ARMII::ShiftShift;     // shift_immed
838  }
839
840  emitWordLE(Binary);
841}
842
843void ARMCodeEmitter::emitMiscLoadStoreInstruction(const MachineInstr &MI,
844                                                  unsigned ImplicitRn) {
845  const TargetInstrDesc &TID = MI.getDesc();
846  unsigned Form = TID.TSFlags & ARMII::FormMask;
847  bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
848
849  // Part of binary is determined by TableGn.
850  unsigned Binary = getBinaryCodeForInstr(MI);
851
852  // Set the conditional execution predicate
853  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
854
855  unsigned OpIdx = 0;
856
857  // Operand 0 of a pre- and post-indexed store is the address base
858  // writeback. Skip it.
859  bool Skipped = false;
860  if (IsPrePost && Form == ARMII::StMiscFrm) {
861    ++OpIdx;
862    Skipped = true;
863  }
864
865  // Set first operand
866  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
867
868  // Skip LDRD and STRD's second operand.
869  if (TID.Opcode == ARM::LDRD || TID.Opcode == ARM::STRD)
870    ++OpIdx;
871
872  // Set second operand
873  if (ImplicitRn)
874    // Special handling for implicit use (e.g. PC).
875    Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
876               << ARMII::RegRnShift);
877  else
878    Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
879
880  // If this is a two-address operand, skip it. e.g. LDRH_POST.
881  if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
882    ++OpIdx;
883
884  const MachineOperand &MO2 = MI.getOperand(OpIdx);
885  unsigned AM3Opc = (ImplicitRn == ARM::PC)
886    ? 0 : MI.getOperand(OpIdx+1).getImm();
887
888  // Set bit U(23) according to sign of immed value (positive or negative)
889  Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
890             ARMII::U_BitShift);
891
892  // If this instr is in register offset/index encoding, set bit[3:0]
893  // to the corresponding Rm register.
894  if (MO2.getReg()) {
895    Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
896    emitWordLE(Binary);
897    return;
898  }
899
900  // This instr is in immediate offset/index encoding, set bit 22 to 1.
901  Binary |= 1 << ARMII::AM3_I_BitShift;
902  if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
903    // Set operands
904    Binary |= (ImmOffs >> 4) << ARMII::ImmHiShift;  // immedH
905    Binary |= (ImmOffs & 0xF);                      // immedL
906  }
907
908  emitWordLE(Binary);
909}
910
911static unsigned getAddrModeUPBits(unsigned Mode) {
912  unsigned Binary = 0;
913
914  // Set addressing mode by modifying bits U(23) and P(24)
915  // IA - Increment after  - bit U = 1 and bit P = 0
916  // IB - Increment before - bit U = 1 and bit P = 1
917  // DA - Decrement after  - bit U = 0 and bit P = 0
918  // DB - Decrement before - bit U = 0 and bit P = 1
919  switch (Mode) {
920  default: llvm_unreachable("Unknown addressing sub-mode!");
921  case ARM_AM::da:                                     break;
922  case ARM_AM::db: Binary |= 0x1 << ARMII::P_BitShift; break;
923  case ARM_AM::ia: Binary |= 0x1 << ARMII::U_BitShift; break;
924  case ARM_AM::ib: Binary |= 0x3 << ARMII::U_BitShift; break;
925  }
926
927  return Binary;
928}
929
930void ARMCodeEmitter::emitLoadStoreMultipleInstruction(const MachineInstr &MI) {
931  const TargetInstrDesc &TID = MI.getDesc();
932  bool IsUpdating = (TID.TSFlags & ARMII::IndexModeMask) != 0;
933
934  // Part of binary is determined by TableGn.
935  unsigned Binary = getBinaryCodeForInstr(MI);
936
937  // Set the conditional execution predicate
938  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
939
940  // Skip operand 0 of an instruction with base register update.
941  unsigned OpIdx = 0;
942  if (IsUpdating)
943    ++OpIdx;
944
945  // Set base address operand
946  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
947
948  // Set addressing mode by modifying bits U(23) and P(24)
949  const MachineOperand &MO = MI.getOperand(OpIdx++);
950  Binary |= getAddrModeUPBits(ARM_AM::getAM4SubMode(MO.getImm()));
951
952  // Set bit W(21)
953  if (IsUpdating)
954    Binary |= 0x1 << ARMII::W_BitShift;
955
956  // Set registers
957  for (unsigned i = OpIdx+2, e = MI.getNumOperands(); i != e; ++i) {
958    const MachineOperand &MO = MI.getOperand(i);
959    if (!MO.isReg() || MO.isImplicit())
960      break;
961    unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
962    assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
963           RegNum < 16);
964    Binary |= 0x1 << RegNum;
965  }
966
967  emitWordLE(Binary);
968}
969
970void ARMCodeEmitter::emitMulFrmInstruction(const MachineInstr &MI) {
971  const TargetInstrDesc &TID = MI.getDesc();
972
973  // Part of binary is determined by TableGn.
974  unsigned Binary = getBinaryCodeForInstr(MI);
975
976  // Set the conditional execution predicate
977  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
978
979  // Encode S bit if MI modifies CPSR.
980  Binary |= getAddrModeSBit(MI, TID);
981
982  // 32x32->64bit operations have two destination registers. The number
983  // of register definitions will tell us if that's what we're dealing with.
984  unsigned OpIdx = 0;
985  if (TID.getNumDefs() == 2)
986    Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
987
988  // Encode Rd
989  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
990
991  // Encode Rm
992  Binary |= getMachineOpValue(MI, OpIdx++);
993
994  // Encode Rs
995  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
996
997  // Many multiple instructions (e.g. MLA) have three src operands. Encode
998  // it as Rn (for multiply, that's in the same offset as RdLo.
999  if (TID.getNumOperands() > OpIdx &&
1000      !TID.OpInfo[OpIdx].isPredicate() &&
1001      !TID.OpInfo[OpIdx].isOptionalDef())
1002    Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdLoShift;
1003
1004  emitWordLE(Binary);
1005}
1006
1007void ARMCodeEmitter::emitExtendInstruction(const MachineInstr &MI) {
1008  const TargetInstrDesc &TID = MI.getDesc();
1009
1010  // Part of binary is determined by TableGn.
1011  unsigned Binary = getBinaryCodeForInstr(MI);
1012
1013  // Set the conditional execution predicate
1014  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1015
1016  unsigned OpIdx = 0;
1017
1018  // Encode Rd
1019  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1020
1021  const MachineOperand &MO1 = MI.getOperand(OpIdx++);
1022  const MachineOperand &MO2 = MI.getOperand(OpIdx);
1023  if (MO2.isReg()) {
1024    // Two register operand form.
1025    // Encode Rn.
1026    Binary |= getMachineOpValue(MI, MO1) << ARMII::RegRnShift;
1027
1028    // Encode Rm.
1029    Binary |= getMachineOpValue(MI, MO2);
1030    ++OpIdx;
1031  } else {
1032    Binary |= getMachineOpValue(MI, MO1);
1033  }
1034
1035  // Encode rot imm (0, 8, 16, or 24) if it has a rotate immediate operand.
1036  if (MI.getOperand(OpIdx).isImm() &&
1037      !TID.OpInfo[OpIdx].isPredicate() &&
1038      !TID.OpInfo[OpIdx].isOptionalDef())
1039    Binary |= (getMachineOpValue(MI, OpIdx) / 8) << ARMII::ExtRotImmShift;
1040
1041  emitWordLE(Binary);
1042}
1043
1044void ARMCodeEmitter::emitMiscArithInstruction(const MachineInstr &MI) {
1045  const TargetInstrDesc &TID = MI.getDesc();
1046
1047  // Part of binary is determined by TableGn.
1048  unsigned Binary = getBinaryCodeForInstr(MI);
1049
1050  // Set the conditional execution predicate
1051  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1052
1053  unsigned OpIdx = 0;
1054
1055  // Encode Rd
1056  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1057
1058  const MachineOperand &MO = MI.getOperand(OpIdx++);
1059  if (OpIdx == TID.getNumOperands() ||
1060      TID.OpInfo[OpIdx].isPredicate() ||
1061      TID.OpInfo[OpIdx].isOptionalDef()) {
1062    // Encode Rm and it's done.
1063    Binary |= getMachineOpValue(MI, MO);
1064    emitWordLE(Binary);
1065    return;
1066  }
1067
1068  // Encode Rn.
1069  Binary |= getMachineOpValue(MI, MO) << ARMII::RegRnShift;
1070
1071  // Encode Rm.
1072  Binary |= getMachineOpValue(MI, OpIdx++);
1073
1074  // Encode shift_imm.
1075  unsigned ShiftAmt = MI.getOperand(OpIdx).getImm();
1076  assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
1077  Binary |= ShiftAmt << ARMII::ShiftShift;
1078
1079  emitWordLE(Binary);
1080}
1081
1082void ARMCodeEmitter::emitBranchInstruction(const MachineInstr &MI) {
1083  const TargetInstrDesc &TID = MI.getDesc();
1084
1085  if (TID.Opcode == ARM::TPsoft) {
1086    llvm_unreachable("ARM::TPsoft FIXME"); // FIXME
1087  }
1088
1089  // Part of binary is determined by TableGn.
1090  unsigned Binary = getBinaryCodeForInstr(MI);
1091
1092  // Set the conditional execution predicate
1093  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1094
1095  // Set signed_immed_24 field
1096  Binary |= getMachineOpValue(MI, 0);
1097
1098  emitWordLE(Binary);
1099}
1100
1101void ARMCodeEmitter::emitInlineJumpTable(unsigned JTIndex) {
1102  // Remember the base address of the inline jump table.
1103  uintptr_t JTBase = MCE.getCurrentPCValue();
1104  JTI->addJumpTableBaseAddr(JTIndex, JTBase);
1105  DEBUG(errs() << "  ** Jump Table #" << JTIndex << " @ " << (void*)JTBase
1106               << '\n');
1107
1108  // Now emit the jump table entries.
1109  const std::vector<MachineBasicBlock*> &MBBs = (*MJTEs)[JTIndex].MBBs;
1110  for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
1111    if (IsPIC)
1112      // DestBB address - JT base.
1113      emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_pic_jt, JTBase);
1114    else
1115      // Absolute DestBB address.
1116      emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_absolute);
1117    emitWordLE(0);
1118  }
1119}
1120
1121void ARMCodeEmitter::emitMiscBranchInstruction(const MachineInstr &MI) {
1122  const TargetInstrDesc &TID = MI.getDesc();
1123
1124  // Handle jump tables.
1125  if (TID.Opcode == ARM::BR_JTr || TID.Opcode == ARM::BR_JTadd) {
1126    // First emit a ldr pc, [] instruction.
1127    emitDataProcessingInstruction(MI, ARM::PC);
1128
1129    // Then emit the inline jump table.
1130    unsigned JTIndex =
1131      (TID.Opcode == ARM::BR_JTr)
1132      ? MI.getOperand(1).getIndex() : MI.getOperand(2).getIndex();
1133    emitInlineJumpTable(JTIndex);
1134    return;
1135  } else if (TID.Opcode == ARM::BR_JTm) {
1136    // First emit a ldr pc, [] instruction.
1137    emitLoadStoreInstruction(MI, ARM::PC);
1138
1139    // Then emit the inline jump table.
1140    emitInlineJumpTable(MI.getOperand(3).getIndex());
1141    return;
1142  }
1143
1144  // Part of binary is determined by TableGn.
1145  unsigned Binary = getBinaryCodeForInstr(MI);
1146
1147  // Set the conditional execution predicate
1148  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1149
1150  if (TID.Opcode == ARM::BX_RET || TID.Opcode == ARM::MOVPCLR)
1151    // The return register is LR.
1152    Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::LR);
1153  else
1154    // otherwise, set the return register
1155    Binary |= getMachineOpValue(MI, 0);
1156
1157  emitWordLE(Binary);
1158}
1159
1160static unsigned encodeVFPRd(const MachineInstr &MI, unsigned OpIdx) {
1161  unsigned RegD = MI.getOperand(OpIdx).getReg();
1162  unsigned Binary = 0;
1163  bool isSPVFP = false;
1164  RegD = ARMRegisterInfo::getRegisterNumbering(RegD, &isSPVFP);
1165  if (!isSPVFP)
1166    Binary |=   RegD               << ARMII::RegRdShift;
1167  else {
1168    Binary |= ((RegD & 0x1E) >> 1) << ARMII::RegRdShift;
1169    Binary |=  (RegD & 0x01)       << ARMII::D_BitShift;
1170  }
1171  return Binary;
1172}
1173
1174static unsigned encodeVFPRn(const MachineInstr &MI, unsigned OpIdx) {
1175  unsigned RegN = MI.getOperand(OpIdx).getReg();
1176  unsigned Binary = 0;
1177  bool isSPVFP = false;
1178  RegN = ARMRegisterInfo::getRegisterNumbering(RegN, &isSPVFP);
1179  if (!isSPVFP)
1180    Binary |=   RegN               << ARMII::RegRnShift;
1181  else {
1182    Binary |= ((RegN & 0x1E) >> 1) << ARMII::RegRnShift;
1183    Binary |=  (RegN & 0x01)       << ARMII::N_BitShift;
1184  }
1185  return Binary;
1186}
1187
1188static unsigned encodeVFPRm(const MachineInstr &MI, unsigned OpIdx) {
1189  unsigned RegM = MI.getOperand(OpIdx).getReg();
1190  unsigned Binary = 0;
1191  bool isSPVFP = false;
1192  RegM = ARMRegisterInfo::getRegisterNumbering(RegM, &isSPVFP);
1193  if (!isSPVFP)
1194    Binary |=   RegM;
1195  else {
1196    Binary |= ((RegM & 0x1E) >> 1);
1197    Binary |=  (RegM & 0x01)       << ARMII::M_BitShift;
1198  }
1199  return Binary;
1200}
1201
1202void ARMCodeEmitter::emitVFPArithInstruction(const MachineInstr &MI) {
1203  const TargetInstrDesc &TID = MI.getDesc();
1204
1205  // Part of binary is determined by TableGn.
1206  unsigned Binary = getBinaryCodeForInstr(MI);
1207
1208  // Set the conditional execution predicate
1209  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1210
1211  unsigned OpIdx = 0;
1212  assert((Binary & ARMII::D_BitShift) == 0 &&
1213         (Binary & ARMII::N_BitShift) == 0 &&
1214         (Binary & ARMII::M_BitShift) == 0 && "VFP encoding bug!");
1215
1216  // Encode Dd / Sd.
1217  Binary |= encodeVFPRd(MI, OpIdx++);
1218
1219  // If this is a two-address operand, skip it, e.g. FMACD.
1220  if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1221    ++OpIdx;
1222
1223  // Encode Dn / Sn.
1224  if ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPBinaryFrm)
1225    Binary |= encodeVFPRn(MI, OpIdx++);
1226
1227  if (OpIdx == TID.getNumOperands() ||
1228      TID.OpInfo[OpIdx].isPredicate() ||
1229      TID.OpInfo[OpIdx].isOptionalDef()) {
1230    // FCMPEZD etc. has only one operand.
1231    emitWordLE(Binary);
1232    return;
1233  }
1234
1235  // Encode Dm / Sm.
1236  Binary |= encodeVFPRm(MI, OpIdx);
1237
1238  emitWordLE(Binary);
1239}
1240
1241void ARMCodeEmitter::emitVFPConversionInstruction(const MachineInstr &MI) {
1242  const TargetInstrDesc &TID = MI.getDesc();
1243  unsigned Form = TID.TSFlags & ARMII::FormMask;
1244
1245  // Part of binary is determined by TableGn.
1246  unsigned Binary = getBinaryCodeForInstr(MI);
1247
1248  // Set the conditional execution predicate
1249  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1250
1251  switch (Form) {
1252  default: break;
1253  case ARMII::VFPConv1Frm:
1254  case ARMII::VFPConv2Frm:
1255  case ARMII::VFPConv3Frm:
1256    // Encode Dd / Sd.
1257    Binary |= encodeVFPRd(MI, 0);
1258    break;
1259  case ARMII::VFPConv4Frm:
1260    // Encode Dn / Sn.
1261    Binary |= encodeVFPRn(MI, 0);
1262    break;
1263  case ARMII::VFPConv5Frm:
1264    // Encode Dm / Sm.
1265    Binary |= encodeVFPRm(MI, 0);
1266    break;
1267  }
1268
1269  switch (Form) {
1270  default: break;
1271  case ARMII::VFPConv1Frm:
1272    // Encode Dm / Sm.
1273    Binary |= encodeVFPRm(MI, 1);
1274    break;
1275  case ARMII::VFPConv2Frm:
1276  case ARMII::VFPConv3Frm:
1277    // Encode Dn / Sn.
1278    Binary |= encodeVFPRn(MI, 1);
1279    break;
1280  case ARMII::VFPConv4Frm:
1281  case ARMII::VFPConv5Frm:
1282    // Encode Dd / Sd.
1283    Binary |= encodeVFPRd(MI, 1);
1284    break;
1285  }
1286
1287  if (Form == ARMII::VFPConv5Frm)
1288    // Encode Dn / Sn.
1289    Binary |= encodeVFPRn(MI, 2);
1290  else if (Form == ARMII::VFPConv3Frm)
1291    // Encode Dm / Sm.
1292    Binary |= encodeVFPRm(MI, 2);
1293
1294  emitWordLE(Binary);
1295}
1296
1297void ARMCodeEmitter::emitVFPLoadStoreInstruction(const MachineInstr &MI) {
1298  // Part of binary is determined by TableGn.
1299  unsigned Binary = getBinaryCodeForInstr(MI);
1300
1301  // Set the conditional execution predicate
1302  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1303
1304  unsigned OpIdx = 0;
1305
1306  // Encode Dd / Sd.
1307  Binary |= encodeVFPRd(MI, OpIdx++);
1308
1309  // Encode address base.
1310  const MachineOperand &Base = MI.getOperand(OpIdx++);
1311  Binary |= getMachineOpValue(MI, Base) << ARMII::RegRnShift;
1312
1313  // If there is a non-zero immediate offset, encode it.
1314  if (Base.isReg()) {
1315    const MachineOperand &Offset = MI.getOperand(OpIdx);
1316    if (unsigned ImmOffs = ARM_AM::getAM5Offset(Offset.getImm())) {
1317      if (ARM_AM::getAM5Op(Offset.getImm()) == ARM_AM::add)
1318        Binary |= 1 << ARMII::U_BitShift;
1319      Binary |= ImmOffs;
1320      emitWordLE(Binary);
1321      return;
1322    }
1323  }
1324
1325  // If immediate offset is omitted, default to +0.
1326  Binary |= 1 << ARMII::U_BitShift;
1327
1328  emitWordLE(Binary);
1329}
1330
1331void
1332ARMCodeEmitter::emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI) {
1333  const TargetInstrDesc &TID = MI.getDesc();
1334  bool IsUpdating = (TID.TSFlags & ARMII::IndexModeMask) != 0;
1335
1336  // Part of binary is determined by TableGn.
1337  unsigned Binary = getBinaryCodeForInstr(MI);
1338
1339  // Set the conditional execution predicate
1340  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1341
1342  // Skip operand 0 of an instruction with base register update.
1343  unsigned OpIdx = 0;
1344  if (IsUpdating)
1345    ++OpIdx;
1346
1347  // Set base address operand
1348  Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1349
1350  // Set addressing mode by modifying bits U(23) and P(24)
1351  const MachineOperand &MO = MI.getOperand(OpIdx++);
1352  Binary |= getAddrModeUPBits(ARM_AM::getAM5SubMode(MO.getImm()));
1353
1354  // Set bit W(21)
1355  if (IsUpdating)
1356    Binary |= 0x1 << ARMII::W_BitShift;
1357
1358  // First register is encoded in Dd.
1359  Binary |= encodeVFPRd(MI, OpIdx+2);
1360
1361  // Number of registers are encoded in offset field.
1362  unsigned NumRegs = 1;
1363  for (unsigned i = OpIdx+3, e = MI.getNumOperands(); i != e; ++i) {
1364    const MachineOperand &MO = MI.getOperand(i);
1365    if (!MO.isReg() || MO.isImplicit())
1366      break;
1367    ++NumRegs;
1368  }
1369  Binary |= NumRegs * 2;
1370
1371  emitWordLE(Binary);
1372}
1373
1374void ARMCodeEmitter::emitMiscInstruction(const MachineInstr &MI) {
1375  // Part of binary is determined by TableGn.
1376  unsigned Binary = getBinaryCodeForInstr(MI);
1377
1378  // Set the conditional execution predicate
1379  Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1380
1381  emitWordLE(Binary);
1382}
1383
1384#include "ARMGenCodeEmitter.inc"
1385