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