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