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 AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "asm-printer"
17 #include "X86AsmPrinter.h"
18 #include "X86ATTInstPrinter.h"
19 #include "X86IntelInstPrinter.h"
20 #include "X86MCInstLower.h"
23 #include "X86COFFMachineModuleInfo.h"
24 #include "X86MachineFunctionInfo.h"
25 #include "X86TargetMachine.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/DerivedTypes.h"
28 #include "llvm/Module.h"
29 #include "llvm/Type.h"
30 #include "llvm/Assembly/Writer.h"
31 #include "llvm/MC/MCContext.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/Support/ErrorHandling.h"
38 #include "llvm/Support/FormattedStream.h"
39 #include "llvm/Support/Mangler.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/Target/TargetLoweringObjectFile.h"
42 #include "llvm/Target/TargetOptions.h"
43 #include "llvm/Target/TargetRegistry.h"
44 #include "llvm/ADT/SmallString.h"
45 #include "llvm/ADT/Statistic.h"
48 STATISTIC(EmittedInsts, "Number of machine instrs printed");
50 //===----------------------------------------------------------------------===//
51 // Primitive Helper Functions.
52 //===----------------------------------------------------------------------===//
54 void X86AsmPrinter::printMCInst(const MCInst *MI) {
55 if (MAI->getAssemblerDialect() == 0)
56 X86ATTInstPrinter(O, *MAI).printInstruction(MI);
58 X86IntelInstPrinter(O, *MAI).printInstruction(MI);
61 void X86AsmPrinter::PrintPICBaseSymbol() const {
62 // FIXME: Gross const cast hack.
63 X86AsmPrinter *AP = const_cast<X86AsmPrinter*>(this);
64 X86MCInstLower(OutContext, 0, *AP).GetPICBaseSymbol()->print(O, MAI);
67 void X86AsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
68 unsigned FnAlign = MF.getAlignment();
69 const Function *F = MF.getFunction();
71 if (Subtarget->isTargetCygMing()) {
72 X86COFFMachineModuleInfo &COFFMMI =
73 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
74 COFFMMI.DecorateCygMingName(CurrentFnName, F, *TM.getTargetData());
77 OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
78 EmitAlignment(FnAlign, F);
80 switch (F->getLinkage()) {
81 default: llvm_unreachable("Unknown linkage type!");
82 case Function::InternalLinkage: // Symbols default to internal.
83 case Function::PrivateLinkage:
85 case Function::DLLExportLinkage:
86 case Function::ExternalLinkage:
87 O << "\t.globl\t" << CurrentFnName << '\n';
89 case Function::LinkerPrivateLinkage:
90 case Function::LinkOnceAnyLinkage:
91 case Function::LinkOnceODRLinkage:
92 case Function::WeakAnyLinkage:
93 case Function::WeakODRLinkage:
94 if (Subtarget->isTargetDarwin()) {
95 O << "\t.globl\t" << CurrentFnName << '\n';
96 O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
97 } else if (Subtarget->isTargetCygMing()) {
98 O << "\t.globl\t" << CurrentFnName << "\n"
99 "\t.linkonce discard\n";
101 O << "\t.weak\t" << CurrentFnName << '\n';
106 printVisibility(CurrentFnName, F->getVisibility());
108 if (Subtarget->isTargetELF())
109 O << "\t.type\t" << CurrentFnName << ",@function\n";
110 else if (Subtarget->isTargetCygMing()) {
111 O << "\t.def\t " << CurrentFnName
113 (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
114 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
118 O << CurrentFnName << ':';
120 O.PadToColumn(MAI->getCommentColumn());
121 O << MAI->getCommentString() << ' ';
122 WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
126 // Add some workaround for linkonce linkage on Cygwin\MinGW
127 if (Subtarget->isTargetCygMing() &&
128 (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
129 O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
132 /// runOnMachineFunction - This uses the printMachineInstruction()
133 /// method to print assembly for each instruction.
135 bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
136 const Function *F = MF.getFunction();
138 CallingConv::ID CC = F->getCallingConv();
140 SetupMachineFunction(MF);
143 if (Subtarget->isTargetCOFF()) {
144 X86COFFMachineModuleInfo &COFFMMI =
145 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
147 // Populate function information map. Don't want to populate
148 // non-stdcall or non-fastcall functions' information right now.
149 if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
150 COFFMMI.AddFunctionInfo(F, *MF.getInfo<X86MachineFunctionInfo>());
153 // Print out constants referenced by the function
154 EmitConstantPool(MF.getConstantPool());
156 // Print the 'header' of function
157 emitFunctionHeader(MF);
159 // Emit pre-function debug and/or EH information.
160 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
161 DW->BeginFunction(&MF);
163 // Print out code for the function.
164 bool hasAnyRealCode = false;
165 for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
167 // Print a label for the basic block.
168 EmitBasicBlockStart(I);
169 for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
171 // Print the assembly for the instruction.
173 hasAnyRealCode = true;
174 printMachineInstruction(II);
178 if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
179 // If the function is empty, then we need to emit *something*. Otherwise,
180 // the function's label might be associated with something that it wasn't
181 // meant to be associated with. We emit a noop in this situation.
182 // We are assuming inline asms are code.
186 if (MAI->hasDotTypeDotSizeDirective())
187 O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
189 // Emit post-function debug information.
190 if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
191 DW->EndFunction(&MF);
193 // Print out jump tables referenced by the function.
194 EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
196 // We didn't modify anything.
200 /// printSymbolOperand - Print a raw symbol reference operand. This handles
201 /// jump tables, constant pools, global address and external symbols, all of
202 /// which print to a label with various suffixes for relocation types etc.
203 void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO) {
204 switch (MO.getType()) {
205 default: llvm_unreachable("unknown symbol type!");
206 case MachineOperand::MO_JumpTableIndex:
207 O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
210 case MachineOperand::MO_ConstantPoolIndex:
211 O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
213 printOffset(MO.getOffset());
215 case MachineOperand::MO_GlobalAddress: {
216 const GlobalValue *GV = MO.getGlobal();
218 const char *Suffix = "";
219 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
221 else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
222 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
223 MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
224 Suffix = "$non_lazy_ptr";
226 std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
227 if (Subtarget->isTargetCygMing()) {
228 X86COFFMachineModuleInfo &COFFMMI =
229 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
230 COFFMMI.DecorateCygMingName(Name, GV, *TM.getTargetData());
233 // Handle dllimport linkage.
234 if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
235 Name = "__imp_" + Name;
237 if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
238 MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
239 SmallString<128> NameStr;
240 Mang->getNameWithPrefix(NameStr, GV, true);
241 NameStr += "$non_lazy_ptr";
242 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
244 const MCSymbol *&StubSym =
245 MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
248 Mang->getNameWithPrefix(NameStr, GV, false);
249 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
251 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
252 SmallString<128> NameStr;
253 Mang->getNameWithPrefix(NameStr, GV, true);
254 NameStr += "$non_lazy_ptr";
255 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
256 const MCSymbol *&StubSym =
257 MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
260 Mang->getNameWithPrefix(NameStr, GV, false);
261 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
263 } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
264 SmallString<128> NameStr;
265 Mang->getNameWithPrefix(NameStr, GV, true);
267 MCSymbol *Sym = OutContext.GetOrCreateSymbol(NameStr.str());
268 const MCSymbol *&StubSym =
269 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
272 Mang->getNameWithPrefix(NameStr, GV, false);
273 StubSym = OutContext.GetOrCreateSymbol(NameStr.str());
277 // If the name begins with a dollar-sign, enclose it in parens. We do this
278 // to avoid having it look like an integer immediate to the assembler.
280 O << '(' << Name << ')';
284 printOffset(MO.getOffset());
287 case MachineOperand::MO_ExternalSymbol: {
288 std::string Name = Mang->makeNameProper(MO.getSymbolName());
289 if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
291 MCSymbol *Sym = OutContext.GetOrCreateSymbol(StringRef(Name));
292 const MCSymbol *&StubSym =
293 MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
295 Name.erase(Name.end()-5, Name.end());
296 StubSym = OutContext.GetOrCreateSymbol(StringRef(Name));
300 // If the name begins with a dollar-sign, enclose it in parens. We do this
301 // to avoid having it look like an integer immediate to the assembler.
303 O << '(' << Name << ')';
310 switch (MO.getTargetFlags()) {
312 llvm_unreachable("Unknown target flag on GV operand");
313 case X86II::MO_NO_FLAG: // No flag.
315 case X86II::MO_DARWIN_NONLAZY:
316 case X86II::MO_DLLIMPORT:
317 case X86II::MO_DARWIN_STUB:
318 // These affect the name of the symbol, not any suffix.
320 case X86II::MO_GOT_ABSOLUTE_ADDRESS:
322 PrintPICBaseSymbol();
325 case X86II::MO_PIC_BASE_OFFSET:
326 case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
327 case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
329 PrintPICBaseSymbol();
331 case X86II::MO_TLSGD: O << "@TLSGD"; break;
332 case X86II::MO_GOTTPOFF: O << "@GOTTPOFF"; break;
333 case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
334 case X86II::MO_TPOFF: O << "@TPOFF"; break;
335 case X86II::MO_NTPOFF: O << "@NTPOFF"; break;
336 case X86II::MO_GOTPCREL: O << "@GOTPCREL"; break;
337 case X86II::MO_GOT: O << "@GOT"; break;
338 case X86II::MO_GOTOFF: O << "@GOTOFF"; break;
339 case X86II::MO_PLT: O << "@PLT"; break;
343 /// print_pcrel_imm - This is used to print an immediate value that ends up
344 /// being encoded as a pc-relative value. These print slightly differently, for
345 /// example, a $ is not emitted.
346 void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
347 const MachineOperand &MO = MI->getOperand(OpNo);
348 switch (MO.getType()) {
349 default: llvm_unreachable("Unknown pcrel immediate operand");
350 case MachineOperand::MO_Immediate:
353 case MachineOperand::MO_MachineBasicBlock:
354 GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
356 case MachineOperand::MO_GlobalAddress:
357 case MachineOperand::MO_ExternalSymbol:
358 printSymbolOperand(MO);
364 void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
365 const char *Modifier) {
366 const MachineOperand &MO = MI->getOperand(OpNo);
367 switch (MO.getType()) {
368 default: llvm_unreachable("unknown operand type!");
369 case MachineOperand::MO_Register: {
371 unsigned Reg = MO.getReg();
372 if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
373 EVT VT = (strcmp(Modifier+6,"64") == 0) ?
374 MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
375 ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
376 Reg = getX86SubSuperRegister(Reg, VT);
378 O << X86ATTInstPrinter::getRegisterName(Reg);
382 case MachineOperand::MO_Immediate:
383 O << '$' << MO.getImm();
386 case MachineOperand::MO_JumpTableIndex:
387 case MachineOperand::MO_ConstantPoolIndex:
388 case MachineOperand::MO_GlobalAddress:
389 case MachineOperand::MO_ExternalSymbol: {
391 printSymbolOperand(MO);
397 void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
398 unsigned char value = MI->getOperand(Op).getImm();
399 assert(value <= 7 && "Invalid ssecc argument!");
401 case 0: O << "eq"; break;
402 case 1: O << "lt"; break;
403 case 2: O << "le"; break;
404 case 3: O << "unord"; break;
405 case 4: O << "neq"; break;
406 case 5: O << "nlt"; break;
407 case 6: O << "nle"; break;
408 case 7: O << "ord"; break;
412 void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
413 const char *Modifier) {
414 const MachineOperand &BaseReg = MI->getOperand(Op);
415 const MachineOperand &IndexReg = MI->getOperand(Op+2);
416 const MachineOperand &DispSpec = MI->getOperand(Op+3);
418 // If we really don't want to print out (rip), don't.
419 bool HasBaseReg = BaseReg.getReg() != 0;
420 if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
421 BaseReg.getReg() == X86::RIP)
424 // HasParenPart - True if we will print out the () part of the mem ref.
425 bool HasParenPart = IndexReg.getReg() || HasBaseReg;
427 if (DispSpec.isImm()) {
428 int DispVal = DispSpec.getImm();
429 if (DispVal || !HasParenPart)
432 assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
433 DispSpec.isJTI() || DispSpec.isSymbol());
434 printSymbolOperand(MI->getOperand(Op+3));
438 assert(IndexReg.getReg() != X86::ESP &&
439 "X86 doesn't allow scaling by ESP");
443 printOperand(MI, Op, Modifier);
445 if (IndexReg.getReg()) {
447 printOperand(MI, Op+2, Modifier);
448 unsigned ScaleVal = MI->getOperand(Op+1).getImm();
450 O << ',' << ScaleVal;
456 void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
457 const char *Modifier) {
458 assert(isMem(MI, Op) && "Invalid memory reference!");
459 const MachineOperand &Segment = MI->getOperand(Op+4);
460 if (Segment.getReg()) {
461 printOperand(MI, Op+4, Modifier);
464 printLeaMemReference(MI, Op, Modifier);
467 void X86AsmPrinter::printPICJumpTableSetLabel(unsigned uid,
468 const MachineBasicBlock *MBB) const {
469 if (!MAI->getSetDirective())
472 // We don't need .set machinery if we have GOT-style relocations
473 if (Subtarget->isPICStyleGOT())
476 O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
477 << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
479 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
481 if (Subtarget->isPICStyleRIPRel())
482 O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
483 << '_' << uid << '\n';
486 PrintPICBaseSymbol();
492 void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
493 PrintPICBaseSymbol();
495 PrintPICBaseSymbol();
499 void X86AsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
500 const MachineBasicBlock *MBB,
501 unsigned uid) const {
502 const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
503 MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
505 O << JTEntryDirective << ' ';
507 if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
508 O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
509 << '_' << uid << "_set_" << MBB->getNumber();
510 } else if (Subtarget->isPICStyleGOT()) {
511 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
514 GetMBBSymbol(MBB->getNumber())->print(O, MAI);
517 bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
518 unsigned Reg = MO.getReg();
520 default: return true; // Unknown mode.
521 case 'b': // Print QImode register
522 Reg = getX86SubSuperRegister(Reg, MVT::i8);
524 case 'h': // Print QImode high register
525 Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
527 case 'w': // Print HImode register
528 Reg = getX86SubSuperRegister(Reg, MVT::i16);
530 case 'k': // Print SImode register
531 Reg = getX86SubSuperRegister(Reg, MVT::i32);
533 case 'q': // Print DImode register
534 Reg = getX86SubSuperRegister(Reg, MVT::i64);
538 O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
542 /// PrintAsmOperand - Print out an operand for an inline asm expression.
544 bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
546 const char *ExtraCode) {
547 // Does this asm operand have a single letter operand modifier?
548 if (ExtraCode && ExtraCode[0]) {
549 if (ExtraCode[1] != 0) return true; // Unknown modifier.
551 const MachineOperand &MO = MI->getOperand(OpNo);
553 switch (ExtraCode[0]) {
554 default: return true; // Unknown modifier.
555 case 'a': // This is an address. Currently only 'i' and 'r' are expected.
560 if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
561 printSymbolOperand(MO);
566 printOperand(MI, OpNo);
572 case 'c': // Don't print "$" before a global var name or constant.
575 else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
576 printSymbolOperand(MO);
578 printOperand(MI, OpNo);
581 case 'A': // Print '*' before a register (it must be a register)
584 printOperand(MI, OpNo);
589 case 'b': // Print QImode register
590 case 'h': // Print QImode high register
591 case 'w': // Print HImode register
592 case 'k': // Print SImode register
593 case 'q': // Print DImode register
595 return printAsmMRegister(MO, ExtraCode[0]);
596 printOperand(MI, OpNo);
599 case 'P': // This is the operand of a call, treat specially.
600 print_pcrel_imm(MI, OpNo);
603 case 'n': // Negate the immediate or print a '-' before the operand.
604 // Note: this is a temporary solution. It should be handled target
605 // independently as part of the 'MC' work.
614 printOperand(MI, OpNo);
618 bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
619 unsigned OpNo, unsigned AsmVariant,
620 const char *ExtraCode) {
621 if (ExtraCode && ExtraCode[0]) {
622 if (ExtraCode[1] != 0) return true; // Unknown modifier.
624 switch (ExtraCode[0]) {
625 default: return true; // Unknown modifier.
626 case 'b': // Print QImode register
627 case 'h': // Print QImode high register
628 case 'w': // Print HImode register
629 case 'k': // Print SImode register
630 case 'q': // Print SImode register
631 // These only apply to registers, ignore on mem.
633 case 'P': // Don't print @PLT, but do print as memory.
634 printMemReference(MI, OpNo, "no-rip");
638 printMemReference(MI, OpNo);
644 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
645 /// AT&T syntax to the current output stream.
647 void X86AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
650 processDebugLoc(MI, true);
652 printInstructionThroughMCStreamer(MI);
658 processDebugLoc(MI, false);
661 void X86AsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
662 if (!GVar->hasInitializer())
663 return; // External global require no code
665 // Check to see if this is a special global used by LLVM, if so, emit it.
666 if (EmitSpecialLLVMGlobal(GVar)) {
667 if (Subtarget->isTargetDarwin() &&
668 TM.getRelocationModel() == Reloc::Static) {
669 if (GVar->getName() == "llvm.global_ctors")
670 O << ".reference .constructors_used\n";
671 else if (GVar->getName() == "llvm.global_dtors")
672 O << ".reference .destructors_used\n";
677 const TargetData *TD = TM.getTargetData();
679 std::string name = Mang->getMangledName(GVar);
680 Constant *C = GVar->getInitializer();
681 const Type *Type = C->getType();
682 unsigned Size = TD->getTypeAllocSize(Type);
683 unsigned Align = TD->getPreferredAlignmentLog(GVar);
685 printVisibility(name, GVar->getVisibility());
687 if (Subtarget->isTargetELF())
688 O << "\t.type\t" << name << ",@object\n";
691 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
692 const MCSection *TheSection =
693 getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
694 OutStreamer.SwitchSection(TheSection);
696 // FIXME: get this stuff from section kind flags.
697 if (C->isNullValue() && !GVar->hasSection() &&
698 // Don't put things that should go in the cstring section into "comm".
699 !TheSection->getKind().isMergeableCString()) {
700 if (GVar->hasExternalLinkage()) {
701 if (const char *Directive = MAI->getZeroFillDirective()) {
702 O << "\t.globl " << name << '\n';
703 O << Directive << "__DATA, __common, " << name << ", "
704 << Size << ", " << Align << '\n';
709 if (!GVar->isThreadLocal() &&
710 (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
711 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
713 if (MAI->getLCOMMDirective() != NULL) {
714 if (GVar->hasLocalLinkage()) {
715 O << MAI->getLCOMMDirective() << name << ',' << Size;
716 if (Subtarget->isTargetDarwin())
718 } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
719 O << "\t.globl " << name << '\n'
720 << MAI->getWeakDefDirective() << name << '\n';
721 EmitAlignment(Align, GVar);
724 O.PadToColumn(MAI->getCommentColumn());
725 O << MAI->getCommentString() << ' ';
726 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
729 EmitGlobalConstant(C);
732 O << MAI->getCOMMDirective() << name << ',' << Size;
733 if (MAI->getCOMMDirectiveTakesAlignment())
734 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
737 if (!Subtarget->isTargetCygMing()) {
738 if (GVar->hasLocalLinkage())
739 O << "\t.local\t" << name << '\n';
741 O << MAI->getCOMMDirective() << name << ',' << Size;
742 if (MAI->getCOMMDirectiveTakesAlignment())
743 O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
746 O.PadToColumn(MAI->getCommentColumn());
747 O << MAI->getCommentString() << ' ';
748 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
755 switch (GVar->getLinkage()) {
756 case GlobalValue::CommonLinkage:
757 case GlobalValue::LinkOnceAnyLinkage:
758 case GlobalValue::LinkOnceODRLinkage:
759 case GlobalValue::WeakAnyLinkage:
760 case GlobalValue::WeakODRLinkage:
761 case GlobalValue::LinkerPrivateLinkage:
762 if (Subtarget->isTargetDarwin()) {
763 O << "\t.globl " << name << '\n'
764 << MAI->getWeakDefDirective() << name << '\n';
765 } else if (Subtarget->isTargetCygMing()) {
766 O << "\t.globl\t" << name << "\n"
767 "\t.linkonce same_size\n";
769 O << "\t.weak\t" << name << '\n';
772 case GlobalValue::DLLExportLinkage:
773 case GlobalValue::AppendingLinkage:
774 // FIXME: appending linkage variables should go into a section of
775 // their name or something. For now, just emit them as external.
776 case GlobalValue::ExternalLinkage:
777 // If external or appending, declare as a global symbol
778 O << "\t.globl " << name << '\n';
780 case GlobalValue::PrivateLinkage:
781 case GlobalValue::InternalLinkage:
784 llvm_unreachable("Unknown linkage type!");
787 EmitAlignment(Align, GVar);
790 O.PadToColumn(MAI->getCommentColumn());
791 O << MAI->getCommentString() << ' ';
792 WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
796 EmitGlobalConstant(C);
798 if (MAI->hasDotTypeDotSizeDirective())
799 O << "\t.size\t" << name << ", " << Size << '\n';
802 void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
803 if (Subtarget->isTargetDarwin()) {
804 // All darwin targets use mach-o.
805 TargetLoweringObjectFileMachO &TLOFMacho =
806 static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
808 MachineModuleInfoMachO &MMIMacho =
809 MMI->getObjFileInfo<MachineModuleInfoMachO>();
811 // Output stubs for dynamically-linked functions.
812 MachineModuleInfoMachO::SymbolListTy Stubs;
814 Stubs = MMIMacho.GetFnStubList();
815 if (!Stubs.empty()) {
816 const MCSection *TheSection =
817 TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
818 MCSectionMachO::S_SYMBOL_STUBS |
819 MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
820 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
821 5, SectionKind::getMetadata());
822 OutStreamer.SwitchSection(TheSection);
824 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
825 Stubs[i].first->print(O, MAI);
826 O << ":\n" << "\t.indirect_symbol ";
827 // Get the MCSymbol without the $stub suffix.
828 Stubs[i].second->print(O, MAI);
829 O << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
836 // Output stubs for external and common global variables.
837 Stubs = MMIMacho.GetGVStubList();
838 if (!Stubs.empty()) {
839 const MCSection *TheSection =
840 TLOFMacho.getMachOSection("__IMPORT", "__pointers",
841 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
842 SectionKind::getMetadata());
843 OutStreamer.SwitchSection(TheSection);
845 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
846 Stubs[i].first->print(O, MAI);
847 O << ":\n\t.indirect_symbol ";
848 Stubs[i].second->print(O, MAI);
849 O << "\n\t.long\t0\n";
854 Stubs = MMIMacho.GetHiddenGVStubList();
855 if (!Stubs.empty()) {
856 OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
859 for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
860 Stubs[i].first->print(O, MAI);
861 O << ":\n" << MAI->getData32bitsDirective();
862 Stubs[i].second->print(O, MAI);
868 // Funny Darwin hack: This flag tells the linker that no global symbols
869 // contain code that falls through to other global symbols (e.g. the obvious
870 // implementation of multiple entry points). If this doesn't occur, the
871 // linker can safely perform dead code stripping. Since LLVM never
872 // generates code that does this, it is always safe to set.
873 OutStreamer.EmitAssemblerFlag(MCStreamer::SubsectionsViaSymbols);
876 if (Subtarget->isTargetCOFF()) {
877 X86COFFMachineModuleInfo &COFFMMI =
878 MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
880 // Emit type information for external functions
881 for (X86COFFMachineModuleInfo::stub_iterator I = COFFMMI.stub_begin(),
882 E = COFFMMI.stub_end(); I != E; ++I) {
883 O << "\t.def\t " << I->getKeyData()
884 << ";\t.scl\t" << COFF::C_EXT
885 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
889 if (Subtarget->isTargetCygMing()) {
890 // Necessary for dllexport support
891 std::vector<std::string> DLLExportedFns, DLLExportedGlobals;
893 TargetLoweringObjectFileCOFF &TLOFCOFF =
894 static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
896 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
897 if (I->hasDLLExportLinkage()) {
898 std::string Name = Mang->getMangledName(I);
899 COFFMMI.DecorateCygMingName(Name, I, *TM.getTargetData());
900 DLLExportedFns.push_back(Name);
903 for (Module::const_global_iterator I = M.global_begin(),
904 E = M.global_end(); I != E; ++I)
905 if (I->hasDLLExportLinkage()) {
906 std::string Name = Mang->getMangledName(I);
907 COFFMMI.DecorateCygMingName(Name, I, *TM.getTargetData());
908 DLLExportedGlobals.push_back(Mang->getMangledName(I));
911 // Output linker support code for dllexported globals on windows.
912 if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
913 OutStreamer.SwitchSection(TLOFCOFF.getCOFFSection(".section .drectve",
915 SectionKind::getMetadata()));
916 for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i)
917 O << "\t.ascii \" -export:" << DLLExportedGlobals[i] << ",data\"\n";
919 for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i)
920 O << "\t.ascii \" -export:" << DLLExportedFns[i] << "\"\n";
927 //===----------------------------------------------------------------------===//
928 // Target Registry Stuff
929 //===----------------------------------------------------------------------===//
931 static MCInstPrinter *createX86MCInstPrinter(const Target &T,
932 unsigned SyntaxVariant,
933 const MCAsmInfo &MAI,
935 if (SyntaxVariant == 0)
936 return new X86ATTInstPrinter(O, MAI);
937 if (SyntaxVariant == 1)
938 return new X86IntelInstPrinter(O, MAI);
942 // Force static initialization.
943 extern "C" void LLVMInitializeX86AsmPrinter() {
944 RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
945 RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
947 TargetRegistry::RegisterMCInstPrinter(TheX86_32Target,createX86MCInstPrinter);
948 TargetRegistry::RegisterMCInstPrinter(TheX86_64Target,createX86MCInstPrinter);