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"
19 #include "X86IntelAsmPrinter.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86Subtarget.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/Assembly/Writer.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/Target/TargetAsmInfo.h"
33 Statistic<> llvm::EmittedInsts("asm-printer",
34 "Number of machine instrs printed");
36 static X86FunctionInfo calculateFunctionInfo(const Function *F,
37 const TargetData *TD) {
41 switch (F->getCallingConv()) {
42 case CallingConv::X86_StdCall:
43 Info.setDecorationStyle(StdCall);
45 case CallingConv::X86_FastCall:
46 Info.setDecorationStyle(FastCall);
52 for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
54 Size += TD->getTypeSize(AI->getType());
56 // Size should be aligned to DWORD boundary
57 Size = ((Size + 3)/4)*4;
59 // We're not supporting tooooo huge arguments :)
60 Info.setBytesToPopOnReturn((unsigned int)Size);
65 /// decorateName - Query FunctionInfoMap and use this information for various
67 void X86SharedAsmPrinter::decorateName(std::string &Name,
68 const GlobalValue *GV) {
69 const Function *F = dyn_cast<Function>(GV);
72 // We don't want to decorate non-stdcall or non-fastcall functions right now
73 unsigned CC = F->getCallingConv();
74 if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
77 FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
79 const X86FunctionInfo *Info;
80 if (info_item == FunctionInfoMap.end()) {
81 // Calculate apropriate function info and populate map
82 FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
83 Info = &FunctionInfoMap[F];
85 Info = &info_item->second;
88 switch (Info->getDecorationStyle()) {
92 if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
93 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
96 if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
97 Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
106 assert(0 && "Unsupported DecorationStyle");
111 bool X86SharedAsmPrinter::doInitialization(Module &M) {
112 if (Subtarget->isTargetDarwin()) {
113 if (!Subtarget->is64Bit())
114 X86PICStyle = PICStyle::Stub;
116 // Emit initial debug information.
118 } else if (Subtarget->isTargetELF() || Subtarget->isTargetCygwin()) {
119 // Emit initial debug information.
123 return AsmPrinter::doInitialization(M);
126 bool X86SharedAsmPrinter::doFinalization(Module &M) {
127 // Note: this code is not shared by the Intel printer as it is too different
128 // from how MASM does things. When making changes here don't forget to look
129 // at X86IntelAsmPrinter::doFinalization().
130 const TargetData *TD = TM.getTargetData();
132 // Print out module-level global variables here.
133 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
135 if (!I->hasInitializer() && !I->hasExternalWeakLinkage())
136 continue; // External global require no code
138 // Check to see if this is a special global used by LLVM, if so, emit it.
139 if (EmitSpecialLLVMGlobal(I))
142 std::string name = Mang->getValueName(I);
143 Constant *C = I->getInitializer();
144 unsigned Size = TD->getTypeSize(C->getType());
145 unsigned Align = TD->getPreferredAlignmentLog(I);
147 if (C->isNullValue() && /* FIXME: Verify correct */
149 (I->hasInternalLinkage() || I->hasWeakLinkage() ||
150 I->hasLinkOnceLinkage() ||
151 (Subtarget->isTargetDarwin() &&
152 I->hasExternalLinkage()))) {
153 if (Size == 0) Size = 1; // .comm Foo, 0 is undefined, avoid it.
154 if (I->hasExternalLinkage()) {
155 O << "\t.globl\t" << name << "\n";
156 O << "\t.zerofill __DATA__, __common, " << name << ", "
157 << Size << ", " << Align;
159 SwitchToDataSection(TAI->getDataSection(), I);
160 if (TAI->getLCOMMDirective() != NULL) {
161 if (I->hasInternalLinkage()) {
162 O << TAI->getLCOMMDirective() << name << "," << Size;
163 if (Subtarget->isTargetDarwin())
164 O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
166 O << TAI->getCOMMDirective() << name << "," << Size;
168 if (!Subtarget->isTargetCygwin()) {
169 if (I->hasInternalLinkage())
170 O << "\t.local\t" << name << "\n";
172 O << TAI->getCOMMDirective() << name << "," << Size;
173 if (TAI->getCOMMDirectiveTakesAlignment())
174 O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
177 O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
179 switch (I->getLinkage()) {
180 case GlobalValue::ExternalWeakLinkage:
181 if (Subtarget->isTargetDarwin()) {
182 assert(0 && "External weak linkage for Darwin not implemented yet");
183 } else if (Subtarget->isTargetCygwin()) {
184 // There is no external weak linkage on Mingw32 platform.
185 // Defaulting just to external
186 O << "\t.globl " << name << "\n";
188 O << "\t.weak " << name << "\n";
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->isTargetCygwin()) {
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->isTargetCygwin()) {
237 SectionName += ",\"aw\"";
239 assert(!Subtarget->isTargetDarwin());
240 SectionName += ",\"aw\",@progbits";
243 SwitchToDataSection(SectionName.c_str());
245 SwitchToDataSection(TAI->getDataSection(), I);
251 assert(0 && "Unknown linkage type!");
254 EmitAlignment(Align, I);
255 O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
257 if (TAI->hasDotTypeDotSizeDirective())
258 O << "\t.size " << name << ", " << Size << "\n";
260 EmitGlobalConstant(C);
265 // Output linker support code for dllexported globals
266 if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
267 SwitchToDataSection(".section .drectve");
270 for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
271 e = DLLExportedGVs.end();
273 O << "\t.ascii \" -export:" << *i << ",data\"\n";
276 if (DLLExportedFns.begin() != DLLExportedFns.end()) {
277 SwitchToDataSection(".section .drectve");
280 for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
281 e = DLLExportedFns.end();
283 O << "\t.ascii \" -export:" << *i << "\"\n";
286 if (Subtarget->isTargetCygwin()) {
287 // There is no external weak linkage on Mingw32 platform.
288 // Defaulting to external
290 if (ExtWeakSymbols.begin() != ExtWeakSymbols.end())
291 SwitchToDataSection("");
293 for (std::set<std::string>::iterator i = ExtWeakSymbols.begin(),
294 e = ExtWeakSymbols.end(); i != e; ++i) {
295 O << (Subtarget->isTargetDarwin() ? "\t.weak_reference" : "\t.weak")
296 << " " << *i << "\n";
300 if (Subtarget->isTargetDarwin()) {
301 SwitchToDataSection("");
303 // Output stubs for dynamically-linked functions
305 for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
307 SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
308 "self_modifying_code+pure_instructions,5", 0);
309 O << "L" << *i << "$stub:\n";
310 O << "\t.indirect_symbol " << *i << "\n";
311 O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
316 // Output stubs for external and common global variables.
317 if (GVStubs.begin() != GVStubs.end())
319 ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
320 for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
322 O << "L" << *i << "$non_lazy_ptr:\n";
323 O << "\t.indirect_symbol " << *i << "\n";
327 // Emit final debug information.
330 // Funny Darwin hack: This flag tells the linker that no global symbols
331 // contain code that falls through to other global symbols (e.g. the obvious
332 // implementation of multiple entry points). If this doesn't occur, the
333 // linker can safely perform dead code stripping. Since LLVM never
334 // generates code that does this, it is always safe to set.
335 O << "\t.subsections_via_symbols\n";
336 } else if (Subtarget->isTargetELF() || Subtarget->isTargetCygwin()) {
337 // Emit final debug information.
341 AsmPrinter::doFinalization(M);
342 return false; // success
345 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
346 /// for a MachineFunction to the given output stream, using the given target
347 /// machine description.
349 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
350 X86TargetMachine &tm) {
351 const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
353 if (Subtarget->isFlavorIntel()) {
354 return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
356 return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());