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