Remove more duplicated code.
[oota-llvm.git] / lib / CodeGen / TargetLoweringObjectFileImpl.cpp
1 //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
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 implements classes used to handle lowerings specific to common
11 // object file formats.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
21 #include "llvm/MC/MCContext.h"
22 #include "llvm/MC/MCExpr.h"
23 #include "llvm/MC/MCSectionMachO.h"
24 #include "llvm/MC/MCSectionELF.h"
25 #include "llvm/MC/MCSectionCOFF.h"
26 #include "llvm/MC/MCSymbol.h"
27 #include "llvm/Target/Mangler.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Support/Dwarf.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/ADT/Triple.h"
38 using namespace llvm;
39 using namespace dwarf;
40
41 //===----------------------------------------------------------------------===//
42 //                                  ELF
43 //===----------------------------------------------------------------------===//
44
45 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
46                                              const TargetMachine &TM) {
47   TargetLoweringObjectFile::Initialize(Ctx, TM);
48
49   BSSSection =
50     getContext().getELFSection(".bss", ELF::SHT_NOBITS,
51                                ELF::SHF_WRITE |ELF::SHF_ALLOC,
52                                SectionKind::getBSS());
53
54   TextSection =
55     getContext().getELFSection(".text", ELF::SHT_PROGBITS,
56                                ELF::SHF_EXECINSTR |
57                                ELF::SHF_ALLOC,
58                                SectionKind::getText());
59
60   DataSection =
61     getContext().getELFSection(".data", ELF::SHT_PROGBITS,
62                                ELF::SHF_WRITE |ELF::SHF_ALLOC,
63                                SectionKind::getDataRel());
64
65   ReadOnlySection =
66     getContext().getELFSection(".rodata", ELF::SHT_PROGBITS,
67                                ELF::SHF_ALLOC,
68                                SectionKind::getReadOnly());
69
70   TLSDataSection =
71     getContext().getELFSection(".tdata", ELF::SHT_PROGBITS,
72                                ELF::SHF_ALLOC | ELF::SHF_TLS |
73                                ELF::SHF_WRITE,
74                                SectionKind::getThreadData());
75
76   TLSBSSSection =
77     getContext().getELFSection(".tbss", ELF::SHT_NOBITS,
78                                ELF::SHF_ALLOC | ELF::SHF_TLS |
79                                ELF::SHF_WRITE,
80                                SectionKind::getThreadBSS());
81
82   DataRelSection =
83     getContext().getELFSection(".data.rel", ELF::SHT_PROGBITS,
84                                ELF::SHF_ALLOC |ELF::SHF_WRITE,
85                                SectionKind::getDataRel());
86
87   DataRelLocalSection =
88     getContext().getELFSection(".data.rel.local", ELF::SHT_PROGBITS,
89                                ELF::SHF_ALLOC |ELF::SHF_WRITE,
90                                SectionKind::getDataRelLocal());
91
92   DataRelROSection =
93     getContext().getELFSection(".data.rel.ro", ELF::SHT_PROGBITS,
94                                ELF::SHF_ALLOC |ELF::SHF_WRITE,
95                                SectionKind::getReadOnlyWithRel());
96
97   DataRelROLocalSection =
98     getContext().getELFSection(".data.rel.ro.local", ELF::SHT_PROGBITS,
99                                ELF::SHF_ALLOC |ELF::SHF_WRITE,
100                                SectionKind::getReadOnlyWithRelLocal());
101
102   MergeableConst4Section =
103     getContext().getELFSection(".rodata.cst4", ELF::SHT_PROGBITS,
104                                ELF::SHF_ALLOC |ELF::SHF_MERGE,
105                                SectionKind::getMergeableConst4());
106
107   MergeableConst8Section =
108     getContext().getELFSection(".rodata.cst8", ELF::SHT_PROGBITS,
109                                ELF::SHF_ALLOC |ELF::SHF_MERGE,
110                                SectionKind::getMergeableConst8());
111
112   MergeableConst16Section =
113     getContext().getELFSection(".rodata.cst16", ELF::SHT_PROGBITS,
114                                ELF::SHF_ALLOC |ELF::SHF_MERGE,
115                                SectionKind::getMergeableConst16());
116
117   StaticCtorSection =
118     getContext().getELFSection(".ctors", ELF::SHT_PROGBITS,
119                                ELF::SHF_ALLOC |ELF::SHF_WRITE,
120                                SectionKind::getDataRel());
121
122   StaticDtorSection =
123     getContext().getELFSection(".dtors", ELF::SHT_PROGBITS,
124                                ELF::SHF_ALLOC |ELF::SHF_WRITE,
125                                SectionKind::getDataRel());
126
127   // Exception Handling Sections.
128
129   // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
130   // it contains relocatable pointers.  In PIC mode, this is probably a big
131   // runtime hit for C++ apps.  Either the contents of the LSDA need to be
132   // adjusted or this should be a data section.
133   LSDASection =
134     getContext().getELFSection(".gcc_except_table", ELF::SHT_PROGBITS,
135                                ELF::SHF_ALLOC,
136                                SectionKind::getReadOnly());
137   EHFrameSection =
138     getContext().getELFSection(".eh_frame", ELF::SHT_PROGBITS,
139                                ELF::SHF_ALLOC,
140                                SectionKind::getDataRel());
141
142   // Debug Info Sections.
143   DwarfAbbrevSection =
144     getContext().getELFSection(".debug_abbrev", ELF::SHT_PROGBITS, 0,
145                                SectionKind::getMetadata());
146   DwarfInfoSection =
147     getContext().getELFSection(".debug_info", ELF::SHT_PROGBITS, 0,
148                                SectionKind::getMetadata());
149   DwarfLineSection =
150     getContext().getELFSection(".debug_line", ELF::SHT_PROGBITS, 0,
151                                SectionKind::getMetadata());
152   DwarfFrameSection =
153     getContext().getELFSection(".debug_frame", ELF::SHT_PROGBITS, 0,
154                                SectionKind::getMetadata());
155   DwarfPubNamesSection =
156     getContext().getELFSection(".debug_pubnames", ELF::SHT_PROGBITS, 0,
157                                SectionKind::getMetadata());
158   DwarfPubTypesSection =
159     getContext().getELFSection(".debug_pubtypes", ELF::SHT_PROGBITS, 0,
160                                SectionKind::getMetadata());
161   DwarfStrSection =
162     getContext().getELFSection(".debug_str", ELF::SHT_PROGBITS, 0,
163                                SectionKind::getMetadata());
164   DwarfLocSection =
165     getContext().getELFSection(".debug_loc", ELF::SHT_PROGBITS, 0,
166                                SectionKind::getMetadata());
167   DwarfARangesSection =
168     getContext().getELFSection(".debug_aranges", ELF::SHT_PROGBITS, 0,
169                                SectionKind::getMetadata());
170   DwarfRangesSection =
171     getContext().getELFSection(".debug_ranges", ELF::SHT_PROGBITS, 0,
172                                SectionKind::getMetadata());
173   DwarfMacroInfoSection =
174     getContext().getELFSection(".debug_macinfo", ELF::SHT_PROGBITS, 0,
175                                SectionKind::getMetadata());
176 }
177
178
179 static SectionKind
180 getELFKindForNamedSection(StringRef Name, SectionKind K) {
181   if (Name.empty() || Name[0] != '.') return K;
182
183   // Some lame default implementation based on some magic section names.
184   if (Name == ".bss" ||
185       Name.startswith(".bss.") ||
186       Name.startswith(".gnu.linkonce.b.") ||
187       Name.startswith(".llvm.linkonce.b.") ||
188       Name == ".sbss" ||
189       Name.startswith(".sbss.") ||
190       Name.startswith(".gnu.linkonce.sb.") ||
191       Name.startswith(".llvm.linkonce.sb."))
192     return SectionKind::getBSS();
193
194   if (Name == ".tdata" ||
195       Name.startswith(".tdata.") ||
196       Name.startswith(".gnu.linkonce.td.") ||
197       Name.startswith(".llvm.linkonce.td."))
198     return SectionKind::getThreadData();
199
200   if (Name == ".tbss" ||
201       Name.startswith(".tbss.") ||
202       Name.startswith(".gnu.linkonce.tb.") ||
203       Name.startswith(".llvm.linkonce.tb."))
204     return SectionKind::getThreadBSS();
205
206   return K;
207 }
208
209
210 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
211
212   if (Name == ".init_array")
213     return ELF::SHT_INIT_ARRAY;
214
215   if (Name == ".fini_array")
216     return ELF::SHT_FINI_ARRAY;
217
218   if (Name == ".preinit_array")
219     return ELF::SHT_PREINIT_ARRAY;
220
221   if (K.isBSS() || K.isThreadBSS())
222     return ELF::SHT_NOBITS;
223
224   return ELF::SHT_PROGBITS;
225 }
226
227
228 static unsigned
229 getELFSectionFlags(SectionKind K) {
230   unsigned Flags = 0;
231
232   if (!K.isMetadata())
233     Flags |= ELF::SHF_ALLOC;
234
235   if (K.isText())
236     Flags |= ELF::SHF_EXECINSTR;
237
238   if (K.isWriteable())
239     Flags |= ELF::SHF_WRITE;
240
241   if (K.isThreadLocal())
242     Flags |= ELF::SHF_TLS;
243
244   // K.isMergeableConst() is left out to honour PR4650
245   if (K.isMergeableCString() || K.isMergeableConst4() ||
246       K.isMergeableConst8() || K.isMergeableConst16())
247     Flags |= ELF::SHF_MERGE;
248
249   if (K.isMergeableCString())
250     Flags |= ELF::SHF_STRINGS;
251
252   return Flags;
253 }
254
255
256 const MCSection *TargetLoweringObjectFileELF::
257 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
258                          Mangler *Mang, const TargetMachine &TM) const {
259   StringRef SectionName = GV->getSection();
260
261   // Infer section flags from the section name if we can.
262   Kind = getELFKindForNamedSection(SectionName, Kind);
263
264   return getContext().getELFSection(SectionName,
265                                     getELFSectionType(SectionName, Kind),
266                                     getELFSectionFlags(Kind), Kind);
267 }
268
269 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
270   if (Kind.isText())                 return ".gnu.linkonce.t.";
271   if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
272
273   if (Kind.isThreadData())           return ".gnu.linkonce.td.";
274   if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
275
276   if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
277   if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
278   if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
279   if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
280
281   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
282   return ".gnu.linkonce.d.rel.ro.";
283 }
284
285 /// getSectionPrefixForGlobal - Return the section prefix name used by options
286 /// FunctionsSections and DataSections.
287 static const char *getSectionPrefixForGlobal(SectionKind Kind) {
288   if (Kind.isText())                 return ".text.";
289   if (Kind.isReadOnly())             return ".rodata.";
290
291   if (Kind.isThreadData())           return ".tdata.";
292   if (Kind.isThreadBSS())            return ".tbss.";
293
294   if (Kind.isDataNoRel())            return ".data.";
295   if (Kind.isDataRelLocal())         return ".data.rel.local.";
296   if (Kind.isDataRel())              return ".data.rel.";
297   if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
298
299   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
300   return ".data.rel.ro.";
301 }
302
303
304 const MCSection *TargetLoweringObjectFileELF::
305 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
306                        Mangler *Mang, const TargetMachine &TM) const {
307   // If we have -ffunction-section or -fdata-section then we should emit the
308   // global value to a uniqued section specifically for it.
309   bool EmitUniquedSection;
310   if (Kind.isText())
311     EmitUniquedSection = TM.getFunctionSections();
312   else
313     EmitUniquedSection = TM.getDataSections();
314
315   // If this global is linkonce/weak and the target handles this by emitting it
316   // into a 'uniqued' section name, create and return the section now.
317   if ((GV->isWeakForLinker() || EmitUniquedSection) &&
318       !Kind.isCommon() && !Kind.isBSS()) {
319     const char *Prefix;
320     if (GV->isWeakForLinker())
321       Prefix = getSectionPrefixForUniqueGlobal(Kind);
322     else {
323       assert(EmitUniquedSection);
324       Prefix = getSectionPrefixForGlobal(Kind);
325     }
326
327     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
328     MCSymbol *Sym = Mang->getSymbol(GV);
329     Name.append(Sym->getName().begin(), Sym->getName().end());
330     return getContext().getELFSection(Name.str(),
331                                       getELFSectionType(Name.str(), Kind),
332                                       getELFSectionFlags(Kind), Kind);
333   }
334
335   if (Kind.isText()) return TextSection;
336
337   if (Kind.isMergeable1ByteCString() ||
338       Kind.isMergeable2ByteCString() ||
339       Kind.isMergeable4ByteCString()) {
340
341     // We also need alignment here.
342     // FIXME: this is getting the alignment of the character, not the
343     // alignment of the global!
344     unsigned Align =
345       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
346
347     const char *SizeSpec = ".rodata.str1.";
348     if (Kind.isMergeable2ByteCString())
349       SizeSpec = ".rodata.str2.";
350     else if (Kind.isMergeable4ByteCString())
351       SizeSpec = ".rodata.str4.";
352     else
353       assert(Kind.isMergeable1ByteCString() && "unknown string width");
354
355
356     std::string Name = SizeSpec + utostr(Align);
357     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
358                                       ELF::SHF_ALLOC |
359                                       ELF::SHF_MERGE |
360                                       ELF::SHF_STRINGS,
361                                       Kind);
362   }
363
364   if (Kind.isMergeableConst()) {
365     if (Kind.isMergeableConst4() && MergeableConst4Section)
366       return MergeableConst4Section;
367     if (Kind.isMergeableConst8() && MergeableConst8Section)
368       return MergeableConst8Section;
369     if (Kind.isMergeableConst16() && MergeableConst16Section)
370       return MergeableConst16Section;
371     return ReadOnlySection;  // .const
372   }
373
374   if (Kind.isReadOnly())             return ReadOnlySection;
375
376   if (Kind.isThreadData())           return TLSDataSection;
377   if (Kind.isThreadBSS())            return TLSBSSSection;
378
379   // Note: we claim that common symbols are put in BSSSection, but they are
380   // really emitted with the magic .comm directive, which creates a symbol table
381   // entry but not a section.
382   if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
383
384   if (Kind.isDataNoRel())            return DataSection;
385   if (Kind.isDataRelLocal())         return DataRelLocalSection;
386   if (Kind.isDataRel())              return DataRelSection;
387   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
388
389   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
390   return DataRelROSection;
391 }
392
393 /// getSectionForConstant - Given a mergeable constant with the
394 /// specified size and relocation information, return a section that it
395 /// should be placed in.
396 const MCSection *TargetLoweringObjectFileELF::
397 getSectionForConstant(SectionKind Kind) const {
398   if (Kind.isMergeableConst4() && MergeableConst4Section)
399     return MergeableConst4Section;
400   if (Kind.isMergeableConst8() && MergeableConst8Section)
401     return MergeableConst8Section;
402   if (Kind.isMergeableConst16() && MergeableConst16Section)
403     return MergeableConst16Section;
404   if (Kind.isReadOnly())
405     return ReadOnlySection;
406
407   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
408   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
409   return DataRelROSection;
410 }
411
412 const MCExpr *TargetLoweringObjectFileELF::
413 getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
414                                MachineModuleInfo *MMI,
415                                unsigned Encoding, MCStreamer &Streamer) const {
416
417   if (Encoding & dwarf::DW_EH_PE_indirect) {
418     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
419
420     SmallString<128> Name;
421     Mang->getNameWithPrefix(Name, GV, true);
422     Name += ".DW.stub";
423
424     // Add information about the stub reference to ELFMMI so that the stub
425     // gets emitted by the asmprinter.
426     MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
427     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
428     if (StubSym.getPointer() == 0) {
429       MCSymbol *Sym = Mang->getSymbol(GV);
430       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
431     }
432
433     return TargetLoweringObjectFile::
434       getExprForDwarfReference(SSym, Mang, MMI,
435                                Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
436   }
437
438   return TargetLoweringObjectFile::
439     getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, Streamer);
440 }
441
442 //===----------------------------------------------------------------------===//
443 //                                 MachO
444 //===----------------------------------------------------------------------===//
445
446 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
447                                                const TargetMachine &TM) {
448   // _foo.eh symbols are currently always exported so that the linker knows
449   // about them.  This is not necessary on 10.6 and later, but it
450   // doesn't hurt anything.
451   // FIXME: I need to get this from Triple.
452   IsFunctionEHSymbolGlobal = true;
453   IsFunctionEHFrameSymbolPrivate = false;
454   SupportsWeakOmittedEHFrame = false;
455
456   Triple T(((LLVMTargetMachine&)TM).getTargetTriple());
457   if (T.getOS() == Triple::Darwin) {
458     switch (T.getDarwinMajorNumber()) {
459     case 7:  // 10.3 Panther.
460     case 8:  // 10.4 Tiger.
461       CommDirectiveSupportsAlignment = false;
462       break;
463     case 9:   // 10.5 Leopard.
464     case 10:  // 10.6 SnowLeopard.
465       break;
466     }
467   }
468
469   TargetLoweringObjectFile::Initialize(Ctx, TM);
470
471   TextSection // .text
472     = getContext().getMachOSection("__TEXT", "__text",
473                                    MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
474                                    SectionKind::getText());
475   DataSection // .data
476     = getContext().getMachOSection("__DATA", "__data", 0,
477                                    SectionKind::getDataRel());
478
479   TLSDataSection // .tdata
480     = getContext().getMachOSection("__DATA", "__thread_data",
481                                    MCSectionMachO::S_THREAD_LOCAL_REGULAR,
482                                    SectionKind::getDataRel());
483   TLSBSSSection // .tbss
484     = getContext().getMachOSection("__DATA", "__thread_bss",
485                                    MCSectionMachO::S_THREAD_LOCAL_ZEROFILL,
486                                    SectionKind::getThreadBSS());
487
488   // TODO: Verify datarel below.
489   TLSTLVSection // .tlv
490     = getContext().getMachOSection("__DATA", "__thread_vars",
491                                    MCSectionMachO::S_THREAD_LOCAL_VARIABLES,
492                                    SectionKind::getDataRel());
493
494   TLSThreadInitSection
495     = getContext().getMachOSection("__DATA", "__thread_init",
496                           MCSectionMachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS,
497                           SectionKind::getDataRel());
498
499   CStringSection // .cstring
500     = getContext().getMachOSection("__TEXT", "__cstring",
501                                    MCSectionMachO::S_CSTRING_LITERALS,
502                                    SectionKind::getMergeable1ByteCString());
503   UStringSection
504     = getContext().getMachOSection("__TEXT","__ustring", 0,
505                                    SectionKind::getMergeable2ByteCString());
506   FourByteConstantSection // .literal4
507     = getContext().getMachOSection("__TEXT", "__literal4",
508                                    MCSectionMachO::S_4BYTE_LITERALS,
509                                    SectionKind::getMergeableConst4());
510   EightByteConstantSection // .literal8
511     = getContext().getMachOSection("__TEXT", "__literal8",
512                                    MCSectionMachO::S_8BYTE_LITERALS,
513                                    SectionKind::getMergeableConst8());
514
515   // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
516   // to using it in -static mode.
517   SixteenByteConstantSection = 0;
518   if (TM.getRelocationModel() != Reloc::Static &&
519       TM.getTargetData()->getPointerSize() == 32)
520     SixteenByteConstantSection =   // .literal16
521       getContext().getMachOSection("__TEXT", "__literal16",
522                                    MCSectionMachO::S_16BYTE_LITERALS,
523                                    SectionKind::getMergeableConst16());
524
525   ReadOnlySection  // .const
526     = getContext().getMachOSection("__TEXT", "__const", 0,
527                                    SectionKind::getReadOnly());
528
529   TextCoalSection
530     = getContext().getMachOSection("__TEXT", "__textcoal_nt",
531                                    MCSectionMachO::S_COALESCED |
532                                    MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
533                                    SectionKind::getText());
534   ConstTextCoalSection
535     = getContext().getMachOSection("__TEXT", "__const_coal",
536                                    MCSectionMachO::S_COALESCED,
537                                    SectionKind::getReadOnly());
538   ConstDataSection  // .const_data
539     = getContext().getMachOSection("__DATA", "__const", 0,
540                                    SectionKind::getReadOnlyWithRel());
541   DataCoalSection
542     = getContext().getMachOSection("__DATA","__datacoal_nt",
543                                    MCSectionMachO::S_COALESCED,
544                                    SectionKind::getDataRel());
545   DataCommonSection
546     = getContext().getMachOSection("__DATA","__common",
547                                    MCSectionMachO::S_ZEROFILL,
548                                    SectionKind::getBSS());
549   DataBSSSection
550     = getContext().getMachOSection("__DATA","__bss", MCSectionMachO::S_ZEROFILL,
551                                    SectionKind::getBSS());
552
553
554   LazySymbolPointerSection
555     = getContext().getMachOSection("__DATA", "__la_symbol_ptr",
556                                    MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
557                                    SectionKind::getMetadata());
558   NonLazySymbolPointerSection
559     = getContext().getMachOSection("__DATA", "__nl_symbol_ptr",
560                                    MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
561                                    SectionKind::getMetadata());
562
563   if (TM.getRelocationModel() == Reloc::Static) {
564     StaticCtorSection
565       = getContext().getMachOSection("__TEXT", "__constructor", 0,
566                                      SectionKind::getDataRel());
567     StaticDtorSection
568       = getContext().getMachOSection("__TEXT", "__destructor", 0,
569                                      SectionKind::getDataRel());
570   } else {
571     StaticCtorSection
572       = getContext().getMachOSection("__DATA", "__mod_init_func",
573                                      MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
574                                      SectionKind::getDataRel());
575     StaticDtorSection
576       = getContext().getMachOSection("__DATA", "__mod_term_func",
577                                      MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
578                                      SectionKind::getDataRel());
579   }
580
581   // Exception Handling.
582   LSDASection = getContext().getMachOSection("__TEXT", "__gcc_except_tab", 0,
583                                              SectionKind::getReadOnlyWithRel());
584   EHFrameSection =
585     getContext().getMachOSection("__TEXT", "__eh_frame",
586                                  MCSectionMachO::S_COALESCED |
587                                  MCSectionMachO::S_ATTR_NO_TOC |
588                                  MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
589                                  MCSectionMachO::S_ATTR_LIVE_SUPPORT,
590                                  SectionKind::getReadOnly());
591
592   // Debug Information.
593   DwarfAbbrevSection =
594     getContext().getMachOSection("__DWARF", "__debug_abbrev",
595                                  MCSectionMachO::S_ATTR_DEBUG,
596                                  SectionKind::getMetadata());
597   DwarfInfoSection =
598     getContext().getMachOSection("__DWARF", "__debug_info",
599                                  MCSectionMachO::S_ATTR_DEBUG,
600                                  SectionKind::getMetadata());
601   DwarfLineSection =
602     getContext().getMachOSection("__DWARF", "__debug_line",
603                                  MCSectionMachO::S_ATTR_DEBUG,
604                                  SectionKind::getMetadata());
605   DwarfFrameSection =
606     getContext().getMachOSection("__DWARF", "__debug_frame",
607                                  MCSectionMachO::S_ATTR_DEBUG,
608                                  SectionKind::getMetadata());
609   DwarfPubNamesSection =
610     getContext().getMachOSection("__DWARF", "__debug_pubnames",
611                                  MCSectionMachO::S_ATTR_DEBUG,
612                                  SectionKind::getMetadata());
613   DwarfPubTypesSection =
614     getContext().getMachOSection("__DWARF", "__debug_pubtypes",
615                                  MCSectionMachO::S_ATTR_DEBUG,
616                                  SectionKind::getMetadata());
617   DwarfStrSection =
618     getContext().getMachOSection("__DWARF", "__debug_str",
619                                  MCSectionMachO::S_ATTR_DEBUG,
620                                  SectionKind::getMetadata());
621   DwarfLocSection =
622     getContext().getMachOSection("__DWARF", "__debug_loc",
623                                  MCSectionMachO::S_ATTR_DEBUG,
624                                  SectionKind::getMetadata());
625   DwarfARangesSection =
626     getContext().getMachOSection("__DWARF", "__debug_aranges",
627                                  MCSectionMachO::S_ATTR_DEBUG,
628                                  SectionKind::getMetadata());
629   DwarfRangesSection =
630     getContext().getMachOSection("__DWARF", "__debug_ranges",
631                                  MCSectionMachO::S_ATTR_DEBUG,
632                                  SectionKind::getMetadata());
633   DwarfMacroInfoSection =
634     getContext().getMachOSection("__DWARF", "__debug_macinfo",
635                                  MCSectionMachO::S_ATTR_DEBUG,
636                                  SectionKind::getMetadata());
637   DwarfDebugInlineSection =
638     getContext().getMachOSection("__DWARF", "__debug_inlined",
639                                  MCSectionMachO::S_ATTR_DEBUG,
640                                  SectionKind::getMetadata());
641
642   TLSExtraDataSection = TLSTLVSection;
643 }
644
645 const MCSection *TargetLoweringObjectFileMachO::
646 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
647                          Mangler *Mang, const TargetMachine &TM) const {
648   // Parse the section specifier and create it if valid.
649   StringRef Segment, Section;
650   unsigned TAA, StubSize;
651   std::string ErrorCode =
652     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
653                                           TAA, StubSize);
654   if (!ErrorCode.empty()) {
655     // If invalid, report the error with report_fatal_error.
656     report_fatal_error("Global variable '" + GV->getNameStr() +
657                       "' has an invalid section specifier '" + GV->getSection()+
658                       "': " + ErrorCode + ".");
659     // Fall back to dropping it into the data section.
660     return DataSection;
661   }
662
663   // Get the section.
664   const MCSectionMachO *S =
665     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
666
667   // Okay, now that we got the section, verify that the TAA & StubSize agree.
668   // If the user declared multiple globals with different section flags, we need
669   // to reject it here.
670   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
671     // If invalid, report the error with report_fatal_error.
672     report_fatal_error("Global variable '" + GV->getNameStr() +
673                       "' section type or attributes does not match previous"
674                       " section specifier");
675   }
676
677   return S;
678 }
679
680 const MCSection *TargetLoweringObjectFileMachO::
681 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
682                        Mangler *Mang, const TargetMachine &TM) const {
683
684   // Handle thread local data.
685   if (Kind.isThreadBSS()) return TLSBSSSection;
686   if (Kind.isThreadData()) return TLSDataSection;
687
688   if (Kind.isText())
689     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
690
691   // If this is weak/linkonce, put this in a coalescable section, either in text
692   // or data depending on if it is writable.
693   if (GV->isWeakForLinker()) {
694     if (Kind.isReadOnly())
695       return ConstTextCoalSection;
696     return DataCoalSection;
697   }
698
699   // FIXME: Alignment check should be handled by section classifier.
700   if (Kind.isMergeable1ByteCString() &&
701       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
702     return CStringSection;
703
704   // Do not put 16-bit arrays in the UString section if they have an
705   // externally visible label, this runs into issues with certain linker
706   // versions.
707   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
708       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
709     return UStringSection;
710
711   if (Kind.isMergeableConst()) {
712     if (Kind.isMergeableConst4())
713       return FourByteConstantSection;
714     if (Kind.isMergeableConst8())
715       return EightByteConstantSection;
716     if (Kind.isMergeableConst16() && SixteenByteConstantSection)
717       return SixteenByteConstantSection;
718   }
719
720   // Otherwise, if it is readonly, but not something we can specially optimize,
721   // just drop it in .const.
722   if (Kind.isReadOnly())
723     return ReadOnlySection;
724
725   // If this is marked const, put it into a const section.  But if the dynamic
726   // linker needs to write to it, put it in the data segment.
727   if (Kind.isReadOnlyWithRel())
728     return ConstDataSection;
729
730   // Put zero initialized globals with strong external linkage in the
731   // DATA, __common section with the .zerofill directive.
732   if (Kind.isBSSExtern())
733     return DataCommonSection;
734
735   // Put zero initialized globals with local linkage in __DATA,__bss directive
736   // with the .zerofill directive (aka .lcomm).
737   if (Kind.isBSSLocal())
738     return DataBSSSection;
739
740   // Otherwise, just drop the variable in the normal data section.
741   return DataSection;
742 }
743
744 const MCSection *
745 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
746   // If this constant requires a relocation, we have to put it in the data
747   // segment, not in the text segment.
748   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
749     return ConstDataSection;
750
751   if (Kind.isMergeableConst4())
752     return FourByteConstantSection;
753   if (Kind.isMergeableConst8())
754     return EightByteConstantSection;
755   if (Kind.isMergeableConst16() && SixteenByteConstantSection)
756     return SixteenByteConstantSection;
757   return ReadOnlySection;  // .const
758 }
759
760 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
761 /// not to emit the UsedDirective for some symbols in llvm.used.
762 // FIXME: REMOVE this (rdar://7071300)
763 bool TargetLoweringObjectFileMachO::
764 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
765   /// On Darwin, internally linked data beginning with "L" or "l" does not have
766   /// the directive emitted (this occurs in ObjC metadata).
767   if (!GV) return false;
768
769   // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
770   if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
771     // FIXME: ObjC metadata is currently emitted as internal symbols that have
772     // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
773     // this horrible hack can go away.
774     MCSymbol *Sym = Mang->getSymbol(GV);
775     if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l')
776       return false;
777   }
778
779   return true;
780 }
781
782 const MCExpr *TargetLoweringObjectFileMachO::
783 getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
784                                MachineModuleInfo *MMI, unsigned Encoding,
785                                MCStreamer &Streamer) const {
786   // The mach-o version of this method defaults to returning a stub reference.
787
788   if (Encoding & DW_EH_PE_indirect) {
789     MachineModuleInfoMachO &MachOMMI =
790       MMI->getObjFileInfo<MachineModuleInfoMachO>();
791
792     SmallString<128> Name;
793     Mang->getNameWithPrefix(Name, GV, true);
794     Name += "$non_lazy_ptr";
795
796     // Add information about the stub reference to MachOMMI so that the stub
797     // gets emitted by the asmprinter.
798     MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
799     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
800     if (StubSym.getPointer() == 0) {
801       MCSymbol *Sym = Mang->getSymbol(GV);
802       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
803     }
804
805     return TargetLoweringObjectFile::
806       getExprForDwarfReference(SSym, Mang, MMI,
807                                Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
808   }
809
810   return TargetLoweringObjectFile::
811     getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, Streamer);
812 }
813
814 unsigned TargetLoweringObjectFileMachO::getPersonalityEncoding() const {
815   return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
816 }
817
818 unsigned TargetLoweringObjectFileMachO::getLSDAEncoding() const {
819   return DW_EH_PE_pcrel;
820 }
821
822 unsigned TargetLoweringObjectFileMachO::getFDEEncoding() const {
823   return DW_EH_PE_pcrel;
824 }
825
826 unsigned TargetLoweringObjectFileMachO::getTTypeEncoding() const {
827   return DW_EH_PE_indirect | DW_EH_PE_pcrel | DW_EH_PE_sdata4;
828 }
829
830 //===----------------------------------------------------------------------===//
831 //                                  COFF
832 //===----------------------------------------------------------------------===//
833
834 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
835                                               const TargetMachine &TM) {
836   TargetLoweringObjectFile::Initialize(Ctx, TM);
837   TextSection =
838     getContext().getCOFFSection(".text",
839                                 COFF::IMAGE_SCN_CNT_CODE |
840                                 COFF::IMAGE_SCN_MEM_EXECUTE |
841                                 COFF::IMAGE_SCN_MEM_READ,
842                                 SectionKind::getText());
843   DataSection =
844     getContext().getCOFFSection(".data",
845                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
846                                 COFF::IMAGE_SCN_MEM_READ |
847                                 COFF::IMAGE_SCN_MEM_WRITE,
848                                 SectionKind::getDataRel());
849   ReadOnlySection =
850     getContext().getCOFFSection(".rdata",
851                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
852                                 COFF::IMAGE_SCN_MEM_READ,
853                                 SectionKind::getReadOnly());
854   StaticCtorSection =
855     getContext().getCOFFSection(".ctors",
856                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
857                                 COFF::IMAGE_SCN_MEM_READ |
858                                 COFF::IMAGE_SCN_MEM_WRITE,
859                                 SectionKind::getDataRel());
860   StaticDtorSection =
861     getContext().getCOFFSection(".dtors",
862                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
863                                 COFF::IMAGE_SCN_MEM_READ |
864                                 COFF::IMAGE_SCN_MEM_WRITE,
865                                 SectionKind::getDataRel());
866
867   // FIXME: We're emitting LSDA info into a readonly section on COFF, even
868   // though it contains relocatable pointers.  In PIC mode, this is probably a
869   // big runtime hit for C++ apps.  Either the contents of the LSDA need to be
870   // adjusted or this should be a data section.
871   LSDASection =
872     getContext().getCOFFSection(".gcc_except_table",
873                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
874                                 COFF::IMAGE_SCN_MEM_READ,
875                                 SectionKind::getReadOnly());
876   EHFrameSection =
877     getContext().getCOFFSection(".eh_frame",
878                                 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
879                                 COFF::IMAGE_SCN_MEM_READ |
880                                 COFF::IMAGE_SCN_MEM_WRITE,
881                                 SectionKind::getDataRel());
882
883   // Debug info.
884   DwarfAbbrevSection =
885     getContext().getCOFFSection(".debug_abbrev",
886                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
887                                 COFF::IMAGE_SCN_MEM_READ,
888                                 SectionKind::getMetadata());
889   DwarfInfoSection =
890     getContext().getCOFFSection(".debug_info",
891                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
892                                 COFF::IMAGE_SCN_MEM_READ,
893                                 SectionKind::getMetadata());
894   DwarfLineSection =
895     getContext().getCOFFSection(".debug_line",
896                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
897                                 COFF::IMAGE_SCN_MEM_READ,
898                                 SectionKind::getMetadata());
899   DwarfFrameSection =
900     getContext().getCOFFSection(".debug_frame",
901                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
902                                 COFF::IMAGE_SCN_MEM_READ,
903                                 SectionKind::getMetadata());
904   DwarfPubNamesSection =
905     getContext().getCOFFSection(".debug_pubnames",
906                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
907                                 COFF::IMAGE_SCN_MEM_READ,
908                                 SectionKind::getMetadata());
909   DwarfPubTypesSection =
910     getContext().getCOFFSection(".debug_pubtypes",
911                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
912                                 COFF::IMAGE_SCN_MEM_READ,
913                                 SectionKind::getMetadata());
914   DwarfStrSection =
915     getContext().getCOFFSection(".debug_str",
916                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
917                                 COFF::IMAGE_SCN_MEM_READ,
918                                 SectionKind::getMetadata());
919   DwarfLocSection =
920     getContext().getCOFFSection(".debug_loc",
921                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
922                                 COFF::IMAGE_SCN_MEM_READ,
923                                 SectionKind::getMetadata());
924   DwarfARangesSection =
925     getContext().getCOFFSection(".debug_aranges",
926                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
927                                 COFF::IMAGE_SCN_MEM_READ,
928                                 SectionKind::getMetadata());
929   DwarfRangesSection =
930     getContext().getCOFFSection(".debug_ranges",
931                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
932                                 COFF::IMAGE_SCN_MEM_READ,
933                                 SectionKind::getMetadata());
934   DwarfMacroInfoSection =
935     getContext().getCOFFSection(".debug_macinfo",
936                                 COFF::IMAGE_SCN_MEM_DISCARDABLE |
937                                 COFF::IMAGE_SCN_MEM_READ,
938                                 SectionKind::getMetadata());
939
940   DrectveSection =
941     getContext().getCOFFSection(".drectve",
942                                 COFF::IMAGE_SCN_LNK_INFO,
943                                 SectionKind::getMetadata());
944 }
945
946 static unsigned
947 getCOFFSectionFlags(SectionKind K) {
948   unsigned Flags = 0;
949
950   if (K.isMetadata())
951     Flags |=
952       COFF::IMAGE_SCN_MEM_DISCARDABLE;
953   else if (K.isText())
954     Flags |=
955       COFF::IMAGE_SCN_MEM_EXECUTE |
956       COFF::IMAGE_SCN_MEM_READ |
957       COFF::IMAGE_SCN_CNT_CODE;
958   else if (K.isBSS ())
959     Flags |=
960       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
961       COFF::IMAGE_SCN_MEM_READ |
962       COFF::IMAGE_SCN_MEM_WRITE;
963   else if (K.isReadOnly())
964     Flags |=
965       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
966       COFF::IMAGE_SCN_MEM_READ;
967   else if (K.isWriteable())
968     Flags |=
969       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
970       COFF::IMAGE_SCN_MEM_READ |
971       COFF::IMAGE_SCN_MEM_WRITE;
972
973   return Flags;
974 }
975
976 const MCSection *TargetLoweringObjectFileCOFF::
977 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
978                          Mangler *Mang, const TargetMachine &TM) const {
979   return getContext().getCOFFSection(GV->getSection(),
980                                      getCOFFSectionFlags(Kind),
981                                      Kind);
982 }
983
984 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
985   if (Kind.isText())
986     return ".text$";
987   if (Kind.isBSS ())
988     return ".bss$";
989   if (Kind.isWriteable())
990     return ".data$";
991   return ".rdata$";
992 }
993
994
995 const MCSection *TargetLoweringObjectFileCOFF::
996 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
997                        Mangler *Mang, const TargetMachine &TM) const {
998   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
999
1000   // If this global is linkonce/weak and the target handles this by emitting it
1001   // into a 'uniqued' section name, create and return the section now.
1002   if (GV->isWeakForLinker()) {
1003     const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1004     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
1005     MCSymbol *Sym = Mang->getSymbol(GV);
1006     Name.append(Sym->getName().begin() + 1, Sym->getName().end());
1007
1008     unsigned Characteristics = getCOFFSectionFlags(Kind);
1009
1010     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1011
1012     return getContext().getCOFFSection(Name.str(), Characteristics,
1013                           COFF::IMAGE_COMDAT_SELECT_ANY, Kind);
1014   }
1015
1016   if (Kind.isText())
1017     return getTextSection();
1018
1019   return getDataSection();
1020 }
1021