4981964094f88f3d2a416c39d5024340ac0a5470
[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 "X86Subtarget.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Module.h"
23 #include "llvm/Type.h"
24 #include "llvm/Assembly/Writer.h"
25 #include "llvm/Support/Mangler.h"
26 #include "llvm/Support/CommandLine.h"
27 using namespace llvm;
28
29 Statistic<> llvm::EmittedInsts("asm-printer",
30                                "Number of machine instrs printed");
31
32 enum AsmWriterFlavorTy { att, intel };
33 cl::opt<AsmWriterFlavorTy>
34 AsmWriterFlavor("x86-asm-syntax",
35                 cl::desc("Choose style of code to emit from X86 backend:"),
36                 cl::values(
37                            clEnumVal(att,   "  Emit AT&T-style assembly"),
38                            clEnumVal(intel, "  Emit Intel-style assembly"),
39                            clEnumValEnd),
40 #ifdef _MSC_VER
41                 cl::init(intel)
42 #else
43                 cl::init(att)
44 #endif
45                 );
46
47 // Out of line virtual function to home classes.
48 void X86DwarfWriter::virtfn() {}
49
50
51 /// doInitialization
52 bool X86SharedAsmPrinter::doInitialization(Module &M) {
53   PrivateGlobalPrefix = ".L";
54   DefaultTextSection = ".text";
55   DefaultDataSection = ".data";
56   
57   switch (Subtarget->TargetType) {
58   case X86Subtarget::isDarwin:
59     AlignmentIsInBytes = false;
60     GlobalPrefix = "_";
61     Data64bitsDirective = 0;       // we can't emit a 64-bit unit
62     ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
63     PrivateGlobalPrefix = "L";     // Marker for constant pool idxs
64     ConstantPoolSection = "\t.const\n";
65     JumpTableDataSection = "\t.const\n"; // FIXME: depends on PIC mode
66     FourByteConstantSection = "\t.literal4\n";
67     EightByteConstantSection = "\t.literal8\n";
68     LCOMMDirective = "\t.lcomm\t";
69     COMMDirectiveTakesAlignment = false;
70     HasDotTypeDotSizeDirective = false;
71     StaticCtorsSection = ".mod_init_func";
72     StaticDtorsSection = ".mod_term_func";
73     InlineAsmStart = "# InlineAsm Start";
74     InlineAsmEnd = "# InlineAsm End";
75     break;
76   case X86Subtarget::isCygwin:
77     GlobalPrefix = "_";
78     COMMDirectiveTakesAlignment = false;
79     HasDotTypeDotSizeDirective = false;
80     StaticCtorsSection = "\t.section .ctors,\"aw\"";
81     StaticDtorsSection = "\t.section .dtors,\"aw\"";
82     break;
83   case X86Subtarget::isWindows:
84     GlobalPrefix = "_";
85     HasDotTypeDotSizeDirective = false;
86     break;
87   default: break;
88   }
89   
90   if (Subtarget->isTargetDarwin()) {
91     // Emit initial debug information.
92     DW.BeginModule(&M);
93   }
94
95   return AsmPrinter::doInitialization(M);
96 }
97
98 bool X86SharedAsmPrinter::doFinalization(Module &M) {
99   // Note: this code is not shared by the Intel printer as it is too different
100   // from how MASM does things.  When making changes here don't forget to look
101   // at X86IntelAsmPrinter::doFinalization().
102   const TargetData *TD = TM.getTargetData();
103
104   // Print out module-level global variables here.
105   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
106        I != E; ++I) {
107     if (!I->hasInitializer()) continue;   // External global require no code
108     
109     // Check to see if this is a special global used by LLVM, if so, emit it.
110     if (EmitSpecialLLVMGlobal(I))
111       continue;
112     
113     std::string name = Mang->getValueName(I);
114     Constant *C = I->getInitializer();
115     unsigned Size = TD->getTypeSize(C->getType());
116     unsigned Align = getPreferredAlignmentLog(I);
117
118     if (C->isNullValue() && /* FIXME: Verify correct */
119         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
120          I->hasLinkOnceLinkage() ||
121          (Subtarget->isTargetDarwin() && 
122           I->hasExternalLinkage() && !I->hasSection()))) {
123       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
124       if (I->hasExternalLinkage()) {
125           O << "\t.globl\t" << name << "\n";
126           O << "\t.zerofill __DATA__, __common, " << name << ", "
127             << Size << ", " << Align;
128       } else {
129         SwitchToDataSection(DefaultDataSection, I);
130         if (LCOMMDirective != NULL) {
131           if (I->hasInternalLinkage()) {
132             O << LCOMMDirective << name << "," << Size;
133             if (Subtarget->isTargetDarwin())
134               O << "," << (AlignmentIsInBytes ? (1 << Align) : Align);
135           } else
136             O << COMMDirective  << name << "," << Size;
137         } else {
138           if (Subtarget->TargetType != X86Subtarget::isCygwin) {
139             if (I->hasInternalLinkage())
140               O << "\t.local\t" << name << "\n";
141           }
142           O << COMMDirective  << name << "," << Size;
143           if (COMMDirectiveTakesAlignment)
144             O << "," << (AlignmentIsInBytes ? (1 << Align) : Align);
145         }
146       }
147       O << "\t\t" << CommentString << " " << I->getName() << "\n";
148     } else {
149       switch (I->getLinkage()) {
150       case GlobalValue::LinkOnceLinkage:
151       case GlobalValue::WeakLinkage:
152         if (Subtarget->isTargetDarwin()) {
153           O << "\t.globl " << name << "\n"
154             << "\t.weak_definition " << name << "\n";
155           SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
156         } else if (Subtarget->TargetType == X86Subtarget::isCygwin) {
157           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\"\n"
158             << "\t.weak " << name << "\n";
159         } else {
160           O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"
161             << "\t.weak " << name << "\n";
162         }
163         break;
164       case GlobalValue::AppendingLinkage:
165         // FIXME: appending linkage variables should go into a section of
166         // their name or something.  For now, just emit them as external.
167       case GlobalValue::ExternalLinkage:
168         // If external or appending, declare as a global symbol
169         O << "\t.globl " << name << "\n";
170         // FALL THROUGH
171       case GlobalValue::InternalLinkage:
172         SwitchToDataSection(DefaultDataSection, I);
173         break;
174       default:
175         assert(0 && "Unknown linkage type!");
176       }
177
178       EmitAlignment(Align, I);
179       O << name << ":\t\t\t\t" << CommentString << " " << I->getName()
180         << "\n";
181       if (HasDotTypeDotSizeDirective)
182         O << "\t.size " << name << ", " << Size << "\n";
183
184       EmitGlobalConstant(C);
185       O << '\n';
186     }
187   }
188   
189   if (Subtarget->isTargetDarwin()) {
190     SwitchToDataSection("", 0);
191
192     // Output stubs for dynamically-linked functions
193     unsigned j = 1;
194     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
195          i != e; ++i, ++j) {
196       SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
197                           "self_modifying_code+pure_instructions,5", 0);
198       O << "L" << *i << "$stub:\n";
199       O << "\t.indirect_symbol " << *i << "\n";
200       O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
201     }
202
203     O << "\n";
204
205     // Output stubs for external and common global variables.
206     if (GVStubs.begin() != GVStubs.end())
207       SwitchToDataSection(
208                     ".section __IMPORT,__pointers,non_lazy_symbol_pointers", 0);
209     for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
210          i != e; ++i) {
211       O << "L" << *i << "$non_lazy_ptr:\n";
212       O << "\t.indirect_symbol " << *i << "\n";
213       O << "\t.long\t0\n";
214     }
215
216     // Emit initial debug information.
217     DW.EndModule();
218
219     // Funny Darwin hack: This flag tells the linker that no global symbols
220     // contain code that falls through to other global symbols (e.g. the obvious
221     // implementation of multiple entry points).  If this doesn't occur, the
222     // linker can safely perform dead code stripping.  Since LLVM never
223     // generates code that does this, it is always safe to set.
224     O << "\t.subsections_via_symbols\n";
225   }
226
227   AsmPrinter::doFinalization(M);
228   return false; // success
229 }
230
231 /// createX86CodePrinterPass - Returns a pass that prints the X86 assembly code
232 /// for a MachineFunction to the given output stream, using the given target
233 /// machine description.
234 ///
235 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
236                                              X86TargetMachine &tm){
237   switch (AsmWriterFlavor) {
238   default:
239     assert(0 && "Unknown asm flavor!");
240   case intel:
241     return new X86IntelAsmPrinter(o, tm);
242   case att:
243     return new X86ATTAsmPrinter(o, tm);
244   }
245 }