Whitespace cleanup
[oota-llvm.git] / lib / Target / X86 / X86TargetAsmInfo.cpp
1 //===-- X86TargetAsmInfo.cpp - X86 asm properties ---------------*- C++ -*-===//
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 contains the declarations of the X86TargetAsmInfo properties.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "X86TargetAsmInfo.h"
15 #include "X86TargetMachine.h"
16 #include "X86Subtarget.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/InlineAsm.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/Module.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/Support/Dwarf.h"
24
25 using namespace llvm;
26 using namespace llvm::dwarf;
27
28 static const char *const x86_asm_table[] = {
29                                       "{si}", "S",
30                                       "{di}", "D",
31                                       "{ax}", "a",
32                                       "{cx}", "c",
33                                       "{memory}", "memory",
34                                       "{flags}", "",
35                                       "{dirflag}", "",
36                                       "{fpsr}", "",
37                                       "{cc}", "cc",
38                                       0,0};
39
40 X86TargetAsmInfo::X86TargetAsmInfo(const X86TargetMachine &TM) {
41   const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
42   X86TM = &TM;
43
44   // FIXME - Should be simplified.
45
46   AsmTransCBE = x86_asm_table;
47
48   switch (Subtarget->TargetType) {
49   case X86Subtarget::isDarwin:
50     AlignmentIsInBytes = false;
51     TextAlignFillValue = 0x90;
52     GlobalPrefix = "_";
53     if (!Subtarget->is64Bit())
54       Data64bitsDirective = 0;       // we can't emit a 64-bit unit
55     ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
56     PrivateGlobalPrefix = "L";     // Marker for constant pool idxs
57     BSSSection = 0;                       // no BSS section.
58     ZeroFillDirective = "\t.zerofill\t";  // Uses .zerofill
59     ConstantPoolSection = "\t.const\n";
60     JumpTableDataSection = "\t.const\n";
61     CStringSection = "\t.cstring";
62     FourByteConstantSection = "\t.literal4\n";
63     EightByteConstantSection = "\t.literal8\n";
64     if (Subtarget->is64Bit())
65       SixteenByteConstantSection = "\t.literal16\n";
66     ReadOnlySection = "\t.const\n";
67     LCOMMDirective = "\t.lcomm\t";
68     SwitchToSectionDirective = "\t.section ";
69     StringConstantPrefix = "\1LC";
70     COMMDirectiveTakesAlignment = false;
71     HasDotTypeDotSizeDirective = false;
72     if (TM.getRelocationModel() == Reloc::Static) {
73       StaticCtorsSection = ".constructor";
74       StaticDtorsSection = ".destructor";
75     } else {
76       StaticCtorsSection = ".mod_init_func";
77       StaticDtorsSection = ".mod_term_func";
78     }
79     if (Subtarget->is64Bit()) {
80       PersonalityPrefix = "";
81       PersonalitySuffix = "+4@GOTPCREL";
82     } else {
83       PersonalityPrefix = "L";
84       PersonalitySuffix = "$non_lazy_ptr";
85     }
86     NeedsIndirectEncoding = true;
87     InlineAsmStart = "## InlineAsm Start";
88     InlineAsmEnd = "## InlineAsm End";
89     CommentString = "##";
90     SetDirective = "\t.set";
91     PCSymbol = ".";
92     UsedDirective = "\t.no_dead_strip\t";
93     WeakDefDirective = "\t.weak_definition ";
94     WeakRefDirective = "\t.weak_reference ";
95     HiddenDirective = "\t.private_extern ";
96     ProtectedDirective = "\t.globl\t";
97
98     // In non-PIC modes, emit a special label before jump tables so that the
99     // linker can perform more accurate dead code stripping.
100     if (TM.getRelocationModel() != Reloc::PIC_) {
101       // Emit a local label that is preserved until the linker runs.
102       JumpTableSpecialLabelPrefix = "l";
103     }
104
105     SupportsDebugInformation = true;
106     NeedsSet = true;
107     DwarfAbbrevSection = ".section __DWARF,__debug_abbrev,regular,debug";
108     DwarfInfoSection = ".section __DWARF,__debug_info,regular,debug";
109     DwarfLineSection = ".section __DWARF,__debug_line,regular,debug";
110     DwarfFrameSection = ".section __DWARF,__debug_frame,regular,debug";
111     DwarfPubNamesSection = ".section __DWARF,__debug_pubnames,regular,debug";
112     DwarfPubTypesSection = ".section __DWARF,__debug_pubtypes,regular,debug";
113     DwarfStrSection = ".section __DWARF,__debug_str,regular,debug";
114     DwarfLocSection = ".section __DWARF,__debug_loc,regular,debug";
115     DwarfARangesSection = ".section __DWARF,__debug_aranges,regular,debug";
116     DwarfRangesSection = ".section __DWARF,__debug_ranges,regular,debug";
117     DwarfMacInfoSection = ".section __DWARF,__debug_macinfo,regular,debug";
118
119     // Exceptions handling
120     SupportsExceptionHandling = true;
121     GlobalEHDirective = "\t.globl\t";
122     SupportsWeakOmittedEHFrame = false;
123     AbsoluteEHSectionOffsets = false;
124     DwarfEHFrameSection =
125     ".section __TEXT,__eh_frame,coalesced,no_toc+strip_static_syms+live_support";
126     DwarfExceptionSection = ".section __DATA,__gcc_except_tab";
127     break;
128
129   case X86Subtarget::isELF:
130     ReadOnlySection = "\t.section\t.rodata";
131     FourByteConstantSection = "\t.section\t.rodata.cst4,\"aM\",@progbits,4";
132     EightByteConstantSection = "\t.section\t.rodata.cst8,\"aM\",@progbits,8";
133     SixteenByteConstantSection = "\t.section\t.rodata.cst16,\"aM\",@progbits,16";
134     CStringSection = "\t.section\t.rodata.str1.1,\"aMS\",@progbits,1";
135     PrivateGlobalPrefix = ".L";
136     WeakRefDirective = "\t.weak\t";
137     SetDirective = "\t.set\t";
138     PCSymbol = ".";
139
140     // Set up DWARF directives
141     HasLEB128 = true;  // Target asm supports leb128 directives (little-endian)
142
143     // Debug Information
144     AbsoluteDebugSectionOffsets = true;
145     SupportsDebugInformation = true;
146     DwarfAbbrevSection =  "\t.section\t.debug_abbrev,\"\",@progbits";
147     DwarfInfoSection =    "\t.section\t.debug_info,\"\",@progbits";
148     DwarfLineSection =    "\t.section\t.debug_line,\"\",@progbits";
149     DwarfFrameSection =   "\t.section\t.debug_frame,\"\",@progbits";
150     DwarfPubNamesSection ="\t.section\t.debug_pubnames,\"\",@progbits";
151     DwarfPubTypesSection ="\t.section\t.debug_pubtypes,\"\",@progbits";
152     DwarfStrSection =     "\t.section\t.debug_str,\"\",@progbits";
153     DwarfLocSection =     "\t.section\t.debug_loc,\"\",@progbits";
154     DwarfARangesSection = "\t.section\t.debug_aranges,\"\",@progbits";
155     DwarfRangesSection =  "\t.section\t.debug_ranges,\"\",@progbits";
156     DwarfMacInfoSection = "\t.section\t.debug_macinfo,\"\",@progbits";
157
158     // Exceptions handling
159     if (!Subtarget->is64Bit())
160       SupportsExceptionHandling = true;
161     AbsoluteEHSectionOffsets = false;
162     DwarfEHFrameSection = "\t.section\t.eh_frame,\"aw\",@progbits";
163     DwarfExceptionSection = "\t.section\t.gcc_except_table,\"a\",@progbits";
164     break;
165
166   case X86Subtarget::isCygwin:
167   case X86Subtarget::isMingw:
168     GlobalPrefix = "_";
169     LCOMMDirective = "\t.lcomm\t";
170     COMMDirectiveTakesAlignment = false;
171     HasDotTypeDotSizeDirective = false;
172     StaticCtorsSection = "\t.section .ctors,\"aw\"";
173     StaticDtorsSection = "\t.section .dtors,\"aw\"";
174     HiddenDirective = NULL;
175     PrivateGlobalPrefix = "L";  // Prefix for private global symbols
176     WeakRefDirective = "\t.weak\t";
177     SetDirective = "\t.set\t";
178
179     // Set up DWARF directives
180     HasLEB128 = true;  // Target asm supports leb128 directives (little-endian)
181     AbsoluteDebugSectionOffsets = true;
182     AbsoluteEHSectionOffsets = false;
183     SupportsDebugInformation = true;
184     DwarfSectionOffsetDirective = "\t.secrel32\t";
185     DwarfAbbrevSection =  "\t.section\t.debug_abbrev,\"dr\"";
186     DwarfInfoSection =    "\t.section\t.debug_info,\"dr\"";
187     DwarfLineSection =    "\t.section\t.debug_line,\"dr\"";
188     DwarfFrameSection =   "\t.section\t.debug_frame,\"dr\"";
189     DwarfPubNamesSection ="\t.section\t.debug_pubnames,\"dr\"";
190     DwarfPubTypesSection ="\t.section\t.debug_pubtypes,\"dr\"";
191     DwarfStrSection =     "\t.section\t.debug_str,\"dr\"";
192     DwarfLocSection =     "\t.section\t.debug_loc,\"dr\"";
193     DwarfARangesSection = "\t.section\t.debug_aranges,\"dr\"";
194     DwarfRangesSection =  "\t.section\t.debug_ranges,\"dr\"";
195     DwarfMacInfoSection = "\t.section\t.debug_macinfo,\"dr\"";
196     break;
197
198   case X86Subtarget::isWindows:
199     GlobalPrefix = "_";
200     HasDotTypeDotSizeDirective = false;
201     break;
202
203   default: break;
204   }
205
206   if (Subtarget->isFlavorIntel()) {
207     GlobalPrefix = "_";
208     CommentString = ";";
209
210     PrivateGlobalPrefix = "$";
211     AlignDirective = "\talign\t";
212     ZeroDirective = "\tdb\t";
213     ZeroDirectiveSuffix = " dup(0)";
214     AsciiDirective = "\tdb\t";
215     AscizDirective = 0;
216     Data8bitsDirective = "\tdb\t";
217     Data16bitsDirective = "\tdw\t";
218     Data32bitsDirective = "\tdd\t";
219     Data64bitsDirective = "\tdq\t";
220     HasDotTypeDotSizeDirective = false;
221
222     TextSection = "_text";
223     DataSection = "_data";
224     JumpTableDataSection = NULL;
225     SwitchToSectionDirective = "";
226     TextSectionStartSuffix = "\tsegment 'CODE'";
227     DataSectionStartSuffix = "\tsegment 'DATA'";
228     SectionEndDirectiveSuffix = "\tends\n";
229   }
230
231   // On Linux we must declare when we can use a non-executable stack.
232   if (Subtarget->isLinux())
233     NonexecutableStackDirective = "\t.section\t.note.GNU-stack,\"\",@progbits";
234
235   AssemblerDialect = Subtarget->getAsmFlavor();
236 }
237
238 bool X86TargetAsmInfo::LowerToBSwap(CallInst *CI) const {
239   // FIXME: this should verify that we are targetting a 486 or better.  If not,
240   // we will turn this bswap into something that will be lowered to logical ops
241   // instead of emitting the bswap asm.  For now, we don't support 486 or lower
242   // so don't worry about this.
243
244   // Verify this is a simple bswap.
245   if (CI->getNumOperands() != 2 ||
246       CI->getType() != CI->getOperand(1)->getType() ||
247       !CI->getType()->isInteger())
248     return false;
249
250   const IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
251   if (!Ty || Ty->getBitWidth() % 16 != 0)
252     return false;
253
254   // Okay, we can do this xform, do so now.
255   const Type *Tys[] = { Ty };
256   Module *M = CI->getParent()->getParent()->getParent();
257   Constant *Int = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
258
259   Value *Op = CI->getOperand(1);
260   Op = CallInst::Create(Int, Op, CI->getName(), CI);
261
262   CI->replaceAllUsesWith(Op);
263   CI->eraseFromParent();
264   return true;
265 }
266
267
268 bool X86TargetAsmInfo::ExpandInlineAsm(CallInst *CI) const {
269   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
270   std::vector<InlineAsm::ConstraintInfo> Constraints = IA->ParseConstraints();
271
272   std::string AsmStr = IA->getAsmString();
273
274   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
275   std::vector<std::string> AsmPieces;
276   SplitString(AsmStr, AsmPieces, "\n");  // ; as separator?
277
278   switch (AsmPieces.size()) {
279   default: return false;
280   case 1:
281     AsmStr = AsmPieces[0];
282     AsmPieces.clear();
283     SplitString(AsmStr, AsmPieces, " \t");  // Split with whitespace.
284
285     // bswap $0
286     if (AsmPieces.size() == 2 &&
287         AsmPieces[0] == "bswap" && AsmPieces[1] == "$0") {
288       // No need to check constraints, nothing other than the equivalent of
289       // "=r,0" would be valid here.
290       return LowerToBSwap(CI);
291     }
292     break;
293   case 3:
294     if (CI->getType() == Type::Int64Ty && Constraints.size() >= 2 &&
295         Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
296         Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
297       // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
298       std::vector<std::string> Words;
299       SplitString(AsmPieces[0], Words, " \t");
300       if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%eax") {
301         Words.clear();
302         SplitString(AsmPieces[1], Words, " \t");
303         if (Words.size() == 2 && Words[0] == "bswap" && Words[1] == "%edx") {
304           Words.clear();
305           SplitString(AsmPieces[2], Words, " \t,");
306           if (Words.size() == 3 && Words[0] == "xchgl" && Words[1] == "%eax" &&
307               Words[2] == "%edx") {
308             return LowerToBSwap(CI);
309           }
310         }
311       }
312     }
313     break;
314   }
315   return false;
316 }
317
318 /// PreferredEHDataFormat - This hook allows the target to select data
319 /// format used for encoding pointers in exception handling data. Reason is
320 /// 0 for data, 1 for code labels, 2 for function pointers. Global is true
321 /// if the symbol can be relocated.
322 unsigned X86TargetAsmInfo::PreferredEHDataFormat(DwarfEncoding::Target Reason,
323                                                  bool Global) const {
324   const X86Subtarget *Subtarget = &X86TM->getSubtarget<X86Subtarget>();
325
326   switch (Subtarget->TargetType) {
327   case X86Subtarget::isDarwin:
328    if (Reason == DwarfEncoding::Functions && Global)
329      return (DW_EH_PE_pcrel | DW_EH_PE_indirect | DW_EH_PE_sdata4);
330    else if (Reason == DwarfEncoding::CodeLabels || !Global)
331      return DW_EH_PE_pcrel;
332    else
333      return DW_EH_PE_absptr;
334
335   case X86Subtarget::isELF:
336   case X86Subtarget::isCygwin:
337   case X86Subtarget::isMingw: {
338     CodeModel::Model CM = X86TM->getCodeModel();
339
340     if (X86TM->getRelocationModel() == Reloc::PIC_) {
341       unsigned Format = 0;
342
343       if (!Subtarget->is64Bit())
344         // 32 bit targets always encode pointers as 4 bytes
345         Format = DW_EH_PE_sdata4;
346       else {
347         // 64 bit targets encode pointers in 4 bytes iff:
348         // - code model is small OR
349         // - code model is medium and we're emitting externally visible symbols
350         //   or any code symbols
351         if (CM == CodeModel::Small ||
352             (CM == CodeModel::Medium && (Global ||
353                                          Reason != DwarfEncoding::Data)))
354           Format = DW_EH_PE_sdata4;
355         else
356           Format = DW_EH_PE_sdata8;
357       }
358
359       if (Global)
360         Format |= DW_EH_PE_indirect;
361
362       return (Format | DW_EH_PE_pcrel);
363     } else {
364       if (Subtarget->is64Bit() &&
365           (CM == CodeModel::Small ||
366            (CM == CodeModel::Medium && Reason != DwarfEncoding::Data)))
367         return DW_EH_PE_udata4;
368       else
369         return DW_EH_PE_absptr;
370     }
371   }
372
373   default:
374    return TargetAsmInfo::PreferredEHDataFormat(Reason, Global);
375   }
376 }
377
378 std::string X86TargetAsmInfo::UniqueSectionForGlobal(const GlobalValue* GV,
379                                                 SectionKind::Kind kind) const {
380   const X86Subtarget *Subtarget = &X86TM->getSubtarget<X86Subtarget>();
381
382   switch (Subtarget->TargetType) {
383    case X86Subtarget::isDarwin:
384     if (kind == SectionKind::Text)
385       return "__TEXT,__textcoal_nt,coalesced,pure_instructions";
386     else
387       return "__DATA,__datacoal_nt,coalesced";
388    case X86Subtarget::isCygwin:
389    case X86Subtarget::isMingw:
390     switch (kind) {
391      case SectionKind::Text:
392       return ".text$linkonce" + GV->getName();
393      case SectionKind::Data:
394      case SectionKind::BSS:
395      case SectionKind::ThreadData:
396      case SectionKind::ThreadBSS:
397       return ".data$linkonce" + GV->getName();
398      case SectionKind::ROData:
399      case SectionKind::RODataMergeConst:
400      case SectionKind::RODataMergeStr:
401       return ".rdata$linkonce" + GV->getName();
402      default:
403       assert(0 && "Unknown section kind");
404     }
405    case X86Subtarget::isELF:
406     return TargetAsmInfo::UniqueSectionForGlobal(GV, kind);
407    default:
408     return "";
409   }
410 }
411
412
413 std::string X86TargetAsmInfo::SectionForGlobal(const GlobalValue *GV) const {
414   SectionKind::Kind kind = SectionKindForGlobal(GV);
415   unsigned flags = SectionFlagsForGlobal(GV, GV->getSection().c_str());
416   std::string Name;
417
418   // FIXME: Should we use some hashing based on section name and just check
419   // flags?
420   // FIXME: It seems, that Darwin uses much more sections.
421
422   // Select section name
423   if (GV->hasSection()) {
424     // Honour section already set, if any
425     Name = GV->getSection();
426   } else {
427     // Use default section depending on the 'type' of global
428     if (const Function *F = dyn_cast<Function>(GV)) {
429       switch (F->getLinkage()) {
430        default: assert(0 && "Unknown linkage type!");
431        case Function::InternalLinkage:
432        case Function::DLLExportLinkage:
433        case Function::ExternalLinkage:
434         Name = TextSection;
435         break;
436        case Function::WeakLinkage:
437        case Function::LinkOnceLinkage:
438         Name = UniqueSectionForGlobal(F, kind);
439         break;
440       }
441     } else if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
442       if (GVar->hasCommonLinkage() ||
443           GVar->hasLinkOnceLinkage() ||
444           GVar->hasWeakLinkage())
445         Name = UniqueSectionForGlobal(GVar, kind);
446       else {
447         switch (kind) {
448          case SectionKind::Data:
449           Name = DataSection;
450           break;
451          case SectionKind::BSS:
452           Name = (BSSSection ? BSSSection : DataSection);
453           break;
454          case SectionKind::ROData:
455          case SectionKind::RODataMergeStr:
456          case SectionKind::RODataMergeConst:
457           // FIXME: Temporary
458           Name = DataSection;
459           break;
460          case SectionKind::ThreadData:
461           Name = (TLSDataSection ? TLSDataSection : DataSection);
462           break;
463          case SectionKind::ThreadBSS:
464           Name = (TLSBSSSection ? TLSBSSSection : DataSection);
465          default:
466           assert(0 && "Unsuported section kind for global");
467         }
468       }
469     } else
470       assert(0 && "Unsupported global");
471   }
472
473   Name += PrintSectionFlags(flags);
474   return Name;
475 }
476
477 std::string X86TargetAsmInfo::PrintSectionFlags(unsigned flags) const {
478   const X86Subtarget *Subtarget = &X86TM->getSubtarget<X86Subtarget>();
479
480   std::string Flags = "";
481
482   // Add all special flags, etc
483   switch (Subtarget->TargetType) {
484    case X86Subtarget::isELF:
485     Flags += ",\"";
486
487     if (!(flags & SectionFlags::Debug))
488       Flags += 'a';
489     if (flags & SectionFlags::Code)
490       Flags += 'x';
491     if (flags & SectionFlags::Writeable)
492       Flags += 'w';
493     if (flags & SectionFlags::Mergeable)
494       Flags += 'M';
495     if (flags & SectionFlags::Strings)
496       Flags += 'S';
497     if (flags & SectionFlags::TLS)
498       Flags += 'T';
499
500     Flags += "\"";
501
502     // FIXME: There can be exceptions here
503     if (flags & SectionFlags::BSS)
504       Flags += ",@nobits";
505     else
506       Flags += ",@progbits";
507
508     // FIXME: entity size for mergeable sections
509     break;
510    case X86Subtarget::isCygwin:
511    case X86Subtarget::isMingw:
512     Flags += ",\"";
513
514     if (flags & SectionFlags::Code)
515       Flags += 'x';
516     if (flags & SectionFlags::Writeable)
517       Flags += 'w';
518
519     Flags += "\"";
520
521     break;
522    case X86Subtarget::isDarwin:
523     // Darwin does not use any special flags
524    default:
525     break;
526   }
527
528   return Flags;
529 }