Implement "general dynamic", "initial exec" and "local exec" TLS models for
[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 "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->getTypeSize(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 && FT->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 && FT->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 (Subtarget->isTargetELF() ||
119       Subtarget->isTargetCygMing() ||
120       Subtarget->isTargetDarwin()) {
121     // Emit initial debug information.
122     DW.BeginModule(&M);
123   }
124
125   return AsmPrinter::doInitialization(M);
126 }
127
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();
133   
134   // Print out module-level global variables here.
135   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
136        I != E; ++I) {
137     if (!I->hasInitializer())
138       continue;   // External global require no code
139     
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";
148       }
149       continue;
150     }
151     
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);
157
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";
163     
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";
170           continue;
171         }
172       }
173       
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);
180         else
181           SwitchToDataSection(TAI->getDataSection(), I);
182         if (TAI->getLCOMMDirective() != NULL) {
183           if (I->hasInternalLinkage()) {
184             O << TAI->getLCOMMDirective() << name << "," << Size;
185             if (Subtarget->isTargetDarwin())
186               O << "," << Align;
187           } else
188             O << TAI->getCOMMDirective()  << name << "," << Size;
189         } else {
190           if (!Subtarget->isTargetCygMing()) {
191             if (I->hasInternalLinkage())
192               O << "\t.local\t" << name << "\n";
193           }
194           O << TAI->getCOMMDirective()  << name << "," << Size;
195           if (TAI->getCOMMDirectiveTakesAlignment())
196             O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
197         }
198         O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
199         continue;
200       }
201     }
202
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." +
212                                 name +
213                                 ",\"aw\"");
214         SwitchToDataSection(SectionName.c_str(), I);
215         O << "\t.globl " << name << "\n"
216           << "\t.linkonce same_size\n";
217       } else {
218         std::string SectionName("\t.section\t.llvm.linkonce.d." +
219                                 name +
220                                 ",\"aw\",@progbits");
221         SwitchToDataSection(SectionName.c_str(), I);
222         O << "\t.weak " << name << "\n";
223       }
224       break;
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(),""));
230       // FALL THROUGH
231     case GlobalValue::ExternalLinkage:
232       // If external or appending, declare as a global symbol
233       O << "\t.globl " << name << "\n";
234       // FALL THROUGH
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);
240           break;
241         }
242       }
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();
248         
249         if (Subtarget->isTargetCygMing()) {
250           SectionName += ",\"aw\"";
251         } else {
252           assert(!Subtarget->isTargetDarwin());
253           SectionName += ",\"aw\",@progbits";
254         }
255
256         SwitchToDataSection(SectionName.c_str());
257       } else {
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());
266         else {
267           // Read-only data.
268           bool HasReloc = C->ContainsRelocations();
269           if (HasReloc &&
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);
284           else
285             SwitchToDataSection(TAI->getDataSection(), I);
286         }
287       }
288       
289       break;
290     }
291     default:
292       assert(0 && "Unknown linkage type!");
293     }
294
295     EmitAlignment(Align, I);
296     O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
297       << "\n";
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
301     // reference!
302     if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
303       if (GV->hasExternalWeakLinkage())
304         ExtWeakSymbols.insert(GV);
305
306     EmitGlobalConstant(C);
307     O << '\n';
308   }
309   
310   // Output linker support code for dllexported globals
311   if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
312     SwitchToDataSection(".section .drectve");
313   }
314
315   for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
316          e = DLLExportedGVs.end();
317          i != e; ++i) {
318     O << "\t.ascii \" -export:" << *i << ",data\"\n";
319   }    
320
321   if (DLLExportedFns.begin() != DLLExportedFns.end()) {
322     SwitchToDataSection(".section .drectve");
323   }
324
325   for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
326          e = DLLExportedFns.end();
327          i != e; ++i) {
328     O << "\t.ascii \" -export:" << *i << "\"\n";
329   }    
330
331   if (Subtarget->isTargetDarwin()) {
332     SwitchToDataSection("");
333
334     // Output stubs for dynamically-linked functions
335     unsigned j = 1;
336     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
337          i != e; ++i, ++j) {
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";
343     }
344
345     O << "\n";
346
347     // Output stubs for external and common global variables.
348     if (GVStubs.begin() != GVStubs.end())
349       SwitchToDataSection(
350                     ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
351     for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
352          i != e; ++i) {
353       O << "L" << *i << "$non_lazy_ptr:\n";
354       O << "\t.indirect_symbol " << *i << "\n";
355       O << "\t.long\t0\n";
356     }
357
358     // Emit final debug information.
359     DW.EndModule();
360
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();
370          i != e; ++i) {
371       O << "\t.def\t " << *i
372         << ";\t.scl\t" << COFF::C_EXT
373         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
374         << ";\t.endef\n";
375     }
376     
377     // Emit final debug information.
378     DW.EndModule();    
379   } else if (Subtarget->isTargetELF()) {
380     // Emit final debug information.
381     DW.EndModule();
382   }
383
384   AsmPrinter::doFinalization(M);
385   return false; // success
386 }
387
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.
391 ///
392 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
393                                              X86TargetMachine &tm) {
394   const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
395
396   if (Subtarget->isFlavorIntel()) {
397     return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
398   } else {
399     return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());
400   }
401 }