1 //===-- X86CodeEmitter.cpp - Convert X86 code to machine code -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the pass that transforms the X86 machine instructions into
11 // relocatable machine code.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "x86-emitter"
17 #include "X86InstrInfo.h"
18 #include "X86JITInfo.h"
19 #include "X86Relocations.h"
20 #include "X86Subtarget.h"
21 #include "X86TargetMachine.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/JITCodeEmitter.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/CodeGen/MachineModuleInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/MC/MCCodeEmitter.h"
30 #include "llvm/MC/MCExpr.h"
31 #include "llvm/MC/MCInst.h"
32 #include "llvm/PassManager.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
39 STATISTIC(NumEmitted, "Number of machine instructions emitted");
42 template<class CodeEmitter>
43 class Emitter : public MachineFunctionPass {
44 const X86InstrInfo *II;
48 MachineModuleInfo *MMI;
49 intptr_t PICBaseOffset;
54 explicit Emitter(X86TargetMachine &tm, CodeEmitter &mce)
55 : MachineFunctionPass(ID), II(0), TD(0), TM(tm),
56 MCE(mce), PICBaseOffset(0), Is64BitMode(false),
57 IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
58 Emitter(X86TargetMachine &tm, CodeEmitter &mce,
59 const X86InstrInfo &ii, const DataLayout &td, bool is64)
60 : MachineFunctionPass(ID), II(&ii), TD(&td), TM(tm),
61 MCE(mce), PICBaseOffset(0), Is64BitMode(is64),
62 IsPIC(TM.getRelocationModel() == Reloc::PIC_) {}
64 bool runOnMachineFunction(MachineFunction &MF);
66 virtual const char *getPassName() const {
67 return "X86 Machine Code Emitter";
70 void emitOpcodePrefix(uint64_t TSFlags, int MemOperand,
71 const MachineInstr &MI,
72 const MCInstrDesc *Desc) const;
74 void emitVEXOpcodePrefix(uint64_t TSFlags, int MemOperand,
75 const MachineInstr &MI,
76 const MCInstrDesc *Desc) const;
78 void emitSegmentOverridePrefix(uint64_t TSFlags,
80 const MachineInstr &MI) const;
82 void emitInstruction(MachineInstr &MI, const MCInstrDesc *Desc);
84 void getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequired<MachineModuleInfo>();
87 MachineFunctionPass::getAnalysisUsage(AU);
91 void emitPCRelativeBlockAddress(MachineBasicBlock *MBB);
92 void emitGlobalAddress(const GlobalValue *GV, unsigned Reloc,
93 intptr_t Disp = 0, intptr_t PCAdj = 0,
94 bool Indirect = false);
95 void emitExternalSymbolAddress(const char *ES, unsigned Reloc);
96 void emitConstPoolAddress(unsigned CPI, unsigned Reloc, intptr_t Disp = 0,
98 void emitJumpTableAddress(unsigned JTI, unsigned Reloc,
101 void emitDisplacementField(const MachineOperand *RelocOp, int DispVal,
102 intptr_t Adj = 0, bool IsPCRel = true);
104 void emitRegModRMByte(unsigned ModRMReg, unsigned RegOpcodeField);
105 void emitRegModRMByte(unsigned RegOpcodeField);
106 void emitSIBByte(unsigned SS, unsigned Index, unsigned Base);
107 void emitConstant(uint64_t Val, unsigned Size);
109 void emitMemModRMByte(const MachineInstr &MI,
110 unsigned Op, unsigned RegOpcodeField,
113 unsigned getX86RegNum(unsigned RegNo) const {
114 const TargetRegisterInfo *TRI = TM.getRegisterInfo();
115 return TRI->getEncodingValue(RegNo) & 0x7;
118 unsigned char getVEXRegisterEncoding(const MachineInstr &MI,
119 unsigned OpNum) const;
122 template<class CodeEmitter>
123 char Emitter<CodeEmitter>::ID = 0;
124 } // end anonymous namespace.
126 /// createX86CodeEmitterPass - Return a pass that emits the collected X86 code
127 /// to the specified JITCodeEmitter object.
128 FunctionPass *llvm::createX86JITCodeEmitterPass(X86TargetMachine &TM,
129 JITCodeEmitter &JCE) {
130 return new Emitter<JITCodeEmitter>(TM, JCE);
133 template<class CodeEmitter>
134 bool Emitter<CodeEmitter>::runOnMachineFunction(MachineFunction &MF) {
135 MMI = &getAnalysis<MachineModuleInfo>();
136 MCE.setModuleInfo(MMI);
138 II = TM.getInstrInfo();
139 TD = TM.getDataLayout();
140 Is64BitMode = TM.getSubtarget<X86Subtarget>().is64Bit();
141 IsPIC = TM.getRelocationModel() == Reloc::PIC_;
144 DEBUG(dbgs() << "JITTing function '" << MF.getName() << "'\n");
145 MCE.startFunction(MF);
146 for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
148 MCE.StartMachineBasicBlock(MBB);
149 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
151 const MCInstrDesc &Desc = I->getDesc();
152 emitInstruction(*I, &Desc);
153 // MOVPC32r is basically a call plus a pop instruction.
154 if (Desc.getOpcode() == X86::MOVPC32r)
155 emitInstruction(*I, &II->get(X86::POP32r));
156 ++NumEmitted; // Keep track of the # of mi's emitted
159 } while (MCE.finishFunction(MF));
164 /// determineREX - Determine if the MachineInstr has to be encoded with a X86-64
165 /// REX prefix which specifies 1) 64-bit instructions, 2) non-default operand
166 /// size, and 3) use of X86-64 extended registers.
167 static unsigned determineREX(const MachineInstr &MI) {
169 const MCInstrDesc &Desc = MI.getDesc();
171 // Pseudo instructions do not need REX prefix byte.
172 if ((Desc.TSFlags & X86II::FormMask) == X86II::Pseudo)
174 if (Desc.TSFlags & X86II::REX_W)
177 unsigned NumOps = Desc.getNumOperands();
179 bool isTwoAddr = NumOps > 1 &&
180 Desc.getOperandConstraint(1, MCOI::TIED_TO) != -1;
182 // If it accesses SPL, BPL, SIL, or DIL, then it requires a 0x40 REX prefix.
183 unsigned i = isTwoAddr ? 1 : 0;
184 for (unsigned e = NumOps; i != e; ++i) {
185 const MachineOperand& MO = MI.getOperand(i);
187 unsigned Reg = MO.getReg();
188 if (X86II::isX86_64NonExtLowByteReg(Reg))
193 switch (Desc.TSFlags & X86II::FormMask) {
194 case X86II::MRMInitReg:
195 if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
196 REX |= (1 << 0) | (1 << 2);
198 case X86II::MRMSrcReg: {
199 if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
201 i = isTwoAddr ? 2 : 1;
202 for (unsigned e = NumOps; i != e; ++i) {
203 const MachineOperand& MO = MI.getOperand(i);
204 if (X86InstrInfo::isX86_64ExtendedReg(MO))
209 case X86II::MRMSrcMem: {
210 if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
213 i = isTwoAddr ? 2 : 1;
214 for (; i != NumOps; ++i) {
215 const MachineOperand& MO = MI.getOperand(i);
217 if (X86InstrInfo::isX86_64ExtendedReg(MO))
224 case X86II::MRM0m: case X86II::MRM1m:
225 case X86II::MRM2m: case X86II::MRM3m:
226 case X86II::MRM4m: case X86II::MRM5m:
227 case X86II::MRM6m: case X86II::MRM7m:
228 case X86II::MRMDestMem: {
229 unsigned e = (isTwoAddr ? X86::AddrNumOperands+1 : X86::AddrNumOperands);
230 i = isTwoAddr ? 1 : 0;
231 if (NumOps > e && X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(e)))
234 for (; i != e; ++i) {
235 const MachineOperand& MO = MI.getOperand(i);
237 if (X86InstrInfo::isX86_64ExtendedReg(MO))
245 if (X86InstrInfo::isX86_64ExtendedReg(MI.getOperand(0)))
247 i = isTwoAddr ? 2 : 1;
248 for (unsigned e = NumOps; i != e; ++i) {
249 const MachineOperand& MO = MI.getOperand(i);
250 if (X86InstrInfo::isX86_64ExtendedReg(MO))
261 /// emitPCRelativeBlockAddress - This method keeps track of the information
262 /// necessary to resolve the address of this block later and emits a dummy
265 template<class CodeEmitter>
266 void Emitter<CodeEmitter>::emitPCRelativeBlockAddress(MachineBasicBlock *MBB) {
267 // Remember where this reference was and where it is to so we can
268 // deal with it later.
269 MCE.addRelocation(MachineRelocation::getBB(MCE.getCurrentPCOffset(),
270 X86::reloc_pcrel_word, MBB));
274 /// emitGlobalAddress - Emit the specified address to the code stream assuming
275 /// this is part of a "take the address of a global" instruction.
277 template<class CodeEmitter>
278 void Emitter<CodeEmitter>::emitGlobalAddress(const GlobalValue *GV,
280 intptr_t Disp /* = 0 */,
281 intptr_t PCAdj /* = 0 */,
282 bool Indirect /* = false */) {
283 intptr_t RelocCST = Disp;
284 if (Reloc == X86::reloc_picrel_word)
285 RelocCST = PICBaseOffset;
286 else if (Reloc == X86::reloc_pcrel_word)
288 MachineRelocation MR = Indirect
289 ? MachineRelocation::getIndirectSymbol(MCE.getCurrentPCOffset(), Reloc,
290 const_cast<GlobalValue *>(GV),
292 : MachineRelocation::getGV(MCE.getCurrentPCOffset(), Reloc,
293 const_cast<GlobalValue *>(GV), RelocCST, false);
294 MCE.addRelocation(MR);
295 // The relocated value will be added to the displacement
296 if (Reloc == X86::reloc_absolute_dword)
297 MCE.emitDWordLE(Disp);
299 MCE.emitWordLE((int32_t)Disp);
302 /// emitExternalSymbolAddress - Arrange for the address of an external symbol to
303 /// be emitted to the current location in the function, and allow it to be PC
305 template<class CodeEmitter>
306 void Emitter<CodeEmitter>::emitExternalSymbolAddress(const char *ES,
308 intptr_t RelocCST = (Reloc == X86::reloc_picrel_word) ? PICBaseOffset : 0;
310 // X86 never needs stubs because instruction selection will always pick
311 // an instruction sequence that is large enough to hold any address
313 // (see X86ISelLowering.cpp, near 2039: X86TargetLowering::LowerCall)
314 bool NeedStub = false;
315 MCE.addRelocation(MachineRelocation::getExtSym(MCE.getCurrentPCOffset(),
318 if (Reloc == X86::reloc_absolute_dword)
324 /// emitConstPoolAddress - Arrange for the address of an constant pool
325 /// to be emitted to the current location in the function, and allow it to be PC
327 template<class CodeEmitter>
328 void Emitter<CodeEmitter>::emitConstPoolAddress(unsigned CPI, unsigned Reloc,
329 intptr_t Disp /* = 0 */,
330 intptr_t PCAdj /* = 0 */) {
331 intptr_t RelocCST = 0;
332 if (Reloc == X86::reloc_picrel_word)
333 RelocCST = PICBaseOffset;
334 else if (Reloc == X86::reloc_pcrel_word)
336 MCE.addRelocation(MachineRelocation::getConstPool(MCE.getCurrentPCOffset(),
337 Reloc, CPI, RelocCST));
338 // The relocated value will be added to the displacement
339 if (Reloc == X86::reloc_absolute_dword)
340 MCE.emitDWordLE(Disp);
342 MCE.emitWordLE((int32_t)Disp);
345 /// emitJumpTableAddress - Arrange for the address of a jump table to
346 /// be emitted to the current location in the function, and allow it to be PC
348 template<class CodeEmitter>
349 void Emitter<CodeEmitter>::emitJumpTableAddress(unsigned JTI, unsigned Reloc,
350 intptr_t PCAdj /* = 0 */) {
351 intptr_t RelocCST = 0;
352 if (Reloc == X86::reloc_picrel_word)
353 RelocCST = PICBaseOffset;
354 else if (Reloc == X86::reloc_pcrel_word)
356 MCE.addRelocation(MachineRelocation::getJumpTable(MCE.getCurrentPCOffset(),
357 Reloc, JTI, RelocCST));
358 // The relocated value will be added to the displacement
359 if (Reloc == X86::reloc_absolute_dword)
365 inline static unsigned char ModRMByte(unsigned Mod, unsigned RegOpcode,
367 assert(Mod < 4 && RegOpcode < 8 && RM < 8 && "ModRM Fields out of range!");
368 return RM | (RegOpcode << 3) | (Mod << 6);
371 template<class CodeEmitter>
372 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned ModRMReg,
373 unsigned RegOpcodeFld){
374 MCE.emitByte(ModRMByte(3, RegOpcodeFld, getX86RegNum(ModRMReg)));
377 template<class CodeEmitter>
378 void Emitter<CodeEmitter>::emitRegModRMByte(unsigned RegOpcodeFld) {
379 MCE.emitByte(ModRMByte(3, RegOpcodeFld, 0));
382 template<class CodeEmitter>
383 void Emitter<CodeEmitter>::emitSIBByte(unsigned SS,
386 // SIB byte is in the same format as the ModRMByte...
387 MCE.emitByte(ModRMByte(SS, Index, Base));
390 template<class CodeEmitter>
391 void Emitter<CodeEmitter>::emitConstant(uint64_t Val, unsigned Size) {
392 // Output the constant in little endian byte order...
393 for (unsigned i = 0; i != Size; ++i) {
394 MCE.emitByte(Val & 255);
399 /// isDisp8 - Return true if this signed displacement fits in a 8-bit
400 /// sign-extended field.
401 static bool isDisp8(int Value) {
402 return Value == (signed char)Value;
405 static bool gvNeedsNonLazyPtr(const MachineOperand &GVOp,
406 const TargetMachine &TM) {
407 // For Darwin-64, simulate the linktime GOT by using the same non-lazy-pointer
408 // mechanism as 32-bit mode.
409 if (TM.getSubtarget<X86Subtarget>().is64Bit() &&
410 !TM.getSubtarget<X86Subtarget>().isTargetDarwin())
413 // Return true if this is a reference to a stub containing the address of the
414 // global, not the global itself.
415 return isGlobalStubReference(GVOp.getTargetFlags());
418 template<class CodeEmitter>
419 void Emitter<CodeEmitter>::emitDisplacementField(const MachineOperand *RelocOp,
421 intptr_t Adj /* = 0 */,
422 bool IsPCRel /* = true */) {
423 // If this is a simple integer displacement that doesn't require a relocation,
426 emitConstant(DispVal, 4);
430 // Otherwise, this is something that requires a relocation. Emit it as such
432 unsigned RelocType = Is64BitMode ?
433 (IsPCRel ? X86::reloc_pcrel_word : X86::reloc_absolute_word_sext)
434 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
435 if (RelocOp->isGlobal()) {
436 // In 64-bit static small code model, we could potentially emit absolute.
437 // But it's probably not beneficial. If the MCE supports using RIP directly
438 // do it, otherwise fallback to absolute (this is determined by IsPCRel).
439 // 89 05 00 00 00 00 mov %eax,0(%rip) # PC-relative
440 // 89 04 25 00 00 00 00 mov %eax,0x0 # Absolute
441 bool Indirect = gvNeedsNonLazyPtr(*RelocOp, TM);
442 emitGlobalAddress(RelocOp->getGlobal(), RelocType, RelocOp->getOffset(),
444 } else if (RelocOp->isSymbol()) {
445 emitExternalSymbolAddress(RelocOp->getSymbolName(), RelocType);
446 } else if (RelocOp->isCPI()) {
447 emitConstPoolAddress(RelocOp->getIndex(), RelocType,
448 RelocOp->getOffset(), Adj);
450 assert(RelocOp->isJTI() && "Unexpected machine operand!");
451 emitJumpTableAddress(RelocOp->getIndex(), RelocType, Adj);
455 template<class CodeEmitter>
456 void Emitter<CodeEmitter>::emitMemModRMByte(const MachineInstr &MI,
457 unsigned Op,unsigned RegOpcodeField,
459 const MachineOperand &Op3 = MI.getOperand(Op+3);
461 const MachineOperand *DispForReloc = 0;
463 // Figure out what sort of displacement we have to handle here.
464 if (Op3.isGlobal()) {
466 } else if (Op3.isSymbol()) {
468 } else if (Op3.isCPI()) {
469 if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
472 DispVal += MCE.getConstantPoolEntryAddress(Op3.getIndex());
473 DispVal += Op3.getOffset();
475 } else if (Op3.isJTI()) {
476 if (!MCE.earlyResolveAddresses() || Is64BitMode || IsPIC) {
479 DispVal += MCE.getJumpTableEntryAddress(Op3.getIndex());
482 DispVal = Op3.getImm();
485 const MachineOperand &Base = MI.getOperand(Op);
486 const MachineOperand &Scale = MI.getOperand(Op+1);
487 const MachineOperand &IndexReg = MI.getOperand(Op+2);
489 unsigned BaseReg = Base.getReg();
491 // Handle %rip relative addressing.
492 if (BaseReg == X86::RIP ||
493 (Is64BitMode && DispForReloc)) { // [disp32+RIP] in X86-64 mode
494 assert(IndexReg.getReg() == 0 && Is64BitMode &&
495 "Invalid rip-relative address");
496 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
497 emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
501 // Indicate that the displacement will use an pcrel or absolute reference
502 // by default. MCEs able to resolve addresses on-the-fly use pcrel by default
503 // while others, unless explicit asked to use RIP, use absolute references.
504 bool IsPCRel = MCE.earlyResolveAddresses() ? true : false;
506 // Is a SIB byte needed?
507 // If no BaseReg, issue a RIP relative instruction only if the MCE can
508 // resolve addresses on-the-fly, otherwise use SIB (Intel Manual 2A, table
509 // 2-7) and absolute references.
510 unsigned BaseRegNo = -1U;
511 if (BaseReg != 0 && BaseReg != X86::RIP)
512 BaseRegNo = getX86RegNum(BaseReg);
514 if (// The SIB byte must be used if there is an index register.
515 IndexReg.getReg() == 0 &&
516 // The SIB byte must be used if the base is ESP/RSP/R12, all of which
517 // encode to an R/M value of 4, which indicates that a SIB byte is
519 BaseRegNo != N86::ESP &&
520 // If there is no base register and we're in 64-bit mode, we need a SIB
521 // byte to emit an addr that is just 'disp32' (the non-RIP relative form).
522 (!Is64BitMode || BaseReg != 0)) {
523 if (BaseReg == 0 || // [disp32] in X86-32 mode
524 BaseReg == X86::RIP) { // [disp32+RIP] in X86-64 mode
525 MCE.emitByte(ModRMByte(0, RegOpcodeField, 5));
526 emitDisplacementField(DispForReloc, DispVal, PCAdj, true);
530 // If the base is not EBP/ESP and there is no displacement, use simple
531 // indirect register encoding, this handles addresses like [EAX]. The
532 // encoding for [EBP] with no displacement means [disp32] so we handle it
533 // by emitting a displacement of 0 below.
534 if (!DispForReloc && DispVal == 0 && BaseRegNo != N86::EBP) {
535 MCE.emitByte(ModRMByte(0, RegOpcodeField, BaseRegNo));
539 // Otherwise, if the displacement fits in a byte, encode as [REG+disp8].
540 if (!DispForReloc && isDisp8(DispVal)) {
541 MCE.emitByte(ModRMByte(1, RegOpcodeField, BaseRegNo));
542 emitConstant(DispVal, 1);
546 // Otherwise, emit the most general non-SIB encoding: [REG+disp32]
547 MCE.emitByte(ModRMByte(2, RegOpcodeField, BaseRegNo));
548 emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
552 // Otherwise we need a SIB byte, so start by outputting the ModR/M byte first.
553 assert(IndexReg.getReg() != X86::ESP &&
554 IndexReg.getReg() != X86::RSP && "Cannot use ESP as index reg!");
556 bool ForceDisp32 = false;
557 bool ForceDisp8 = false;
559 // If there is no base register, we emit the special case SIB byte with
560 // MOD=0, BASE=4, to JUST get the index, scale, and displacement.
561 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
563 } else if (DispForReloc) {
564 // Emit the normal disp32 encoding.
565 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
567 } else if (DispVal == 0 && BaseRegNo != N86::EBP) {
568 // Emit no displacement ModR/M byte
569 MCE.emitByte(ModRMByte(0, RegOpcodeField, 4));
570 } else if (isDisp8(DispVal)) {
571 // Emit the disp8 encoding...
572 MCE.emitByte(ModRMByte(1, RegOpcodeField, 4));
573 ForceDisp8 = true; // Make sure to force 8 bit disp if Base=EBP
575 // Emit the normal disp32 encoding...
576 MCE.emitByte(ModRMByte(2, RegOpcodeField, 4));
579 // Calculate what the SS field value should be...
580 static const unsigned SSTable[] = { ~0U, 0, 1, ~0U, 2, ~0U, ~0U, ~0U, 3 };
581 unsigned SS = SSTable[Scale.getImm()];
584 // Handle the SIB byte for the case where there is no base, see Intel
585 // Manual 2A, table 2-7. The displacement has already been output.
587 if (IndexReg.getReg())
588 IndexRegNo = getX86RegNum(IndexReg.getReg());
589 else // Examples: [ESP+1*<noreg>+4] or [scaled idx]+disp32 (MOD=0,BASE=5)
591 emitSIBByte(SS, IndexRegNo, 5);
593 unsigned BaseRegNo = getX86RegNum(BaseReg);
595 if (IndexReg.getReg())
596 IndexRegNo = getX86RegNum(IndexReg.getReg());
598 IndexRegNo = 4; // For example [ESP+1*<noreg>+4]
599 emitSIBByte(SS, IndexRegNo, BaseRegNo);
602 // Do we need to output a displacement?
604 emitConstant(DispVal, 1);
605 } else if (DispVal != 0 || ForceDisp32) {
606 emitDisplacementField(DispForReloc, DispVal, PCAdj, IsPCRel);
610 static const MCInstrDesc *UpdateOp(MachineInstr &MI, const X86InstrInfo *II,
612 const MCInstrDesc *Desc = &II->get(Opcode);
617 /// Is16BitMemOperand - Return true if the specified instruction has
618 /// a 16-bit memory operand. Op specifies the operand # of the memoperand.
619 static bool Is16BitMemOperand(const MachineInstr &MI, unsigned Op) {
620 const MachineOperand &BaseReg = MI.getOperand(Op+X86::AddrBaseReg);
621 const MachineOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
623 if ((BaseReg.getReg() != 0 &&
624 X86MCRegisterClasses[X86::GR16RegClassID].contains(BaseReg.getReg())) ||
625 (IndexReg.getReg() != 0 &&
626 X86MCRegisterClasses[X86::GR16RegClassID].contains(IndexReg.getReg())))
631 /// Is32BitMemOperand - Return true if the specified instruction has
632 /// a 32-bit memory operand. Op specifies the operand # of the memoperand.
633 static bool Is32BitMemOperand(const MachineInstr &MI, unsigned Op) {
634 const MachineOperand &BaseReg = MI.getOperand(Op+X86::AddrBaseReg);
635 const MachineOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
637 if ((BaseReg.getReg() != 0 &&
638 X86MCRegisterClasses[X86::GR32RegClassID].contains(BaseReg.getReg())) ||
639 (IndexReg.getReg() != 0 &&
640 X86MCRegisterClasses[X86::GR32RegClassID].contains(IndexReg.getReg())))
645 /// Is64BitMemOperand - Return true if the specified instruction has
646 /// a 64-bit memory operand. Op specifies the operand # of the memoperand.
648 static bool Is64BitMemOperand(const MachineInstr &MI, unsigned Op) {
649 const MachineOperand &BaseReg = MI.getOperand(Op+X86::AddrBaseReg);
650 const MachineOperand &IndexReg = MI.getOperand(Op+X86::AddrIndexReg);
652 if ((BaseReg.getReg() != 0 &&
653 X86MCRegisterClasses[X86::GR64RegClassID].contains(BaseReg.getReg())) ||
654 (IndexReg.getReg() != 0 &&
655 X86MCRegisterClasses[X86::GR64RegClassID].contains(IndexReg.getReg())))
661 template<class CodeEmitter>
662 void Emitter<CodeEmitter>::emitOpcodePrefix(uint64_t TSFlags,
664 const MachineInstr &MI,
665 const MCInstrDesc *Desc) const {
666 // Emit the lock opcode prefix as needed.
667 if (Desc->TSFlags & X86II::LOCK)
670 // Emit segment override opcode prefix as needed.
671 emitSegmentOverridePrefix(TSFlags, MemOperand, MI);
673 // Emit the repeat opcode prefix as needed.
674 if ((Desc->TSFlags & X86II::Op0Mask) == X86II::REP)
677 // Emit the address size opcode prefix as needed.
678 bool need_address_override;
679 if (TSFlags & X86II::AdSize) {
680 need_address_override = true;
681 } else if (MemOperand == -1) {
682 need_address_override = false;
683 } else if (Is64BitMode) {
684 assert(!Is16BitMemOperand(MI, MemOperand));
685 need_address_override = Is32BitMemOperand(MI, MemOperand);
687 assert(!Is64BitMemOperand(MI, MemOperand));
688 need_address_override = Is16BitMemOperand(MI, MemOperand);
691 if (need_address_override)
694 // Emit the operand size opcode prefix as needed.
695 if (TSFlags & X86II::OpSize)
698 bool Need0FPrefix = false;
699 switch (Desc->TSFlags & X86II::Op0Mask) {
700 case X86II::TB: // Two-byte opcode prefix
701 case X86II::T8: // 0F 38
702 case X86II::TA: // 0F 3A
703 case X86II::A6: // 0F A6
704 case X86II::A7: // 0F A7
707 case X86II::REP: break; // already handled.
708 case X86II::T8XS: // F3 0F 38
709 case X86II::XS: // F3 0F
713 case X86II::T8XD: // F2 0F 38
714 case X86II::TAXD: // F2 0F 3A
715 case X86II::XD: // F2 0F
719 case X86II::D8: case X86II::D9: case X86II::DA: case X86II::DB:
720 case X86II::DC: case X86II::DD: case X86II::DE: case X86II::DF:
722 (((Desc->TSFlags & X86II::Op0Mask)-X86II::D8)
723 >> X86II::Op0Shift));
724 break; // Two-byte opcode prefix
725 default: llvm_unreachable("Invalid prefix!");
726 case 0: break; // No prefix!
729 // Handle REX prefix.
731 if (unsigned REX = determineREX(MI))
732 MCE.emitByte(0x40 | REX);
735 // 0x0F escape code must be emitted just before the opcode.
739 switch (Desc->TSFlags & X86II::Op0Mask) {
740 case X86II::T8XD: // F2 0F 38
741 case X86II::T8XS: // F3 0F 38
742 case X86II::T8: // 0F 38
745 case X86II::TAXD: // F2 0F 38
746 case X86II::TA: // 0F 3A
749 case X86II::A6: // 0F A6
752 case X86II::A7: // 0F A7
758 // On regular x86, both XMM0-XMM7 and XMM8-XMM15 are encoded in the range
759 // 0-7 and the difference between the 2 groups is given by the REX prefix.
760 // In the VEX prefix, registers are seen sequencially from 0-15 and encoded
761 // in 1's complement form, example:
763 // ModRM field => XMM9 => 1
764 // VEX.VVVV => XMM9 => ~9
766 // See table 4-35 of Intel AVX Programming Reference for details.
767 template<class CodeEmitter>
769 Emitter<CodeEmitter>::getVEXRegisterEncoding(const MachineInstr &MI,
770 unsigned OpNum) const {
771 unsigned SrcReg = MI.getOperand(OpNum).getReg();
772 unsigned SrcRegNum = getX86RegNum(MI.getOperand(OpNum).getReg());
773 if (X86II::isX86_64ExtendedReg(SrcReg))
776 // The registers represented through VEX_VVVV should
777 // be encoded in 1's complement form.
778 return (~SrcRegNum) & 0xf;
781 /// EmitSegmentOverridePrefix - Emit segment override opcode prefix as needed
782 template<class CodeEmitter>
783 void Emitter<CodeEmitter>::emitSegmentOverridePrefix(uint64_t TSFlags,
785 const MachineInstr &MI) const {
786 switch (TSFlags & X86II::SegOvrMask) {
787 default: llvm_unreachable("Invalid segment!");
789 // No segment override, check for explicit one on memory operand.
790 if (MemOperand != -1) { // If the instruction has a memory operand.
791 switch (MI.getOperand(MemOperand+X86::AddrSegmentReg).getReg()) {
792 default: llvm_unreachable("Unknown segment register!");
794 case X86::CS: MCE.emitByte(0x2E); break;
795 case X86::SS: MCE.emitByte(0x36); break;
796 case X86::DS: MCE.emitByte(0x3E); break;
797 case X86::ES: MCE.emitByte(0x26); break;
798 case X86::FS: MCE.emitByte(0x64); break;
799 case X86::GS: MCE.emitByte(0x65); break;
812 template<class CodeEmitter>
813 void Emitter<CodeEmitter>::emitVEXOpcodePrefix(uint64_t TSFlags,
815 const MachineInstr &MI,
816 const MCInstrDesc *Desc) const {
817 bool HasVEX_4V = (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
818 bool HasVEX_4VOp3 = (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
819 bool HasMemOp4 = (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
821 // VEX_R: opcode externsion equivalent to REX.R in
822 // 1's complement (inverted) form
824 // 1: Same as REX_R=0 (must be 1 in 32-bit mode)
825 // 0: Same as REX_R=1 (64 bit mode only)
827 unsigned char VEX_R = 0x1;
829 // VEX_X: equivalent to REX.X, only used when a
830 // register is used for index in SIB Byte.
832 // 1: Same as REX.X=0 (must be 1 in 32-bit mode)
833 // 0: Same as REX.X=1 (64-bit mode only)
834 unsigned char VEX_X = 0x1;
838 // 1: Same as REX_B=0 (ignored in 32-bit mode)
839 // 0: Same as REX_B=1 (64 bit mode only)
841 unsigned char VEX_B = 0x1;
843 // VEX_W: opcode specific (use like REX.W, or used for
844 // opcode extension, or ignored, depending on the opcode byte)
845 unsigned char VEX_W = 0;
847 // XOP: Use XOP prefix byte 0x8f instead of VEX.
848 unsigned char XOP = 0;
850 // VEX_5M (VEX m-mmmmm field):
852 // 0b00000: Reserved for future use
853 // 0b00001: implied 0F leading opcode
854 // 0b00010: implied 0F 38 leading opcode bytes
855 // 0b00011: implied 0F 3A leading opcode bytes
856 // 0b00100-0b11111: Reserved for future use
857 // 0b01000: XOP map select - 08h instructions with imm byte
858 // 0b10001: XOP map select - 09h instructions with no imm byte
859 unsigned char VEX_5M = 0x1;
861 // VEX_4V (VEX vvvv field): a register specifier
862 // (in 1's complement form) or 1111 if unused.
863 unsigned char VEX_4V = 0xf;
865 // VEX_L (Vector Length):
867 // 0: scalar or 128-bit vector
870 unsigned char VEX_L = 0;
872 // VEX_PP: opcode extension providing equivalent
873 // functionality of a SIMD prefix
880 unsigned char VEX_PP = 0;
882 // Encode the operand size opcode prefix as needed.
883 if (TSFlags & X86II::OpSize)
886 if ((TSFlags >> X86II::VEXShift) & X86II::VEX_W)
889 if ((TSFlags >> X86II::VEXShift) & X86II::XOP)
892 if ((TSFlags >> X86II::VEXShift) & X86II::VEX_L)
895 switch (TSFlags & X86II::Op0Mask) {
896 default: llvm_unreachable("Invalid prefix!");
897 case X86II::T8: // 0F 38
900 case X86II::TA: // 0F 3A
903 case X86II::T8XS: // F3 0F 38
907 case X86II::T8XD: // F2 0F 38
911 case X86II::TAXD: // F2 0F 3A
915 case X86II::XS: // F3 0F
918 case X86II::XD: // F2 0F
927 case X86II::A6: // Bypass: Not used by VEX
928 case X86II::A7: // Bypass: Not used by VEX
929 case X86II::TB: // Bypass: Not used by VEX
935 // Classify VEX_B, VEX_4V, VEX_R, VEX_X
936 unsigned NumOps = Desc->getNumOperands();
938 if (NumOps > 1 && Desc->getOperandConstraint(1, MCOI::TIED_TO) == 0)
940 else if (NumOps > 3 && Desc->getOperandConstraint(2, MCOI::TIED_TO) == 0) {
941 assert(Desc->getOperandConstraint(NumOps - 1, MCOI::TIED_TO) == 1);
942 // Special case for GATHER with 2 TIED_TO operands
943 // Skip the first 2 operands: dst, mask_wb
947 switch (TSFlags & X86II::FormMask) {
948 case X86II::MRMInitReg:
949 // Duplicate register.
950 if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
954 VEX_4V = getVEXRegisterEncoding(MI, CurOp);
955 if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
958 VEX_4V = getVEXRegisterEncoding(MI, CurOp);
960 case X86II::MRMDestMem: {
961 // MRMDestMem instructions forms:
962 // MemAddr, src1(ModR/M)
963 // MemAddr, src1(VEX_4V), src2(ModR/M)
964 // MemAddr, src1(ModR/M), imm8
966 if (X86II::isX86_64ExtendedReg(MI.getOperand(X86::AddrBaseReg).getReg()))
968 if (X86II::isX86_64ExtendedReg(MI.getOperand(X86::AddrIndexReg).getReg()))
971 CurOp = X86::AddrNumOperands;
973 VEX_4V = getVEXRegisterEncoding(MI, CurOp++);
975 const MachineOperand &MO = MI.getOperand(CurOp);
976 if (MO.isReg() && X86II::isX86_64ExtendedReg(MO.getReg()))
980 case X86II::MRMSrcMem:
981 // MRMSrcMem instructions forms:
982 // src1(ModR/M), MemAddr
983 // src1(ModR/M), src2(VEX_4V), MemAddr
984 // src1(ModR/M), MemAddr, imm8
985 // src1(ModR/M), MemAddr, src2(VEX_I8IMM)
988 // dst(ModR/M.reg), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
989 // dst(ModR/M.reg), src1(VEX_4V), src2(VEX_I8IMM), src3(ModR/M),
990 if (X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
994 VEX_4V = getVEXRegisterEncoding(MI, 1);
996 if (X86II::isX86_64ExtendedReg(
997 MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
999 if (X86II::isX86_64ExtendedReg(
1000 MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
1004 VEX_4V = getVEXRegisterEncoding(MI, X86::AddrNumOperands+1);
1006 case X86II::MRM0m: case X86II::MRM1m:
1007 case X86II::MRM2m: case X86II::MRM3m:
1008 case X86II::MRM4m: case X86II::MRM5m:
1009 case X86II::MRM6m: case X86II::MRM7m: {
1010 // MRM[0-9]m instructions forms:
1012 // src1(VEX_4V), MemAddr
1014 VEX_4V = getVEXRegisterEncoding(MI, 0);
1016 if (X86II::isX86_64ExtendedReg(
1017 MI.getOperand(MemOperand+X86::AddrBaseReg).getReg()))
1019 if (X86II::isX86_64ExtendedReg(
1020 MI.getOperand(MemOperand+X86::AddrIndexReg).getReg()))
1024 case X86II::MRMSrcReg:
1025 // MRMSrcReg instructions forms:
1026 // dst(ModR/M), src1(VEX_4V), src2(ModR/M), src3(VEX_I8IMM)
1027 // dst(ModR/M), src1(ModR/M)
1028 // dst(ModR/M), src1(ModR/M), imm8
1030 if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
1035 VEX_4V = getVEXRegisterEncoding(MI, CurOp++);
1037 if (HasMemOp4) // Skip second register source (encoded in I8IMM)
1040 if (X86II::isX86_64ExtendedReg(MI.getOperand(CurOp).getReg()))
1044 VEX_4V = getVEXRegisterEncoding(MI, CurOp);
1046 case X86II::MRMDestReg:
1047 // MRMDestReg instructions forms:
1048 // dst(ModR/M), src(ModR/M)
1049 // dst(ModR/M), src(ModR/M), imm8
1050 if (X86II::isX86_64ExtendedReg(MI.getOperand(0).getReg()))
1052 if (X86II::isX86_64ExtendedReg(MI.getOperand(1).getReg()))
1055 case X86II::MRM0r: case X86II::MRM1r:
1056 case X86II::MRM2r: case X86II::MRM3r:
1057 case X86II::MRM4r: case X86II::MRM5r:
1058 case X86II::MRM6r: case X86II::MRM7r:
1059 // MRM0r-MRM7r instructions forms:
1060 // dst(VEX_4V), src(ModR/M), imm8
1061 VEX_4V = getVEXRegisterEncoding(MI, 0);
1062 if (X86II::isX86_64ExtendedReg(MI.getOperand(1).getReg()))
1069 // Emit segment override opcode prefix as needed.
1070 emitSegmentOverridePrefix(TSFlags, MemOperand, MI);
1072 // VEX opcode prefix can have 2 or 3 bytes
1075 // +-----+ +--------------+ +-------------------+
1076 // | C4h | | RXB | m-mmmm | | W | vvvv | L | pp |
1077 // +-----+ +--------------+ +-------------------+
1079 // +-----+ +-------------------+
1080 // | C5h | | R | vvvv | L | pp |
1081 // +-----+ +-------------------+
1083 unsigned char LastByte = VEX_PP | (VEX_L << 2) | (VEX_4V << 3);
1085 if (VEX_B && VEX_X && !VEX_W && !XOP && (VEX_5M == 1)) { // 2 byte VEX prefix
1087 MCE.emitByte(LastByte | (VEX_R << 7));
1091 // 3 byte VEX prefix
1092 MCE.emitByte(XOP ? 0x8F : 0xC4);
1093 MCE.emitByte(VEX_R << 7 | VEX_X << 6 | VEX_B << 5 | VEX_5M);
1094 MCE.emitByte(LastByte | (VEX_W << 7));
1097 template<class CodeEmitter>
1098 void Emitter<CodeEmitter>::emitInstruction(MachineInstr &MI,
1099 const MCInstrDesc *Desc) {
1100 DEBUG(dbgs() << MI);
1102 // If this is a pseudo instruction, lower it.
1103 switch (Desc->getOpcode()) {
1104 case X86::ADD16rr_DB: Desc = UpdateOp(MI, II, X86::OR16rr); break;
1105 case X86::ADD32rr_DB: Desc = UpdateOp(MI, II, X86::OR32rr); break;
1106 case X86::ADD64rr_DB: Desc = UpdateOp(MI, II, X86::OR64rr); break;
1107 case X86::ADD16ri_DB: Desc = UpdateOp(MI, II, X86::OR16ri); break;
1108 case X86::ADD32ri_DB: Desc = UpdateOp(MI, II, X86::OR32ri); break;
1109 case X86::ADD64ri32_DB: Desc = UpdateOp(MI, II, X86::OR64ri32); break;
1110 case X86::ADD16ri8_DB: Desc = UpdateOp(MI, II, X86::OR16ri8); break;
1111 case X86::ADD32ri8_DB: Desc = UpdateOp(MI, II, X86::OR32ri8); break;
1112 case X86::ADD64ri8_DB: Desc = UpdateOp(MI, II, X86::OR64ri8); break;
1113 case X86::ACQUIRE_MOV8rm: Desc = UpdateOp(MI, II, X86::MOV8rm); break;
1114 case X86::ACQUIRE_MOV16rm: Desc = UpdateOp(MI, II, X86::MOV16rm); break;
1115 case X86::ACQUIRE_MOV32rm: Desc = UpdateOp(MI, II, X86::MOV32rm); break;
1116 case X86::ACQUIRE_MOV64rm: Desc = UpdateOp(MI, II, X86::MOV64rm); break;
1117 case X86::RELEASE_MOV8mr: Desc = UpdateOp(MI, II, X86::MOV8mr); break;
1118 case X86::RELEASE_MOV16mr: Desc = UpdateOp(MI, II, X86::MOV16mr); break;
1119 case X86::RELEASE_MOV32mr: Desc = UpdateOp(MI, II, X86::MOV32mr); break;
1120 case X86::RELEASE_MOV64mr: Desc = UpdateOp(MI, II, X86::MOV64mr); break;
1124 MCE.processDebugLoc(MI.getDebugLoc(), true);
1126 unsigned Opcode = Desc->Opcode;
1128 // If this is a two-address instruction, skip one of the register operands.
1129 unsigned NumOps = Desc->getNumOperands();
1131 if (NumOps > 1 && Desc->getOperandConstraint(1, MCOI::TIED_TO) == 0)
1133 else if (NumOps > 3 && Desc->getOperandConstraint(2, MCOI::TIED_TO) == 0) {
1134 assert(Desc->getOperandConstraint(NumOps - 1, MCOI::TIED_TO) == 1);
1135 // Special case for GATHER with 2 TIED_TO operands
1136 // Skip the first 2 operands: dst, mask_wb
1140 uint64_t TSFlags = Desc->TSFlags;
1142 // Is this instruction encoded using the AVX VEX prefix?
1143 bool HasVEXPrefix = (TSFlags >> X86II::VEXShift) & X86II::VEX;
1144 // It uses the VEX.VVVV field?
1145 bool HasVEX_4V = (TSFlags >> X86II::VEXShift) & X86II::VEX_4V;
1146 bool HasVEX_4VOp3 = (TSFlags >> X86II::VEXShift) & X86II::VEX_4VOp3;
1147 bool HasMemOp4 = (TSFlags >> X86II::VEXShift) & X86II::MemOp4;
1148 const unsigned MemOp4_I8IMMOperand = 2;
1150 // Determine where the memory operand starts, if present.
1151 int MemoryOperand = X86II::getMemoryOperandNo(TSFlags, Opcode);
1152 if (MemoryOperand != -1) MemoryOperand += CurOp;
1155 emitOpcodePrefix(TSFlags, MemoryOperand, MI, Desc);
1157 emitVEXOpcodePrefix(TSFlags, MemoryOperand, MI, Desc);
1159 unsigned char BaseOpcode = X86II::getBaseOpcodeFor(Desc->TSFlags);
1160 switch (TSFlags & X86II::FormMask) {
1162 llvm_unreachable("Unknown FormMask value in X86 MachineCodeEmitter!");
1164 // Remember the current PC offset, this is the PIC relocation
1168 llvm_unreachable("pseudo instructions should be removed before code"
1170 // Do nothing for Int_MemBarrier - it's just a comment. Add a debug
1171 // to make it slightly easier to see.
1172 case X86::Int_MemBarrier:
1173 DEBUG(dbgs() << "#MEMBARRIER\n");
1176 case TargetOpcode::INLINEASM:
1177 // We allow inline assembler nodes with empty bodies - they can
1178 // implicitly define registers, which is ok for JIT.
1179 if (MI.getOperand(0).getSymbolName()[0])
1180 report_fatal_error("JIT does not support inline asm!");
1182 case TargetOpcode::PROLOG_LABEL:
1183 case TargetOpcode::GC_LABEL:
1184 case TargetOpcode::EH_LABEL:
1185 MCE.emitLabel(MI.getOperand(0).getMCSymbol());
1188 case TargetOpcode::IMPLICIT_DEF:
1189 case TargetOpcode::KILL:
1191 case X86::MOVPC32r: {
1192 // This emits the "call" portion of this pseudo instruction.
1193 MCE.emitByte(BaseOpcode);
1194 emitConstant(0, X86II::getSizeOfImm(Desc->TSFlags));
1195 // Remember PIC base.
1196 PICBaseOffset = (intptr_t) MCE.getCurrentPCOffset();
1197 X86JITInfo *JTI = TM.getJITInfo();
1198 JTI->setPICBase(MCE.getCurrentPCValue());
1204 case X86II::RawFrm: {
1205 MCE.emitByte(BaseOpcode);
1207 if (CurOp == NumOps)
1210 const MachineOperand &MO = MI.getOperand(CurOp++);
1212 DEBUG(dbgs() << "RawFrm CurOp " << CurOp << "\n");
1213 DEBUG(dbgs() << "isMBB " << MO.isMBB() << "\n");
1214 DEBUG(dbgs() << "isGlobal " << MO.isGlobal() << "\n");
1215 DEBUG(dbgs() << "isSymbol " << MO.isSymbol() << "\n");
1216 DEBUG(dbgs() << "isImm " << MO.isImm() << "\n");
1219 emitPCRelativeBlockAddress(MO.getMBB());
1223 if (MO.isGlobal()) {
1224 emitGlobalAddress(MO.getGlobal(), X86::reloc_pcrel_word,
1229 if (MO.isSymbol()) {
1230 emitExternalSymbolAddress(MO.getSymbolName(), X86::reloc_pcrel_word);
1234 // FIXME: Only used by hackish MCCodeEmitter, remove when dead.
1236 emitJumpTableAddress(MO.getIndex(), X86::reloc_pcrel_word);
1240 assert(MO.isImm() && "Unknown RawFrm operand!");
1241 if (Opcode == X86::CALLpcrel32 || Opcode == X86::CALL64pcrel32) {
1242 // Fix up immediate operand for pc relative calls.
1243 intptr_t Imm = (intptr_t)MO.getImm();
1244 Imm = Imm - MCE.getCurrentPCValue() - 4;
1245 emitConstant(Imm, X86II::getSizeOfImm(Desc->TSFlags));
1247 emitConstant(MO.getImm(), X86II::getSizeOfImm(Desc->TSFlags));
1251 case X86II::AddRegFrm: {
1252 MCE.emitByte(BaseOpcode +
1253 getX86RegNum(MI.getOperand(CurOp++).getReg()));
1255 if (CurOp == NumOps)
1258 const MachineOperand &MO1 = MI.getOperand(CurOp++);
1259 unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
1261 emitConstant(MO1.getImm(), Size);
1265 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
1266 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
1267 if (Opcode == X86::MOV64ri64i32)
1268 rt = X86::reloc_absolute_word; // FIXME: add X86II flag?
1269 // This should not occur on Darwin for relocatable objects.
1270 if (Opcode == X86::MOV64ri)
1271 rt = X86::reloc_absolute_dword; // FIXME: add X86II flag?
1272 if (MO1.isGlobal()) {
1273 bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
1274 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
1276 } else if (MO1.isSymbol())
1277 emitExternalSymbolAddress(MO1.getSymbolName(), rt);
1278 else if (MO1.isCPI())
1279 emitConstPoolAddress(MO1.getIndex(), rt);
1280 else if (MO1.isJTI())
1281 emitJumpTableAddress(MO1.getIndex(), rt);
1285 case X86II::MRMDestReg: {
1286 MCE.emitByte(BaseOpcode);
1287 emitRegModRMByte(MI.getOperand(CurOp).getReg(),
1288 getX86RegNum(MI.getOperand(CurOp+1).getReg()));
1292 case X86II::MRMDestMem: {
1293 MCE.emitByte(BaseOpcode);
1295 unsigned SrcRegNum = CurOp + X86::AddrNumOperands;
1296 if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1298 emitMemModRMByte(MI, CurOp,
1299 getX86RegNum(MI.getOperand(SrcRegNum).getReg()));
1300 CurOp = SrcRegNum + 1;
1304 case X86II::MRMSrcReg: {
1305 MCE.emitByte(BaseOpcode);
1307 unsigned SrcRegNum = CurOp+1;
1308 if (HasVEX_4V) // Skip 1st src (which is encoded in VEX_VVVV)
1311 if (HasMemOp4) // Skip 2nd src (which is encoded in I8IMM)
1314 emitRegModRMByte(MI.getOperand(SrcRegNum).getReg(),
1315 getX86RegNum(MI.getOperand(CurOp).getReg()));
1316 // 2 operands skipped with HasMemOp4, compensate accordingly
1317 CurOp = HasMemOp4 ? SrcRegNum : SrcRegNum + 1;
1322 case X86II::MRMSrcMem: {
1323 int AddrOperands = X86::AddrNumOperands;
1324 unsigned FirstMemOp = CurOp+1;
1327 ++FirstMemOp; // Skip the register source (which is encoded in VEX_VVVV).
1329 if (HasMemOp4) // Skip second register source (encoded in I8IMM)
1332 MCE.emitByte(BaseOpcode);
1334 intptr_t PCAdj = (CurOp + AddrOperands + 1 != NumOps) ?
1335 X86II::getSizeOfImm(Desc->TSFlags) : 0;
1336 emitMemModRMByte(MI, FirstMemOp,
1337 getX86RegNum(MI.getOperand(CurOp).getReg()),PCAdj);
1338 CurOp += AddrOperands + 1;
1344 case X86II::MRM0r: case X86II::MRM1r:
1345 case X86II::MRM2r: case X86II::MRM3r:
1346 case X86II::MRM4r: case X86II::MRM5r:
1347 case X86II::MRM6r: case X86II::MRM7r: {
1348 if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
1350 MCE.emitByte(BaseOpcode);
1351 emitRegModRMByte(MI.getOperand(CurOp++).getReg(),
1352 (Desc->TSFlags & X86II::FormMask)-X86II::MRM0r);
1354 if (CurOp == NumOps)
1357 const MachineOperand &MO1 = MI.getOperand(CurOp++);
1358 unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
1360 emitConstant(MO1.getImm(), Size);
1364 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
1365 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
1366 if (Opcode == X86::MOV64ri32)
1367 rt = X86::reloc_absolute_word_sext; // FIXME: add X86II flag?
1368 if (MO1.isGlobal()) {
1369 bool Indirect = gvNeedsNonLazyPtr(MO1, TM);
1370 emitGlobalAddress(MO1.getGlobal(), rt, MO1.getOffset(), 0,
1372 } else if (MO1.isSymbol())
1373 emitExternalSymbolAddress(MO1.getSymbolName(), rt);
1374 else if (MO1.isCPI())
1375 emitConstPoolAddress(MO1.getIndex(), rt);
1376 else if (MO1.isJTI())
1377 emitJumpTableAddress(MO1.getIndex(), rt);
1381 case X86II::MRM0m: case X86II::MRM1m:
1382 case X86II::MRM2m: case X86II::MRM3m:
1383 case X86II::MRM4m: case X86II::MRM5m:
1384 case X86II::MRM6m: case X86II::MRM7m: {
1385 if (HasVEX_4V) // Skip the register dst (which is encoded in VEX_VVVV).
1387 intptr_t PCAdj = (CurOp + X86::AddrNumOperands != NumOps) ?
1388 (MI.getOperand(CurOp+X86::AddrNumOperands).isImm() ?
1389 X86II::getSizeOfImm(Desc->TSFlags) : 4) : 0;
1391 MCE.emitByte(BaseOpcode);
1392 emitMemModRMByte(MI, CurOp, (Desc->TSFlags & X86II::FormMask)-X86II::MRM0m,
1394 CurOp += X86::AddrNumOperands;
1396 if (CurOp == NumOps)
1399 const MachineOperand &MO = MI.getOperand(CurOp++);
1400 unsigned Size = X86II::getSizeOfImm(Desc->TSFlags);
1402 emitConstant(MO.getImm(), Size);
1406 unsigned rt = Is64BitMode ? X86::reloc_pcrel_word
1407 : (IsPIC ? X86::reloc_picrel_word : X86::reloc_absolute_word);
1408 if (Opcode == X86::MOV64mi32)
1409 rt = X86::reloc_absolute_word_sext; // FIXME: add X86II flag?
1410 if (MO.isGlobal()) {
1411 bool Indirect = gvNeedsNonLazyPtr(MO, TM);
1412 emitGlobalAddress(MO.getGlobal(), rt, MO.getOffset(), 0,
1414 } else if (MO.isSymbol())
1415 emitExternalSymbolAddress(MO.getSymbolName(), rt);
1416 else if (MO.isCPI())
1417 emitConstPoolAddress(MO.getIndex(), rt);
1418 else if (MO.isJTI())
1419 emitJumpTableAddress(MO.getIndex(), rt);
1423 case X86II::MRMInitReg:
1424 MCE.emitByte(BaseOpcode);
1425 // Duplicate register, used by things like MOV8r0 (aka xor reg,reg).
1426 emitRegModRMByte(MI.getOperand(CurOp).getReg(),
1427 getX86RegNum(MI.getOperand(CurOp).getReg()));
1432 MCE.emitByte(BaseOpcode);
1436 MCE.emitByte(BaseOpcode);
1440 MCE.emitByte(BaseOpcode);
1444 MCE.emitByte(BaseOpcode);
1448 MCE.emitByte(BaseOpcode);
1453 while (CurOp != NumOps && NumOps - CurOp <= 2) {
1454 // The last source register of a 4 operand instruction in AVX is encoded
1455 // in bits[7:4] of a immediate byte.
1456 if ((TSFlags >> X86II::VEXShift) & X86II::VEX_I8IMM) {
1457 const MachineOperand &MO = MI.getOperand(HasMemOp4 ? MemOp4_I8IMMOperand
1460 unsigned RegNum = getX86RegNum(MO.getReg()) << 4;
1461 if (X86II::isX86_64ExtendedReg(MO.getReg()))
1463 // If there is an additional 5th operand it must be an immediate, which
1464 // is encoded in bits[3:0]
1465 if (CurOp != NumOps) {
1466 const MachineOperand &MIMM = MI.getOperand(CurOp++);
1468 unsigned Val = MIMM.getImm();
1469 assert(Val < 16 && "Immediate operand value out of range");
1473 emitConstant(RegNum, 1);
1475 emitConstant(MI.getOperand(CurOp++).getImm(),
1476 X86II::getSizeOfImm(Desc->TSFlags));
1480 if (!MI.isVariadic() && CurOp != NumOps) {
1482 dbgs() << "Cannot encode all operands of: " << MI << "\n";
1484 llvm_unreachable(0);
1487 MCE.processDebugLoc(MI.getDebugLoc(), false);