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/Type.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/Support/Mangler.h"
30 #include "llvm/Target/TargetAsmInfo.h"
31 #include "llvm/Target/TargetOptions.h"
34 static X86FunctionInfo calculateFunctionInfo(const Function *F,
35 const TargetData *TD) {
39 switch (F->getCallingConv()) {
40 case CallingConv::X86_StdCall:
41 Info.setDecorationStyle(StdCall);
43 case CallingConv::X86_FastCall:
44 Info.setDecorationStyle(FastCall);
50 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
52 Size += TD->getTypeSize(AI->getType());
54 // Size should be aligned to DWORD boundary
55 Size = ((Size + 3)/4)*4;
57 // We're not supporting tooooo huge arguments :)
58 Info.setBytesToPopOnReturn((unsigned int)Size);
63 /// decorateName - Query FunctionInfoMap and use this information for various
65 void X86SharedAsmPrinter::decorateName(std::string &Name,
66 const GlobalValue *GV) {
67 const Function *F = dyn_cast<Function>(GV);
70 // We don't want to decorate non-stdcall or non-fastcall functions right now
71 unsigned CC = F->getCallingConv();
72 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
75 // Decorate names only when we're targeting Cygwin/Mingw32 targets
76 if (!Subtarget->isTargetCygMing())
79 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
81 const X86FunctionInfo *Info;
82 if (info_item == FunctionInfoMap.end()) {
83 // Calculate apropriate function info and populate map
84 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
85 Info = &FunctionInfoMap[F];
87 Info = &info_item->second;
90 switch (Info->getDecorationStyle()) {
94 if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
95 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
98 if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
99 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
101 if (Name[0] == '_') {
108 assert(0 && "Unsupported DecorationStyle");
113 bool X86SharedAsmPrinter::doInitialization(Module &M) {
114 if (Subtarget->isTargetELF() ||
115 Subtarget->isTargetCygMing() ||
116 Subtarget->isTargetDarwin()) {
117 // Emit initial debug information.
121 return AsmPrinter::doInitialization(M);
124 bool X86SharedAsmPrinter::doFinalization(Module &M) {
125 // Note: this code is not shared by the Intel printer as it is too different
126 // from how MASM does things. When making changes here don't forget to look
127 // at X86IntelAsmPrinter::doFinalization().
128 const TargetData *TD = TM.getTargetData();
130 // Print out module-level global variables here.
131 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
133 if (!I->hasInitializer())
134 continue; // External global require no code
136 // Check to see if this is a special global used by LLVM, if so, emit it.
137 if (EmitSpecialLLVMGlobal(I))
140 std::string name = Mang->getValueName(I);
141 Constant *C = I->getInitializer();
142 unsigned Size = TD->getTypeSize(C->getType());
143 unsigned Align = TD->getPreferredAlignmentLog(I);
145 if (I->hasHiddenVisibility())
146 if (const char *Directive = TAI->getHiddenDirective())
147 O << Directive << name << "\n";
148 if (Subtarget->isTargetELF())
149 O << "\t.type " << name << ",@object\n";
151 if (C->isNullValue()) {
152 if (I->hasExternalLinkage()) {
153 if (const char *Directive = TAI->getZeroFillDirective()) {
154 O << "\t.globl\t" << name << "\n";
155 O << Directive << "__DATA__, __common, " << name << ", "
156 << Size << ", " << Align << "\n";
161 if (!I->hasSection() &&
162 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
163 I->hasLinkOnceLinkage())) {
164 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
165 if (!NoZerosInBSS && TAI->getBSSSection())
166 SwitchToDataSection(TAI->getBSSSection(), I);
168 SwitchToDataSection(TAI->getDataSection(), I);
169 if (TAI->getLCOMMDirective() != NULL) {
170 if (I->hasInternalLinkage()) {
171 O << TAI->getLCOMMDirective() << name << "," << Size;
172 if (Subtarget->isTargetDarwin())
175 O << TAI->getCOMMDirective() << name << "," << Size;
177 if (!Subtarget->isTargetCygMing()) {
178 if (I->hasInternalLinkage())
179 O << "\t.local\t" << name << "\n";
181 O << TAI->getCOMMDirective() << name << "," << Size;
182 if (TAI->getCOMMDirectiveTakesAlignment())
183 O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
185 O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
190 switch (I->getLinkage()) {
191 case GlobalValue::LinkOnceLinkage:
192 case GlobalValue::WeakLinkage:
193 if (Subtarget->isTargetDarwin()) {
194 O << "\t.globl " << name << "\n"
195 << "\t.weak_definition " << name << "\n";
196 SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
197 } else if (Subtarget->isTargetCygMing()) {
198 std::string SectionName(".section\t.data$linkonce." +
201 SwitchToDataSection(SectionName.c_str(), I);
202 O << "\t.globl " << name << "\n"
203 << "\t.linkonce same_size\n";
205 std::string SectionName("\t.section\t.llvm.linkonce.d." +
207 ",\"aw\",@progbits");
208 SwitchToDataSection(SectionName.c_str(), I);
209 O << "\t.weak " << name << "\n";
212 case GlobalValue::AppendingLinkage:
213 // FIXME: appending linkage variables should go into a section of
214 // their name or something. For now, just emit them as external.
215 case GlobalValue::DLLExportLinkage:
216 DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
218 case GlobalValue::ExternalLinkage:
219 // If external or appending, declare as a global symbol
220 O << "\t.globl " << name << "\n";
222 case GlobalValue::InternalLinkage: {
223 if (I->isConstant()) {
224 const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
225 if (TAI->getCStringSection() && CVA && CVA->isCString()) {
226 SwitchToDataSection(TAI->getCStringSection(), I);
230 // FIXME: special handling for ".ctors" & ".dtors" sections
231 if (I->hasSection() &&
232 (I->getSection() == ".ctors" ||
233 I->getSection() == ".dtors")) {
234 std::string SectionName = ".section " + I->getSection();
236 if (Subtarget->isTargetCygMing()) {
237 SectionName += ",\"aw\"";
239 assert(!Subtarget->isTargetDarwin());
240 SectionName += ",\"aw\",@progbits";
243 SwitchToDataSection(SectionName.c_str());
245 if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
246 SwitchToDataSection(TAI->getBSSSection(), I);
248 SwitchToDataSection(TAI->getDataSection(), I);
254 assert(0 && "Unknown linkage type!");
257 EmitAlignment(Align, I);
258 O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
260 if (TAI->hasDotTypeDotSizeDirective())
261 O << "\t.size " << name << ", " << Size << "\n";
262 // If the initializer is a extern weak symbol, remember to emit the weak
264 if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
265 if (GV->hasExternalWeakLinkage())
266 ExtWeakSymbols.insert(GV);
268 EmitGlobalConstant(C);
272 // Output linker support code for dllexported globals
273 if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
274 SwitchToDataSection(".section .drectve");
277 for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
278 e = DLLExportedGVs.end();
280 O << "\t.ascii \" -export:" << *i << ",data\"\n";
283 if (DLLExportedFns.begin() != DLLExportedFns.end()) {
284 SwitchToDataSection(".section .drectve");
287 for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
288 e = DLLExportedFns.end();
290 O << "\t.ascii \" -export:" << *i << "\"\n";
293 if (Subtarget->isTargetDarwin()) {
294 SwitchToDataSection("");
296 // Output stubs for dynamically-linked functions
298 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
300 SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
301 "self_modifying_code+pure_instructions,5", 0);
302 O << "L" << *i << "$stub:\n";
303 O << "\t.indirect_symbol " << *i << "\n";
304 O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
309 // Output stubs for external and common global variables.
310 if (GVStubs.begin() != GVStubs.end())
312 ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
313 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
315 O << "L" << *i << "$non_lazy_ptr:\n";
316 O << "\t.indirect_symbol " << *i << "\n";
320 // Emit final debug information.
323 // Funny Darwin hack: This flag tells the linker that no global symbols
324 // contain code that falls through to other global symbols (e.g. the obvious
325 // implementation of multiple entry points). If this doesn't occur, the
326 // linker can safely perform dead code stripping. Since LLVM never
327 // generates code that does this, it is always safe to set.
328 O << "\t.subsections_via_symbols\n";
329 } else if (Subtarget->isTargetCygMing()) {
330 // Emit type information for external functions
331 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
333 O << "\t.def\t " << *i
334 << ";\t.scl\t" << COFF::C_EXT
335 << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
339 // Emit final debug information.
341 } else if (Subtarget->isTargetELF()) {
342 // Emit final debug information.
346 AsmPrinter::doFinalization(M);
347 return false; // success
350 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
351 /// for a MachineFunction to the given output stream, using the given target
352 /// machine description.
354 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
355 X86TargetMachine &tm) {
356 const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
358 if (Subtarget->isFlavorIntel()) {
359 return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
361 return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());