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