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