Encode extend instructions; more clean up.
[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/MachineConstantPool.h"
29 #include "llvm/CodeGen/MachineFunctionPass.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 using namespace llvm;
36
37 STATISTIC(NumEmitted, "Number of machine instructions emitted");
38
39 namespace {
40   class VISIBILITY_HIDDEN ARMCodeEmitter : public MachineFunctionPass {
41     ARMJITInfo                *JTI;
42     const ARMInstrInfo        *II;
43     const TargetData          *TD;
44     TargetMachine             &TM;
45     MachineCodeEmitter        &MCE;
46     const std::vector<MachineConstantPoolEntry> *MCPEs;
47     
48   public:
49     static char ID;
50     explicit ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce)
51       : MachineFunctionPass(&ID), JTI(0), II(0), TD(0), TM(tm),
52       MCE(mce), MCPEs(0) {}
53     ARMCodeEmitter(TargetMachine &tm, MachineCodeEmitter &mce,
54             const ARMInstrInfo &ii, const TargetData &td)
55       : MachineFunctionPass(&ID), JTI(0), II(&ii), TD(&td), TM(tm),
56       MCE(mce), MCPEs(0) {}
57
58     bool runOnMachineFunction(MachineFunction &MF);
59
60     virtual const char *getPassName() const {
61       return "ARM Machine Code Emitter";
62     }
63
64     void emitInstruction(const MachineInstr &MI);
65
66   private:
67
68     void emitWordLE(unsigned Binary);
69
70     void emitConstPoolInstruction(const MachineInstr &MI);
71
72     void emitMOVi2piecesInstruction(const MachineInstr &MI);
73
74     void addPCLabel(unsigned LabelID);
75
76     void emitPseudoInstruction(const MachineInstr &MI);
77
78     unsigned getMachineSoRegOpValue(const MachineInstr &MI,
79                                     const TargetInstrDesc &TID,
80                                     const MachineOperand &MO,
81                                     unsigned OpIdx);
82
83     unsigned getMachineSoImmOpValue(unsigned SoImm);
84
85     unsigned getAddrModeSBit(const MachineInstr &MI,
86                              const TargetInstrDesc &TID) const;
87
88     void emitDataProcessingInstruction(const MachineInstr &MI,
89                                        unsigned ImplicitRn = 0);
90
91     void emitLoadStoreInstruction(const MachineInstr &MI,
92                                   unsigned ImplicitRn = 0);
93
94     void emitMiscLoadStoreInstruction(const MachineInstr &MI,
95                                       unsigned ImplicitRn = 0);
96
97     void emitLoadStoreMultipleInstruction(const MachineInstr &MI);
98
99     void emitMulFrmInstruction(const MachineInstr &MI);
100
101     void emitExtendInstruction(const MachineInstr &MI);
102
103     void emitBranchInstruction(const MachineInstr &MI);
104
105     void emitMiscBranchInstruction(const MachineInstr &MI);
106
107     /// getBinaryCodeForInstr - This function, generated by the
108     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
109     /// machine instructions.
110     ///
111     unsigned getBinaryCodeForInstr(const MachineInstr &MI);
112
113     /// getMachineOpValue - Return binary encoding of operand. If the machine
114     /// operand requires relocation, record the relocation and return zero.
115     unsigned getMachineOpValue(const MachineInstr &MI,const MachineOperand &MO);
116     unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) {
117       return getMachineOpValue(MI, MI.getOperand(OpIdx));
118     }
119
120     /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
121     ///
122     unsigned getShiftOp(unsigned Imm) const ;
123
124     /// Routines that handle operands which add machine relocations which are
125     /// fixed up by the JIT fixup stage.
126     void emitGlobalAddress(GlobalValue *GV, unsigned Reloc,
127                            bool NeedStub);
128     void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
129     void emitConstPoolAddress(unsigned CPI, unsigned Reloc,
130                               int Disp = 0, unsigned PCAdj = 0 );
131     void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc,
132                               unsigned PCAdj = 0);
133     void emitGlobalConstant(const Constant *CV);
134     void emitMachineBasicBlock(MachineBasicBlock *BB);
135   };
136   char ARMCodeEmitter::ID = 0;
137 }
138
139 /// createARMCodeEmitterPass - Return a pass that emits the collected ARM code
140 /// to the specified MCE object.
141 FunctionPass *llvm::createARMCodeEmitterPass(ARMTargetMachine &TM,
142                                              MachineCodeEmitter &MCE) {
143   return new ARMCodeEmitter(TM, MCE);
144 }
145
146 bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
147   assert((MF.getTarget().getRelocationModel() != Reloc::Default ||
148           MF.getTarget().getRelocationModel() != Reloc::Static) &&
149          "JIT relocation model must be set to static or default!");
150   II = ((ARMTargetMachine&)MF.getTarget()).getInstrInfo();
151   TD = ((ARMTargetMachine&)MF.getTarget()).getTargetData();
152   JTI = ((ARMTargetMachine&)MF.getTarget()).getJITInfo();
153   MCPEs = &MF.getConstantPool()->getConstants();
154   JTI->Initialize(MCPEs);
155
156   do {
157     DOUT << "JITTing function '" << MF.getFunction()->getName() << "'\n";
158     MCE.startFunction(MF);
159     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end(); 
160          MBB != E; ++MBB) {
161       MCE.StartMachineBasicBlock(MBB);
162       for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
163            I != E; ++I)
164         emitInstruction(*I);
165     }
166   } while (MCE.finishFunction(MF));
167
168   return false;
169 }
170
171 /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
172 ///
173 unsigned ARMCodeEmitter::getShiftOp(unsigned Imm) const {
174   switch (ARM_AM::getAM2ShiftOpc(Imm)) {
175   default: assert(0 && "Unknown shift opc!");
176   case ARM_AM::asr: return 2;
177   case ARM_AM::lsl: return 0;
178   case ARM_AM::lsr: return 1;
179   case ARM_AM::ror:
180   case ARM_AM::rrx: return 3;
181   }
182   return 0;
183 }
184
185 /// getMachineOpValue - Return binary encoding of operand. If the machine
186 /// operand requires relocation, record the relocation and return zero.
187 unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
188                                            const MachineOperand &MO) {
189   if (MO.isReg())
190     return ARMRegisterInfo::getRegisterNumbering(MO.getReg());
191   else if (MO.isImm())
192     return static_cast<unsigned>(MO.getImm());
193   else if (MO.isGlobal())
194     emitGlobalAddress(MO.getGlobal(), ARM::reloc_arm_branch, true);
195   else if (MO.isSymbol())
196     emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_relative);
197   else if (MO.isCPI())
198     emitConstPoolAddress(MO.getIndex(), ARM::reloc_arm_cp_entry);
199   else if (MO.isJTI())
200     emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
201   else if (MO.isMBB())
202     emitMachineBasicBlock(MO.getMBB());
203   else {
204     cerr << "ERROR: Unknown type of MachineOperand: " << MO << "\n";
205     abort();
206   }
207   return 0;
208 }
209
210 /// emitGlobalAddress - Emit the specified address to the code stream.
211 ///
212 void ARMCodeEmitter::emitGlobalAddress(GlobalValue *GV,
213                                        unsigned Reloc, bool NeedStub) {
214   MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
215                                              Reloc, GV, 0, NeedStub));
216 }
217
218 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
219 /// be emitted to the current location in the function, and allow it to be PC
220 /// relative.
221 void ARMCodeEmitter::emitExternalSymbolAddress(const char *ES, unsigned Reloc) {
222   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
223                                                  Reloc, ES));
224 }
225
226 /// emitConstPoolAddress - Arrange for the address of an constant pool
227 /// to be emitted to the current location in the function, and allow it to be PC
228 /// relative.
229 void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
230                                           int Disp /* = 0 */,
231                                           unsigned PCAdj /* = 0 */) {
232   // Tell JIT emitter we'll resolve the address.
233   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
234                                                     Reloc, CPI, PCAdj, true));
235 }
236
237 /// emitJumpTableAddress - Arrange for the address of a jump table to
238 /// be emitted to the current location in the function, and allow it to be PC
239 /// relative.
240 void ARMCodeEmitter::emitJumpTableAddress(unsigned JTIndex, unsigned Reloc,
241                                           unsigned PCAdj /* = 0 */) {
242   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
243                                                     Reloc, JTIndex, PCAdj));
244 }
245
246 /// emitMachineBasicBlock - Emit the specified address basic block.
247 void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB) {
248   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
249                                              ARM::reloc_arm_branch, BB));
250 }
251
252 void ARMCodeEmitter::emitWordLE(unsigned Binary) {
253   DOUT << "  " << (void*)Binary << "\n";
254   MCE.emitWordLE(Binary);
255 }
256
257 void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
258   DOUT << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI;
259
260   NumEmitted++;  // Keep track of the # of mi's emitted
261   switch (MI.getDesc().TSFlags & ARMII::FormMask) {
262   default:
263     assert(0 && "Unhandled instruction encoding format!");
264     break;
265   case ARMII::Pseudo:
266     emitPseudoInstruction(MI);
267     break;
268   case ARMII::DPFrm:
269   case ARMII::DPSoRegFrm:
270     emitDataProcessingInstruction(MI);
271     break;
272   case ARMII::LdFrm:
273   case ARMII::StFrm:
274     emitLoadStoreInstruction(MI);
275     break;
276   case ARMII::LdMiscFrm:
277   case ARMII::StMiscFrm:
278     emitMiscLoadStoreInstruction(MI);
279     break;
280   case ARMII::LdMulFrm:
281   case ARMII::StMulFrm:
282     emitLoadStoreMultipleInstruction(MI);
283     break;
284   case ARMII::MulFrm:
285     emitMulFrmInstruction(MI);
286     break;
287   case ARMII::ExtFrm:
288     emitExtendInstruction(MI);
289     break;
290   case ARMII::BrFrm:
291     emitBranchInstruction(MI);
292     break;
293   case ARMII::BrMiscFrm:
294     emitMiscBranchInstruction(MI);
295     break;
296   }
297 }
298
299 void ARMCodeEmitter::emitConstPoolInstruction(const MachineInstr &MI) {
300   unsigned CPI = MI.getOperand(0).getImm();
301   unsigned CPIndex = MI.getOperand(1).getIndex();
302   const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
303   
304   // Remember the CONSTPOOL_ENTRY address for later relocation.
305   JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
306
307   // Emit constpool island entry. In most cases, the actual values will be
308   // resolved and relocated after code emission.
309   if (MCPE.isMachineConstantPoolEntry()) {
310     ARMConstantPoolValue *ACPV =
311       static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
312
313     DOUT << "  ** ARM constant pool #" << CPI << " @ "
314          << (void*)MCE.getCurrentPCValue() << " " << *ACPV << "\n";
315
316     GlobalValue *GV = ACPV->getGV();
317     if (GV) {
318       assert(!ACPV->isStub() && "Don't know how to deal this yet!");
319       MCE.addRelocation(MachineRelocation::getGV(MCE.getCurrentPCOffset(),
320                                                 ARM::reloc_arm_machine_cp_entry,
321                                                 GV, CPIndex, false));
322      } else  {
323       assert(!ACPV->isNonLazyPointer() && "Don't know how to deal this yet!");
324       emitExternalSymbolAddress(ACPV->getSymbol(), ARM::reloc_arm_absolute);
325     }
326     emitWordLE(0);
327   } else {
328     Constant *CV = MCPE.Val.ConstVal;
329
330     DOUT << "  ** Constant pool #" << CPI << " @ "
331          << (void*)MCE.getCurrentPCValue() << " " << *CV << "\n";
332
333     if (GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
334       emitGlobalAddress(GV, ARM::reloc_arm_absolute, false);
335       emitWordLE(0);
336     } else {
337       assert(CV->getType()->isInteger() &&
338              "Not expecting non-integer constpool entries yet!");
339       const ConstantInt *CI = dyn_cast<ConstantInt>(CV);
340       uint32_t Val = *(uint32_t*)CI->getValue().getRawData();
341       emitWordLE(Val);
342     }
343   }
344 }
345
346 void ARMCodeEmitter::emitMOVi2piecesInstruction(const MachineInstr &MI) {
347   const MachineOperand &MO0 = MI.getOperand(0);
348   const MachineOperand &MO1 = MI.getOperand(1);
349   assert(MO1.isImm() && "Not a valid so_imm value!");
350   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO1.getImm());
351   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO1.getImm());
352
353   // Emit the 'mov' instruction.
354   unsigned Binary = 0xd << 21;  // mov: Insts{24-21} = 0b1101
355
356   // Set the conditional execution predicate.
357   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
358
359   // Encode Rd.
360   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
361
362   // Encode so_imm.
363   // Set bit I(25) to identify this is the immediate form of <shifter_op>
364   Binary |= 1 << ARMII::I_BitShift;
365   Binary |= getMachineSoImmOpValue(ARM_AM::getSOImmVal(V1));
366   emitWordLE(Binary);
367
368   // Now the 'orr' instruction.
369   Binary = 0xc << 21;  // orr: Insts{24-21} = 0b1100
370
371   // Set the conditional execution predicate.
372   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
373
374   // Encode Rd.
375   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
376
377   // Encode Rn.
378   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRnShift;
379
380   // Encode so_imm.
381   // Set bit I(25) to identify this is the immediate form of <shifter_op>
382   Binary |= 1 << ARMII::I_BitShift;
383   Binary |= getMachineSoImmOpValue(ARM_AM::getSOImmVal(V2));
384   emitWordLE(Binary);
385 }
386
387 void ARMCodeEmitter::addPCLabel(unsigned LabelID) {
388   DOUT << "  ** LPC" << LabelID << " @ "
389        << (void*)MCE.getCurrentPCValue() << '\n';
390   JTI->addPCLabelAddr(LabelID, MCE.getCurrentPCValue());
391 }
392
393 void ARMCodeEmitter::emitPseudoInstruction(const MachineInstr &MI) {
394   unsigned Opcode = MI.getDesc().Opcode;
395   switch (Opcode) {
396   default:
397     abort(); // FIXME:
398   case ARM::CONSTPOOL_ENTRY:
399     emitConstPoolInstruction(MI);
400     break;
401   case ARM::PICADD: {
402     // Remember of the address of the PC label for relocation later.
403     addPCLabel(MI.getOperand(2).getImm());
404     // PICADD is just an add instruction that implicitly read pc.
405     emitDataProcessingInstruction(MI, ARM::PC);
406     break;
407   }
408   case ARM::PICLDR:
409   case ARM::PICLDRB:
410   case ARM::PICSTR:
411   case ARM::PICSTRB: {
412     // Remember of the address of the PC label for relocation later.
413     addPCLabel(MI.getOperand(2).getImm());
414     // These are just load / store instructions that implicitly read pc.
415     emitLoadStoreInstruction(MI, ARM::PC);
416     break;
417   }
418   case ARM::PICLDRH:
419   case ARM::PICLDRSH:
420   case ARM::PICLDRSB:
421   case ARM::PICSTRH: {
422     // Remember of the address of the PC label for relocation later.
423     addPCLabel(MI.getOperand(2).getImm());
424     // These are just load / store instructions that implicitly read pc.
425     emitMiscLoadStoreInstruction(MI, ARM::PC);
426     break;
427   }
428   case ARM::MOVi2pieces:
429     // Two instructions to materialize a constant.
430     emitMOVi2piecesInstruction(MI);
431     break;
432   }
433 }
434
435
436 unsigned ARMCodeEmitter::getMachineSoRegOpValue(const MachineInstr &MI,
437                                                 const TargetInstrDesc &TID,
438                                                 const MachineOperand &MO,
439                                                 unsigned OpIdx) {
440   unsigned Binary = getMachineOpValue(MI, MO);
441
442   const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
443   const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
444   ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
445
446   // Encode the shift opcode.
447   unsigned SBits = 0;
448   unsigned Rs = MO1.getReg();
449   if (Rs) {
450     // Set shift operand (bit[7:4]).
451     // LSL - 0001
452     // LSR - 0011
453     // ASR - 0101
454     // ROR - 0111
455     // RRX - 0110 and bit[11:8] clear.
456     switch (SOpc) {
457     default: assert(0 && "Unknown shift opc!");
458     case ARM_AM::lsl: SBits = 0x1; break;
459     case ARM_AM::lsr: SBits = 0x3; break;
460     case ARM_AM::asr: SBits = 0x5; break;
461     case ARM_AM::ror: SBits = 0x7; break;
462     case ARM_AM::rrx: SBits = 0x6; break;
463     }
464   } else {
465     // Set shift operand (bit[6:4]).
466     // LSL - 000
467     // LSR - 010
468     // ASR - 100
469     // ROR - 110
470     switch (SOpc) {
471     default: assert(0 && "Unknown shift opc!");
472     case ARM_AM::lsl: SBits = 0x0; break;
473     case ARM_AM::lsr: SBits = 0x2; break;
474     case ARM_AM::asr: SBits = 0x4; break;
475     case ARM_AM::ror: SBits = 0x6; break;
476     }
477   }
478   Binary |= SBits << 4;
479   if (SOpc == ARM_AM::rrx)
480     return Binary;
481
482   // Encode the shift operation Rs or shift_imm (except rrx).
483   if (Rs) {
484     // Encode Rs bit[11:8].
485     assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
486     return Binary |
487       (ARMRegisterInfo::getRegisterNumbering(Rs) << ARMII::RegRsShift);
488   }
489
490   // Encode shift_imm bit[11:7].
491   return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
492 }
493
494 unsigned ARMCodeEmitter::getMachineSoImmOpValue(unsigned SoImm) {
495   // Encode rotate_imm.
496   unsigned Binary = (ARM_AM::getSOImmValRot(SoImm) >> 1)
497     << ARMII::SoRotImmShift;
498
499   // Encode immed_8.
500   Binary |= ARM_AM::getSOImmValImm(SoImm);
501   return Binary;
502 }
503
504 unsigned ARMCodeEmitter::getAddrModeSBit(const MachineInstr &MI,
505                                          const TargetInstrDesc &TID) const {
506   for (unsigned i = MI.getNumOperands(), e = TID.getNumOperands(); i != e; --i){
507     const MachineOperand &MO = MI.getOperand(i-1);
508     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)
509       return 1 << ARMII::S_BitShift;
510   }
511   return 0;
512 }
513
514 void ARMCodeEmitter::emitDataProcessingInstruction(const MachineInstr &MI,
515                                                    unsigned ImplicitRn) {
516   const TargetInstrDesc &TID = MI.getDesc();
517
518   // Part of binary is determined by TableGn.
519   unsigned Binary = getBinaryCodeForInstr(MI);
520
521   // Set the conditional execution predicate
522   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
523
524   // Encode S bit if MI modifies CPSR.
525   Binary |= getAddrModeSBit(MI, TID);
526
527   // Encode register def if there is one.
528   unsigned NumDefs = TID.getNumDefs();
529   unsigned OpIdx = 0;
530   if (NumDefs) {
531     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdShift;
532     ++OpIdx;
533   }
534
535   // If this is a two-address operand, skip it. e.g. MOVCCr operand 1.
536   if (TID.getOperandConstraint(OpIdx, TOI::TIED_TO) != -1)
537     ++OpIdx;
538
539   // Encode first non-shifter register operand if there is one.
540   bool isUnary = TID.TSFlags & ARMII::UnaryDP;
541   if (!isUnary) {
542     if (ImplicitRn)
543       // Special handling for implicit use (e.g. PC).
544       Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
545                  << ARMII::RegRnShift);
546     else {
547       Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
548       ++OpIdx;
549     }
550   }
551
552   // Encode shifter operand.
553   const MachineOperand &MO = MI.getOperand(OpIdx);
554   if ((TID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
555     // Encode SoReg.
556     emitWordLE(Binary | getMachineSoRegOpValue(MI, TID, MO, OpIdx));
557     return;
558   }
559
560   if (MO.isReg()) {
561     // Encode register Rm.
562     emitWordLE(Binary | ARMRegisterInfo::getRegisterNumbering(MO.getReg()));
563     return;
564   }
565
566   // Encode so_imm.
567   // Set bit I(25) to identify this is the immediate form of <shifter_op>
568   Binary |= 1 << ARMII::I_BitShift;
569   Binary |= getMachineSoImmOpValue(MO.getImm());
570
571   emitWordLE(Binary);
572 }
573
574 void ARMCodeEmitter::emitLoadStoreInstruction(const MachineInstr &MI,
575                                               unsigned ImplicitRn) {
576   // Part of binary is determined by TableGn.
577   unsigned Binary = getBinaryCodeForInstr(MI);
578
579   // Set the conditional execution predicate
580   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
581
582   // Set first operand
583   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
584
585   // Set second operand
586   unsigned OpIdx = 1;
587   if (ImplicitRn)
588     // Special handling for implicit use (e.g. PC).
589     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
590                << ARMII::RegRnShift);
591   else {
592     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
593     ++OpIdx;
594   }
595
596   const MachineOperand &MO2 = MI.getOperand(OpIdx);
597   unsigned AM2Opc = (ImplicitRn == ARM::PC)
598     ? 0 : MI.getOperand(OpIdx+1).getImm();
599
600   // Set bit U(23) according to sign of immed value (positive or negative).
601   Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
602              ARMII::U_BitShift);
603   if (!MO2.getReg()) { // is immediate
604     if (ARM_AM::getAM2Offset(AM2Opc))
605       // Set the value of offset_12 field
606       Binary |= ARM_AM::getAM2Offset(AM2Opc);
607     emitWordLE(Binary);
608     return;
609   }
610
611   // Set bit I(25), because this is not in immediate enconding.
612   Binary |= 1 << ARMII::I_BitShift;
613   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
614   // Set bit[3:0] to the corresponding Rm register
615   Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
616
617   // if this instr is in scaled register offset/index instruction, set
618   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
619   if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
620     Binary |= getShiftOp(AM2Opc) << 5;  // shift
621     Binary |= ShImm              << 7;  // shift_immed
622   }
623
624   emitWordLE(Binary);
625 }
626
627 void ARMCodeEmitter::emitMiscLoadStoreInstruction(const MachineInstr &MI,
628                                                   unsigned ImplicitRn) {
629   // Part of binary is determined by TableGn.
630   unsigned Binary = getBinaryCodeForInstr(MI);
631
632   // Set the conditional execution predicate
633   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
634
635   // Set first operand
636   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
637
638   // Set second operand
639   unsigned OpIdx = 1;
640   if (ImplicitRn)
641     // Special handling for implicit use (e.g. PC).
642     Binary |= (ARMRegisterInfo::getRegisterNumbering(ImplicitRn)
643                << ARMII::RegRnShift);
644   else {
645     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
646     ++OpIdx;
647   }
648
649   const MachineOperand &MO2 = MI.getOperand(OpIdx);
650   unsigned AM3Opc = (ImplicitRn == ARM::PC)
651     ? 0 : MI.getOperand(OpIdx+1).getImm();
652
653   // Set bit U(23) according to sign of immed value (positive or negative)
654   Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
655              ARMII::U_BitShift);
656
657   // If this instr is in register offset/index encoding, set bit[3:0]
658   // to the corresponding Rm register.
659   if (MO2.getReg()) {
660     Binary |= ARMRegisterInfo::getRegisterNumbering(MO2.getReg());
661     emitWordLE(Binary);
662     return;
663   }
664
665   // This instr is in immediate offset/index encoding, set bit 22 to 1.
666   Binary |= 1 << ARMII::AM3_I_BitShift;
667   if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
668     // Set operands
669     Binary |= (ImmOffs >> 4) << 8;  // immedH
670     Binary |= (ImmOffs & ~0xF);     // immedL
671   }
672
673   emitWordLE(Binary);
674 }
675
676 void ARMCodeEmitter::emitLoadStoreMultipleInstruction(const MachineInstr &MI) {
677   // Part of binary is determined by TableGn.
678   unsigned Binary = getBinaryCodeForInstr(MI);
679
680   // Set the conditional execution predicate
681   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
682
683   // Set first operand
684   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRnShift;
685
686   // Set addressing mode by modifying bits U(23) and P(24)
687   // IA - Increment after  - bit U = 1 and bit P = 0
688   // IB - Increment before - bit U = 1 and bit P = 1
689   // DA - Decrement after  - bit U = 0 and bit P = 0
690   // DB - Decrement before - bit U = 0 and bit P = 1
691   const MachineOperand &MO = MI.getOperand(1);
692   ARM_AM::AMSubMode Mode = ARM_AM::getAM4SubMode(MO.getImm());
693   switch (Mode) {
694   default: assert(0 && "Unknown addressing sub-mode!");
695   case ARM_AM::da:                      break;
696   case ARM_AM::db: Binary |= 0x1 << ARMII::P_BitShift; break;
697   case ARM_AM::ia: Binary |= 0x1 << ARMII::U_BitShift; break;
698   case ARM_AM::ib: Binary |= 0x3 << ARMII::U_BitShift; break;
699   }
700
701   // Set bit W(21)
702   if (ARM_AM::getAM4WBFlag(MO.getImm()))
703     Binary |= 0x1 << ARMII::W_BitShift;
704
705   // Set registers
706   for (unsigned i = 4, e = MI.getNumOperands(); i != e; ++i) {
707     const MachineOperand &MO = MI.getOperand(i);
708     if (MO.isReg() && MO.isImplicit())
709       continue;
710     unsigned RegNum = ARMRegisterInfo::getRegisterNumbering(MO.getReg());
711     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
712            RegNum < 16);
713     Binary |= 0x1 << RegNum;
714   }
715
716   emitWordLE(Binary);
717 }
718
719 void ARMCodeEmitter::emitMulFrmInstruction(const MachineInstr &MI) {
720   const TargetInstrDesc &TID = MI.getDesc();
721
722   // Part of binary is determined by TableGn.
723   unsigned Binary = getBinaryCodeForInstr(MI);
724
725   // Set the conditional execution predicate
726   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
727
728   // Encode S bit if MI modifies CPSR.
729   Binary |= getAddrModeSBit(MI, TID);
730
731   // 32x32->64bit operations have two destination registers. The number
732   // of register definitions will tell us if that's what we're dealing with.
733   unsigned OpIdx = 0;
734   if (TID.getNumDefs() == 2)
735     Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
736
737   // Encode Rd
738   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
739
740   // Encode Rm
741   Binary |= getMachineOpValue(MI, OpIdx++);
742
743   // Encode Rs
744   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
745
746   // Many multiple instructions (e.g. MLA) have three src operands. Encode
747   // it as Rn (for multiply, that's in the same offset as RdLo.
748   if (TID.getNumOperands() > OpIdx &&
749       !TID.OpInfo[OpIdx].isPredicate() &&
750       !TID.OpInfo[OpIdx].isOptionalDef())
751     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdLoShift;
752
753   emitWordLE(Binary);
754 }
755
756 void ARMCodeEmitter::emitExtendInstruction(const MachineInstr &MI) {
757   const TargetInstrDesc &TID = MI.getDesc();
758
759   // Part of binary is determined by TableGn.
760   unsigned Binary = getBinaryCodeForInstr(MI);
761
762   // Set the conditional execution predicate
763   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
764
765   unsigned OpIdx = 0;
766
767   // Encode Rd
768   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
769
770   const MachineOperand &MO1 = MI.getOperand(OpIdx++);
771   const MachineOperand &MO2 = MI.getOperand(OpIdx);
772   if (MO2.isReg()) {
773     // Two register operand form.
774     // Encode Rn.
775     Binary |= getMachineOpValue(MI, MO1) << ARMII::RegRnShift;
776
777     // Encode Rm.
778     Binary |= getMachineOpValue(MI, MO2);
779     ++OpIdx;
780   } else {
781     Binary |= getMachineOpValue(MI, MO1);
782   }
783
784   // Encode rot imm (0, 8, 16, or 24) if it has a rotate immediate operand.
785   if (MI.getOperand(OpIdx).isImm() &&
786       !TID.OpInfo[OpIdx].isPredicate() &&
787       !TID.OpInfo[OpIdx].isOptionalDef())
788     Binary |= (getMachineOpValue(MI, OpIdx) / 8) << ARMII::ExtRotImmShift;
789
790   emitWordLE(Binary);
791 }
792
793 void ARMCodeEmitter::emitBranchInstruction(const MachineInstr &MI) {
794   const TargetInstrDesc &TID = MI.getDesc();
795
796   if (TID.Opcode == ARM::TPsoft)
797     abort(); // FIXME
798
799   // Part of binary is determined by TableGn.
800   unsigned Binary = getBinaryCodeForInstr(MI);
801
802   // Set the conditional execution predicate
803   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
804
805   // Set signed_immed_24 field
806   Binary |= getMachineOpValue(MI, 0);
807
808   emitWordLE(Binary);
809 }
810
811 void ARMCodeEmitter::emitMiscBranchInstruction(const MachineInstr &MI) {
812   const TargetInstrDesc &TID = MI.getDesc();
813   if (TID.Opcode == ARM::BX ||
814       TID.Opcode == ARM::BR_JTr ||
815       TID.Opcode == ARM::BR_JTm ||
816       TID.Opcode == ARM::BR_JTadd)
817     abort(); // FIXME
818
819   // Part of binary is determined by TableGn.
820   unsigned Binary = getBinaryCodeForInstr(MI);
821
822   // Set the conditional execution predicate
823   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
824
825   if (TID.Opcode == ARM::BX_RET)
826     // The return register is LR.
827     Binary |= ARMRegisterInfo::getRegisterNumbering(ARM::LR);
828   else 
829     // otherwise, set the return register
830     Binary |= getMachineOpValue(MI, 0);
831
832   emitWordLE(Binary);
833 }
834
835 #include "ARMGenCodeEmitter.inc"