Remove attribution from file headers, per discussion on llvmdev.
[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 is distributed under the University of Illinois Open Source
6 // 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 "X86COFF.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"
33 using namespace llvm;
34
35 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
36                                                     const TargetData *TD) {
37   X86MachineFunctionInfo Info;
38   uint64_t Size = 0;
39   
40   switch (F->getCallingConv()) {
41   case CallingConv::X86_StdCall:
42     Info.setDecorationStyle(StdCall);
43     break;
44   case CallingConv::X86_FastCall:
45     Info.setDecorationStyle(FastCall);
46     break;
47   default:
48     return Info;
49   }
50
51   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
52        AI != AE; ++AI)
53     // Size should be aligned to DWORD boundary
54     Size += ((TD->getABITypeSize(AI->getType()) + 3)/4)*4;
55   
56   // We're not supporting tooooo huge arguments :)
57   Info.setBytesToPopOnReturn((unsigned int)Size);
58   return Info;
59 }
60
61
62 /// decorateName - Query FunctionInfoMap and use this information for various
63 /// name decoration.
64 void X86SharedAsmPrinter::decorateName(std::string &Name,
65                                        const GlobalValue *GV) {
66   const Function *F = dyn_cast<Function>(GV);
67   if (!F) return;
68
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)
72     return;
73
74   // Decorate names only when we're targeting Cygwin/Mingw32 targets
75   if (!Subtarget->isTargetCygMing())
76     return;
77     
78   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
79
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];
85   } else {
86     Info = &info_item->second;
87   }
88   
89   const FunctionType *FT = F->getFunctionType();
90   switch (Info->getDecorationStyle()) {
91   case None:
92     break;
93   case StdCall:
94     // "Pure" variadic functions do not receive @0 suffix.
95     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
96         (FT->getNumParams() == 1 && F->isStructReturn()))
97       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
98     break;
99   case FastCall:
100     // "Pure" variadic functions do not receive @0 suffix.
101     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
102         (FT->getNumParams() == 1 && F->isStructReturn()))
103       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
104
105     if (Name[0] == '_') {
106       Name[0] = '@';
107     } else {
108       Name = '@' + Name;
109     }    
110     break;
111   default:
112     assert(0 && "Unsupported DecorationStyle");
113   }
114 }
115
116 /// doInitialization
117 bool X86SharedAsmPrinter::doInitialization(Module &M) {
118   if (TAI->doesSupportDebugInformation()) {
119     // Emit initial debug information.
120     DW.BeginModule(&M);
121   }
122
123   bool Result = AsmPrinter::doInitialization(M);
124
125   // Darwin wants symbols to be quoted if they have complex names.
126   if (Subtarget->isTargetDarwin())
127     Mang->setUseQuotes(true);
128
129   return Result;
130 }
131
132 bool X86SharedAsmPrinter::doFinalization(Module &M) {
133   // Note: this code is not shared by the Intel printer as it is too different
134   // from how MASM does things.  When making changes here don't forget to look
135   // at X86IntelAsmPrinter::doFinalization().
136   const TargetData *TD = TM.getTargetData();
137   
138   // Print out module-level global variables here.
139   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
140        I != E; ++I) {
141     if (!I->hasInitializer())
142       continue;   // External global require no code
143     
144     // Check to see if this is a special global used by LLVM, if so, emit it.
145     if (EmitSpecialLLVMGlobal(I)) {
146       if (Subtarget->isTargetDarwin() &&
147           TM.getRelocationModel() == Reloc::Static) {
148         if (I->getName() == "llvm.global_ctors")
149           O << ".reference .constructors_used\n";
150         else if (I->getName() == "llvm.global_dtors")
151           O << ".reference .destructors_used\n";
152       }
153       continue;
154     }
155     
156     std::string name = Mang->getValueName(I);
157     Constant *C = I->getInitializer();
158     const Type *Type = C->getType();
159     unsigned Size = TD->getABITypeSize(Type);
160     unsigned Align = TD->getPreferredAlignmentLog(I);
161
162     if (I->hasHiddenVisibility()) {
163       if (const char *Directive = TAI->getHiddenDirective())
164         O << Directive << name << "\n";
165     } else if (I->hasProtectedVisibility()) {
166       if (const char *Directive = TAI->getProtectedDirective())
167         O << Directive << name << "\n";
168     }
169     
170     if (Subtarget->isTargetELF())
171       O << "\t.type\t" << name << ",@object\n";
172     
173     if (C->isNullValue() && !I->hasSection()) {
174       if (I->hasExternalLinkage()) {
175         if (const char *Directive = TAI->getZeroFillDirective()) {
176           O << "\t.globl\t" << name << "\n";
177           O << Directive << "__DATA__, __common, " << name << ", "
178             << Size << ", " << Align << "\n";
179           continue;
180         }
181       }
182       
183       if (!I->isThreadLocal() &&
184           (I->hasInternalLinkage() || I->hasWeakLinkage() ||
185            I->hasLinkOnceLinkage())) {
186         if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
187         if (!NoZerosInBSS && TAI->getBSSSection())
188           SwitchToDataSection(TAI->getBSSSection(), I);
189         else
190           SwitchToDataSection(TAI->getDataSection(), I);
191         if (TAI->getLCOMMDirective() != NULL) {
192           if (I->hasInternalLinkage()) {
193             O << TAI->getLCOMMDirective() << name << "," << Size;
194             if (Subtarget->isTargetDarwin())
195               O << "," << Align;
196           } else
197             O << TAI->getCOMMDirective()  << name << "," << Size;
198         } else {
199           if (!Subtarget->isTargetCygMing()) {
200             if (I->hasInternalLinkage())
201               O << "\t.local\t" << name << "\n";
202           }
203           O << TAI->getCOMMDirective()  << name << "," << Size;
204           if (TAI->getCOMMDirectiveTakesAlignment())
205             O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
206         }
207         O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
208         continue;
209       }
210     }
211
212     switch (I->getLinkage()) {
213     case GlobalValue::LinkOnceLinkage:
214     case GlobalValue::WeakLinkage:
215       if (Subtarget->isTargetDarwin()) {
216         O << "\t.globl\t" << name << "\n"
217           << TAI->getWeakDefDirective() << name << "\n";
218         SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
219       } else if (Subtarget->isTargetCygMing()) {
220         std::string SectionName(".section\t.data$linkonce." +
221                                 name +
222                                 ",\"aw\"");
223         SwitchToDataSection(SectionName.c_str(), I);
224         O << "\t.globl\t" << name << "\n"
225           << "\t.linkonce same_size\n";
226       } else {
227         std::string SectionName("\t.section\t.llvm.linkonce.d." +
228                                 name +
229                                 ",\"aw\",@progbits");
230         SwitchToDataSection(SectionName.c_str(), I);
231         O << "\t.weak\t" << name << "\n";
232       }
233       break;
234     case GlobalValue::DLLExportLinkage:
235       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
236       // FALL THROUGH
237     case GlobalValue::AppendingLinkage:
238       // FIXME: appending linkage variables should go into a section of
239       // their name or something.  For now, just emit them as external.
240     case GlobalValue::ExternalLinkage:
241       // If external or appending, declare as a global symbol
242       O << "\t.globl\t" << name << "\n";
243       // FALL THROUGH
244     case GlobalValue::InternalLinkage: {
245       if (I->isConstant()) {
246         const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
247         if (TAI->getCStringSection() && CVA && CVA->isCString()) {
248           SwitchToDataSection(TAI->getCStringSection(), I);
249           break;
250         }
251       }
252       // FIXME: special handling for ".ctors" & ".dtors" sections
253       if (I->hasSection() &&
254           (I->getSection() == ".ctors" ||
255            I->getSection() == ".dtors")) {
256         std::string SectionName = ".section " + I->getSection();
257         
258         if (Subtarget->isTargetCygMing()) {
259           SectionName += ",\"aw\"";
260         } else {
261           assert(!Subtarget->isTargetDarwin());
262           SectionName += ",\"aw\",@progbits";
263         }
264
265         SwitchToDataSection(SectionName.c_str());
266       } else {
267         if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
268           SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSBSSSection() :
269                               TAI->getBSSSection(), I);
270         else if (!I->isConstant())
271           SwitchToDataSection(I->isThreadLocal() ? TAI->getTLSDataSection() :
272                               TAI->getDataSection(), I);
273         else if (I->isThreadLocal())
274           SwitchToDataSection(TAI->getTLSDataSection());
275         else {
276           // Read-only data.
277           bool HasReloc = C->ContainsRelocations();
278           if (HasReloc &&
279               Subtarget->isTargetDarwin() &&
280               TM.getRelocationModel() != Reloc::Static)
281             SwitchToDataSection("\t.const_data\n");
282           else if (!HasReloc && Size == 4 &&
283                    TAI->getFourByteConstantSection())
284             SwitchToDataSection(TAI->getFourByteConstantSection(), I);
285           else if (!HasReloc && Size == 8 &&
286                    TAI->getEightByteConstantSection())
287             SwitchToDataSection(TAI->getEightByteConstantSection(), I);
288           else if (!HasReloc && Size == 16 &&
289                    TAI->getSixteenByteConstantSection())
290             SwitchToDataSection(TAI->getSixteenByteConstantSection(), I);
291           else if (TAI->getReadOnlySection())
292             SwitchToDataSection(TAI->getReadOnlySection(), I);
293           else
294             SwitchToDataSection(TAI->getDataSection(), I);
295         }
296       }
297       
298       break;
299     }
300     default:
301       assert(0 && "Unknown linkage type!");
302     }
303
304     EmitAlignment(Align, I);
305     O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
306       << "\n";
307     if (TAI->hasDotTypeDotSizeDirective())
308       O << "\t.size\t" << name << ", " << Size << "\n";
309     // If the initializer is a extern weak symbol, remember to emit the weak
310     // reference!
311     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
312       if (GV->hasExternalWeakLinkage())
313         ExtWeakSymbols.insert(GV);
314
315     EmitGlobalConstant(C);
316   }
317   
318   // Output linker support code for dllexported globals
319   if (!DLLExportedGVs.empty()) {
320     SwitchToDataSection(".section .drectve");
321   }
322
323   for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
324          e = DLLExportedGVs.end();
325          i != e; ++i) {
326     O << "\t.ascii \" -export:" << *i << ",data\"\n";
327   }    
328
329   if (!DLLExportedFns.empty()) {
330     SwitchToDataSection(".section .drectve");
331   }
332
333   for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
334          e = DLLExportedFns.end();
335          i != e; ++i) {
336     O << "\t.ascii \" -export:" << *i << "\"\n";
337   }    
338
339   if (Subtarget->isTargetDarwin()) {
340     SwitchToDataSection("");
341
342     // Output stubs for dynamically-linked functions
343     unsigned j = 1;
344     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
345          i != e; ++i, ++j) {
346       SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
347                           "self_modifying_code+pure_instructions,5", 0);
348       O << "L" << *i << "$stub:\n";
349       O << "\t.indirect_symbol " << *i << "\n";
350       O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
351     }
352
353     O << "\n";
354
355     if (ExceptionHandling && TAI->doesSupportExceptionHandling() && MMI) {
356       // Add the (possibly multiple) personalities to the set of global values.
357       const std::vector<Function *>& Personalities = MMI->getPersonalities();
358
359       for (std::vector<Function *>::const_iterator I = Personalities.begin(),
360              E = Personalities.end(); I != E; ++I)
361         if (*I) GVStubs.insert("_" + (*I)->getName());
362     }
363
364     // Output stubs for external and common global variables.
365     if (!GVStubs.empty())
366       SwitchToDataSection(
367                     ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
368     for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
369          i != e; ++i) {
370       O << "L" << *i << "$non_lazy_ptr:\n";
371       O << "\t.indirect_symbol " << *i << "\n";
372       O << "\t.long\t0\n";
373     }
374
375     // Emit final debug information.
376     DW.EndModule();
377
378     // Funny Darwin hack: This flag tells the linker that no global symbols
379     // contain code that falls through to other global symbols (e.g. the obvious
380     // implementation of multiple entry points).  If this doesn't occur, the
381     // linker can safely perform dead code stripping.  Since LLVM never
382     // generates code that does this, it is always safe to set.
383     O << "\t.subsections_via_symbols\n";
384   } else if (Subtarget->isTargetCygMing()) {
385     // Emit type information for external functions
386     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
387          i != e; ++i) {
388       O << "\t.def\t " << *i
389         << ";\t.scl\t" << COFF::C_EXT
390         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
391         << ";\t.endef\n";
392     }
393     
394     // Emit final debug information.
395     DW.EndModule();    
396   } else if (Subtarget->isTargetELF()) {
397     // Emit final debug information.
398     DW.EndModule();
399   }
400
401   return AsmPrinter::doFinalization(M);
402 }
403
404 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
405 /// for a MachineFunction to the given output stream, using the given target
406 /// machine description.
407 ///
408 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
409                                              X86TargetMachine &tm) {
410   const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
411
412   if (Subtarget->isFlavorIntel()) {
413     return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
414   } else {
415     return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());
416   }
417 }