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