Nuke dead code.
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
1 //===-- X86AsmPrinter.cpp - Convert X86 LLVM IR to X86 assembly -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
12 // assembly language.
13 // This printer is the output mechanism used by `llc'.
14 //
15 //===----------------------------------------------------------------------===//
16
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"
30
31 using namespace llvm;
32
33 Statistic<> llvm::EmittedInsts("asm-printer",
34                                "Number of machine instrs printed");
35
36 static X86FunctionInfo calculateFunctionInfo(const Function *F,
37                                              const TargetData *TD) {
38   X86FunctionInfo Info;
39   uint64_t Size = 0;
40   
41   switch (F->getCallingConv()) {
42   case CallingConv::X86_StdCall:
43     Info.setDecorationStyle(StdCall);
44     break;
45   case CallingConv::X86_FastCall:
46     Info.setDecorationStyle(FastCall);
47     break;
48   default:
49     return Info;
50   }
51
52   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
53        AI != AE; ++AI)
54     Size += TD->getTypeSize(AI->getType());
55
56   // Size should be aligned to DWORD boundary
57   Size = ((Size + 3)/4)*4;
58   
59   // We're not supporting tooooo huge arguments :)
60   Info.setBytesToPopOnReturn((unsigned int)Size);
61   return Info;
62 }
63
64
65 /// decorateName - Query FunctionInfoMap and use this information for various
66 /// name decoration.
67 void X86SharedAsmPrinter::decorateName(std::string &Name,
68                                        const GlobalValue *GV) {
69   const Function *F = dyn_cast<Function>(GV);
70   if (!F) return;
71
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)
75     return;
76     
77   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
78
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];
84   } else {
85     Info = &info_item->second;
86   }
87         
88   switch (Info->getDecorationStyle()) {
89   case None:
90     break;
91   case StdCall:
92     if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
93       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
94     break;
95   case FastCall:
96     if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
97       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
98
99     if (Name[0] == '_') {
100       Name[0] = '@';
101     } else {
102       Name = '@' + Name;
103     }    
104     break;
105   default:
106     assert(0 && "Unsupported DecorationStyle");
107   }
108 }
109
110 /// doInitialization
111 bool X86SharedAsmPrinter::doInitialization(Module &M) {
112   if (Subtarget->isTargetDarwin()) {
113     if (!Subtarget->is64Bit())
114       X86PICStyle = PICStyle::Stub;
115
116     // Emit initial debug information.
117     DW.BeginModule(&M);
118   } else if (Subtarget->isTargetELF() || Subtarget->isTargetCygwin()) {
119     // Emit initial debug information.
120     DW.BeginModule(&M);
121   }
122
123   return AsmPrinter::doInitialization(M);
124 }
125
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();
131
132   // Print out module-level global variables here.
133   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
134        I != E; ++I) {
135     if (!I->hasInitializer()) continue;   // External global require no code
136     
137     // Check to see if this is a special global used by LLVM, if so, emit it.
138     if (EmitSpecialLLVMGlobal(I))
139       continue;
140     
141     std::string name = Mang->getValueName(I);
142     Constant *C = I->getInitializer();
143     unsigned Size = TD->getTypeSize(C->getType());
144     unsigned Align = TD->getPreferredAlignmentLog(I);
145
146     if (C->isNullValue() && /* FIXME: Verify correct */
147         !I->hasSection() &&
148         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
149          I->hasLinkOnceLinkage() ||
150          (Subtarget->isTargetDarwin() && 
151           I->hasExternalLinkage()))) {
152       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
153       if (I->hasExternalLinkage()) {
154           O << "\t.globl\t" << name << "\n";
155           O << "\t.zerofill __DATA__, __common, " << name << ", "
156             << Size << ", " << Align;
157       } else {
158         SwitchToDataSection(TAI->getDataSection(), I);
159         if (TAI->getLCOMMDirective() != NULL) {
160           if (I->hasInternalLinkage()) {
161             O << TAI->getLCOMMDirective() << name << "," << Size;
162             if (Subtarget->isTargetDarwin())
163               O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
164           } else
165             O << TAI->getCOMMDirective()  << name << "," << Size;
166         } else {
167           if (!Subtarget->isTargetCygwin()) {
168             if (I->hasInternalLinkage())
169               O << "\t.local\t" << name << "\n";
170           }
171           O << TAI->getCOMMDirective()  << name << "," << Size;
172           if (TAI->getCOMMDirectiveTakesAlignment())
173             O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
174         }
175       }
176       O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
177     } else {
178       switch (I->getLinkage()) {
179       case GlobalValue::LinkOnceLinkage:
180       case GlobalValue::WeakLinkage:
181         if (Subtarget->isTargetDarwin()) {
182           O << "\t.globl " << name << "\n"
183             << "\t.weak_definition " << name << "\n";
184           SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
185         } else if (Subtarget->isTargetCygwin()) {
186           std::string SectionName(".section\t.data$linkonce." +
187                                   name +
188                                   ",\"aw\"");
189           SwitchToDataSection(SectionName.c_str(), I);
190           O << "\t.globl " << name << "\n"
191             << "\t.linkonce same_size\n";
192         } else {
193           std::string SectionName("\t.section\t.llvm.linkonce.d." +
194                                   name +
195                                   ",\"aw\",@progbits");
196           SwitchToDataSection(SectionName.c_str(), I);
197           O << "\t.weak " << name << "\n";
198         }
199         break;
200       case GlobalValue::AppendingLinkage:
201         // FIXME: appending linkage variables should go into a section of
202         // their name or something.  For now, just emit them as external.
203       case GlobalValue::DLLExportLinkage:
204         DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
205         // FALL THROUGH
206       case GlobalValue::ExternalLinkage:
207         // If external or appending, declare as a global symbol
208         O << "\t.globl " << name << "\n";
209         // FALL THROUGH
210       case GlobalValue::InternalLinkage: {
211         if (I->isConstant()) {
212           const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
213           if (TAI->getCStringSection() && CVA && CVA->isCString()) {
214             SwitchToDataSection(TAI->getCStringSection(), I);
215             break;
216           }
217         }
218         // FIXME: special handling for ".ctors" & ".dtors" sections
219         if (I->hasSection() &&
220             (I->getSection() == ".ctors" ||
221              I->getSection() == ".dtors")) {
222           std::string SectionName = ".section " + I->getSection();
223           
224           if (Subtarget->isTargetCygwin()) {
225             SectionName += ",\"aw\"";
226           } else {
227             assert(!Subtarget->isTargetDarwin());
228             SectionName += ",\"aw\",@progbits";
229           }
230
231           SwitchToDataSection(SectionName.c_str());
232         } else {
233           SwitchToDataSection(TAI->getDataSection(), I);
234         }
235         
236         break;
237       }
238       default:
239         assert(0 && "Unknown linkage type!");
240       }
241
242       EmitAlignment(Align, I);
243       O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
244         << "\n";
245       if (TAI->hasDotTypeDotSizeDirective())
246         O << "\t.size " << name << ", " << Size << "\n";
247
248       EmitGlobalConstant(C);
249       O << '\n';
250     }
251   }
252   
253   // Output linker support code for dllexported globals
254   if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
255     SwitchToDataSection(".section .drectve");
256   }
257
258   for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
259          e = DLLExportedGVs.end();
260          i != e; ++i) {
261     O << "\t.ascii \" -export:" << *i << ",data\"\n";
262   }    
263
264   if (DLLExportedFns.begin() != DLLExportedFns.end()) {
265     SwitchToDataSection(".section .drectve");
266   }
267
268   for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
269          e = DLLExportedFns.end();
270          i != e; ++i) {
271     O << "\t.ascii \" -export:" << *i << "\"\n";
272   }    
273  
274   if (Subtarget->isTargetDarwin()) {
275     SwitchToDataSection("");
276
277     // Output stubs for dynamically-linked functions
278     unsigned j = 1;
279     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
280          i != e; ++i, ++j) {
281       SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
282                           "self_modifying_code+pure_instructions,5", 0);
283       O << "L" << *i << "$stub:\n";
284       O << "\t.indirect_symbol " << *i << "\n";
285       O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
286     }
287
288     O << "\n";
289
290     // Output stubs for external and common global variables.
291     if (GVStubs.begin() != GVStubs.end())
292       SwitchToDataSection(
293                     ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
294     for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
295          i != e; ++i) {
296       O << "L" << *i << "$non_lazy_ptr:\n";
297       O << "\t.indirect_symbol " << *i << "\n";
298       O << "\t.long\t0\n";
299     }
300
301     // Emit final debug information.
302     DW.EndModule();
303
304     // Funny Darwin hack: This flag tells the linker that no global symbols
305     // contain code that falls through to other global symbols (e.g. the obvious
306     // implementation of multiple entry points).  If this doesn't occur, the
307     // linker can safely perform dead code stripping.  Since LLVM never
308     // generates code that does this, it is always safe to set.
309     O << "\t.subsections_via_symbols\n";
310   } else if (Subtarget->isTargetELF() || Subtarget->isTargetCygwin()) {
311     // Emit final debug information.
312     DW.EndModule();
313   }
314
315   AsmPrinter::doFinalization(M);
316   return false; // success
317 }
318
319 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
320 /// for a MachineFunction to the given output stream, using the given target
321 /// machine description.
322 ///
323 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
324                                              X86TargetMachine &tm) {
325   const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
326
327   if (Subtarget->isFlavorIntel()) {
328     return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
329   } else {
330     return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());
331   }
332 }