1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM IR to X86 assembly -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Type.h"
29 #include "llvm/Assembly/Writer.h"
30 #include "llvm/Support/Mangler.h"
31 #include "llvm/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetOptions.h"
35 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
36 const TargetData *TD) {
37 X86MachineFunctionInfo Info;
40 switch (F->getCallingConv()) {
41 case CallingConv::X86_StdCall:
42 Info.setDecorationStyle(StdCall);
44 case CallingConv::X86_FastCall:
45 Info.setDecorationStyle(FastCall);
51 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
53 // Size should be aligned to DWORD boundary
54 Size += ((TD->getTypeSize(AI->getType()) + 3)/4)*4;
56 // We're not supporting tooooo huge arguments :)
57 Info.setBytesToPopOnReturn((unsigned int)Size);
62 /// decorateName - Query FunctionInfoMap and use this information for various
64 void X86SharedAsmPrinter::decorateName(std::string &Name,
65 const GlobalValue *GV) {
66 const Function *F = dyn_cast<Function>(GV);
69 // We don't want to decorate non-stdcall or non-fastcall functions right now
70 unsigned CC = F->getCallingConv();
71 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
74 // Decorate names only when we're targeting Cygwin/Mingw32 targets
75 if (!Subtarget->isTargetCygMing())
78 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
80 const X86MachineFunctionInfo *Info;
81 if (info_item == FunctionInfoMap.end()) {
82 // Calculate apropriate function info and populate map
83 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
84 Info = &FunctionInfoMap[F];
86 Info = &info_item->second;
89 const FunctionType *FT = F->getFunctionType();
90 switch (Info->getDecorationStyle()) {
94 // "Pure" variadic functions do not receive @0 suffix.
95 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
96 (FT->getNumParams() == 1 && FT->isStructReturn()))
97 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
100 // "Pure" variadic functions do not receive @0 suffix.
101 if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
102 (FT->getNumParams() == 1 && FT->isStructReturn()))
103 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
105 if (Name[0] == '_') {
112 assert(0 && "Unsupported DecorationStyle");
117 bool X86SharedAsmPrinter::doInitialization(Module &M) {
118 if (Subtarget->isTargetELF() ||
119 Subtarget->isTargetCygMing() ||
120 Subtarget->isTargetDarwin()) {
121 // Emit initial debug information.
125 return AsmPrinter::doInitialization(M);
128 bool X86SharedAsmPrinter::doFinalization(Module &M) {
129 // Note: this code is not shared by the Intel printer as it is too different
130 // from how MASM does things. When making changes here don't forget to look
131 // at X86IntelAsmPrinter::doFinalization().
132 const TargetData *TD = TM.getTargetData();
134 // Print out module-level global variables here.
135 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
137 if (!I->hasInitializer())
138 continue; // External global require no code
140 // Check to see if this is a special global used by LLVM, if so, emit it.
141 if (EmitSpecialLLVMGlobal(I)) {
142 if (Subtarget->isTargetDarwin() &&
143 TM.getRelocationModel() == Reloc::Static) {
144 if (I->getName() == "llvm.global_ctors")
145 O << ".reference .constructors_used\n";
146 else if (I->getName() == "llvm.global_dtors")
147 O << ".reference .destructors_used\n";
152 std::string name = Mang->getValueName(I);
153 Constant *C = I->getInitializer();
154 const Type *Type = C->getType();
155 unsigned Size = TD->getTypeSize(Type);
156 unsigned Align = TD->getPreferredAlignmentLog(I);
158 if (I->hasHiddenVisibility())
159 if (const char *Directive = TAI->getHiddenDirective())
160 O << Directive << name << "\n";
161 if (Subtarget->isTargetELF())
162 O << "\t.type " << name << ",@object\n";
164 if (C->isNullValue()) {
165 if (I->hasExternalLinkage()) {
166 if (const char *Directive = TAI->getZeroFillDirective()) {
167 O << "\t.globl\t" << name << "\n";
168 O << Directive << "__DATA__, __common, " << name << ", "
169 << Size << ", " << Align << "\n";
174 if (!I->hasSection() && !I->isThreadLocal() &&
175 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
176 I->hasLinkOnceLinkage())) {
177 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
178 if (!NoZerosInBSS && TAI->getBSSSection())
179 SwitchToDataSection(TAI->getBSSSection(), I);
181 SwitchToDataSection(TAI->getDataSection(), I);
182 if (TAI->getLCOMMDirective() != NULL) {
183 if (I->hasInternalLinkage()) {
184 O << TAI->getLCOMMDirective() << name << "," << Size;
185 if (Subtarget->isTargetDarwin())
188 O << TAI->getCOMMDirective() << name << "," << Size;
190 if (!Subtarget->isTargetCygMing()) {
191 if (I->hasInternalLinkage())
192 O << "\t.local\t" << name << "\n";
194 O << TAI->getCOMMDirective() << name << "," << Size;
195 if (TAI->getCOMMDirectiveTakesAlignment())
196 O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
198 O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
203 switch (I->getLinkage()) {
204 case GlobalValue::LinkOnceLinkage:
205 case GlobalValue::WeakLinkage:
206 if (Subtarget->isTargetDarwin()) {
207 O << "\t.globl " << name << "\n"
208 << "\t.weak_definition " << name << "\n";
209 SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
210 } else if (Subtarget->isTargetCygMing()) {
211 std::string SectionName(".section\t.data$linkonce." +
214 SwitchToDataSection(SectionName.c_str(), I);
215 O << "\t.globl " << name << "\n"
216 << "\t.linkonce same_size\n";
218 std::string SectionName("\t.section\t.llvm.linkonce.d." +
220 ",\"aw\",@progbits");
221 SwitchToDataSection(SectionName.c_str(), I);
222 O << "\t.weak " << name << "\n";
225 case GlobalValue::AppendingLinkage:
226 // FIXME: appending linkage variables should go into a section of
227 // their name or something. For now, just emit them as external.
228 case GlobalValue::DLLExportLinkage:
229 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
231 case GlobalValue::ExternalLinkage:
232 // If external or appending, declare as a global symbol
233 O << "\t.globl " << name << "\n";
235 case GlobalValue::InternalLinkage: {
236 if (I->isConstant()) {
237 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
238 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
239 SwitchToDataSection(TAI->getCStringSection(), I);
243 // FIXME: special handling for ".ctors" & ".dtors" sections
244 if (I->hasSection() &&
245 (I->getSection() == ".ctors" ||
246 I->getSection() == ".dtors")) {
247 std::string SectionName = ".section " + I->getSection();
249 if (Subtarget->isTargetCygMing()) {
250 SectionName += ",\"aw\"";
252 assert(!Subtarget->isTargetDarwin());
253 SectionName += ",\"aw\",@progbits";
256 SwitchToDataSection(SectionName.c_str());
258 if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
259 SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSBSSSection() :
260 TAI->getBSSSection(), I);
261 else if (!I->isConstant())
262 SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSDataSection() :
263 TAI->getDataSection(), I);
264 else if (I->isThreadLocal())
265 SwitchToDataSection(TAI->getTLSDataSection());
268 bool HasReloc = C->ContainsRelocations();
270 Subtarget->isTargetDarwin() &&
271 TM.getRelocationModel() != Reloc::Static)
272 SwitchToDataSection("\t.const_data\n");
273 else if (!HasReloc && Size == 4 &&
274 TAI->getFourByteConstantSection())
275 SwitchToDataSection(TAI->getFourByteConstantSection(), I);
276 else if (!HasReloc && Size == 8 &&
277 TAI->getEightByteConstantSection())
278 SwitchToDataSection(TAI->getEightByteConstantSection(), I);
279 else if (!HasReloc && Size == 16 &&
280 TAI->getSixteenByteConstantSection())
281 SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
282 else if (TAI->getReadOnlySection())
283 SwitchToDataSection(TAI->getReadOnlySection(), I);
285 SwitchToDataSection(TAI->getDataSection(), I);
292 assert(0 && "Unknown linkage type!");
295 EmitAlignment(Align, I);
296 O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
298 if (TAI->hasDotTypeDotSizeDirective())
299 O << "\t.size " << name << ", " << Size << "\n";
300 // If the initializer is a extern weak symbol, remember to emit the weak
302 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
303 if (GV->hasExternalWeakLinkage())
304 ExtWeakSymbols.insert(GV);
306 EmitGlobalConstant(C);
310 // Output linker support code for dllexported globals
311 if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
312 SwitchToDataSection(".section .drectve");
315 for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
316 e = DLLExportedGVs.end();
318 O << "\t.ascii \" -export:" << *i << ",data\"\n";
321 if (DLLExportedFns.begin() != DLLExportedFns.end()) {
322 SwitchToDataSection(".section .drectve");
325 for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
326 e = DLLExportedFns.end();
328 O << "\t.ascii \" -export:" << *i << "\"\n";
331 if (Subtarget->isTargetDarwin()) {
332 SwitchToDataSection("");
334 // Output stubs for dynamically-linked functions
336 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
338 SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
339 "self_modifying_code+pure_instructions,5", 0);
340 O << "L" << *i << "$stub:\n";
341 O << "\t.indirect_symbol " << *i << "\n";
342 O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
347 // Output stubs for external and common global variables.
348 if (GVStubs.begin() != GVStubs.end())
350 ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
351 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
353 O << "L" << *i << "$non_lazy_ptr:\n";
354 O << "\t.indirect_symbol " << *i << "\n";
358 // Emit final debug information.
361 // Funny Darwin hack: This flag tells the linker that no global symbols
362 // contain code that falls through to other global symbols (e.g. the obvious
363 // implementation of multiple entry points). If this doesn't occur, the
364 // linker can safely perform dead code stripping. Since LLVM never
365 // generates code that does this, it is always safe to set.
366 O << "\t.subsections_via_symbols\n";
367 } else if (Subtarget->isTargetCygMing()) {
368 // Emit type information for external functions
369 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
371 O << "\t.def\t " << *i
372 << ";\t.scl\t" << COFF::C_EXT
373 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
377 // Emit final debug information.
379 } else if (Subtarget->isTargetELF()) {
380 // Emit final debug information.
384 AsmPrinter::doFinalization(M);
385 return false; // success
388 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
389 /// for a MachineFunction to the given output stream, using the given target
390 /// machine description.
392 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
393 X86TargetMachine &tm) {
394 const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
396 if (Subtarget->isFlavorIntel()) {
397 return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
399 return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());