Adding the missing implementation for ARM::SBFX and ARM::UBFX.
[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   // Part of binary is determined by TableGn.
785   unsigned Binary = getBinaryCodeForInstr(MI);
786
787   // Set the conditional execution predicate
788   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
789
790   // Encode S bit if MI modifies CPSR.
791   Binary |= getAddrModeSBit(MI, TID);
792
793   // Encode register def if there is one.
794   unsigned NumDefs = TID.getNumDefs();
795   unsigned OpIdx = 0;
796   if (NumDefs)
797     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
798   else if (ImplicitRd)
799     // Special handling for implicit use (e.g. PC).
800     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
801                << ARMII::RegRdShift);
802
803   if (TID.Opcode == ARM::MOVi16) {
804       // Get immediate from MI.
805       unsigned Lo16 = getMovi32Value(MI, MI.getOperand(OpIdx),
806                       ARM::reloc_arm_movw);
807       // Encode imm which is the same as in emitMOVi32immInstruction().
808       Binary |= Lo16 & 0xFFF;
809       Binary |= ((Lo16 >> 12) & 0xF) << 16;
810       emitWordLE(Binary);
811       return;
812   } else if(TID.Opcode == ARM::MOVTi16) {
813       unsigned Hi16 = (getMovi32Value(MI, MI.getOperand(OpIdx),
814                        ARM::reloc_arm_movt) >> 16);
815       Binary |= Hi16 & 0xFFF;
816       Binary |= ((Hi16 >> 12) & 0xF) << 16;
817       emitWordLE(Binary);
818       return;
819   } else if((TID.Opcode == ARM::BFC) || (TID.Opcode == ARM::BFI)) {
820       uint32_t v = ~MI.getOperand(2).getImm();
821       int32_t lsb = CountTrailingZeros_32(v);
822       int32_t msb = (32 - CountLeadingZeros_32(v)) - 1;
823       // Instr{20-16} = msb, Instr{11-7} = lsb
824       Binary |= (msb & 0x1F) << 16;
825       Binary |= (lsb & 0x1F) << 7;
826       emitWordLE(Binary);
827       return;
828   } else if ((TID.Opcode == ARM::UBFX) || (TID.Opcode == ARM::SBFX)) {
829       // Encode Rn in Instr{0-3}
830       Binary |= getMachineOpValue(MI, OpIdx++);
831
832       uint32_t lsb = MI.getOperand(OpIdx++).getImm();
833       uint32_t widthm1 = MI.getOperand(OpIdx++).getImm() - 1;
834
835       // Instr{20-16} = widthm1, Instr{11-7} = lsb
836       Binary |= (widthm1 & 0x1F) << 16;
837       Binary |= (lsb & 0x1F) << 7;
838       emitWordLE(Binary);
839       return;
840   }
841
842   // If this is a two-address operand, skip it. e.g. MOVCCr operand 1.
843   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
844     ++OpIdx;
845
846   // Encode first non-shifter register operand if there is one.
847   bool isUnary = TID.TSFlags & ARMII::UnaryDP;
848   if (!isUnary) {
849     if (ImplicitRn)
850       // Special handling for implicit use (e.g. PC).
851       Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
852                  << ARMII::RegRnShift);
853     else {
854       Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
855       ++OpIdx;
856     }
857   }
858
859   // Encode shifter operand.
860   const MachineOperand &MO = MI.getOperand(OpIdx);
861   if ((TID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
862     // Encode SoReg.
863     emitWordLE(Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx));
864     return;
865   }
866
867   if (MO.isReg()) {
868     // Encode register Rm.
869     emitWordLE(Binary | ARMRegisterInfo::getRegisterNumbering(MO.getReg()));
870     return;
871   }
872
873   // Encode so_imm.
874   Binary |= getMachineSoImmOpValue((unsigned)MO.getImm());
875
876   emitWordLE(Binary);
877 }
878
879 void ARMCodeEmitter::emitLoadStoreInstruction(const MachineInstr &MI,
880                                               unsigned ImplicitRd,
881                                               unsigned ImplicitRn) {
882   const TargetInstrDesc &TID = MI.getDesc();
883   unsigned Form = TID.TSFlags & ARMII::FormMask;
884   bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
885
886   // Part of binary is determined by TableGn.
887   unsigned Binary = getBinaryCodeForInstr(MI);
888
889   // Set the conditional execution predicate
890   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
891
892   unsigned OpIdx = 0;
893
894   // Operand 0 of a pre- and post-indexed store is the address base
895   // writeback. Skip it.
896   bool Skipped = false;
897   if (IsPrePost && Form == ARMII::StFrm) {
898     ++OpIdx;
899     Skipped = true;
900   }
901
902   // Set first operand
903   if (ImplicitRd)
904     // Special handling for implicit use (e.g. PC).
905     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRd)
906                << ARMII::RegRdShift);
907   else
908     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
909
910   // Set second operand
911   if (ImplicitRn)
912     // Special handling for implicit use (e.g. PC).
913     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
914                << ARMII::RegRnShift);
915   else
916     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
917
918   // If this is a two-address operand, skip it. e.g. LDR_PRE.
919   if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
920     ++OpIdx;
921
922   const MachineOperand &MO2 = MI.getOperand(OpIdx);
923   unsigned AM2Opc = (ImplicitRn == ARM::PC)
924     ? 0 : MI.getOperand(OpIdx+1).getImm();
925
926   // Set bit U(23) according to sign of immed value (positive or negative).
927   Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
928              ARMII::U_BitShift);
929   if (!MO2.getReg()) { // is immediate
930     if (ARM_AM::getAM2Offset(AM2Opc))
931       // Set the value of offset_12 field
932       Binary |= ARM_AM::getAM2Offset(AM2Opc);
933     emitWordLE(Binary);
934     return;
935   }
936
937   // Set bit I(25), because this is not in immediate enconding.
938   Binary |= 1 << ARMII::I_BitShift;
939   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
940   // Set bit[3:0] to the corresponding Rm register
941   Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
942
943   // If this instr is in scaled register offset/index instruction, set
944   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
945   if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
946     Binary |= getShiftOp(AM2Opc) << ARMII::ShiftImmShift;  // shift
947     Binary |= ShImm              << ARMII::ShiftShift;     // shift_immed
948   }
949
950   emitWordLE(Binary);
951 }
952
953 void ARMCodeEmitter::emitMiscLoadStoreInstruction(const MachineInstr &MI,
954                                                   unsigned ImplicitRn) {
955   const TargetInstrDesc &TID = MI.getDesc();
956   unsigned Form = TID.TSFlags & ARMII::FormMask;
957   bool IsPrePost = (TID.TSFlags & ARMII::IndexModeMask) != 0;
958
959   // Part of binary is determined by TableGn.
960   unsigned Binary = getBinaryCodeForInstr(MI);
961
962   // Set the conditional execution predicate
963   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
964
965   unsigned OpIdx = 0;
966
967   // Operand 0 of a pre- and post-indexed store is the address base
968   // writeback. Skip it.
969   bool Skipped = false;
970   if (IsPrePost && Form == ARMII::StMiscFrm) {
971     ++OpIdx;
972     Skipped = true;
973   }
974
975   // Set first operand
976   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
977
978   // Skip LDRD and STRD's second operand.
979   if (TID.Opcode == ARM::LDRD || TID.Opcode == ARM::STRD)
980     ++OpIdx;
981
982   // Set second operand
983   if (ImplicitRn)
984     // Special handling for implicit use (e.g. PC).
985     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
986                << ARMII::RegRnShift);
987   else
988     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
989
990   // If this is a two-address operand, skip it. e.g. LDRH_POST.
991   if (!Skipped && TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
992     ++OpIdx;
993
994   const MachineOperand &MO2 = MI.getOperand(OpIdx);
995   unsigned AM3Opc = (ImplicitRn == ARM::PC)
996     ? 0 : MI.getOperand(OpIdx+1).getImm();
997
998   // Set bit U(23) according to sign of immed value (positive or negative)
999   Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
1000              ARMII::U_BitShift);
1001
1002   // If this instr is in register offset/index encoding, set bit[3:0]
1003   // to the corresponding Rm register.
1004   if (MO2.getReg()) {
1005     Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
1006     emitWordLE(Binary);
1007     return;
1008   }
1009
1010   // This instr is in immediate offset/index encoding, set bit 22 to 1.
1011   Binary |= 1 << ARMII::AM3_I_BitShift;
1012   if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
1013     // Set operands
1014     Binary |= (ImmOffs >> 4) << ARMII::ImmHiShift;  // immedH
1015     Binary |= (ImmOffs & 0xF);                      // immedL
1016   }
1017
1018   emitWordLE(Binary);
1019 }
1020
1021 static unsigned getAddrModeUPBits(unsigned Mode) {
1022   unsigned Binary = 0;
1023
1024   // Set addressing mode by modifying bits U(23) and P(24)
1025   // IA - Increment after  - bit U = 1 and bit P = 0
1026   // IB - Increment before - bit U = 1 and bit P = 1
1027   // DA - Decrement after  - bit U = 0 and bit P = 0
1028   // DB - Decrement before - bit U = 0 and bit P = 1
1029   switch (Mode) {
1030   default: llvm_unreachable("Unknown addressing sub-mode!");
1031   case ARM_AM::da:                                     break;
1032   case ARM_AM::db: Binary |= 0x1 << ARMII::P_BitShift; break;
1033   case ARM_AM::ia: Binary |= 0x1 << ARMII::U_BitShift; break;
1034   case ARM_AM::ib: Binary |= 0x3 << ARMII::U_BitShift; break;
1035   }
1036
1037   return Binary;
1038 }
1039
1040 void ARMCodeEmitter::emitLoadStoreMultipleInstruction(const MachineInstr &MI) {
1041   const TargetInstrDesc &TID = MI.getDesc();
1042   bool IsUpdating = (TID.TSFlags & ARMII::IndexModeMask) != 0;
1043
1044   // Part of binary is determined by TableGn.
1045   unsigned Binary = getBinaryCodeForInstr(MI);
1046
1047   // Set the conditional execution predicate
1048   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1049
1050   // Skip operand 0 of an instruction with base register update.
1051   unsigned OpIdx = 0;
1052   if (IsUpdating)
1053     ++OpIdx;
1054
1055   // Set base address operand
1056   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1057
1058   // Set addressing mode by modifying bits U(23) and P(24)
1059   const MachineOperand &MO = MI.getOperand(OpIdx++);
1060   Binary |= getAddrModeUPBits(ARM_AM::getAM4SubMode(MO.getImm()));
1061
1062   // Set bit W(21)
1063   if (IsUpdating)
1064     Binary |= 0x1 << ARMII::W_BitShift;
1065
1066   // Set registers
1067   for (unsigned i = OpIdx+2, e = MI.getNumOperands(); i != e; ++i) {
1068     const MachineOperand &MO = MI.getOperand(i);
1069     if (!MO.isReg() || MO.isImplicit())
1070       break;
1071     unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
1072     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
1073            RegNum < 16);
1074     Binary |= 0x1 << RegNum;
1075   }
1076
1077   emitWordLE(Binary);
1078 }
1079
1080 void ARMCodeEmitter::emitMulFrmInstruction(const MachineInstr &MI) {
1081   const TargetInstrDesc &TID = MI.getDesc();
1082
1083   // Part of binary is determined by TableGn.
1084   unsigned Binary = getBinaryCodeForInstr(MI);
1085
1086   // Set the conditional execution predicate
1087   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1088
1089   // Encode S bit if MI modifies CPSR.
1090   Binary |= getAddrModeSBit(MI, TID);
1091
1092   // 32x32->64bit operations have two destination registers. The number
1093   // of register definitions will tell us if that's what we're dealing with.
1094   unsigned OpIdx = 0;
1095   if (TID.getNumDefs() == 2)
1096     Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
1097
1098   // Encode Rd
1099   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
1100
1101   // Encode Rm
1102   Binary |= getMachineOpValue(MI, OpIdx++);
1103
1104   // Encode Rs
1105   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
1106
1107   // Many multiple instructions (e.g. MLA) have three src operands. Encode
1108   // it as Rn (for multiply, that's in the same offset as RdLo.
1109   if (TID.getNumOperands() > OpIdx &&
1110       !TID.OpInfo[OpIdx].isPredicate() &&
1111       !TID.OpInfo[OpIdx].isOptionalDef())
1112     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdLoShift;
1113
1114   emitWordLE(Binary);
1115 }
1116
1117 void ARMCodeEmitter::emitExtendInstruction(const MachineInstr &MI) {
1118   const TargetInstrDesc &TID = MI.getDesc();
1119
1120   // Part of binary is determined by TableGn.
1121   unsigned Binary = getBinaryCodeForInstr(MI);
1122
1123   // Set the conditional execution predicate
1124   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1125
1126   unsigned OpIdx = 0;
1127
1128   // Encode Rd
1129   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1130
1131   const MachineOperand &MO1 = MI.getOperand(OpIdx++);
1132   const MachineOperand &MO2 = MI.getOperand(OpIdx);
1133   if (MO2.isReg()) {
1134     // Two register operand form.
1135     // Encode Rn.
1136     Binary |= getMachineOpValue(MI, MO1) << ARMII::RegRnShift;
1137
1138     // Encode Rm.
1139     Binary |= getMachineOpValue(MI, MO2);
1140     ++OpIdx;
1141   } else {
1142     Binary |= getMachineOpValue(MI, MO1);
1143   }
1144
1145   // Encode rot imm (0, 8, 16, or 24) if it has a rotate immediate operand.
1146   if (MI.getOperand(OpIdx).isImm() &&
1147       !TID.OpInfo[OpIdx].isPredicate() &&
1148       !TID.OpInfo[OpIdx].isOptionalDef())
1149     Binary |= (getMachineOpValue(MI, OpIdx) / 8) << ARMII::ExtRotImmShift;
1150
1151   emitWordLE(Binary);
1152 }
1153
1154 void ARMCodeEmitter::emitMiscArithInstruction(const MachineInstr &MI) {
1155   const TargetInstrDesc &TID = MI.getDesc();
1156
1157   // Part of binary is determined by TableGn.
1158   unsigned Binary = getBinaryCodeForInstr(MI);
1159
1160   // Set the conditional execution predicate
1161   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1162
1163   unsigned OpIdx = 0;
1164
1165   // Encode Rd
1166   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1167
1168   const MachineOperand &MO = MI.getOperand(OpIdx++);
1169   if (OpIdx == TID.getNumOperands() ||
1170       TID.OpInfo[OpIdx].isPredicate() ||
1171       TID.OpInfo[OpIdx].isOptionalDef()) {
1172     // Encode Rm and it's done.
1173     Binary |= getMachineOpValue(MI, MO);
1174     emitWordLE(Binary);
1175     return;
1176   }
1177
1178   // Encode Rn.
1179   Binary |= getMachineOpValue(MI, MO) << ARMII::RegRnShift;
1180
1181   // Encode Rm.
1182   Binary |= getMachineOpValue(MI, OpIdx++);
1183
1184   // Encode shift_imm.
1185   unsigned ShiftAmt = MI.getOperand(OpIdx).getImm();
1186   assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
1187   Binary |= ShiftAmt << ARMII::ShiftShift;
1188
1189   emitWordLE(Binary);
1190 }
1191
1192 void ARMCodeEmitter::emitBranchInstruction(const MachineInstr &MI) {
1193   const TargetInstrDesc &TID = MI.getDesc();
1194
1195   if (TID.Opcode == ARM::TPsoft) {
1196     llvm_unreachable("ARM::TPsoft FIXME"); // FIXME
1197   }
1198
1199   // Part of binary is determined by TableGn.
1200   unsigned Binary = getBinaryCodeForInstr(MI);
1201
1202   // Set the conditional execution predicate
1203   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1204
1205   // Set signed_immed_24 field
1206   Binary |= getMachineOpValue(MI, 0);
1207
1208   emitWordLE(Binary);
1209 }
1210
1211 void ARMCodeEmitter::emitInlineJumpTable(unsigned JTIndex) {
1212   // Remember the base address of the inline jump table.
1213   uintptr_t JTBase = MCE.getCurrentPCValue();
1214   JTI->addJumpTableBaseAddr(JTIndex, JTBase);
1215   DEBUG(errs() << "  ** Jump Table #" << JTIndex << " @ " << (void*)JTBase
1216                << '\n');
1217
1218   // Now emit the jump table entries.
1219   const std::vector<MachineBasicBlock*> &MBBs = (*MJTEs)[JTIndex].MBBs;
1220   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
1221     if (IsPIC)
1222       // DestBB address - JT base.
1223       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_pic_jt, JTBase);
1224     else
1225       // Absolute DestBB address.
1226       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_absolute);
1227     emitWordLE(0);
1228   }
1229 }
1230
1231 void ARMCodeEmitter::emitMiscBranchInstruction(const MachineInstr &MI) {
1232   const TargetInstrDesc &TID = MI.getDesc();
1233
1234   // Handle jump tables.
1235   if (TID.Opcode == ARM::BR_JTr || TID.Opcode == ARM::BR_JTadd) {
1236     // First emit a ldr pc, [] instruction.
1237     emitDataProcessingInstruction(MI, ARM::PC);
1238
1239     // Then emit the inline jump table.
1240     unsigned JTIndex =
1241       (TID.Opcode == ARM::BR_JTr)
1242       ? MI.getOperand(1).getIndex() : MI.getOperand(2).getIndex();
1243     emitInlineJumpTable(JTIndex);
1244     return;
1245   } else if (TID.Opcode == ARM::BR_JTm) {
1246     // First emit a ldr pc, [] instruction.
1247     emitLoadStoreInstruction(MI, ARM::PC);
1248
1249     // Then emit the inline jump table.
1250     emitInlineJumpTable(MI.getOperand(3).getIndex());
1251     return;
1252   }
1253
1254   // Part of binary is determined by TableGn.
1255   unsigned Binary = getBinaryCodeForInstr(MI);
1256
1257   // Set the conditional execution predicate
1258   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1259
1260   if (TID.Opcode == ARM::BX_RET || TID.Opcode == ARM::MOVPCLR)
1261     // The return register is LR.
1262     Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::LR);
1263   else
1264     // otherwise, set the return register
1265     Binary |= getMachineOpValue(MI, 0);
1266
1267   emitWordLE(Binary);
1268 }
1269
1270 static unsigned encodeVFPRd(const MachineInstr &MI, unsigned OpIdx) {
1271   unsigned RegD = MI.getOperand(OpIdx).getReg();
1272   unsigned Binary = 0;
1273   bool isSPVFP = false;
1274   RegD = ARMRegisterInfo::getRegisterNumbering(RegD, &isSPVFP);
1275   if (!isSPVFP)
1276     Binary |=   RegD               << ARMII::RegRdShift;
1277   else {
1278     Binary |= ((RegD & 0x1E) >> 1) << ARMII::RegRdShift;
1279     Binary |=  (RegD & 0x01)       << ARMII::D_BitShift;
1280   }
1281   return Binary;
1282 }
1283
1284 static unsigned encodeVFPRn(const MachineInstr &MI, unsigned OpIdx) {
1285   unsigned RegN = MI.getOperand(OpIdx).getReg();
1286   unsigned Binary = 0;
1287   bool isSPVFP = false;
1288   RegN = ARMRegisterInfo::getRegisterNumbering(RegN, &isSPVFP);
1289   if (!isSPVFP)
1290     Binary |=   RegN               << ARMII::RegRnShift;
1291   else {
1292     Binary |= ((RegN & 0x1E) >> 1) << ARMII::RegRnShift;
1293     Binary |=  (RegN & 0x01)       << ARMII::N_BitShift;
1294   }
1295   return Binary;
1296 }
1297
1298 static unsigned encodeVFPRm(const MachineInstr &MI, unsigned OpIdx) {
1299   unsigned RegM = MI.getOperand(OpIdx).getReg();
1300   unsigned Binary = 0;
1301   bool isSPVFP = false;
1302   RegM = ARMRegisterInfo::getRegisterNumbering(RegM, &isSPVFP);
1303   if (!isSPVFP)
1304     Binary |=   RegM;
1305   else {
1306     Binary |= ((RegM & 0x1E) >> 1);
1307     Binary |=  (RegM & 0x01)       << ARMII::M_BitShift;
1308   }
1309   return Binary;
1310 }
1311
1312 void ARMCodeEmitter::emitVFPArithInstruction(const MachineInstr &MI) {
1313   const TargetInstrDesc &TID = MI.getDesc();
1314
1315   // Part of binary is determined by TableGn.
1316   unsigned Binary = getBinaryCodeForInstr(MI);
1317
1318   // Set the conditional execution predicate
1319   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1320
1321   unsigned OpIdx = 0;
1322   assert((Binary & ARMII::D_BitShift) == 0 &&
1323          (Binary & ARMII::N_BitShift) == 0 &&
1324          (Binary & ARMII::M_BitShift) == 0 && "VFP encoding bug!");
1325
1326   // Encode Dd / Sd.
1327   Binary |= encodeVFPRd(MI, OpIdx++);
1328
1329   // If this is a two-address operand, skip it, e.g. FMACD.
1330   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
1331     ++OpIdx;
1332
1333   // Encode Dn / Sn.
1334   if ((TID.TSFlags & ARMII::FormMask) == ARMII::VFPBinaryFrm)
1335     Binary |= encodeVFPRn(MI, OpIdx++);
1336
1337   if (OpIdx == TID.getNumOperands() ||
1338       TID.OpInfo[OpIdx].isPredicate() ||
1339       TID.OpInfo[OpIdx].isOptionalDef()) {
1340     // FCMPEZD etc. has only one operand.
1341     emitWordLE(Binary);
1342     return;
1343   }
1344
1345   // Encode Dm / Sm.
1346   Binary |= encodeVFPRm(MI, OpIdx);
1347
1348   emitWordLE(Binary);
1349 }
1350
1351 void ARMCodeEmitter::emitVFPConversionInstruction(const MachineInstr &MI) {
1352   const TargetInstrDesc &TID = MI.getDesc();
1353   unsigned Form = TID.TSFlags & ARMII::FormMask;
1354
1355   // Part of binary is determined by TableGn.
1356   unsigned Binary = getBinaryCodeForInstr(MI);
1357
1358   // Set the conditional execution predicate
1359   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1360
1361   switch (Form) {
1362   default: break;
1363   case ARMII::VFPConv1Frm:
1364   case ARMII::VFPConv2Frm:
1365   case ARMII::VFPConv3Frm:
1366     // Encode Dd / Sd.
1367     Binary |= encodeVFPRd(MI, 0);
1368     break;
1369   case ARMII::VFPConv4Frm:
1370     // Encode Dn / Sn.
1371     Binary |= encodeVFPRn(MI, 0);
1372     break;
1373   case ARMII::VFPConv5Frm:
1374     // Encode Dm / Sm.
1375     Binary |= encodeVFPRm(MI, 0);
1376     break;
1377   }
1378
1379   switch (Form) {
1380   default: break;
1381   case ARMII::VFPConv1Frm:
1382     // Encode Dm / Sm.
1383     Binary |= encodeVFPRm(MI, 1);
1384     break;
1385   case ARMII::VFPConv2Frm:
1386   case ARMII::VFPConv3Frm:
1387     // Encode Dn / Sn.
1388     Binary |= encodeVFPRn(MI, 1);
1389     break;
1390   case ARMII::VFPConv4Frm:
1391   case ARMII::VFPConv5Frm:
1392     // Encode Dd / Sd.
1393     Binary |= encodeVFPRd(MI, 1);
1394     break;
1395   }
1396
1397   if (Form == ARMII::VFPConv5Frm)
1398     // Encode Dn / Sn.
1399     Binary |= encodeVFPRn(MI, 2);
1400   else if (Form == ARMII::VFPConv3Frm)
1401     // Encode Dm / Sm.
1402     Binary |= encodeVFPRm(MI, 2);
1403
1404   emitWordLE(Binary);
1405 }
1406
1407 void ARMCodeEmitter::emitVFPLoadStoreInstruction(const MachineInstr &MI) {
1408   // Part of binary is determined by TableGn.
1409   unsigned Binary = getBinaryCodeForInstr(MI);
1410
1411   // Set the conditional execution predicate
1412   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1413
1414   unsigned OpIdx = 0;
1415
1416   // Encode Dd / Sd.
1417   Binary |= encodeVFPRd(MI, OpIdx++);
1418
1419   // Encode address base.
1420   const MachineOperand &Base = MI.getOperand(OpIdx++);
1421   Binary |= getMachineOpValue(MI, Base) << ARMII::RegRnShift;
1422
1423   // If there is a non-zero immediate offset, encode it.
1424   if (Base.isReg()) {
1425     const MachineOperand &Offset = MI.getOperand(OpIdx);
1426     if (unsigned ImmOffs = ARM_AM::getAM5Offset(Offset.getImm())) {
1427       if (ARM_AM::getAM5Op(Offset.getImm()) == ARM_AM::add)
1428         Binary |= 1 << ARMII::U_BitShift;
1429       Binary |= ImmOffs;
1430       emitWordLE(Binary);
1431       return;
1432     }
1433   }
1434
1435   // If immediate offset is omitted, default to +0.
1436   Binary |= 1 << ARMII::U_BitShift;
1437
1438   emitWordLE(Binary);
1439 }
1440
1441 void
1442 ARMCodeEmitter::emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI) {
1443   const TargetInstrDesc &TID = MI.getDesc();
1444   bool IsUpdating = (TID.TSFlags & ARMII::IndexModeMask) != 0;
1445
1446   // Part of binary is determined by TableGn.
1447   unsigned Binary = getBinaryCodeForInstr(MI);
1448
1449   // Set the conditional execution predicate
1450   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1451
1452   // Skip operand 0 of an instruction with base register update.
1453   unsigned OpIdx = 0;
1454   if (IsUpdating)
1455     ++OpIdx;
1456
1457   // Set base address operand
1458   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1459
1460   // Set addressing mode by modifying bits U(23) and P(24)
1461   const MachineOperand &MO = MI.getOperand(OpIdx++);
1462   Binary |= getAddrModeUPBits(ARM_AM::getAM5SubMode(MO.getImm()));
1463
1464   // Set bit W(21)
1465   if (IsUpdating)
1466     Binary |= 0x1 << ARMII::W_BitShift;
1467
1468   // First register is encoded in Dd.
1469   Binary |= encodeVFPRd(MI, OpIdx+2);
1470
1471   // Number of registers are encoded in offset field.
1472   unsigned NumRegs = 1;
1473   for (unsigned i = OpIdx+3, e = MI.getNumOperands(); i != e; ++i) {
1474     const MachineOperand &MO = MI.getOperand(i);
1475     if (!MO.isReg() || MO.isImplicit())
1476       break;
1477     ++NumRegs;
1478   }
1479   // Bit 8 will be set if <list> is consecutive 64-bit registers (e.g., D0)
1480   // Otherwise, it will be 0, in the case of 32-bit registers.
1481   if(Binary & 0x100)
1482     Binary |= NumRegs * 2;
1483   else
1484     Binary |= NumRegs;
1485
1486   emitWordLE(Binary);
1487 }
1488
1489 void ARMCodeEmitter::emitMiscInstruction(const MachineInstr &MI) {
1490   unsigned Opcode = MI.getDesc().Opcode;
1491   // Part of binary is determined by TableGn.
1492   unsigned Binary = getBinaryCodeForInstr(MI);
1493
1494   // Set the conditional execution predicate
1495   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1496
1497   switch(Opcode) {
1498   default:
1499     llvm_unreachable("ARMCodeEmitter::emitMiscInstruction");
1500
1501   case ARM::FMSTAT:
1502     // No further encoding needed.
1503     break;
1504
1505   case ARM::VMRS:
1506   case ARM::VMSR: {
1507     const MachineOperand &MO0 = MI.getOperand(0);
1508     // Encode Rt.
1509     Binary |= ARMRegisterInfo::getRegisterNumbering(MO0.getReg())
1510                 << ARMII::RegRdShift;
1511     break;
1512   }
1513
1514   case ARM::FCONSTD:
1515   case ARM::FCONSTS: {
1516     // Encode Dd / Sd.
1517     Binary |= encodeVFPRd(MI, 0);
1518
1519     // Encode imm., Table A7-18 VFP modified immediate constants
1520     const MachineOperand &MO1 = MI.getOperand(1);
1521     unsigned Imm = static_cast<unsigned>(MO1.getFPImm()->getValueAPF()
1522                       .bitcastToAPInt().getHiBits(32).getLimitedValue());
1523     unsigned ModifiedImm;
1524
1525     if(Opcode == ARM::FCONSTS)
1526       ModifiedImm = (Imm & 0x80000000) >> 24 | // a
1527                     (Imm & 0x03F80000) >> 19;  // bcdefgh
1528     else // Opcode == ARM::FCONSTD
1529       ModifiedImm = (Imm & 0x80000000) >> 24 | // a
1530                     (Imm & 0x007F0000) >> 16;  // bcdefgh
1531
1532     // Insts{19-16} = abcd, Insts{3-0} = efgh
1533     Binary |= ((ModifiedImm & 0xF0) >> 4) << 16;
1534     Binary |= (ModifiedImm & 0xF);
1535     break;
1536   }
1537   }
1538
1539   emitWordLE(Binary);
1540 }
1541
1542 #include "ARMGenCodeEmitter.inc"