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/MCAsmInfo.h"
30 #include "llvm/MC/MCContext.h"
31 #include "llvm/MC/MCExpr.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbol.h"
35 #include "llvm/CodeGen/MachineJumpTableInfo.h"
36 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
37 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Target/Mangler.h"
41 #include "llvm/Target/TargetOptions.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/ADT/SmallString.h"
46 //===----------------------------------------------------------------------===//
47 // Primitive Helper Functions.
48 //===----------------------------------------------------------------------===//
50 void X86AsmPrinter::PrintPICBaseSymbol() const {
51 const TargetLowering *TLI = TM.getTargetLowering();
52 O << *static_cast<const X86TargetLowering*>(TLI)->getPICBaseSymbol(MF,
56 MCSymbol *X86AsmPrinter::GetGlobalValueSymbol(const GlobalValue *GV) const {
57 SmallString<60> NameStr;
58 Mang->getNameWithPrefix(NameStr, GV, false);
59 MCSymbol *Symb = OutContext.GetOrCreateSymbol(NameStr.str());
61 if (Subtarget->isTargetCygMing()) {
62 X86COFFMachineModuleInfo &COFFMMI =
63 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
64 COFFMMI.DecorateCygMingName(Symb, OutContext, GV, *TM.getTargetData());
66 // Save function name for later type emission.
67 if (const Function *F = dyn_cast<Function>(GV))
68 if (F->isDeclaration())
69 COFFMMI.addExternalFunction(Symb->getName());
76 /// runOnMachineFunction - Emit the function body.
78 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
79 SetupMachineFunction(MF);
81 if (Subtarget->isTargetCOFF()) {
82 const Function *F = MF.getFunction();
83 O << "\t.def\t " << *CurrentFnSym << ";\t.scl\t" <<
84 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
85 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
89 // Have common code print out the function header with linkage info etc.
92 // Emit the rest of the function body.
95 // We didn't modify anything.
99 /// printSymbolOperand - Print a raw symbol reference operand. This handles
100 /// jump tables, constant pools, global address and external symbols, all of
101 /// which print to a label with various suffixes for relocation types etc.
102 void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
103 switch (MO.getType()) {
104 default: llvm_unreachable("unknown symbol type!");
105 case MachineOperand::MO_JumpTableIndex:
106 O << *GetJTISymbol(MO.getIndex());
108 case MachineOperand::MO_ConstantPoolIndex:
109 O << *GetCPISymbol(MO.getIndex());
110 printOffset(MO.getOffset());
112 case MachineOperand::MO_GlobalAddress: {
113 const GlobalValue *GV = MO.getGlobal();
116 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
117 GVSym = GetSymbolWithGlobalValueBase(GV, "$stub");
118 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
119 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
120 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
121 GVSym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
123 GVSym = GetGlobalValueSymbol(GV);
125 // Handle dllimport linkage.
126 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
127 GVSym = OutContext.GetOrCreateSymbol(Twine("__imp_") + GVSym->getName());
129 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
130 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
131 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
134 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
136 StubSym = GetGlobalValueSymbol(GV);
138 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
139 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
141 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
143 StubSym = GetGlobalValueSymbol(GV);
144 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
145 MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
147 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
149 StubSym = GetGlobalValueSymbol(GV);
152 // If the name begins with a dollar-sign, enclose it in parens. We do this
153 // to avoid having it look like an integer immediate to the assembler.
154 if (GVSym->getName()[0] != '$')
157 O << '(' << *GVSym << ')';
158 printOffset(MO.getOffset());
161 case MachineOperand::MO_ExternalSymbol: {
162 const MCSymbol *SymToPrint;
163 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
164 SmallString<128> TempNameStr;
165 TempNameStr += StringRef(MO.getSymbolName());
166 TempNameStr += StringRef("$stub");
168 MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
170 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
172 TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
173 StubSym = OutContext.GetOrCreateSymbol(TempNameStr.str());
175 SymToPrint = StubSym;
177 SymToPrint = GetExternalSymbolSymbol(MO.getSymbolName());
180 // If the name begins with a dollar-sign, enclose it in parens. We do this
181 // to avoid having it look like an integer immediate to the assembler.
182 if (SymToPrint->getName()[0] != '$')
185 O << '(' << *SymToPrint << '(';
190 switch (MO.getTargetFlags()) {
192 llvm_unreachable("Unknown target flag on GV operand");
193 case X86II::MO_NO_FLAG: // No flag.
195 case X86II::MO_DARWIN_NONLAZY:
196 case X86II::MO_DLLIMPORT:
197 case X86II::MO_DARWIN_STUB:
198 // These affect the name of the symbol, not any suffix.
200 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
202 PrintPICBaseSymbol();
205 case X86II::MO_PIC_BASE_OFFSET:
206 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
207 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
209 PrintPICBaseSymbol();
211 case X86II::MO_TLSGD: O << "@TLSGD"; break;
212 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
213 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
214 case X86II::MO_TPOFF: O << "@TPOFF"; break;
215 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
216 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
217 case X86II::MO_GOT: O << "@GOT"; break;
218 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
219 case X86II::MO_PLT: O << "@PLT"; break;
223 /// print_pcrel_imm - This is used to print an immediate value that ends up
224 /// being encoded as a pc-relative value. These print slightly differently, for
225 /// example, a $ is not emitted.
226 void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
227 const MachineOperand &MO = MI->getOperand(OpNo);
228 switch (MO.getType()) {
229 default: llvm_unreachable("Unknown pcrel immediate operand");
230 case MachineOperand::MO_Immediate:
233 case MachineOperand::MO_MachineBasicBlock:
234 O << *MO.getMBB()->getSymbol(OutContext);
236 case MachineOperand::MO_GlobalAddress:
237 case MachineOperand::MO_ExternalSymbol:
238 printSymbolOperand(MO);
244 void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
245 const char *Modifier) {
246 const MachineOperand &MO = MI->getOperand(OpNo);
247 switch (MO.getType()) {
248 default: llvm_unreachable("unknown operand type!");
249 case MachineOperand::MO_Register: {
251 unsigned Reg = MO.getReg();
252 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
253 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
254 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
255 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
256 Reg = getX86SubSuperRegister(Reg, VT);
258 O << X86ATTInstPrinter::getRegisterName(Reg);
262 case MachineOperand::MO_Immediate:
263 O << '$' << MO.getImm();
266 case MachineOperand::MO_JumpTableIndex:
267 case MachineOperand::MO_ConstantPoolIndex:
268 case MachineOperand::MO_GlobalAddress:
269 case MachineOperand::MO_ExternalSymbol: {
271 printSymbolOperand(MO);
277 void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
278 unsigned char value = MI->getOperand(Op).getImm();
279 assert(value <= 7 && "Invalid ssecc argument!");
281 case 0: O << "eq"; break;
282 case 1: O << "lt"; break;
283 case 2: O << "le"; break;
284 case 3: O << "unord"; break;
285 case 4: O << "neq"; break;
286 case 5: O << "nlt"; break;
287 case 6: O << "nle"; break;
288 case 7: O << "ord"; break;
292 void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
293 const char *Modifier) {
294 const MachineOperand &BaseReg = MI->getOperand(Op);
295 const MachineOperand &IndexReg = MI->getOperand(Op+2);
296 const MachineOperand &DispSpec = MI->getOperand(Op+3);
298 // If we really don't want to print out (rip), don't.
299 bool HasBaseReg = BaseReg.getReg() != 0;
300 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
301 BaseReg.getReg() == X86::RIP)
304 // HasParenPart - True if we will print out the () part of the mem ref.
305 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
307 if (DispSpec.isImm()) {
308 int DispVal = DispSpec.getImm();
309 if (DispVal || !HasParenPart)
312 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
313 DispSpec.isJTI() || DispSpec.isSymbol());
314 printSymbolOperand(MI->getOperand(Op+3));
318 assert(IndexReg.getReg() != X86::ESP &&
319 "X86 doesn't allow scaling by ESP");
323 printOperand(MI, Op, Modifier);
325 if (IndexReg.getReg()) {
327 printOperand(MI, Op+2, Modifier);
328 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
330 O << ',' << ScaleVal;
336 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
337 const char *Modifier) {
338 assert(isMem(MI, Op) && "Invalid memory reference!");
339 const MachineOperand &Segment = MI->getOperand(Op+4);
340 if (Segment.getReg()) {
341 printOperand(MI, Op+4, Modifier);
344 printLeaMemReference(MI, Op, Modifier);
347 void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
348 PrintPICBaseSymbol();
350 PrintPICBaseSymbol();
354 bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
355 unsigned Reg = MO.getReg();
357 default: return true; // Unknown mode.
358 case 'b': // Print QImode register
359 Reg = getX86SubSuperRegister(Reg, MVT::i8);
361 case 'h': // Print QImode high register
362 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
364 case 'w': // Print HImode register
365 Reg = getX86SubSuperRegister(Reg, MVT::i16);
367 case 'k': // Print SImode register
368 Reg = getX86SubSuperRegister(Reg, MVT::i32);
370 case 'q': // Print DImode register
371 Reg = getX86SubSuperRegister(Reg, MVT::i64);
375 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
379 /// PrintAsmOperand - Print out an operand for an inline asm expression.
381 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
383 const char *ExtraCode) {
384 // Does this asm operand have a single letter operand modifier?
385 if (ExtraCode && ExtraCode[0]) {
386 if (ExtraCode[1] != 0) return true; // Unknown modifier.
388 const MachineOperand &MO = MI->getOperand(OpNo);
390 switch (ExtraCode[0]) {
391 default: return true; // Unknown modifier.
392 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
397 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
398 printSymbolOperand(MO);
403 printOperand(MI, OpNo);
409 case 'c': // Don't print "$" before a global var name or constant.
412 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
413 printSymbolOperand(MO);
415 printOperand(MI, OpNo);
418 case 'A': // Print '*' before a register (it must be a register)
421 printOperand(MI, OpNo);
426 case 'b': // Print QImode register
427 case 'h': // Print QImode high register
428 case 'w': // Print HImode register
429 case 'k': // Print SImode register
430 case 'q': // Print DImode register
432 return printAsmMRegister(MO, ExtraCode[0]);
433 printOperand(MI, OpNo);
436 case 'P': // This is the operand of a call, treat specially.
437 print_pcrel_imm(MI, OpNo);
440 case 'n': // Negate the immediate or print a '-' before the operand.
441 // Note: this is a temporary solution. It should be handled target
442 // independently as part of the 'MC' work.
451 printOperand(MI, OpNo);
455 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
456 unsigned OpNo, unsigned AsmVariant,
457 const char *ExtraCode) {
458 if (ExtraCode && ExtraCode[0]) {
459 if (ExtraCode[1] != 0) return true; // Unknown modifier.
461 switch (ExtraCode[0]) {
462 default: return true; // Unknown modifier.
463 case 'b': // Print QImode register
464 case 'h': // Print QImode high register
465 case 'w': // Print HImode register
466 case 'k': // Print SImode register
467 case 'q': // Print SImode register
468 // These only apply to registers, ignore on mem.
470 case 'P': // Don't print @PLT, but do print as memory.
471 printMemReference(MI, OpNo, "no-rip");
475 printMemReference(MI, OpNo);
480 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
481 if (Subtarget->isTargetDarwin()) {
482 // All darwin targets use mach-o.
483 TargetLoweringObjectFileMachO &TLOFMacho =
484 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
486 MachineModuleInfoMachO &MMIMacho =
487 MMI->getObjFileInfo<MachineModuleInfoMachO>();
489 // Output stubs for dynamically-linked functions.
490 MachineModuleInfoMachO::SymbolListTy Stubs;
492 Stubs = MMIMacho.GetFnStubList();
493 if (!Stubs.empty()) {
494 const MCSection *TheSection =
495 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
496 MCSectionMachO::S_SYMBOL_STUBS |
497 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
498 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
499 5, SectionKind::getMetadata());
500 OutStreamer.SwitchSection(TheSection);
502 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
504 OutStreamer.EmitLabel(Stubs[i].first);
505 // .indirect_symbol _foo
506 OutStreamer.EmitSymbolAttribute(Stubs[i].second, MCSA_IndirectSymbol);
507 // hlt; hlt; hlt; hlt; hlt hlt = 0xf4 = -12.
508 const char HltInsts[] = { -12, -12, -12, -12, -12 };
509 OutStreamer.EmitBytes(StringRef(HltInsts, 5), 0/*addrspace*/);
513 OutStreamer.AddBlankLine();
516 // Output stubs for external and common global variables.
517 Stubs = MMIMacho.GetGVStubList();
518 if (!Stubs.empty()) {
519 const MCSection *TheSection =
520 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
521 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
522 SectionKind::getMetadata());
523 OutStreamer.SwitchSection(TheSection);
525 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
526 // L_foo$non_lazy_ptr:
527 OutStreamer.EmitLabel(Stubs[i].first);
528 // .indirect_symbol _foo
529 OutStreamer.EmitSymbolAttribute(Stubs[i].second, MCSA_IndirectSymbol);
531 OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
534 OutStreamer.AddBlankLine();
537 Stubs = MMIMacho.GetHiddenGVStubList();
538 if (!Stubs.empty()) {
539 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
542 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
543 // L_foo$non_lazy_ptr:
544 OutStreamer.EmitLabel(Stubs[i].first);
546 OutStreamer.EmitValue(MCSymbolRefExpr::Create(Stubs[i].second,
548 4/*size*/, 0/*addrspace*/);
551 OutStreamer.AddBlankLine();
554 // Funny Darwin hack: This flag tells the linker that no global symbols
555 // contain code that falls through to other global symbols (e.g. the obvious
556 // implementation of multiple entry points). If this doesn't occur, the
557 // linker can safely perform dead code stripping. Since LLVM never
558 // generates code that does this, it is always safe to set.
559 OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
562 if (Subtarget->isTargetCOFF()) {
563 X86COFFMachineModuleInfo &COFFMMI =
564 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
566 // Emit type information for external functions
567 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
568 E = COFFMMI.stub_end(); I != E; ++I) {
569 O << "\t.def\t " << I->getKeyData()
570 << ";\t.scl\t" << COFF::C_EXT
571 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
575 if (Subtarget->isTargetCygMing()) {
576 // Necessary for dllexport support
577 std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
579 TargetLoweringObjectFileCOFF &TLOFCOFF =
580 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
582 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
583 if (I->hasDLLExportLinkage()) {
584 MCSymbol *Sym = GetGlobalValueSymbol(I);
585 DLLExportedFns.push_back(Sym);
588 for (Module::const_global_iterator I = M.global_begin(),
589 E = M.global_end(); I != E; ++I)
590 if (I->hasDLLExportLinkage())
591 DLLExportedGlobals.push_back(GetGlobalValueSymbol(I));
593 // Output linker support code for dllexported globals on windows.
594 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
595 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
597 SectionKind::getMetadata()));
598 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
599 O << "\t.ascii \" -export:" << *DLLExportedGlobals[i] << ",data\"\n";
601 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
602 O << "\t.ascii \" -export:" << *DLLExportedFns[i] << "\"\n";
607 if (Subtarget->isTargetELF()) {
608 TargetLoweringObjectFileELF &TLOFELF =
609 static_cast<TargetLoweringObjectFileELF &>(getObjFileLowering());
611 MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
613 // Output stubs for external and common global variables.
614 MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
615 if (!Stubs.empty()) {
616 OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
617 const TargetData *TD = TM.getTargetData();
619 for (unsigned i = 0, e = Stubs.size(); i != e; ++i)
620 O << *Stubs[i].first << ":\n"
621 << (TD->getPointerSize() == 8 ?
622 MAI->getData64bitsDirective() : MAI->getData32bitsDirective())
623 << *Stubs[i].second << '\n';
631 //===----------------------------------------------------------------------===//
632 // Target Registry Stuff
633 //===----------------------------------------------------------------------===//
635 static MCInstPrinter *createX86MCInstPrinter(const Target &T,
636 unsigned SyntaxVariant,
637 const MCAsmInfo &MAI,
639 if (SyntaxVariant == 0)
640 return new X86ATTInstPrinter(O, MAI);
641 if (SyntaxVariant == 1)
642 return new X86IntelInstPrinter(O, MAI);
646 // Force static initialization.
647 extern "C" void LLVMInitializeX86AsmPrinter() {
648 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
649 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
651 TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
652 TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);