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