remove a bunch of unused private methods
[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 "ARMBaseInstrInfo.h"
18 #include "ARMConstantPoolValue.h"
19 #include "ARMRelocations.h"
20 #include "ARMSubtarget.h"
21 #include "ARMTargetMachine.h"
22 #include "MCTargetDesc/ARMAddressingModes.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/JITCodeEmitter.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachineInstr.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineModuleInfo.h"
30 #include "llvm/CodeGen/Passes.h"
31 #include "llvm/IR/Constants.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/PassManager.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 ARMBaseInstrInfo    *II;
50     const DataLayout          *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     bool IsThumb;
59
60     void getAnalysisUsage(AnalysisUsage &AU) const override {
61       AU.addRequired<MachineModuleInfo>();
62       MachineFunctionPass::getAnalysisUsage(AU);
63     }
64
65     static char ID;
66   public:
67     ARMCodeEmitter(TargetMachine &tm, JITCodeEmitter &mce)
68       : MachineFunctionPass(ID), JTI(0),
69         II((const ARMBaseInstrInfo *)tm.getInstrInfo()),
70         TD(tm.getDataLayout()), TM(tm),
71         MCE(mce), MCPEs(0), MJTEs(0),
72         IsPIC(TM.getRelocationModel() == Reloc::PIC_), IsThumb(false) {}
73
74     /// getBinaryCodeForInstr - This function, generated by the
75     /// CodeEmitterGenerator using TableGen, produces the binary encoding for
76     /// machine instructions.
77     uint64_t getBinaryCodeForInstr(const MachineInstr &MI) const;
78
79     bool runOnMachineFunction(MachineFunction &MF) override;
80
81     const char *getPassName() const override {
82       return "ARM Machine Code Emitter";
83     }
84
85     void emitInstruction(const MachineInstr &MI);
86
87   private:
88
89     void emitWordLE(unsigned Binary);
90     void emitDWordLE(uint64_t Binary);
91     void emitConstPoolInstruction(const MachineInstr &MI);
92     void emitMOVi32immInstruction(const MachineInstr &MI);
93     void emitMOVi2piecesInstruction(const MachineInstr &MI);
94     void emitLEApcrelJTInstruction(const MachineInstr &MI);
95     void emitPseudoMoveInstruction(const MachineInstr &MI);
96     void addPCLabel(unsigned LabelID);
97     void emitPseudoInstruction(const MachineInstr &MI);
98     unsigned getMachineSoRegOpValue(const MachineInstr &MI,
99                                     const MCInstrDesc &MCID,
100                                     const MachineOperand &MO,
101                                     unsigned OpIdx);
102
103     unsigned getMachineSoImmOpValue(unsigned SoImm);
104     unsigned getAddrModeSBit(const MachineInstr &MI,
105                              const MCInstrDesc &MCID) 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 emitSaturateInstruction(const MachineInstr &MI);
127
128     void emitBranchInstruction(const MachineInstr &MI);
129
130     void emitInlineJumpTable(unsigned JTIndex);
131
132     void emitMiscBranchInstruction(const MachineInstr &MI);
133
134     void emitVFPArithInstruction(const MachineInstr &MI);
135
136     void emitVFPConversionInstruction(const MachineInstr &MI);
137
138     void emitVFPLoadStoreInstruction(const MachineInstr &MI);
139
140     void emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI);
141
142     void emitNEONLaneInstruction(const MachineInstr &MI);
143     void emitNEONDupInstruction(const MachineInstr &MI);
144     void emitNEON1RegModImmInstruction(const MachineInstr &MI);
145     void emitNEON2RegInstruction(const MachineInstr &MI);
146     void emitNEON3RegInstruction(const MachineInstr &MI);
147
148     /// getMachineOpValue - Return binary encoding of operand. If the machine
149     /// operand requires relocation, record the relocation and return zero.
150     unsigned getMachineOpValue(const MachineInstr &MI,
151                                const MachineOperand &MO) const;
152     unsigned getMachineOpValue(const MachineInstr &MI, unsigned OpIdx) const {
153       return getMachineOpValue(MI, MI.getOperand(OpIdx));
154     }
155
156     // FIXME: The legacy JIT ARMCodeEmitter doesn't rely on the the
157     //  TableGen'erated getBinaryCodeForInstr() function to encode any
158     //  operand values, instead querying getMachineOpValue() directly for
159     //  each operand it needs to encode. Thus, any of the new encoder
160     //  helper functions can simply return 0 as the values the return
161     //  are already handled elsewhere. They are placeholders to allow this
162     //  encoder to continue to function until the MC encoder is sufficiently
163     //  far along that this one can be eliminated entirely.
164     unsigned NEONThumb2DataIPostEncoder(const MachineInstr &MI, unsigned Val)
165       const { return 0; }
166     unsigned NEONThumb2LoadStorePostEncoder(const MachineInstr &MI,unsigned Val)
167       const { return 0; }
168     unsigned NEONThumb2DupPostEncoder(const MachineInstr &MI,unsigned Val)
169       const { return 0; }
170     unsigned NEONThumb2V8PostEncoder(const MachineInstr &MI,unsigned Val)
171       const { return 0; }
172     unsigned VFPThumb2PostEncoder(const MachineInstr&MI, unsigned Val)
173       const { return 0; }
174     unsigned getAdrLabelOpValue(const MachineInstr &MI, unsigned Op)
175       const { return 0; }
176     unsigned getThumbAdrLabelOpValue(const MachineInstr &MI, unsigned Op)
177       const { return 0; }
178     unsigned getThumbBLTargetOpValue(const MachineInstr &MI, unsigned Op)
179       const { return 0; }
180     unsigned getThumbBLXTargetOpValue(const MachineInstr &MI, unsigned Op)
181       const { return 0; }
182     unsigned getThumbBRTargetOpValue(const MachineInstr &MI, unsigned Op)
183       const { return 0; }
184     unsigned getThumbBCCTargetOpValue(const MachineInstr &MI, unsigned Op)
185       const { return 0; }
186     unsigned getThumbCBTargetOpValue(const MachineInstr &MI, unsigned Op)
187       const { return 0; }
188     unsigned getBranchTargetOpValue(const MachineInstr &MI, unsigned Op)
189       const { return 0; }
190     unsigned getUnconditionalBranchTargetOpValue(const MachineInstr &MI,
191       unsigned Op) const { return 0; }
192     unsigned getARMBranchTargetOpValue(const MachineInstr &MI, unsigned Op)
193       const { return 0; }
194     unsigned getARMBLTargetOpValue(const MachineInstr &MI, unsigned Op)
195       const { return 0; }
196     unsigned getARMBLXTargetOpValue(const MachineInstr &MI, unsigned Op)
197       const { return 0; }
198     unsigned getCCOutOpValue(const MachineInstr &MI, unsigned Op)
199       const { return 0; }
200     unsigned getSOImmOpValue(const MachineInstr &MI, unsigned Op)
201       const { return 0; }
202     unsigned getT2SOImmOpValue(const MachineInstr &MI, unsigned Op)
203       const { return 0; }
204     unsigned getSORegRegOpValue(const MachineInstr &MI, unsigned Op)
205       const { return 0; }
206     unsigned getSORegImmOpValue(const MachineInstr &MI, unsigned Op)
207       const { return 0; }
208     unsigned getThumbAddrModeRegRegOpValue(const MachineInstr &MI, unsigned Op)
209       const { return 0; }
210     unsigned getT2AddrModeImm8OpValue(const MachineInstr &MI, unsigned Op)
211       const { return 0; }
212     unsigned getT2Imm8s4OpValue(const MachineInstr &MI, unsigned Op)
213       const { return 0; }
214     unsigned getT2AddrModeImm8s4OpValue(const MachineInstr &MI, unsigned Op)
215       const { return 0; }
216     unsigned getT2AddrModeImm0_1020s4OpValue(const MachineInstr &MI,unsigned Op)
217       const { return 0; }
218     unsigned getT2AddrModeImm8OffsetOpValue(const MachineInstr &MI, unsigned Op)
219       const { return 0; }
220     unsigned getT2AddrModeSORegOpValue(const MachineInstr &MI, unsigned Op)
221       const { return 0; }
222     unsigned getT2SORegOpValue(const MachineInstr &MI, unsigned Op)
223       const { return 0; }
224     unsigned getT2AdrLabelOpValue(const MachineInstr &MI, unsigned Op)
225       const { return 0; }
226     unsigned getAddrMode6AddressOpValue(const MachineInstr &MI, unsigned Op)
227       const { return 0; }
228     unsigned getAddrMode6OneLane32AddressOpValue(const MachineInstr &MI,
229                                                  unsigned Op)
230       const { return 0; }
231     unsigned getAddrMode6DupAddressOpValue(const MachineInstr &MI, unsigned Op)
232       const { return 0; }
233     unsigned getAddrMode6OffsetOpValue(const MachineInstr &MI, unsigned Op)
234       const { return 0; }
235     unsigned getBitfieldInvertedMaskOpValue(const MachineInstr &MI,
236                                             unsigned Op) const { return 0; }
237     uint32_t getLdStSORegOpValue(const MachineInstr &MI, unsigned OpIdx)
238       const { return 0; }
239
240     unsigned getAddrModeImm12OpValue(const MachineInstr &MI, unsigned Op)
241       const {
242       // {17-13} = reg
243       // {12}    = (U)nsigned (add == '1', sub == '0')
244       // {11-0}  = imm12
245       const MachineOperand &MO  = MI.getOperand(Op);
246       const MachineOperand &MO1 = MI.getOperand(Op + 1);
247       if (!MO.isReg()) {
248         emitConstPoolAddress(MO.getIndex(), ARM::reloc_arm_cp_entry);
249         return 0;
250       }
251       unsigned Reg = II->getRegisterInfo().getEncodingValue(MO.getReg());
252       int32_t Imm12 = MO1.getImm();
253       uint32_t Binary;
254       Binary = Imm12 & 0xfff;
255       if (Imm12 >= 0)
256         Binary |= (1 << 12);
257       Binary |= (Reg << 13);
258       return Binary;
259     }
260
261     unsigned getHiLo16ImmOpValue(const MachineInstr &MI, unsigned Op) const {
262       return 0;
263     }
264
265     uint32_t getAddrMode2OffsetOpValue(const MachineInstr &MI, unsigned OpIdx)
266       const { return 0;}
267     uint32_t getPostIdxRegOpValue(const MachineInstr &MI, unsigned OpIdx)
268       const { return 0;}
269     uint32_t getAddrMode3OffsetOpValue(const MachineInstr &MI, unsigned OpIdx)
270       const { return 0;}
271     uint32_t getAddrMode3OpValue(const MachineInstr &MI, unsigned Op)
272       const { return 0; }
273     uint32_t getAddrModeThumbSPOpValue(const MachineInstr &MI, unsigned Op)
274       const { return 0; }
275     uint32_t getAddrModeISOpValue(const MachineInstr &MI, unsigned Op)
276       const { return 0; }
277     uint32_t getAddrModePCOpValue(const MachineInstr &MI, unsigned Op)
278       const { return 0; }
279     uint32_t getAddrMode5OpValue(const MachineInstr &MI, unsigned Op) const {
280       // {17-13} = reg
281       // {12}    = (U)nsigned (add == '1', sub == '0')
282       // {11-0}  = imm12
283       const MachineOperand &MO  = MI.getOperand(Op);
284       const MachineOperand &MO1 = MI.getOperand(Op + 1);
285       if (!MO.isReg()) {
286         emitConstPoolAddress(MO.getIndex(), ARM::reloc_arm_cp_entry);
287         return 0;
288       }
289       unsigned Reg = II->getRegisterInfo().getEncodingValue(MO.getReg());
290       int32_t Imm12 = MO1.getImm();
291
292       // Special value for #-0
293       if (Imm12 == INT32_MIN)
294         Imm12 = 0;
295
296       // Immediate is always encoded as positive. The 'U' bit controls add vs
297       // sub.
298       bool isAdd = true;
299       if (Imm12 < 0) {
300         Imm12 = -Imm12;
301         isAdd = false;
302       }
303
304       uint32_t Binary = Imm12 & 0xfff;
305       if (isAdd)
306         Binary |= (1 << 12);
307       Binary |= (Reg << 13);
308       return Binary;
309     }
310     unsigned getNEONVcvtImm32OpValue(const MachineInstr &MI, unsigned Op)
311       const { return 0; }
312
313     unsigned getRegisterListOpValue(const MachineInstr &MI, unsigned Op)
314       const { return 0; }
315
316     unsigned getShiftRight8Imm(const MachineInstr &MI, unsigned Op)
317       const { return 0; }
318     unsigned getShiftRight16Imm(const MachineInstr &MI, unsigned Op)
319       const { return 0; }
320     unsigned getShiftRight32Imm(const MachineInstr &MI, unsigned Op)
321       const { return 0; }
322     unsigned getShiftRight64Imm(const MachineInstr &MI, unsigned Op)
323       const { return 0; }
324
325     /// getMovi32Value - Return binary encoding of operand for movw/movt. If the
326     /// machine operand requires relocation, record the relocation and return
327     /// zero.
328     unsigned getMovi32Value(const MachineInstr &MI,const MachineOperand &MO,
329                             unsigned Reloc);
330
331     /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
332     ///
333     unsigned getShiftOp(unsigned Imm) const ;
334
335     /// Routines that handle operands which add machine relocations which are
336     /// fixed up by the relocation stage.
337     void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
338                            bool MayNeedFarStub,  bool Indirect,
339                            intptr_t ACPV = 0) const;
340     void emitExternalSymbolAddress(const char *ES, unsigned Reloc) const;
341     void emitConstPoolAddress(unsigned CPI, unsigned Reloc) const;
342     void emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) const;
343     void emitMachineBasicBlock(MachineBasicBlock *BB, unsigned Reloc,
344                                intptr_t JTBase = 0) const;
345     unsigned encodeVFPRd(const MachineInstr &MI, unsigned OpIdx) const;
346     unsigned encodeVFPRn(const MachineInstr &MI, unsigned OpIdx) const;
347     unsigned encodeVFPRm(const MachineInstr &MI, unsigned OpIdx) const;
348     unsigned encodeNEONRd(const MachineInstr &MI, unsigned OpIdx) const;
349     unsigned encodeNEONRn(const MachineInstr &MI, unsigned OpIdx) const;
350     unsigned encodeNEONRm(const MachineInstr &MI, unsigned OpIdx) const;
351   };
352 }
353
354 char ARMCodeEmitter::ID = 0;
355
356 /// createARMJITCodeEmitterPass - Return a pass that emits the collected ARM
357 /// code to the specified MCE object.
358 FunctionPass *llvm::createARMJITCodeEmitterPass(ARMBaseTargetMachine &TM,
359                                                 JITCodeEmitter &JCE) {
360   return new ARMCodeEmitter(TM, JCE);
361 }
362
363 bool ARMCodeEmitter::runOnMachineFunction(MachineFunction &MF) {
364   TargetMachine &Target = const_cast<TargetMachine&>(MF.getTarget());
365
366   assert((Target.getRelocationModel() != Reloc::Default ||
367           Target.getRelocationModel() != Reloc::Static) &&
368          "JIT relocation model must be set to static or default!");
369
370   JTI = static_cast<ARMJITInfo*>(Target.getJITInfo());
371   II = static_cast<const ARMBaseInstrInfo*>(Target.getInstrInfo());
372   TD = Target.getDataLayout();
373
374   Subtarget = &TM.getSubtarget<ARMSubtarget>();
375   MCPEs = &MF.getConstantPool()->getConstants();
376   MJTEs = 0;
377   if (MF.getJumpTableInfo()) MJTEs = &MF.getJumpTableInfo()->getJumpTables();
378   IsPIC = TM.getRelocationModel() == Reloc::PIC_;
379   IsThumb = MF.getInfo<ARMFunctionInfo>()->isThumbFunction();
380   JTI->Initialize(MF, IsPIC);
381   MMI = &getAnalysis<MachineModuleInfo>();
382   MCE.setModuleInfo(MMI);
383
384   do {
385     DEBUG(errs() << "JITTing function '"
386           << MF.getName() << "'\n");
387     MCE.startFunction(MF);
388     for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
389          MBB != E; ++MBB) {
390       MCE.StartMachineBasicBlock(MBB);
391       for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
392            I != E; ++I)
393         emitInstruction(*I);
394     }
395   } while (MCE.finishFunction(MF));
396
397   return false;
398 }
399
400 /// getShiftOp - Return the shift opcode (bit[6:5]) of the immediate value.
401 ///
402 unsigned ARMCodeEmitter::getShiftOp(unsigned Imm) const {
403   switch (ARM_AM::getAM2ShiftOpc(Imm)) {
404   default: llvm_unreachable("Unknown shift opc!");
405   case ARM_AM::asr: return 2;
406   case ARM_AM::lsl: return 0;
407   case ARM_AM::lsr: return 1;
408   case ARM_AM::ror:
409   case ARM_AM::rrx: return 3;
410   }
411 }
412
413 /// getMovi32Value - Return binary encoding of operand for movw/movt. If the
414 /// machine operand requires relocation, record the relocation and return zero.
415 unsigned ARMCodeEmitter::getMovi32Value(const MachineInstr &MI,
416                                         const MachineOperand &MO,
417                                         unsigned Reloc) {
418   assert(((Reloc == ARM::reloc_arm_movt) || (Reloc == ARM::reloc_arm_movw))
419       && "Relocation to this function should be for movt or movw");
420
421   if (MO.isImm())
422     return static_cast<unsigned>(MO.getImm());
423   else if (MO.isGlobal())
424     emitGlobalAddress(MO.getGlobal(), Reloc, true, false);
425   else if (MO.isSymbol())
426     emitExternalSymbolAddress(MO.getSymbolName(), Reloc);
427   else if (MO.isMBB())
428     emitMachineBasicBlock(MO.getMBB(), Reloc);
429   else {
430 #ifndef NDEBUG
431     errs() << MO;
432 #endif
433     llvm_unreachable("Unsupported operand type for movw/movt");
434   }
435   return 0;
436 }
437
438 /// getMachineOpValue - Return binary encoding of operand. If the machine
439 /// operand requires relocation, record the relocation and return zero.
440 unsigned ARMCodeEmitter::getMachineOpValue(const MachineInstr &MI,
441                                            const MachineOperand &MO) const {
442   if (MO.isReg())
443     return II->getRegisterInfo().getEncodingValue(MO.getReg());
444   else if (MO.isImm())
445     return static_cast<unsigned>(MO.getImm());
446   else if (MO.isGlobal())
447     emitGlobalAddress(MO.getGlobal(), ARM::reloc_arm_branch, true, false);
448   else if (MO.isSymbol())
449     emitExternalSymbolAddress(MO.getSymbolName(), ARM::reloc_arm_branch);
450   else if (MO.isCPI()) {
451     const MCInstrDesc &MCID = MI.getDesc();
452     // For VFP load, the immediate offset is multiplied by 4.
453     unsigned Reloc =  ((MCID.TSFlags & ARMII::FormMask) == ARMII::VFPLdStFrm)
454       ? ARM::reloc_arm_vfp_cp_entry : ARM::reloc_arm_cp_entry;
455     emitConstPoolAddress(MO.getIndex(), Reloc);
456   } else if (MO.isJTI())
457     emitJumpTableAddress(MO.getIndex(), ARM::reloc_arm_relative);
458   else if (MO.isMBB())
459     emitMachineBasicBlock(MO.getMBB(), ARM::reloc_arm_branch);
460   else
461     llvm_unreachable("Unable to encode MachineOperand!");
462   return 0;
463 }
464
465 /// emitGlobalAddress - Emit the specified address to the code stream.
466 ///
467 void ARMCodeEmitter::emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
468                                        bool MayNeedFarStub, bool Indirect,
469                                        intptr_t ACPV) const {
470   MachineRelocation MR = Indirect
471     ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
472                                            const_cast<GlobalValue *>(GV),
473                                            ACPV, MayNeedFarStub)
474     : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
475                                const_cast<GlobalValue *>(GV), ACPV,
476                                MayNeedFarStub);
477   MCE.addRelocation(MR);
478 }
479
480 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
481 /// be emitted to the current location in the function, and allow it to be PC
482 /// relative.
483 void ARMCodeEmitter::
484 emitExternalSymbolAddress(const char *ES, unsigned Reloc) const {
485   MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
486                                                  Reloc, ES));
487 }
488
489 /// emitConstPoolAddress - Arrange for the address of an constant pool
490 /// to be emitted to the current location in the function, and allow it to be PC
491 /// relative.
492 void ARMCodeEmitter::emitConstPoolAddress(unsigned CPI, unsigned Reloc) const {
493   // Tell JIT emitter we'll resolve the address.
494   MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
495                                                     Reloc, CPI, 0, true));
496 }
497
498 /// emitJumpTableAddress - Arrange for the address of a jump table to
499 /// be emitted to the current location in the function, and allow it to be PC
500 /// relative.
501 void ARMCodeEmitter::
502 emitJumpTableAddress(unsigned JTIndex, unsigned Reloc) const {
503   MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
504                                                     Reloc, JTIndex, 0, true));
505 }
506
507 /// emitMachineBasicBlock - Emit the specified address basic block.
508 void ARMCodeEmitter::emitMachineBasicBlock(MachineBasicBlock *BB,
509                                            unsigned Reloc,
510                                            intptr_t JTBase) const {
511   MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
512                                              Reloc, BB, JTBase));
513 }
514
515 void ARMCodeEmitter::emitWordLE(unsigned Binary) {
516   DEBUG(errs() << "  0x";
517         errs().write_hex(Binary) << "\n");
518   MCE.emitWordLE(Binary);
519 }
520
521 void ARMCodeEmitter::emitDWordLE(uint64_t Binary) {
522   DEBUG(errs() << "  0x";
523         errs().write_hex(Binary) << "\n");
524   MCE.emitDWordLE(Binary);
525 }
526
527 void ARMCodeEmitter::emitInstruction(const MachineInstr &MI) {
528   DEBUG(errs() << "JIT: " << (void*)MCE.getCurrentPCValue() << ":\t" << MI);
529
530   MCE.processDebugLoc(MI.getDebugLoc(), true);
531
532   ++NumEmitted;  // Keep track of the # of mi's emitted
533   switch (MI.getDesc().TSFlags & ARMII::FormMask) {
534   default: {
535     llvm_unreachable("Unhandled instruction encoding format!");
536   }
537   case ARMII::MiscFrm:
538     if (MI.getOpcode() == ARM::LEApcrelJT) {
539       // Materialize jumptable address.
540       emitLEApcrelJTInstruction(MI);
541       break;
542     }
543     llvm_unreachable("Unhandled instruction encoding!");
544   case ARMII::Pseudo:
545     emitPseudoInstruction(MI);
546     break;
547   case ARMII::DPFrm:
548   case ARMII::DPSoRegFrm:
549     emitDataProcessingInstruction(MI);
550     break;
551   case ARMII::LdFrm:
552   case ARMII::StFrm:
553     emitLoadStoreInstruction(MI);
554     break;
555   case ARMII::LdMiscFrm:
556   case ARMII::StMiscFrm:
557     emitMiscLoadStoreInstruction(MI);
558     break;
559   case ARMII::LdStMulFrm:
560     emitLoadStoreMultipleInstruction(MI);
561     break;
562   case ARMII::MulFrm:
563     emitMulFrmInstruction(MI);
564     break;
565   case ARMII::ExtFrm:
566     emitExtendInstruction(MI);
567     break;
568   case ARMII::ArithMiscFrm:
569     emitMiscArithInstruction(MI);
570     break;
571   case ARMII::SatFrm:
572     emitSaturateInstruction(MI);
573     break;
574   case ARMII::BrFrm:
575     emitBranchInstruction(MI);
576     break;
577   case ARMII::BrMiscFrm:
578     emitMiscBranchInstruction(MI);
579     break;
580   // VFP instructions.
581   case ARMII::VFPUnaryFrm:
582   case ARMII::VFPBinaryFrm:
583     emitVFPArithInstruction(MI);
584     break;
585   case ARMII::VFPConv1Frm:
586   case ARMII::VFPConv2Frm:
587   case ARMII::VFPConv3Frm:
588   case ARMII::VFPConv4Frm:
589   case ARMII::VFPConv5Frm:
590     emitVFPConversionInstruction(MI);
591     break;
592   case ARMII::VFPLdStFrm:
593     emitVFPLoadStoreInstruction(MI);
594     break;
595   case ARMII::VFPLdStMulFrm:
596     emitVFPLoadStoreMultipleInstruction(MI);
597     break;
598
599   // NEON instructions.
600   case ARMII::NGetLnFrm:
601   case ARMII::NSetLnFrm:
602     emitNEONLaneInstruction(MI);
603     break;
604   case ARMII::NDupFrm:
605     emitNEONDupInstruction(MI);
606     break;
607   case ARMII::N1RegModImmFrm:
608     emitNEON1RegModImmInstruction(MI);
609     break;
610   case ARMII::N2RegFrm:
611     emitNEON2RegInstruction(MI);
612     break;
613   case ARMII::N3RegFrm:
614     emitNEON3RegInstruction(MI);
615     break;
616   }
617   MCE.processDebugLoc(MI.getDebugLoc(), false);
618 }
619
620 void ARMCodeEmitter::emitConstPoolInstruction(const MachineInstr &MI) {
621   unsigned CPI = MI.getOperand(0).getImm();       // CP instruction index.
622   unsigned CPIndex = MI.getOperand(1).getIndex(); // Actual cp entry index.
623   const MachineConstantPoolEntry &MCPE = (*MCPEs)[CPIndex];
624
625   // Remember the CONSTPOOL_ENTRY address for later relocation.
626   JTI->addConstantPoolEntryAddr(CPI, MCE.getCurrentPCValue());
627
628   // Emit constpool island entry. In most cases, the actual values will be
629   // resolved and relocated after code emission.
630   if (MCPE.isMachineConstantPoolEntry()) {
631     ARMConstantPoolValue *ACPV =
632       static_cast<ARMConstantPoolValue*>(MCPE.Val.MachineCPVal);
633
634     DEBUG(errs() << "  ** ARM constant pool #" << CPI << " @ "
635           << (void*)MCE.getCurrentPCValue() << " " << *ACPV << '\n');
636
637     assert(ACPV->isGlobalValue() && "unsupported constant pool value");
638     const GlobalValue *GV = cast<ARMConstantPoolConstant>(ACPV)->getGV();
639     if (GV) {
640       Reloc::Model RelocM = TM.getRelocationModel();
641       emitGlobalAddress(GV, ARM::reloc_arm_machine_cp_entry,
642                         isa<Function>(GV),
643                         Subtarget->GVIsIndirectSymbol(GV, RelocM),
644                         (intptr_t)ACPV);
645     } else  {
646       const char *Sym = cast<ARMConstantPoolSymbol>(ACPV)->getSymbol();
647       emitExternalSymbolAddress(Sym, ARM::reloc_arm_absolute);
648     }
649     emitWordLE(0);
650   } else {
651     const Constant *CV = MCPE.Val.ConstVal;
652
653     DEBUG({
654         errs() << "  ** Constant pool #" << CPI << " @ "
655                << (void*)MCE.getCurrentPCValue() << " ";
656         if (const Function *F = dyn_cast<Function>(CV))
657           errs() << F->getName();
658         else
659           errs() << *CV;
660         errs() << '\n';
661       });
662
663     if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
664       emitGlobalAddress(GV, ARM::reloc_arm_absolute, isa<Function>(GV), false);
665       emitWordLE(0);
666     } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
667       uint32_t Val = uint32_t(*CI->getValue().getRawData());
668       emitWordLE(Val);
669     } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
670       if (CFP->getType()->isFloatTy())
671         emitWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
672       else if (CFP->getType()->isDoubleTy())
673         emitDWordLE(CFP->getValueAPF().bitcastToAPInt().getZExtValue());
674       else {
675         llvm_unreachable("Unable to handle this constantpool entry!");
676       }
677     } else {
678       llvm_unreachable("Unable to handle this constantpool entry!");
679     }
680   }
681 }
682
683 void ARMCodeEmitter::emitMOVi32immInstruction(const MachineInstr &MI) {
684   const MachineOperand &MO0 = MI.getOperand(0);
685   const MachineOperand &MO1 = MI.getOperand(1);
686
687   // Emit the 'movw' instruction.
688   unsigned Binary = 0x30 << 20;  // mov: Insts{27-20} = 0b00110000
689
690   unsigned Lo16 = getMovi32Value(MI, MO1, ARM::reloc_arm_movw) & 0xFFFF;
691
692   // Set the conditional execution predicate.
693   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
694
695   // Encode Rd.
696   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
697
698   // Encode imm16 as imm4:imm12
699   Binary |= Lo16 & 0xFFF; // Insts{11-0} = imm12
700   Binary |= ((Lo16 >> 12) & 0xF) << 16; // Insts{19-16} = imm4
701   emitWordLE(Binary);
702
703   unsigned Hi16 = getMovi32Value(MI, MO1, ARM::reloc_arm_movt) >> 16;
704   // Emit the 'movt' instruction.
705   Binary = 0x34 << 20; // movt: Insts{27-20} = 0b00110100
706
707   // Set the conditional execution predicate.
708   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
709
710   // Encode Rd.
711   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
712
713   // Encode imm16 as imm4:imm1, same as movw above.
714   Binary |= Hi16 & 0xFFF;
715   Binary |= ((Hi16 >> 12) & 0xF) << 16;
716   emitWordLE(Binary);
717 }
718
719 void ARMCodeEmitter::emitMOVi2piecesInstruction(const MachineInstr &MI) {
720   const MachineOperand &MO0 = MI.getOperand(0);
721   const MachineOperand &MO1 = MI.getOperand(1);
722   assert(MO1.isImm() && ARM_AM::isSOImmTwoPartVal(MO1.getImm()) &&
723                                                   "Not a valid so_imm value!");
724   unsigned V1 = ARM_AM::getSOImmTwoPartFirst(MO1.getImm());
725   unsigned V2 = ARM_AM::getSOImmTwoPartSecond(MO1.getImm());
726
727   // Emit the 'mov' instruction.
728   unsigned Binary = 0xd << 21;  // mov: Insts{24-21} = 0b1101
729
730   // Set the conditional execution predicate.
731   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
732
733   // Encode Rd.
734   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
735
736   // Encode so_imm.
737   // Set bit I(25) to identify this is the immediate form of <shifter_op>
738   Binary |= 1 << ARMII::I_BitShift;
739   Binary |= getMachineSoImmOpValue(V1);
740   emitWordLE(Binary);
741
742   // Now the 'orr' instruction.
743   Binary = 0xc << 21;  // orr: Insts{24-21} = 0b1100
744
745   // Set the conditional execution predicate.
746   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
747
748   // Encode Rd.
749   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRdShift;
750
751   // Encode Rn.
752   Binary |= getMachineOpValue(MI, MO0) << ARMII::RegRnShift;
753
754   // Encode so_imm.
755   // Set bit I(25) to identify this is the immediate form of <shifter_op>
756   Binary |= 1 << ARMII::I_BitShift;
757   Binary |= getMachineSoImmOpValue(V2);
758   emitWordLE(Binary);
759 }
760
761 void ARMCodeEmitter::emitLEApcrelJTInstruction(const MachineInstr &MI) {
762   // It's basically add r, pc, (LJTI - $+8)
763
764   const MCInstrDesc &MCID = MI.getDesc();
765
766   // Emit the 'add' instruction.
767   unsigned Binary = 0x4 << 21;  // add: Insts{24-21} = 0b0100
768
769   // Set the conditional execution predicate
770   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
771
772   // Encode S bit if MI modifies CPSR.
773   Binary |= getAddrModeSBit(MI, MCID);
774
775   // Encode Rd.
776   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
777
778   // Encode Rn which is PC.
779   Binary |= II->getRegisterInfo().getEncodingValue(ARM::PC) << ARMII::RegRnShift;
780
781   // Encode the displacement.
782   Binary |= 1 << ARMII::I_BitShift;
783   emitJumpTableAddress(MI.getOperand(1).getIndex(), ARM::reloc_arm_jt_base);
784
785   emitWordLE(Binary);
786 }
787
788 void ARMCodeEmitter::emitPseudoMoveInstruction(const MachineInstr &MI) {
789   unsigned Opcode = MI.getDesc().Opcode;
790
791   // Part of binary is determined by TableGn.
792   unsigned Binary = getBinaryCodeForInstr(MI);
793
794   // Set the conditional execution predicate
795   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
796
797   // Encode S bit if MI modifies CPSR.
798   if (Opcode == ARM::MOVsrl_flag || Opcode == ARM::MOVsra_flag)
799     Binary |= 1 << ARMII::S_BitShift;
800
801   // Encode register def if there is one.
802   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
803
804   // Encode the shift operation.
805   switch (Opcode) {
806   default: break;
807   case ARM::RRX:
808     // rrx
809     Binary |= 0x6 << 4;
810     break;
811   case ARM::MOVsrl_flag:
812     // lsr #1
813     Binary |= (0x2 << 4) | (1 << 7);
814     break;
815   case ARM::MOVsra_flag:
816     // asr #1
817     Binary |= (0x4 << 4) | (1 << 7);
818     break;
819   }
820
821   // Encode register Rm.
822   Binary |= getMachineOpValue(MI, 1);
823
824   emitWordLE(Binary);
825 }
826
827 void ARMCodeEmitter::addPCLabel(unsigned LabelID) {
828   DEBUG(errs() << "  ** LPC" << LabelID << " @ "
829         << (void*)MCE.getCurrentPCValue() << '\n');
830   JTI->addPCLabelAddr(LabelID, MCE.getCurrentPCValue());
831 }
832
833 void ARMCodeEmitter::emitPseudoInstruction(const MachineInstr &MI) {
834   unsigned Opcode = MI.getDesc().Opcode;
835   switch (Opcode) {
836   default:
837     llvm_unreachable("ARMCodeEmitter::emitPseudoInstruction");
838   case ARM::BX_CALL:
839   case ARM::BMOVPCRX_CALL: {
840     // First emit mov lr, pc
841     unsigned Binary = 0x01a0e00f;
842     Binary |= II->getPredicate(&MI) << ARMII::CondShift;
843     emitWordLE(Binary);
844
845     // and then emit the branch.
846     emitMiscBranchInstruction(MI);
847     break;
848   }
849   case TargetOpcode::INLINEASM: {
850     // We allow inline assembler nodes with empty bodies - they can
851     // implicitly define registers, which is ok for JIT.
852     if (MI.getOperand(0).getSymbolName()[0]) {
853       report_fatal_error("JIT does not support inline asm!");
854     }
855     break;
856   }
857   case TargetOpcode::CFI_INSTRUCTION:
858     break;
859   case TargetOpcode::EH_LABEL:
860     MCE.emitLabel(MI.getOperand(0).getMCSymbol());
861     break;
862   case TargetOpcode::IMPLICIT_DEF:
863   case TargetOpcode::KILL:
864     // Do nothing.
865     break;
866   case ARM::CONSTPOOL_ENTRY:
867     emitConstPoolInstruction(MI);
868     break;
869   case ARM::PICADD: {
870     // Remember of the address of the PC label for relocation later.
871     addPCLabel(MI.getOperand(2).getImm());
872     // PICADD is just an add instruction that implicitly read pc.
873     emitDataProcessingInstruction(MI, 0, ARM::PC);
874     break;
875   }
876   case ARM::PICLDR:
877   case ARM::PICLDRB:
878   case ARM::PICSTR:
879   case ARM::PICSTRB: {
880     // Remember of the address of the PC label for relocation later.
881     addPCLabel(MI.getOperand(2).getImm());
882     // These are just load / store instructions that implicitly read pc.
883     emitLoadStoreInstruction(MI, 0, ARM::PC);
884     break;
885   }
886   case ARM::PICLDRH:
887   case ARM::PICLDRSH:
888   case ARM::PICLDRSB:
889   case ARM::PICSTRH: {
890     // Remember of the address of the PC label for relocation later.
891     addPCLabel(MI.getOperand(2).getImm());
892     // These are just load / store instructions that implicitly read pc.
893     emitMiscLoadStoreInstruction(MI, ARM::PC);
894     break;
895   }
896
897   case ARM::MOVi32imm:
898     // Two instructions to materialize a constant.
899     if (Subtarget->hasV6T2Ops())
900       emitMOVi32immInstruction(MI);
901     else
902       emitMOVi2piecesInstruction(MI);
903     break;
904
905   case ARM::LEApcrelJT:
906     // Materialize jumptable address.
907     emitLEApcrelJTInstruction(MI);
908     break;
909   case ARM::RRX:
910   case ARM::MOVsrl_flag:
911   case ARM::MOVsra_flag:
912     emitPseudoMoveInstruction(MI);
913     break;
914   }
915 }
916
917 unsigned ARMCodeEmitter::getMachineSoRegOpValue(const MachineInstr &MI,
918                                                 const MCInstrDesc &MCID,
919                                                 const MachineOperand &MO,
920                                                 unsigned OpIdx) {
921   unsigned Binary = getMachineOpValue(MI, MO);
922
923   const MachineOperand &MO1 = MI.getOperand(OpIdx + 1);
924   const MachineOperand &MO2 = MI.getOperand(OpIdx + 2);
925   ARM_AM::ShiftOpc SOpc = ARM_AM::getSORegShOp(MO2.getImm());
926
927   // Encode the shift opcode.
928   unsigned SBits = 0;
929   unsigned Rs = MO1.getReg();
930   if (Rs) {
931     // Set shift operand (bit[7:4]).
932     // LSL - 0001
933     // LSR - 0011
934     // ASR - 0101
935     // ROR - 0111
936     // RRX - 0110 and bit[11:8] clear.
937     switch (SOpc) {
938     default: llvm_unreachable("Unknown shift opc!");
939     case ARM_AM::lsl: SBits = 0x1; break;
940     case ARM_AM::lsr: SBits = 0x3; break;
941     case ARM_AM::asr: SBits = 0x5; break;
942     case ARM_AM::ror: SBits = 0x7; break;
943     case ARM_AM::rrx: SBits = 0x6; break;
944     }
945   } else {
946     // Set shift operand (bit[6:4]).
947     // LSL - 000
948     // LSR - 010
949     // ASR - 100
950     // ROR - 110
951     switch (SOpc) {
952     default: llvm_unreachable("Unknown shift opc!");
953     case ARM_AM::lsl: SBits = 0x0; break;
954     case ARM_AM::lsr: SBits = 0x2; break;
955     case ARM_AM::asr: SBits = 0x4; break;
956     case ARM_AM::ror: SBits = 0x6; break;
957     }
958   }
959   Binary |= SBits << 4;
960   if (SOpc == ARM_AM::rrx)
961     return Binary;
962
963   // Encode the shift operation Rs or shift_imm (except rrx).
964   if (Rs) {
965     // Encode Rs bit[11:8].
966     assert(ARM_AM::getSORegOffset(MO2.getImm()) == 0);
967     return Binary | (II->getRegisterInfo().getEncodingValue(Rs) << ARMII::RegRsShift);
968   }
969
970   // Encode shift_imm bit[11:7].
971   return Binary | ARM_AM::getSORegOffset(MO2.getImm()) << 7;
972 }
973
974 unsigned ARMCodeEmitter::getMachineSoImmOpValue(unsigned SoImm) {
975   int SoImmVal = ARM_AM::getSOImmVal(SoImm);
976   assert(SoImmVal != -1 && "Not a valid so_imm value!");
977
978   // Encode rotate_imm.
979   unsigned Binary = (ARM_AM::getSOImmValRot((unsigned)SoImmVal) >> 1)
980     << ARMII::SoRotImmShift;
981
982   // Encode immed_8.
983   Binary |= ARM_AM::getSOImmValImm((unsigned)SoImmVal);
984   return Binary;
985 }
986
987 unsigned ARMCodeEmitter::getAddrModeSBit(const MachineInstr &MI,
988                                          const MCInstrDesc &MCID) const {
989   for (unsigned i = MI.getNumOperands(), e = MCID.getNumOperands(); i >= e;--i){
990     const MachineOperand &MO = MI.getOperand(i-1);
991     if (MO.isReg() && MO.isDef() && MO.getReg() == ARM::CPSR)
992       return 1 << ARMII::S_BitShift;
993   }
994   return 0;
995 }
996
997 void ARMCodeEmitter::emitDataProcessingInstruction(const MachineInstr &MI,
998                                                    unsigned ImplicitRd,
999                                                    unsigned ImplicitRn) {
1000   const MCInstrDesc &MCID = MI.getDesc();
1001
1002   // Part of binary is determined by TableGn.
1003   unsigned Binary = getBinaryCodeForInstr(MI);
1004
1005   // Set the conditional execution predicate
1006   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1007
1008   // Encode S bit if MI modifies CPSR.
1009   Binary |= getAddrModeSBit(MI, MCID);
1010
1011   // Encode register def if there is one.
1012   unsigned NumDefs = MCID.getNumDefs();
1013   unsigned OpIdx = 0;
1014   if (NumDefs)
1015     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1016   else if (ImplicitRd)
1017     // Special handling for implicit use (e.g. PC).
1018     Binary |= (II->getRegisterInfo().getEncodingValue(ImplicitRd) << ARMII::RegRdShift);
1019
1020   if (MCID.Opcode == ARM::MOVi16) {
1021       // Get immediate from MI.
1022       unsigned Lo16 = getMovi32Value(MI, MI.getOperand(OpIdx),
1023                       ARM::reloc_arm_movw);
1024       // Encode imm which is the same as in emitMOVi32immInstruction().
1025       Binary |= Lo16 & 0xFFF;
1026       Binary |= ((Lo16 >> 12) & 0xF) << 16;
1027       emitWordLE(Binary);
1028       return;
1029   } else if(MCID.Opcode == ARM::MOVTi16) {
1030       unsigned Hi16 = (getMovi32Value(MI, MI.getOperand(OpIdx),
1031                        ARM::reloc_arm_movt) >> 16);
1032       Binary |= Hi16 & 0xFFF;
1033       Binary |= ((Hi16 >> 12) & 0xF) << 16;
1034       emitWordLE(Binary);
1035       return;
1036   } else if ((MCID.Opcode == ARM::BFC) || (MCID.Opcode == ARM::BFI)) {
1037       uint32_t v = ~MI.getOperand(2).getImm();
1038       int32_t lsb = countTrailingZeros(v);
1039       int32_t msb = (32 - countLeadingZeros(v)) - 1;
1040       // Instr{20-16} = msb, Instr{11-7} = lsb
1041       Binary |= (msb & 0x1F) << 16;
1042       Binary |= (lsb & 0x1F) << 7;
1043       emitWordLE(Binary);
1044       return;
1045   } else if ((MCID.Opcode == ARM::UBFX) || (MCID.Opcode == ARM::SBFX)) {
1046       // Encode Rn in Instr{0-3}
1047       Binary |= getMachineOpValue(MI, OpIdx++);
1048
1049       uint32_t lsb = MI.getOperand(OpIdx++).getImm();
1050       uint32_t widthm1 = MI.getOperand(OpIdx++).getImm() - 1;
1051
1052       // Instr{20-16} = widthm1, Instr{11-7} = lsb
1053       Binary |= (widthm1 & 0x1F) << 16;
1054       Binary |= (lsb & 0x1F) << 7;
1055       emitWordLE(Binary);
1056       return;
1057   }
1058
1059   // If this is a two-address operand, skip it. e.g. MOVCCr operand 1.
1060   if (MCID.getOperandConstraint(OpIdx, MCOI::TIED_TO) != -1)
1061     ++OpIdx;
1062
1063   // Encode first non-shifter register operand if there is one.
1064   bool isUnary = MCID.TSFlags & ARMII::UnaryDP;
1065   if (!isUnary) {
1066     if (ImplicitRn)
1067       // Special handling for implicit use (e.g. PC).
1068       Binary |= (II->getRegisterInfo().getEncodingValue(ImplicitRn) << ARMII::RegRnShift);
1069     else {
1070       Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRnShift;
1071       ++OpIdx;
1072     }
1073   }
1074
1075   // Encode shifter operand.
1076   const MachineOperand &MO = MI.getOperand(OpIdx);
1077   if ((MCID.TSFlags & ARMII::FormMask) == ARMII::DPSoRegFrm) {
1078     // Encode SoReg.
1079     emitWordLE(Binary | getMachineSoRegOpValue(MI, MCID, MO, OpIdx));
1080     return;
1081   }
1082
1083   if (MO.isReg()) {
1084     // Encode register Rm.
1085     emitWordLE(Binary | II->getRegisterInfo().getEncodingValue(MO.getReg()));
1086     return;
1087   }
1088
1089   // Encode so_imm.
1090   Binary |= getMachineSoImmOpValue((unsigned)MO.getImm());
1091
1092   emitWordLE(Binary);
1093 }
1094
1095 void ARMCodeEmitter::emitLoadStoreInstruction(const MachineInstr &MI,
1096                                               unsigned ImplicitRd,
1097                                               unsigned ImplicitRn) {
1098   const MCInstrDesc &MCID = MI.getDesc();
1099   unsigned Form = MCID.TSFlags & ARMII::FormMask;
1100   bool IsPrePost = (MCID.TSFlags & ARMII::IndexModeMask) != 0;
1101
1102   // Part of binary is determined by TableGn.
1103   unsigned Binary = getBinaryCodeForInstr(MI);
1104
1105   // If this is an LDRi12, STRi12 or LDRcp, nothing more needs be done.
1106   if (MI.getOpcode() == ARM::LDRi12 || MI.getOpcode() == ARM::LDRcp ||
1107       MI.getOpcode() == ARM::STRi12) {
1108     emitWordLE(Binary);
1109     return;
1110   }
1111
1112   // Set the conditional execution predicate
1113   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1114
1115   unsigned OpIdx = 0;
1116
1117   // Operand 0 of a pre- and post-indexed store is the address base
1118   // writeback. Skip it.
1119   bool Skipped = false;
1120   if (IsPrePost && Form == ARMII::StFrm) {
1121     ++OpIdx;
1122     Skipped = true;
1123   }
1124
1125   // Set first operand
1126   if (ImplicitRd)
1127     // Special handling for implicit use (e.g. PC).
1128     Binary |= (II->getRegisterInfo().getEncodingValue(ImplicitRd) << ARMII::RegRdShift);
1129   else
1130     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1131
1132   // Set second operand
1133   if (ImplicitRn)
1134     // Special handling for implicit use (e.g. PC).
1135     Binary |= (II->getRegisterInfo().getEncodingValue(ImplicitRn) << ARMII::RegRnShift);
1136   else
1137     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1138
1139   // If this is a two-address operand, skip it. e.g. LDR_PRE.
1140   if (!Skipped && MCID.getOperandConstraint(OpIdx, MCOI::TIED_TO) != -1)
1141     ++OpIdx;
1142
1143   const MachineOperand &MO2 = MI.getOperand(OpIdx);
1144   unsigned AM2Opc = (ImplicitRn == ARM::PC)
1145     ? 0 : MI.getOperand(OpIdx+1).getImm();
1146
1147   // Set bit U(23) according to sign of immed value (positive or negative).
1148   Binary |= ((ARM_AM::getAM2Op(AM2Opc) == ARM_AM::add ? 1 : 0) <<
1149              ARMII::U_BitShift);
1150   if (!MO2.getReg()) { // is immediate
1151     if (ARM_AM::getAM2Offset(AM2Opc))
1152       // Set the value of offset_12 field
1153       Binary |= ARM_AM::getAM2Offset(AM2Opc);
1154     emitWordLE(Binary);
1155     return;
1156   }
1157
1158   // Set bit I(25), because this is not in immediate encoding.
1159   Binary |= 1 << ARMII::I_BitShift;
1160   assert(TargetRegisterInfo::isPhysicalRegister(MO2.getReg()));
1161   // Set bit[3:0] to the corresponding Rm register
1162   Binary |= II->getRegisterInfo().getEncodingValue(MO2.getReg());
1163
1164   // If this instr is in scaled register offset/index instruction, set
1165   // shift_immed(bit[11:7]) and shift(bit[6:5]) fields.
1166   if (unsigned ShImm = ARM_AM::getAM2Offset(AM2Opc)) {
1167     Binary |= getShiftOp(AM2Opc) << ARMII::ShiftImmShift;  // shift
1168     Binary |= ShImm              << ARMII::ShiftShift;     // shift_immed
1169   }
1170
1171   emitWordLE(Binary);
1172 }
1173
1174 void ARMCodeEmitter::emitMiscLoadStoreInstruction(const MachineInstr &MI,
1175                                                   unsigned ImplicitRn) {
1176   const MCInstrDesc &MCID = MI.getDesc();
1177   unsigned Form = MCID.TSFlags & ARMII::FormMask;
1178   bool IsPrePost = (MCID.TSFlags & ARMII::IndexModeMask) != 0;
1179
1180   // Part of binary is determined by TableGn.
1181   unsigned Binary = getBinaryCodeForInstr(MI);
1182
1183   // Set the conditional execution predicate
1184   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1185
1186   unsigned OpIdx = 0;
1187
1188   // Operand 0 of a pre- and post-indexed store is the address base
1189   // writeback. Skip it.
1190   bool Skipped = false;
1191   if (IsPrePost && Form == ARMII::StMiscFrm) {
1192     ++OpIdx;
1193     Skipped = true;
1194   }
1195
1196   // Set first operand
1197   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1198
1199   // Skip LDRD and STRD's second operand.
1200   if (MCID.Opcode == ARM::LDRD || MCID.Opcode == ARM::STRD)
1201     ++OpIdx;
1202
1203   // Set second operand
1204   if (ImplicitRn)
1205     // Special handling for implicit use (e.g. PC).
1206     Binary |= (II->getRegisterInfo().getEncodingValue(ImplicitRn) << ARMII::RegRnShift);
1207   else
1208     Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1209
1210   // If this is a two-address operand, skip it. e.g. LDRH_POST.
1211   if (!Skipped && MCID.getOperandConstraint(OpIdx, MCOI::TIED_TO) != -1)
1212     ++OpIdx;
1213
1214   const MachineOperand &MO2 = MI.getOperand(OpIdx);
1215   unsigned AM3Opc = (ImplicitRn == ARM::PC)
1216     ? 0 : MI.getOperand(OpIdx+1).getImm();
1217
1218   // Set bit U(23) according to sign of immed value (positive or negative)
1219   Binary |= ((ARM_AM::getAM3Op(AM3Opc) == ARM_AM::add ? 1 : 0) <<
1220              ARMII::U_BitShift);
1221
1222   // If this instr is in register offset/index encoding, set bit[3:0]
1223   // to the corresponding Rm register.
1224   if (MO2.getReg()) {
1225     Binary |= II->getRegisterInfo().getEncodingValue(MO2.getReg());
1226     emitWordLE(Binary);
1227     return;
1228   }
1229
1230   // This instr is in immediate offset/index encoding, set bit 22 to 1.
1231   Binary |= 1 << ARMII::AM3_I_BitShift;
1232   if (unsigned ImmOffs = ARM_AM::getAM3Offset(AM3Opc)) {
1233     // Set operands
1234     Binary |= (ImmOffs >> 4) << ARMII::ImmHiShift;  // immedH
1235     Binary |= (ImmOffs & 0xF);                      // immedL
1236   }
1237
1238   emitWordLE(Binary);
1239 }
1240
1241 static unsigned getAddrModeUPBits(unsigned Mode) {
1242   unsigned Binary = 0;
1243
1244   // Set addressing mode by modifying bits U(23) and P(24)
1245   // IA - Increment after  - bit U = 1 and bit P = 0
1246   // IB - Increment before - bit U = 1 and bit P = 1
1247   // DA - Decrement after  - bit U = 0 and bit P = 0
1248   // DB - Decrement before - bit U = 0 and bit P = 1
1249   switch (Mode) {
1250   default: llvm_unreachable("Unknown addressing sub-mode!");
1251   case ARM_AM::da:                                     break;
1252   case ARM_AM::db: Binary |= 0x1 << ARMII::P_BitShift; break;
1253   case ARM_AM::ia: Binary |= 0x1 << ARMII::U_BitShift; break;
1254   case ARM_AM::ib: Binary |= 0x3 << ARMII::U_BitShift; break;
1255   }
1256
1257   return Binary;
1258 }
1259
1260 void ARMCodeEmitter::emitLoadStoreMultipleInstruction(const MachineInstr &MI) {
1261   const MCInstrDesc &MCID = MI.getDesc();
1262   bool IsUpdating = (MCID.TSFlags & ARMII::IndexModeMask) != 0;
1263
1264   // Part of binary is determined by TableGn.
1265   unsigned Binary = getBinaryCodeForInstr(MI);
1266
1267   // Set the conditional execution predicate
1268   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1269
1270   // Skip operand 0 of an instruction with base register update.
1271   unsigned OpIdx = 0;
1272   if (IsUpdating)
1273     ++OpIdx;
1274
1275   // Set base address operand
1276   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1277
1278   // Set addressing mode by modifying bits U(23) and P(24)
1279   ARM_AM::AMSubMode Mode = ARM_AM::getLoadStoreMultipleSubMode(MI.getOpcode());
1280   Binary |= getAddrModeUPBits(ARM_AM::getAM4SubMode(Mode));
1281
1282   // Set bit W(21)
1283   if (IsUpdating)
1284     Binary |= 0x1 << ARMII::W_BitShift;
1285
1286   // Set registers
1287   for (unsigned i = OpIdx+2, e = MI.getNumOperands(); i != e; ++i) {
1288     const MachineOperand &MO = MI.getOperand(i);
1289     if (!MO.isReg() || MO.isImplicit())
1290       break;
1291     unsigned RegNum = II->getRegisterInfo().getEncodingValue(MO.getReg());
1292     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
1293            RegNum < 16);
1294     Binary |= 0x1 << RegNum;
1295   }
1296
1297   emitWordLE(Binary);
1298 }
1299
1300 void ARMCodeEmitter::emitMulFrmInstruction(const MachineInstr &MI) {
1301   const MCInstrDesc &MCID = MI.getDesc();
1302
1303   // Part of binary is determined by TableGn.
1304   unsigned Binary = getBinaryCodeForInstr(MI);
1305
1306   // Set the conditional execution predicate
1307   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1308
1309   // Encode S bit if MI modifies CPSR.
1310   Binary |= getAddrModeSBit(MI, MCID);
1311
1312   // 32x32->64bit operations have two destination registers. The number
1313   // of register definitions will tell us if that's what we're dealing with.
1314   unsigned OpIdx = 0;
1315   if (MCID.getNumDefs() == 2)
1316     Binary |= getMachineOpValue (MI, OpIdx++) << ARMII::RegRdLoShift;
1317
1318   // Encode Rd
1319   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdHiShift;
1320
1321   // Encode Rm
1322   Binary |= getMachineOpValue(MI, OpIdx++);
1323
1324   // Encode Rs
1325   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRsShift;
1326
1327   // Many multiple instructions (e.g. MLA) have three src operands. Encode
1328   // it as Rn (for multiply, that's in the same offset as RdLo.
1329   if (MCID.getNumOperands() > OpIdx &&
1330       !MCID.OpInfo[OpIdx].isPredicate() &&
1331       !MCID.OpInfo[OpIdx].isOptionalDef())
1332     Binary |= getMachineOpValue(MI, OpIdx) << ARMII::RegRdLoShift;
1333
1334   emitWordLE(Binary);
1335 }
1336
1337 void ARMCodeEmitter::emitExtendInstruction(const MachineInstr &MI) {
1338   const MCInstrDesc &MCID = MI.getDesc();
1339
1340   // Part of binary is determined by TableGn.
1341   unsigned Binary = getBinaryCodeForInstr(MI);
1342
1343   // Set the conditional execution predicate
1344   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1345
1346   unsigned OpIdx = 0;
1347
1348   // Encode Rd
1349   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1350
1351   const MachineOperand &MO1 = MI.getOperand(OpIdx++);
1352   const MachineOperand &MO2 = MI.getOperand(OpIdx);
1353   if (MO2.isReg()) {
1354     // Two register operand form.
1355     // Encode Rn.
1356     Binary |= getMachineOpValue(MI, MO1) << ARMII::RegRnShift;
1357
1358     // Encode Rm.
1359     Binary |= getMachineOpValue(MI, MO2);
1360     ++OpIdx;
1361   } else {
1362     Binary |= getMachineOpValue(MI, MO1);
1363   }
1364
1365   // Encode rot imm (0, 8, 16, or 24) if it has a rotate immediate operand.
1366   if (MI.getOperand(OpIdx).isImm() &&
1367       !MCID.OpInfo[OpIdx].isPredicate() &&
1368       !MCID.OpInfo[OpIdx].isOptionalDef())
1369     Binary |= (getMachineOpValue(MI, OpIdx) / 8) << ARMII::ExtRotImmShift;
1370
1371   emitWordLE(Binary);
1372 }
1373
1374 void ARMCodeEmitter::emitMiscArithInstruction(const MachineInstr &MI) {
1375   const MCInstrDesc &MCID = MI.getDesc();
1376
1377   // Part of binary is determined by TableGn.
1378   unsigned Binary = getBinaryCodeForInstr(MI);
1379
1380   // Set the conditional execution predicate
1381   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1382
1383   // PKH instructions are finished at this point
1384   if (MCID.Opcode == ARM::PKHBT || MCID.Opcode == ARM::PKHTB) {
1385     emitWordLE(Binary);
1386     return;
1387   }
1388
1389   unsigned OpIdx = 0;
1390
1391   // Encode Rd
1392   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRdShift;
1393
1394   const MachineOperand &MO = MI.getOperand(OpIdx++);
1395   if (OpIdx == MCID.getNumOperands() ||
1396       MCID.OpInfo[OpIdx].isPredicate() ||
1397       MCID.OpInfo[OpIdx].isOptionalDef()) {
1398     // Encode Rm and it's done.
1399     Binary |= getMachineOpValue(MI, MO);
1400     emitWordLE(Binary);
1401     return;
1402   }
1403
1404   // Encode Rn.
1405   Binary |= getMachineOpValue(MI, MO) << ARMII::RegRnShift;
1406
1407   // Encode Rm.
1408   Binary |= getMachineOpValue(MI, OpIdx++);
1409
1410   // Encode shift_imm.
1411   unsigned ShiftAmt = MI.getOperand(OpIdx).getImm();
1412   if (MCID.Opcode == ARM::PKHTB) {
1413     assert(ShiftAmt != 0 && "PKHTB shift_imm is 0!");
1414     if (ShiftAmt == 32)
1415       ShiftAmt = 0;
1416   }
1417   assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
1418   Binary |= ShiftAmt << ARMII::ShiftShift;
1419
1420   emitWordLE(Binary);
1421 }
1422
1423 void ARMCodeEmitter::emitSaturateInstruction(const MachineInstr &MI) {
1424   const MCInstrDesc &MCID = MI.getDesc();
1425
1426   // Part of binary is determined by TableGen.
1427   unsigned Binary = getBinaryCodeForInstr(MI);
1428
1429   // Set the conditional execution predicate
1430   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1431
1432   // Encode Rd
1433   Binary |= getMachineOpValue(MI, 0) << ARMII::RegRdShift;
1434
1435   // Encode saturate bit position.
1436   unsigned Pos = MI.getOperand(1).getImm();
1437   if (MCID.Opcode == ARM::SSAT || MCID.Opcode == ARM::SSAT16)
1438     Pos -= 1;
1439   assert((Pos < 16 || (Pos < 32 &&
1440                        MCID.Opcode != ARM::SSAT16 &&
1441                        MCID.Opcode != ARM::USAT16)) &&
1442          "saturate bit position out of range");
1443   Binary |= Pos << 16;
1444
1445   // Encode Rm
1446   Binary |= getMachineOpValue(MI, 2);
1447
1448   // Encode shift_imm.
1449   if (MCID.getNumOperands() == 4) {
1450     unsigned ShiftOp = MI.getOperand(3).getImm();
1451     ARM_AM::ShiftOpc Opc = ARM_AM::getSORegShOp(ShiftOp);
1452     if (Opc == ARM_AM::asr)
1453       Binary |= (1 << 6);
1454     unsigned ShiftAmt = MI.getOperand(3).getImm();
1455     if (ShiftAmt == 32 && Opc == ARM_AM::asr)
1456       ShiftAmt = 0;
1457     assert(ShiftAmt < 32 && "shift_imm range is 0 to 31!");
1458     Binary |= ShiftAmt << ARMII::ShiftShift;
1459   }
1460
1461   emitWordLE(Binary);
1462 }
1463
1464 void ARMCodeEmitter::emitBranchInstruction(const MachineInstr &MI) {
1465   const MCInstrDesc &MCID = MI.getDesc();
1466
1467   if (MCID.Opcode == ARM::TPsoft) {
1468     llvm_unreachable("ARM::TPsoft FIXME"); // FIXME
1469   }
1470
1471   // Part of binary is determined by TableGn.
1472   unsigned Binary = getBinaryCodeForInstr(MI);
1473
1474   // Set the conditional execution predicate
1475   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1476
1477   // Set signed_immed_24 field
1478   Binary |= getMachineOpValue(MI, 0);
1479
1480   emitWordLE(Binary);
1481 }
1482
1483 void ARMCodeEmitter::emitInlineJumpTable(unsigned JTIndex) {
1484   // Remember the base address of the inline jump table.
1485   uintptr_t JTBase = MCE.getCurrentPCValue();
1486   JTI->addJumpTableBaseAddr(JTIndex, JTBase);
1487   DEBUG(errs() << "  ** Jump Table #" << JTIndex << " @ " << (void*)JTBase
1488                << '\n');
1489
1490   // Now emit the jump table entries.
1491   const std::vector<MachineBasicBlock*> &MBBs = (*MJTEs)[JTIndex].MBBs;
1492   for (unsigned i = 0, e = MBBs.size(); i != e; ++i) {
1493     if (IsPIC)
1494       // DestBB address - JT base.
1495       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_pic_jt, JTBase);
1496     else
1497       // Absolute DestBB address.
1498       emitMachineBasicBlock(MBBs[i], ARM::reloc_arm_absolute);
1499     emitWordLE(0);
1500   }
1501 }
1502
1503 void ARMCodeEmitter::emitMiscBranchInstruction(const MachineInstr &MI) {
1504   const MCInstrDesc &MCID = MI.getDesc();
1505
1506   // Handle jump tables.
1507   if (MCID.Opcode == ARM::BR_JTr || MCID.Opcode == ARM::BR_JTadd) {
1508     // First emit a ldr pc, [] instruction.
1509     emitDataProcessingInstruction(MI, ARM::PC);
1510
1511     // Then emit the inline jump table.
1512     unsigned JTIndex =
1513       (MCID.Opcode == ARM::BR_JTr)
1514       ? MI.getOperand(1).getIndex() : MI.getOperand(2).getIndex();
1515     emitInlineJumpTable(JTIndex);
1516     return;
1517   } else if (MCID.Opcode == ARM::BR_JTm) {
1518     // First emit a ldr pc, [] instruction.
1519     emitLoadStoreInstruction(MI, ARM::PC);
1520
1521     // Then emit the inline jump table.
1522     emitInlineJumpTable(MI.getOperand(3).getIndex());
1523     return;
1524   }
1525
1526   // Part of binary is determined by TableGn.
1527   unsigned Binary = getBinaryCodeForInstr(MI);
1528
1529   // Set the conditional execution predicate
1530   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1531
1532   if (MCID.Opcode == ARM::BX_RET || MCID.Opcode == ARM::MOVPCLR)
1533     // The return register is LR.
1534     Binary |= II->getRegisterInfo().getEncodingValue(ARM::LR);
1535   else
1536     // otherwise, set the return register
1537     Binary |= getMachineOpValue(MI, 0);
1538
1539   emitWordLE(Binary);
1540 }
1541
1542 unsigned ARMCodeEmitter::encodeVFPRd(const MachineInstr &MI,
1543                                      unsigned OpIdx) const {
1544   unsigned RegD = MI.getOperand(OpIdx).getReg();
1545   unsigned Binary = 0;
1546   bool isSPVFP = ARM::SPRRegClass.contains(RegD);
1547   RegD = II->getRegisterInfo().getEncodingValue(RegD);
1548   if (!isSPVFP)
1549     Binary |=   RegD               << ARMII::RegRdShift;
1550   else {
1551     Binary |= ((RegD & 0x1E) >> 1) << ARMII::RegRdShift;
1552     Binary |=  (RegD & 0x01)       << ARMII::D_BitShift;
1553   }
1554   return Binary;
1555 }
1556
1557 unsigned ARMCodeEmitter::encodeVFPRn(const MachineInstr &MI,
1558                                      unsigned OpIdx) const {
1559   unsigned RegN = MI.getOperand(OpIdx).getReg();
1560   unsigned Binary = 0;
1561   bool isSPVFP = ARM::SPRRegClass.contains(RegN);
1562   RegN = II->getRegisterInfo().getEncodingValue(RegN);
1563   if (!isSPVFP)
1564     Binary |=   RegN               << ARMII::RegRnShift;
1565   else {
1566     Binary |= ((RegN & 0x1E) >> 1) << ARMII::RegRnShift;
1567     Binary |=  (RegN & 0x01)       << ARMII::N_BitShift;
1568   }
1569   return Binary;
1570 }
1571
1572 unsigned ARMCodeEmitter::encodeVFPRm(const MachineInstr &MI,
1573                                      unsigned OpIdx) const {
1574   unsigned RegM = MI.getOperand(OpIdx).getReg();
1575   unsigned Binary = 0;
1576   bool isSPVFP = ARM::SPRRegClass.contains(RegM);
1577   RegM = II->getRegisterInfo().getEncodingValue(RegM);
1578   if (!isSPVFP)
1579     Binary |=   RegM;
1580   else {
1581     Binary |= ((RegM & 0x1E) >> 1);
1582     Binary |=  (RegM & 0x01)       << ARMII::M_BitShift;
1583   }
1584   return Binary;
1585 }
1586
1587 void ARMCodeEmitter::emitVFPArithInstruction(const MachineInstr &MI) {
1588   const MCInstrDesc &MCID = MI.getDesc();
1589
1590   // Part of binary is determined by TableGn.
1591   unsigned Binary = getBinaryCodeForInstr(MI);
1592
1593   // Set the conditional execution predicate
1594   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1595
1596   unsigned OpIdx = 0;
1597   assert((Binary & ARMII::D_BitShift) == 0 &&
1598          (Binary & ARMII::N_BitShift) == 0 &&
1599          (Binary & ARMII::M_BitShift) == 0 && "VFP encoding bug!");
1600
1601   // Encode Dd / Sd.
1602   Binary |= encodeVFPRd(MI, OpIdx++);
1603
1604   // If this is a two-address operand, skip it, e.g. FMACD.
1605   if (MCID.getOperandConstraint(OpIdx, MCOI::TIED_TO) != -1)
1606     ++OpIdx;
1607
1608   // Encode Dn / Sn.
1609   if ((MCID.TSFlags & ARMII::FormMask) == ARMII::VFPBinaryFrm)
1610     Binary |= encodeVFPRn(MI, OpIdx++);
1611
1612   if (OpIdx == MCID.getNumOperands() ||
1613       MCID.OpInfo[OpIdx].isPredicate() ||
1614       MCID.OpInfo[OpIdx].isOptionalDef()) {
1615     // FCMPEZD etc. has only one operand.
1616     emitWordLE(Binary);
1617     return;
1618   }
1619
1620   // Encode Dm / Sm.
1621   Binary |= encodeVFPRm(MI, OpIdx);
1622
1623   emitWordLE(Binary);
1624 }
1625
1626 void ARMCodeEmitter::emitVFPConversionInstruction(const MachineInstr &MI) {
1627   const MCInstrDesc &MCID = MI.getDesc();
1628   unsigned Form = MCID.TSFlags & ARMII::FormMask;
1629
1630   // Part of binary is determined by TableGn.
1631   unsigned Binary = getBinaryCodeForInstr(MI);
1632
1633   // Set the conditional execution predicate
1634   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1635
1636   switch (Form) {
1637   default: break;
1638   case ARMII::VFPConv1Frm:
1639   case ARMII::VFPConv2Frm:
1640   case ARMII::VFPConv3Frm:
1641     // Encode Dd / Sd.
1642     Binary |= encodeVFPRd(MI, 0);
1643     break;
1644   case ARMII::VFPConv4Frm:
1645     // Encode Dn / Sn.
1646     Binary |= encodeVFPRn(MI, 0);
1647     break;
1648   case ARMII::VFPConv5Frm:
1649     // Encode Dm / Sm.
1650     Binary |= encodeVFPRm(MI, 0);
1651     break;
1652   }
1653
1654   switch (Form) {
1655   default: break;
1656   case ARMII::VFPConv1Frm:
1657     // Encode Dm / Sm.
1658     Binary |= encodeVFPRm(MI, 1);
1659     break;
1660   case ARMII::VFPConv2Frm:
1661   case ARMII::VFPConv3Frm:
1662     // Encode Dn / Sn.
1663     Binary |= encodeVFPRn(MI, 1);
1664     break;
1665   case ARMII::VFPConv4Frm:
1666   case ARMII::VFPConv5Frm:
1667     // Encode Dd / Sd.
1668     Binary |= encodeVFPRd(MI, 1);
1669     break;
1670   }
1671
1672   if (Form == ARMII::VFPConv5Frm)
1673     // Encode Dn / Sn.
1674     Binary |= encodeVFPRn(MI, 2);
1675   else if (Form == ARMII::VFPConv3Frm)
1676     // Encode Dm / Sm.
1677     Binary |= encodeVFPRm(MI, 2);
1678
1679   emitWordLE(Binary);
1680 }
1681
1682 void ARMCodeEmitter::emitVFPLoadStoreInstruction(const MachineInstr &MI) {
1683   // Part of binary is determined by TableGn.
1684   unsigned Binary = getBinaryCodeForInstr(MI);
1685
1686   // Set the conditional execution predicate
1687   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1688
1689   unsigned OpIdx = 0;
1690
1691   // Encode Dd / Sd.
1692   Binary |= encodeVFPRd(MI, OpIdx++);
1693
1694   // Encode address base.
1695   const MachineOperand &Base = MI.getOperand(OpIdx++);
1696   Binary |= getMachineOpValue(MI, Base) << ARMII::RegRnShift;
1697
1698   // If there is a non-zero immediate offset, encode it.
1699   if (Base.isReg()) {
1700     const MachineOperand &Offset = MI.getOperand(OpIdx);
1701     if (unsigned ImmOffs = ARM_AM::getAM5Offset(Offset.getImm())) {
1702       if (ARM_AM::getAM5Op(Offset.getImm()) == ARM_AM::add)
1703         Binary |= 1 << ARMII::U_BitShift;
1704       Binary |= ImmOffs;
1705       emitWordLE(Binary);
1706       return;
1707     }
1708   }
1709
1710   // If immediate offset is omitted, default to +0.
1711   Binary |= 1 << ARMII::U_BitShift;
1712
1713   emitWordLE(Binary);
1714 }
1715
1716 void
1717 ARMCodeEmitter::emitVFPLoadStoreMultipleInstruction(const MachineInstr &MI) {
1718   const MCInstrDesc &MCID = MI.getDesc();
1719   bool IsUpdating = (MCID.TSFlags & ARMII::IndexModeMask) != 0;
1720
1721   // Part of binary is determined by TableGn.
1722   unsigned Binary = getBinaryCodeForInstr(MI);
1723
1724   // Set the conditional execution predicate
1725   Binary |= II->getPredicate(&MI) << ARMII::CondShift;
1726
1727   // Skip operand 0 of an instruction with base register update.
1728   unsigned OpIdx = 0;
1729   if (IsUpdating)
1730     ++OpIdx;
1731
1732   // Set base address operand
1733   Binary |= getMachineOpValue(MI, OpIdx++) << ARMII::RegRnShift;
1734
1735   // Set addressing mode by modifying bits U(23) and P(24)
1736   ARM_AM::AMSubMode Mode = ARM_AM::getLoadStoreMultipleSubMode(MI.getOpcode());
1737   Binary |= getAddrModeUPBits(ARM_AM::getAM4SubMode(Mode));
1738
1739   // Set bit W(21)
1740   if (IsUpdating)
1741     Binary |= 0x1 << ARMII::W_BitShift;
1742
1743   // First register is encoded in Dd.
1744   Binary |= encodeVFPRd(MI, OpIdx+2);
1745
1746   // Count the number of registers.
1747   unsigned NumRegs = 1;
1748   for (unsigned i = OpIdx+3, e = MI.getNumOperands(); i != e; ++i) {
1749     const MachineOperand &MO = MI.getOperand(i);
1750     if (!MO.isReg() || MO.isImplicit())
1751       break;
1752     ++NumRegs;
1753   }
1754   // Bit 8 will be set if <list> is consecutive 64-bit registers (e.g., D0)
1755   // Otherwise, it will be 0, in the case of 32-bit registers.
1756   if(Binary & 0x100)
1757     Binary |= NumRegs * 2;
1758   else
1759     Binary |= NumRegs;
1760
1761   emitWordLE(Binary);
1762 }
1763
1764 unsigned ARMCodeEmitter::encodeNEONRd(const MachineInstr &MI,
1765                                       unsigned OpIdx) const {
1766   unsigned RegD = MI.getOperand(OpIdx).getReg();
1767   unsigned Binary = 0;
1768   RegD = II->getRegisterInfo().getEncodingValue(RegD);
1769   Binary |= (RegD & 0xf) << ARMII::RegRdShift;
1770   Binary |= ((RegD >> 4) & 1) << ARMII::D_BitShift;
1771   return Binary;
1772 }
1773
1774 unsigned ARMCodeEmitter::encodeNEONRn(const MachineInstr &MI,
1775                                       unsigned OpIdx) const {
1776   unsigned RegN = MI.getOperand(OpIdx).getReg();
1777   unsigned Binary = 0;
1778   RegN = II->getRegisterInfo().getEncodingValue(RegN);
1779   Binary |= (RegN & 0xf) << ARMII::RegRnShift;
1780   Binary |= ((RegN >> 4) & 1) << ARMII::N_BitShift;
1781   return Binary;
1782 }
1783
1784 unsigned ARMCodeEmitter::encodeNEONRm(const MachineInstr &MI,
1785                                       unsigned OpIdx) const {
1786   unsigned RegM = MI.getOperand(OpIdx).getReg();
1787   unsigned Binary = 0;
1788   RegM = II->getRegisterInfo().getEncodingValue(RegM);
1789   Binary |= (RegM & 0xf);
1790   Binary |= ((RegM >> 4) & 1) << ARMII::M_BitShift;
1791   return Binary;
1792 }
1793
1794 /// convertNEONDataProcToThumb - Convert the ARM mode encoding for a NEON
1795 /// data-processing instruction to the corresponding Thumb encoding.
1796 static unsigned convertNEONDataProcToThumb(unsigned Binary) {
1797   assert((Binary & 0xfe000000) == 0xf2000000 &&
1798          "not an ARM NEON data-processing instruction");
1799   unsigned UBit = (Binary >> 24) & 1;
1800   return 0xef000000 | (UBit << 28) | (Binary & 0xffffff);
1801 }
1802
1803 void ARMCodeEmitter::emitNEONLaneInstruction(const MachineInstr &MI) {
1804   unsigned Binary = getBinaryCodeForInstr(MI);
1805
1806   unsigned RegTOpIdx, RegNOpIdx, LnOpIdx;
1807   const MCInstrDesc &MCID = MI.getDesc();
1808   if ((MCID.TSFlags & ARMII::FormMask) == ARMII::NGetLnFrm) {
1809     RegTOpIdx = 0;
1810     RegNOpIdx = 1;
1811     LnOpIdx = 2;
1812   } else { // ARMII::NSetLnFrm
1813     RegTOpIdx = 2;
1814     RegNOpIdx = 0;
1815     LnOpIdx = 3;
1816   }
1817
1818   // Set the conditional execution predicate
1819   Binary |= (IsThumb ? ARMCC::AL : II->getPredicate(&MI)) << ARMII::CondShift;
1820
1821   unsigned RegT = MI.getOperand(RegTOpIdx).getReg();
1822   RegT = II->getRegisterInfo().getEncodingValue(RegT);
1823   Binary |= (RegT << ARMII::RegRdShift);
1824   Binary |= encodeNEONRn(MI, RegNOpIdx);
1825
1826   unsigned LaneShift;
1827   if ((Binary & (1 << 22)) != 0)
1828     LaneShift = 0; // 8-bit elements
1829   else if ((Binary & (1 << 5)) != 0)
1830     LaneShift = 1; // 16-bit elements
1831   else
1832     LaneShift = 2; // 32-bit elements
1833
1834   unsigned Lane = MI.getOperand(LnOpIdx).getImm() << LaneShift;
1835   unsigned Opc1 = Lane >> 2;
1836   unsigned Opc2 = Lane & 3;
1837   assert((Opc1 & 3) == 0 && "out-of-range lane number operand");
1838   Binary |= (Opc1 << 21);
1839   Binary |= (Opc2 << 5);
1840
1841   emitWordLE(Binary);
1842 }
1843
1844 void ARMCodeEmitter::emitNEONDupInstruction(const MachineInstr &MI) {
1845   unsigned Binary = getBinaryCodeForInstr(MI);
1846
1847   // Set the conditional execution predicate
1848   Binary |= (IsThumb ? ARMCC::AL : II->getPredicate(&MI)) << ARMII::CondShift;
1849
1850   unsigned RegT = MI.getOperand(1).getReg();
1851   RegT = II->getRegisterInfo().getEncodingValue(RegT);
1852   Binary |= (RegT << ARMII::RegRdShift);
1853   Binary |= encodeNEONRn(MI, 0);
1854   emitWordLE(Binary);
1855 }
1856
1857 void ARMCodeEmitter::emitNEON1RegModImmInstruction(const MachineInstr &MI) {
1858   unsigned Binary = getBinaryCodeForInstr(MI);
1859   // Destination register is encoded in Dd.
1860   Binary |= encodeNEONRd(MI, 0);
1861   // Immediate fields: Op, Cmode, I, Imm3, Imm4
1862   unsigned Imm = MI.getOperand(1).getImm();
1863   unsigned Op = (Imm >> 12) & 1;
1864   unsigned Cmode = (Imm >> 8) & 0xf;
1865   unsigned I = (Imm >> 7) & 1;
1866   unsigned Imm3 = (Imm >> 4) & 0x7;
1867   unsigned Imm4 = Imm & 0xf;
1868   Binary |= (I << 24) | (Imm3 << 16) | (Cmode << 8) | (Op << 5) | Imm4;
1869   if (IsThumb)
1870     Binary = convertNEONDataProcToThumb(Binary);
1871   emitWordLE(Binary);
1872 }
1873
1874 void ARMCodeEmitter::emitNEON2RegInstruction(const MachineInstr &MI) {
1875   const MCInstrDesc &MCID = MI.getDesc();
1876   unsigned Binary = getBinaryCodeForInstr(MI);
1877   // Destination register is encoded in Dd; source register in Dm.
1878   unsigned OpIdx = 0;
1879   Binary |= encodeNEONRd(MI, OpIdx++);
1880   if (MCID.getOperandConstraint(OpIdx, MCOI::TIED_TO) != -1)
1881     ++OpIdx;
1882   Binary |= encodeNEONRm(MI, OpIdx);
1883   if (IsThumb)
1884     Binary = convertNEONDataProcToThumb(Binary);
1885   // FIXME: This does not handle VDUPfdf or VDUPfqf.
1886   emitWordLE(Binary);
1887 }
1888
1889 void ARMCodeEmitter::emitNEON3RegInstruction(const MachineInstr &MI) {
1890   const MCInstrDesc &MCID = MI.getDesc();
1891   unsigned Binary = getBinaryCodeForInstr(MI);
1892   // Destination register is encoded in Dd; source registers in Dn and Dm.
1893   unsigned OpIdx = 0;
1894   Binary |= encodeNEONRd(MI, OpIdx++);
1895   if (MCID.getOperandConstraint(OpIdx, MCOI::TIED_TO) != -1)
1896     ++OpIdx;
1897   Binary |= encodeNEONRn(MI, OpIdx++);
1898   if (MCID.getOperandConstraint(OpIdx, MCOI::TIED_TO) != -1)
1899     ++OpIdx;
1900   Binary |= encodeNEONRm(MI, OpIdx);
1901   if (IsThumb)
1902     Binary = convertNEONDataProcToThumb(Binary);
1903   // FIXME: This does not handle VMOVDneon or VMOVQ.
1904   emitWordLE(Binary);
1905 }
1906
1907 #include "ARMGenCodeEmitter.inc"