1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly --------===//
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 a printer that converts from our internal representation
11 // of machine-dependent LLVM code to X86 machine code.
13 //===----------------------------------------------------------------------===//
15 #include "X86AsmPrinter.h"
16 #include "X86ATTInstPrinter.h"
17 #include "X86IntelInstPrinter.h"
18 #include "X86MCInstLower.h"
21 #include "X86COFFMachineModuleInfo.h"
22 #include "X86MachineFunctionInfo.h"
23 #include "X86TargetMachine.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Type.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/MC/MCAsmInfo.h"
38 #include "llvm/Target/TargetLoweringObjectFile.h"
39 #include "llvm/Target/TargetOptions.h"
40 #include "llvm/Target/TargetRegistry.h"
41 #include "llvm/ADT/SmallString.h"
44 //===----------------------------------------------------------------------===//
45 // Primitive Helper Functions.
46 //===----------------------------------------------------------------------===//
48 void X86AsmPrinter::PrintPICBaseSymbol() const {
49 const TargetLowering *TLI = TM.getTargetLowering();
50 O << *static_cast<const X86TargetLowering*>(TLI)->getPICBaseSymbol(MF,
54 /// runOnMachineFunction - Emit the function body.
56 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
57 SetupMachineFunction(MF);
59 // COFF and Cygwin specific mangling stuff. This should be moved out to the
60 // mangler or handled some other way?
61 if (Subtarget->isTargetCOFF()) {
62 X86COFFMachineModuleInfo &COFFMMI =
63 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
65 // Populate function information map. Don't want to populate
66 // non-stdcall or non-fastcall functions' information right now.
67 const Function *F = MF.getFunction();
68 CallingConv::ID CC = F->getCallingConv();
69 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
70 COFFMMI.AddFunctionInfo(F, *MF.getInfo<X86MachineFunctionInfo>());
72 if (Subtarget->isTargetCygMing()) {
73 const Function *F = MF.getFunction();
74 X86COFFMachineModuleInfo &COFFMMI =
75 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
76 COFFMMI.DecorateCygMingName(CurrentFnSym, OutContext,F,*TM.getTargetData());
78 O << "\t.def\t " << *CurrentFnSym;
80 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
81 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
85 // Have common code print out the function header with linkage info etc.
88 // Emit the rest of the function body.
91 // We didn't modify anything.
95 /// printSymbolOperand - Print a raw symbol reference operand. This handles
96 /// jump tables, constant pools, global address and external symbols, all of
97 /// which print to a label with various suffixes for relocation types etc.
98 void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
99 switch (MO.getType()) {
100 default: llvm_unreachable("unknown symbol type!");
101 case MachineOperand::MO_JumpTableIndex:
102 O << *GetJTISymbol(MO.getIndex());
104 case MachineOperand::MO_ConstantPoolIndex:
105 O << *GetCPISymbol(MO.getIndex());
106 printOffset(MO.getOffset());
108 case MachineOperand::MO_GlobalAddress: {
109 const GlobalValue *GV = MO.getGlobal();
112 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
113 GVSym = GetSymbolWithGlobalValueBase(GV, "$stub");
114 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
115 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
116 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
117 GVSym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
119 GVSym = GetGlobalValueSymbol(GV);
121 if (Subtarget->isTargetCygMing()) {
122 X86COFFMachineModuleInfo &COFFMMI =
123 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
124 COFFMMI.DecorateCygMingName(GVSym, OutContext, GV, *TM.getTargetData());
127 // Handle dllimport linkage.
128 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
129 GVSym = OutContext.GetOrCreateSymbol(Twine("__imp_") + GVSym->getName());
131 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
132 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
133 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
135 const MCSymbol *&StubSym =
136 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
138 StubSym = GetGlobalValueSymbol(GV);
140 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
141 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
142 const MCSymbol *&StubSym =
143 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
145 StubSym = GetGlobalValueSymbol(GV);
146 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
147 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
148 const MCSymbol *&StubSym =
149 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
151 StubSym = GetGlobalValueSymbol(GV);
154 // If the name begins with a dollar-sign, enclose it in parens. We do this
155 // to avoid having it look like an integer immediate to the assembler.
156 if (GVSym->getName()[0] != '$')
159 O << '(' << *GVSym << ')';
160 printOffset(MO.getOffset());
163 case MachineOperand::MO_ExternalSymbol: {
164 const MCSymbol *SymToPrint;
165 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
166 SmallString<128> TempNameStr;
167 TempNameStr += StringRef(MO.getSymbolName());
168 TempNameStr += StringRef("$stub");
170 const MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
171 const MCSymbol *&StubSym =
172 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
174 TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
175 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
177 SymToPrint = StubSym;
179 SymToPrint = GetExternalSymbolSymbol(MO.getSymbolName());
182 // If the name begins with a dollar-sign, enclose it in parens. We do this
183 // to avoid having it look like an integer immediate to the assembler.
184 if (SymToPrint->getName()[0] != '$')
187 O << '(' << *SymToPrint << '(';
192 switch (MO.getTargetFlags()) {
194 llvm_unreachable("Unknown target flag on GV operand");
195 case X86II::MO_NO_FLAG: // No flag.
197 case X86II::MO_DARWIN_NONLAZY:
198 case X86II::MO_DLLIMPORT:
199 case X86II::MO_DARWIN_STUB:
200 // These affect the name of the symbol, not any suffix.
202 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
204 PrintPICBaseSymbol();
207 case X86II::MO_PIC_BASE_OFFSET:
208 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
209 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
211 PrintPICBaseSymbol();
213 case X86II::MO_TLSGD: O << "@TLSGD"; break;
214 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
215 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
216 case X86II::MO_TPOFF: O << "@TPOFF"; break;
217 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
218 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
219 case X86II::MO_GOT: O << "@GOT"; break;
220 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
221 case X86II::MO_PLT: O << "@PLT"; break;
225 /// print_pcrel_imm - This is used to print an immediate value that ends up
226 /// being encoded as a pc-relative value. These print slightly differently, for
227 /// example, a $ is not emitted.
228 void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
229 const MachineOperand &MO = MI->getOperand(OpNo);
230 switch (MO.getType()) {
231 default: llvm_unreachable("Unknown pcrel immediate operand");
232 case MachineOperand::MO_Immediate:
235 case MachineOperand::MO_MachineBasicBlock:
236 O << *MO.getMBB()->getSymbol(OutContext);
238 case MachineOperand::MO_GlobalAddress:
239 case MachineOperand::MO_ExternalSymbol:
240 printSymbolOperand(MO);
246 void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
247 const char *Modifier) {
248 const MachineOperand &MO = MI->getOperand(OpNo);
249 switch (MO.getType()) {
250 default: llvm_unreachable("unknown operand type!");
251 case MachineOperand::MO_Register: {
253 unsigned Reg = MO.getReg();
254 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
255 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
256 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
257 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
258 Reg = getX86SubSuperRegister(Reg, VT);
260 O << X86ATTInstPrinter::getRegisterName(Reg);
264 case MachineOperand::MO_Immediate:
265 O << '$' << MO.getImm();
268 case MachineOperand::MO_JumpTableIndex:
269 case MachineOperand::MO_ConstantPoolIndex:
270 case MachineOperand::MO_GlobalAddress:
271 case MachineOperand::MO_ExternalSymbol: {
273 printSymbolOperand(MO);
279 void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
280 unsigned char value = MI->getOperand(Op).getImm();
281 assert(value <= 7 && "Invalid ssecc argument!");
283 case 0: O << "eq"; break;
284 case 1: O << "lt"; break;
285 case 2: O << "le"; break;
286 case 3: O << "unord"; break;
287 case 4: O << "neq"; break;
288 case 5: O << "nlt"; break;
289 case 6: O << "nle"; break;
290 case 7: O << "ord"; break;
294 void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
295 const char *Modifier) {
296 const MachineOperand &BaseReg = MI->getOperand(Op);
297 const MachineOperand &IndexReg = MI->getOperand(Op+2);
298 const MachineOperand &DispSpec = MI->getOperand(Op+3);
300 // If we really don't want to print out (rip), don't.
301 bool HasBaseReg = BaseReg.getReg() != 0;
302 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
303 BaseReg.getReg() == X86::RIP)
306 // HasParenPart - True if we will print out the () part of the mem ref.
307 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
309 if (DispSpec.isImm()) {
310 int DispVal = DispSpec.getImm();
311 if (DispVal || !HasParenPart)
314 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
315 DispSpec.isJTI() || DispSpec.isSymbol());
316 printSymbolOperand(MI->getOperand(Op+3));
320 assert(IndexReg.getReg() != X86::ESP &&
321 "X86 doesn't allow scaling by ESP");
325 printOperand(MI, Op, Modifier);
327 if (IndexReg.getReg()) {
329 printOperand(MI, Op+2, Modifier);
330 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
332 O << ',' << ScaleVal;
338 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
339 const char *Modifier) {
340 assert(isMem(MI, Op) && "Invalid memory reference!");
341 const MachineOperand &Segment = MI->getOperand(Op+4);
342 if (Segment.getReg()) {
343 printOperand(MI, Op+4, Modifier);
346 printLeaMemReference(MI, Op, Modifier);
349 void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
350 PrintPICBaseSymbol();
352 PrintPICBaseSymbol();
356 bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
357 unsigned Reg = MO.getReg();
359 default: return true; // Unknown mode.
360 case 'b': // Print QImode register
361 Reg = getX86SubSuperRegister(Reg, MVT::i8);
363 case 'h': // Print QImode high register
364 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
366 case 'w': // Print HImode register
367 Reg = getX86SubSuperRegister(Reg, MVT::i16);
369 case 'k': // Print SImode register
370 Reg = getX86SubSuperRegister(Reg, MVT::i32);
372 case 'q': // Print DImode register
373 Reg = getX86SubSuperRegister(Reg, MVT::i64);
377 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
381 /// PrintAsmOperand - Print out an operand for an inline asm expression.
383 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
385 const char *ExtraCode) {
386 // Does this asm operand have a single letter operand modifier?
387 if (ExtraCode && ExtraCode[0]) {
388 if (ExtraCode[1] != 0) return true; // Unknown modifier.
390 const MachineOperand &MO = MI->getOperand(OpNo);
392 switch (ExtraCode[0]) {
393 default: return true; // Unknown modifier.
394 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
399 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
400 printSymbolOperand(MO);
405 printOperand(MI, OpNo);
411 case 'c': // Don't print "$" before a global var name or constant.
414 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
415 printSymbolOperand(MO);
417 printOperand(MI, OpNo);
420 case 'A': // Print '*' before a register (it must be a register)
423 printOperand(MI, OpNo);
428 case 'b': // Print QImode register
429 case 'h': // Print QImode high register
430 case 'w': // Print HImode register
431 case 'k': // Print SImode register
432 case 'q': // Print DImode register
434 return printAsmMRegister(MO, ExtraCode[0]);
435 printOperand(MI, OpNo);
438 case 'P': // This is the operand of a call, treat specially.
439 print_pcrel_imm(MI, OpNo);
442 case 'n': // Negate the immediate or print a '-' before the operand.
443 // Note: this is a temporary solution. It should be handled target
444 // independently as part of the 'MC' work.
453 printOperand(MI, OpNo);
457 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
458 unsigned OpNo, unsigned AsmVariant,
459 const char *ExtraCode) {
460 if (ExtraCode && ExtraCode[0]) {
461 if (ExtraCode[1] != 0) return true; // Unknown modifier.
463 switch (ExtraCode[0]) {
464 default: return true; // Unknown modifier.
465 case 'b': // Print QImode register
466 case 'h': // Print QImode high register
467 case 'w': // Print HImode register
468 case 'k': // Print SImode register
469 case 'q': // Print SImode register
470 // These only apply to registers, ignore on mem.
472 case 'P': // Don't print @PLT, but do print as memory.
473 printMemReference(MI, OpNo, "no-rip");
477 printMemReference(MI, OpNo);
482 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
483 if (Subtarget->isTargetDarwin()) {
484 // All darwin targets use mach-o.
485 TargetLoweringObjectFileMachO &TLOFMacho =
486 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
488 MachineModuleInfoMachO &MMIMacho =
489 MMI->getObjFileInfo<MachineModuleInfoMachO>();
491 // Output stubs for dynamically-linked functions.
492 MachineModuleInfoMachO::SymbolListTy Stubs;
494 Stubs = MMIMacho.GetFnStubList();
495 if (!Stubs.empty()) {
496 const MCSection *TheSection =
497 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
498 MCSectionMachO::S_SYMBOL_STUBS |
499 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
500 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
501 5, SectionKind::getMetadata());
502 OutStreamer.SwitchSection(TheSection);
504 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
505 O << *Stubs[i].first << ":\n";
506 // Get the MCSymbol without the $stub suffix.
507 O << "\t.indirect_symbol " << *Stubs[i].second;
508 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
515 // Output stubs for external and common global variables.
516 Stubs = MMIMacho.GetGVStubList();
517 if (!Stubs.empty()) {
518 const MCSection *TheSection =
519 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
520 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
521 SectionKind::getMetadata());
522 OutStreamer.SwitchSection(TheSection);
524 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
525 O << *Stubs[i].first << ":\n\t.indirect_symbol " << *Stubs[i].second;
526 O << "\n\t.long\t0\n";
531 Stubs = MMIMacho.GetHiddenGVStubList();
532 if (!Stubs.empty()) {
533 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
536 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
537 O << *Stubs[i].first << ":\n" << MAI->getData32bitsDirective();
538 O << *Stubs[i].second << '\n';
543 // Funny Darwin hack: This flag tells the linker that no global symbols
544 // contain code that falls through to other global symbols (e.g. the obvious
545 // implementation of multiple entry points). If this doesn't occur, the
546 // linker can safely perform dead code stripping. Since LLVM never
547 // generates code that does this, it is always safe to set.
548 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
551 if (Subtarget->isTargetCOFF()) {
552 X86COFFMachineModuleInfo &COFFMMI =
553 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
555 // Emit type information for external functions
556 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
557 E = COFFMMI.stub_end(); I != E; ++I) {
558 O << "\t.def\t " << I->getKeyData()
559 << ";\t.scl\t" << COFF::C_EXT
560 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
564 if (Subtarget->isTargetCygMing()) {
565 // Necessary for dllexport support
566 std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
568 TargetLoweringObjectFileCOFF &TLOFCOFF =
569 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
571 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
572 if (I->hasDLLExportLinkage()) {
573 MCSymbol *Sym = GetGlobalValueSymbol(I);
574 COFFMMI.DecorateCygMingName(Sym, OutContext, I, *TM.getTargetData());
575 DLLExportedFns.push_back(Sym);
578 for (Module::const_global_iterator I = M.global_begin(),
579 E = M.global_end(); I != E; ++I)
580 if (I->hasDLLExportLinkage())
581 DLLExportedGlobals.push_back(GetGlobalValueSymbol(I));
583 // Output linker support code for dllexported globals on windows.
584 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
585 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
587 SectionKind::getMetadata()));
588 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
589 O << "\t.ascii \" -export:" << *DLLExportedGlobals[i] << ",data\"\n";
591 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
592 O << "\t.ascii \" -export:" << *DLLExportedFns[i] << "\"\n";
599 //===----------------------------------------------------------------------===//
600 // Target Registry Stuff
601 //===----------------------------------------------------------------------===//
603 static MCInstPrinter *createX86MCInstPrinter(const Target &T,
604 unsigned SyntaxVariant,
605 const MCAsmInfo &MAI,
607 if (SyntaxVariant == 0)
608 return new X86ATTInstPrinter(O, MAI);
609 if (SyntaxVariant == 1)
610 return new X86IntelInstPrinter(O, MAI);
614 // Force static initialization.
615 extern "C" void LLVMInitializeX86AsmPrinter() {
616 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
617 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
619 TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
620 TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);