1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM IR to X86 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 the shared super class printer that converts from our internal
11 // representation of machine-dependent LLVM code to Intel and AT&T format
13 // This printer is the output mechanism used by `llc'.
15 //===----------------------------------------------------------------------===//
17 #include "X86AsmPrinter.h"
18 #include "X86ATTAsmPrinter.h"
20 #include "X86IntelAsmPrinter.h"
21 #include "X86MachineFunctionInfo.h"
22 #include "X86Subtarget.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Module.h"
27 #include "llvm/DerivedTypes.h"
28 #include "llvm/ParameterAttributes.h"
29 #include "llvm/Type.h"
30 #include "llvm/Assembly/Writer.h"
31 #include "llvm/Support/Mangler.h"
32 #include "llvm/Target/TargetAsmInfo.h"
33 #include "llvm/Target/TargetOptions.h"
36 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
37 const TargetData *TD) {
38 X86MachineFunctionInfo Info;
41 switch (F->getCallingConv()) {
42 case CallingConv::X86_StdCall:
43 Info.setDecorationStyle(StdCall);
45 case CallingConv::X86_FastCall:
46 Info.setDecorationStyle(FastCall);
53 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
54 AI != AE; ++AI, ++argNum) {
55 const Type* Ty = AI->getType();
57 // 'Dereference' type in case of byval parameter attribute
58 if (F->paramHasAttr(argNum, ParamAttr::ByVal))
59 Ty = cast<PointerType>(Ty)->getElementType();
61 // Size should be aligned to DWORD boundary
62 Size += ((TD->getABITypeSize(Ty) + 3)/4)*4;
65 // We're not supporting tooooo huge arguments :)
66 Info.setBytesToPopOnReturn((unsigned int)Size);
71 /// decorateName - Query FunctionInfoMap and use this information for various
73 void X86SharedAsmPrinter::decorateName(std::string &Name,
74 const GlobalValue *GV) {
75 const Function *F = dyn_cast<Function>(GV);
78 // We don't want to decorate non-stdcall or non-fastcall functions right now
79 unsigned CC = F->getCallingConv();
80 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
83 // Decorate names only when we're targeting Cygwin/Mingw32 targets
84 if (!Subtarget->isTargetCygMing())
87 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
89 const X86MachineFunctionInfo *Info;
90 if (info_item == FunctionInfoMap.end()) {
91 // Calculate apropriate function info and populate map
92 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
93 Info = &FunctionInfoMap[F];
95 Info = &info_item->second;
98 const FunctionType *FT = F->getFunctionType();
99 switch (Info->getDecorationStyle()) {
103 // "Pure" variadic functions do not receive @0 suffix.
104 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
105 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
106 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
109 // "Pure" variadic functions do not receive @0 suffix.
110 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
111 (FT->getNumParams() == 1 && F->hasStructRetAttr()))
112 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
114 if (Name[0] == '_') {
121 assert(0 && "Unsupported DecorationStyle");
126 bool X86SharedAsmPrinter::doInitialization(Module &M) {
127 if (TAI->doesSupportDebugInformation()) {
128 // Emit initial debug information.
132 bool Result = AsmPrinter::doInitialization(M);
134 // Darwin wants symbols to be quoted if they have complex names.
135 if (Subtarget->isTargetDarwin())
136 Mang->setUseQuotes(true);
141 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
142 /// Don't print things like \n or \0.
143 static void PrintUnmangledNameSafely(const Value *V, std::ostream &OS) {
144 for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
150 bool X86SharedAsmPrinter::doFinalization(Module &M) {
151 // Note: this code is not shared by the Intel printer as it is too different
152 // from how MASM does things. When making changes here don't forget to look
153 // at X86IntelAsmPrinter::doFinalization().
154 const TargetData *TD = TM.getTargetData();
156 // Print out module-level global variables here.
157 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
159 if (!I->hasInitializer())
160 continue; // External global require no code
162 // Check to see if this is a special global used by LLVM, if so, emit it.
163 if (EmitSpecialLLVMGlobal(I)) {
164 if (Subtarget->isTargetDarwin() &&
165 TM.getRelocationModel() == Reloc::Static) {
166 if (I->getName() == "llvm.global_ctors")
167 O << ".reference .constructors_used\n";
168 else if (I->getName() == "llvm.global_dtors")
169 O << ".reference .destructors_used\n";
174 std::string name = Mang->getValueName(I);
175 Constant *C = I->getInitializer();
176 const Type *Type = C->getType();
177 unsigned Size = TD->getABITypeSize(Type);
178 unsigned Align = TD->getPreferredAlignmentLog(I);
180 if (I->hasHiddenVisibility()) {
181 if (const char *Directive = TAI->getHiddenDirective())
182 O << Directive << name << "\n";
183 } else if (I->hasProtectedVisibility()) {
184 if (const char *Directive = TAI->getProtectedDirective())
185 O << Directive << name << "\n";
188 if (Subtarget->isTargetELF())
189 O << "\t.type\t" << name << ",@object\n";
191 if (C->isNullValue() && !I->hasSection()) {
192 if (I->hasExternalLinkage()) {
193 if (const char *Directive = TAI->getZeroFillDirective()) {
194 O << "\t.globl " << name << "\n";
195 O << Directive << "__DATA, __common, " << name << ", "
196 << Size << ", " << Align << "\n";
201 if (!I->isThreadLocal() &&
202 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
203 I->hasLinkOnceLinkage() || I->hasCommonLinkage())) {
204 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
205 if (!NoZerosInBSS && TAI->getBSSSection())
206 SwitchToDataSection(TAI->getBSSSection(), I);
208 SwitchToDataSection(TAI->getDataSection(), I);
209 if (TAI->getLCOMMDirective() != NULL) {
210 if (I->hasInternalLinkage()) {
211 O << TAI->getLCOMMDirective() << name << "," << Size;
212 if (Subtarget->isTargetDarwin())
214 } else if (Subtarget->isTargetDarwin() && !I->hasCommonLinkage()) {
215 O << "\t.globl " << name << "\n"
216 << TAI->getWeakDefDirective() << name << "\n";
217 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I);
218 EmitAlignment(Align, I);
219 O << name << ":\t\t\t\t" << TAI->getCommentString() << " ";
220 PrintUnmangledNameSafely(I, O);
222 EmitGlobalConstant(C);
225 O << TAI->getCOMMDirective() << name << "," << Size;
227 // Leopard and above support aligned common symbols.
228 if (Subtarget->getDarwinVers() >= 9)
232 if (!Subtarget->isTargetCygMing()) {
233 if (I->hasInternalLinkage())
234 O << "\t.local\t" << name << "\n";
236 O << TAI->getCOMMDirective() << name << "," << Size;
237 if (TAI->getCOMMDirectiveTakesAlignment())
238 O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
240 O << "\t\t" << TAI->getCommentString() << " ";
241 PrintUnmangledNameSafely(I, O);
247 switch (I->getLinkage()) {
248 case GlobalValue::CommonLinkage:
249 case GlobalValue::LinkOnceLinkage:
250 case GlobalValue::WeakLinkage:
251 if (Subtarget->isTargetDarwin()) {
252 O << "\t.globl " << name << "\n"
253 << TAI->getWeakDefDirective() << name << "\n";
254 SwitchToDataSection("\t.section __DATA,__datacoal_nt,coalesced", I);
255 } else if (Subtarget->isTargetCygMing()) {
256 std::string SectionName(".section\t.data$linkonce." +
259 SwitchToDataSection(SectionName.c_str(), I);
260 O << "\t.globl\t" << name << "\n"
261 << "\t.linkonce same_size\n";
263 std::string SectionName("\t.section\t.llvm.linkonce.d." +
265 ",\"aw\",@progbits");
266 SwitchToDataSection(SectionName.c_str(), I);
267 O << "\t.weak\t" << name << "\n";
270 case GlobalValue::DLLExportLinkage:
271 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
273 case GlobalValue::AppendingLinkage:
274 // FIXME: appending linkage variables should go into a section of
275 // their name or something. For now, just emit them as external.
276 case GlobalValue::ExternalLinkage:
277 // If external or appending, declare as a global symbol
278 O << "\t.globl " << name << "\n";
280 case GlobalValue::InternalLinkage: {
281 if (I->isConstant()) {
282 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
283 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
284 SwitchToDataSection(TAI->getCStringSection(), I);
288 // FIXME: special handling for ".ctors" & ".dtors" sections
289 if (I->hasSection() &&
290 (I->getSection() == ".ctors" ||
291 I->getSection() == ".dtors")) {
292 std::string SectionName = ".section " + I->getSection();
294 if (Subtarget->isTargetCygMing()) {
295 SectionName += ",\"aw\"";
297 assert(!Subtarget->isTargetDarwin());
298 SectionName += ",\"aw\",@progbits";
300 SwitchToDataSection(SectionName.c_str());
301 } else if (I->hasSection() && Subtarget->isTargetDarwin()) {
302 // Honor all section names on Darwin; ObjC uses this
303 std::string SectionName = ".section " + I->getSection();
304 SwitchToDataSection(SectionName.c_str());
306 if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
307 SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSBSSSection() :
308 TAI->getBSSSection(), I);
309 else if (!I->isConstant())
310 SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSDataSection() :
311 TAI->getDataSection(), I);
312 else if (I->isThreadLocal())
313 SwitchToDataSection(TAI->getTLSDataSection());
316 bool HasReloc = C->ContainsRelocations();
318 Subtarget->isTargetDarwin() &&
319 TM.getRelocationModel() != Reloc::Static)
320 SwitchToDataSection("\t.const_data\n");
321 else if (!HasReloc && Size == 4 &&
322 TAI->getFourByteConstantSection())
323 SwitchToDataSection(TAI->getFourByteConstantSection(), I);
324 else if (!HasReloc && Size == 8 &&
325 TAI->getEightByteConstantSection())
326 SwitchToDataSection(TAI->getEightByteConstantSection(), I);
327 else if (!HasReloc && Size == 16 &&
328 TAI->getSixteenByteConstantSection())
329 SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
330 else if (TAI->getReadOnlySection())
331 SwitchToDataSection(TAI->getReadOnlySection(), I);
333 SwitchToDataSection(TAI->getDataSection(), I);
340 assert(0 && "Unknown linkage type!");
343 EmitAlignment(Align, I);
344 O << name << ":\t\t\t\t" << TAI->getCommentString() << " ";
345 PrintUnmangledNameSafely(I, O);
347 if (TAI->hasDotTypeDotSizeDirective())
348 O << "\t.size\t" << name << ", " << Size << "\n";
349 // If the initializer is a extern weak symbol, remember to emit the weak
351 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
352 if (GV->hasExternalWeakLinkage())
353 ExtWeakSymbols.insert(GV);
355 EmitGlobalConstant(C);
358 // Output linker support code for dllexported globals
359 if (!DLLExportedGVs.empty()) {
360 SwitchToDataSection(".section .drectve");
363 for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
364 e = DLLExportedGVs.end();
366 O << "\t.ascii \" -export:" << *i << ",data\"\n";
369 if (!DLLExportedFns.empty()) {
370 SwitchToDataSection(".section .drectve");
373 for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
374 e = DLLExportedFns.end();
376 O << "\t.ascii \" -export:" << *i << "\"\n";
379 if (Subtarget->isTargetDarwin()) {
380 SwitchToDataSection("");
382 // Output stubs for dynamically-linked functions
384 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
386 SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
387 "self_modifying_code+pure_instructions,5", 0);
389 printSuffixedName(p, "$stub");
391 O << "\t.indirect_symbol " << p << "\n";
392 O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
397 if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
398 // Add the (possibly multiple) personalities to the set of global values.
399 // Only referenced functions get into the Personalities list.
400 const std::vector<Function *>& Personalities = MMI->getPersonalities();
402 for (std::vector<Function *>::const_iterator I = Personalities.begin(),
403 E = Personalities.end(); I != E; ++I)
404 if (*I) GVStubs.insert("_" + (*I)->getName());
407 // Output stubs for external and common global variables.
408 if (!GVStubs.empty())
410 "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
411 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
414 printSuffixedName(p, "$non_lazy_ptr");
416 O << "\t.indirect_symbol " << p << "\n";
420 // Emit final debug information.
423 // Funny Darwin hack: This flag tells the linker that no global symbols
424 // contain code that falls through to other global symbols (e.g. the obvious
425 // implementation of multiple entry points). If this doesn't occur, the
426 // linker can safely perform dead code stripping. Since LLVM never
427 // generates code that does this, it is always safe to set.
428 O << "\t.subsections_via_symbols\n";
429 } else if (Subtarget->isTargetCygMing()) {
430 // Emit type information for external functions
431 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
433 O << "\t.def\t " << *i
434 << ";\t.scl\t" << COFF::C_EXT
435 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
439 // Emit final debug information.
441 } else if (Subtarget->isTargetELF()) {
442 // Emit final debug information.
446 return AsmPrinter::doFinalization(M);
449 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
450 /// for a MachineFunction to the given output stream, using the given target
451 /// machine description.
453 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
454 X86TargetMachine &tm) {
455 const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
457 if (Subtarget->isFlavorIntel()) {
458 return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
460 return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());