8a60086f7a7e9cef397901207c08bb1ac3f39a09
[oota-llvm.git] / lib / Target / TargetLoweringObjectFile.cpp
1 //===-- llvm/Target/TargetLoweringObjectFile.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/Target/TargetLoweringObjectFile.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/GlobalVariable.h"
19 #include "llvm/MC/MCContext.h"
20 #include "llvm/MC/MCSection.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/Support/Mangler.h"
25 #include "llvm/ADT/StringExtras.h"
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 //                              Generic Code
30 //===----------------------------------------------------------------------===//
31
32 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
33   TextSection = 0;
34   DataSection = 0;
35   BSSSection = 0;
36   ReadOnlySection = 0;
37   StaticCtorSection = 0;
38   StaticDtorSection = 0;
39   LSDASection = 0;
40   EHFrameSection = 0;
41
42   DwarfAbbrevSection = 0;
43   DwarfInfoSection = 0;
44   DwarfLineSection = 0;
45   DwarfFrameSection = 0;
46   DwarfPubNamesSection = 0;
47   DwarfPubTypesSection = 0;
48   DwarfDebugInlineSection = 0;
49   DwarfStrSection = 0;
50   DwarfLocSection = 0;
51   DwarfARangesSection = 0;
52   DwarfRangesSection = 0;
53   DwarfMacroInfoSection = 0;
54 }
55
56 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
57 }
58
59 static bool isSuitableForBSS(const GlobalVariable *GV) {
60   Constant *C = GV->getInitializer();
61   
62   // Must have zero initializer.
63   if (!C->isNullValue())
64     return false;
65   
66   // Leave constant zeros in readonly constant sections, so they can be shared.
67   if (GV->isConstant())
68     return false;
69   
70   // If the global has an explicit section specified, don't put it in BSS.
71   if (!GV->getSection().empty())
72     return false;
73   
74   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
75   if (NoZerosInBSS)
76     return false;
77   
78   // Otherwise, put it in BSS!
79   return true;
80 }
81
82 /// IsNullTerminatedString - Return true if the specified constant (which is
83 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
84 /// nul value and contains no other nuls in it.
85 static bool IsNullTerminatedString(const Constant *C) {
86   const ArrayType *ATy = cast<ArrayType>(C->getType());
87   
88   // First check: is we have constant array of i8 terminated with zero
89   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
90     if (ATy->getNumElements() == 0) return false;
91
92     ConstantInt *Null =
93       dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
94     if (Null == 0 || Null->getZExtValue() != 0)
95       return false; // Not null terminated.
96     
97     // Verify that the null doesn't occur anywhere else in the string.
98     for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
99       // Reject constantexpr elements etc.
100       if (!isa<ConstantInt>(CVA->getOperand(i)) ||
101           CVA->getOperand(i) == Null)
102         return false;
103     return true;
104   }
105
106   // Another possibility: [1 x i8] zeroinitializer
107   if (isa<ConstantAggregateZero>(C))
108     return ATy->getNumElements() == 1;
109
110   return false;
111 }
112
113 /// getKindForGlobal - This is a top-level target-independent classifier for
114 /// a global variable.  Given an global variable and information from TM, it
115 /// classifies the global in a variety of ways that make various target
116 /// implementations simpler.  The target implementation is free to ignore this
117 /// extra info of course.
118 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
119                                                        const TargetMachine &TM){
120   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
121          "Can only be used for global definitions");
122   
123   Reloc::Model ReloModel = TM.getRelocationModel();
124   
125   // Early exit - functions should be always in text sections.
126   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
127   if (GVar == 0)
128     return SectionKind::getText();
129
130   
131   // Handle thread-local data first.
132   if (GVar->isThreadLocal()) {
133     if (isSuitableForBSS(GVar))
134       return SectionKind::getThreadBSS();
135     return SectionKind::getThreadData();
136   }
137
138   // Variable can be easily put to BSS section.
139   if (isSuitableForBSS(GVar))
140     return SectionKind::getBSS();
141
142   Constant *C = GVar->getInitializer();
143   
144   // If the global is marked constant, we can put it into a mergable section,
145   // a mergable string section, or general .data if it contains relocations.
146   if (GVar->isConstant()) {
147     // If the initializer for the global contains something that requires a
148     // relocation, then we may have to drop this into a wriable data section
149     // even though it is marked const.
150     switch (C->getRelocationInfo()) {
151     default: llvm_unreachable("unknown relocation info kind");
152     case Constant::NoRelocation:
153       // If initializer is a null-terminated string, put it in a "cstring"
154       // section of the right width.
155       if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
156         if (const IntegerType *ITy = 
157               dyn_cast<IntegerType>(ATy->getElementType())) {
158           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
159                ITy->getBitWidth() == 32) &&
160               IsNullTerminatedString(C)) {
161             if (ITy->getBitWidth() == 8)
162               return SectionKind::getMergeable1ByteCString();
163             if (ITy->getBitWidth() == 16)
164               return SectionKind::getMergeable2ByteCString();
165                                          
166             assert(ITy->getBitWidth() == 32 && "Unknown width");
167             return SectionKind::getMergeable4ByteCString();
168           }
169         }
170       }
171         
172       // Otherwise, just drop it into a mergable constant section.  If we have
173       // a section for this size, use it, otherwise use the arbitrary sized
174       // mergable section.
175       switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
176       case 4:  return SectionKind::getMergeableConst4();
177       case 8:  return SectionKind::getMergeableConst8();
178       case 16: return SectionKind::getMergeableConst16();
179       default: return SectionKind::getMergeableConst();
180       }
181       
182     case Constant::LocalRelocation:
183       // In static relocation model, the linker will resolve all addresses, so
184       // the relocation entries will actually be constants by the time the app
185       // starts up.  However, we can't put this into a mergable section, because
186       // the linker doesn't take relocations into consideration when it tries to
187       // merge entries in the section.
188       if (ReloModel == Reloc::Static)
189         return SectionKind::getReadOnly();
190               
191       // Otherwise, the dynamic linker needs to fix it up, put it in the
192       // writable data.rel.local section.
193       return SectionKind::getReadOnlyWithRelLocal();
194               
195     case Constant::GlobalRelocations:
196       // In static relocation model, the linker will resolve all addresses, so
197       // the relocation entries will actually be constants by the time the app
198       // starts up.  However, we can't put this into a mergable section, because
199       // the linker doesn't take relocations into consideration when it tries to
200       // merge entries in the section.
201       if (ReloModel == Reloc::Static)
202         return SectionKind::getReadOnly();
203       
204       // Otherwise, the dynamic linker needs to fix it up, put it in the
205       // writable data.rel section.
206       return SectionKind::getReadOnlyWithRel();
207     }
208   }
209
210   // Okay, this isn't a constant.  If the initializer for the global is going
211   // to require a runtime relocation by the dynamic linker, put it into a more
212   // specific section to improve startup time of the app.  This coalesces these
213   // globals together onto fewer pages, improving the locality of the dynamic
214   // linker.
215   if (ReloModel == Reloc::Static)
216     return SectionKind::getDataNoRel();
217
218   switch (C->getRelocationInfo()) {
219   default: llvm_unreachable("unknown relocation info kind");
220   case Constant::NoRelocation:
221     return SectionKind::getDataNoRel();
222   case Constant::LocalRelocation:
223     return SectionKind::getDataRelLocal();
224   case Constant::GlobalRelocations:
225     return SectionKind::getDataRel();
226   }
227 }
228
229 /// SectionForGlobal - This method computes the appropriate section to emit
230 /// the specified global variable or function definition.  This should not
231 /// be passed external (or available externally) globals.
232 const MCSection *TargetLoweringObjectFile::
233 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
234                  const TargetMachine &TM) const {
235   // Select section name.
236   if (GV->hasSection())
237     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
238   
239   
240   // Use default section depending on the 'type' of global
241   return SelectSectionForGlobal(GV, Kind, Mang, TM);
242 }
243
244
245 // Lame default implementation. Calculate the section name for global.
246 const MCSection *
247 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
248                                                  SectionKind Kind,
249                                                  Mangler *Mang,
250                                                  const TargetMachine &TM) const{
251   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
252   
253   if (Kind.isText())
254     return getTextSection();
255   
256   if (Kind.isBSS() && BSSSection != 0)
257     return BSSSection;
258   
259   if (Kind.isReadOnly() && ReadOnlySection != 0)
260     return ReadOnlySection;
261
262   return getDataSection();
263 }
264
265 /// getSectionForConstant - Given a mergable constant with the
266 /// specified size and relocation information, return a section that it
267 /// should be placed in.
268 const MCSection *
269 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
270   if (Kind.isReadOnly() && ReadOnlySection != 0)
271     return ReadOnlySection;
272   
273   return DataSection;
274 }
275
276
277
278 //===----------------------------------------------------------------------===//
279 //                                  ELF
280 //===----------------------------------------------------------------------===//
281
282 const MCSection *TargetLoweringObjectFileELF::
283 getELFSection(const char *Name, bool isDirective, SectionKind Kind) const {
284   if (MCSection *S = getContext().GetSection(Name))
285     return S;
286   return MCSection::Create(Name, isDirective, Kind, getContext());
287 }
288
289 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
290                                              const TargetMachine &TM) {
291   TargetLoweringObjectFile::Initialize(Ctx, TM);
292   if (!HasCrazyBSS)
293     BSSSection = getELFSection("\t.bss", true, SectionKind::getBSS());
294   else
295     // PPC/Linux doesn't support the .bss directive, it needs .section .bss.
296     // FIXME: Does .section .bss work everywhere??
297     // FIXME2: this should just be handle by the section printer.  We should get
298     // away from syntactic view of the sections and MCSection should just be a
299     // semantic view.
300     BSSSection = getELFSection("\t.bss", false, SectionKind::getBSS());
301
302     
303   TextSection = getELFSection("\t.text", true, SectionKind::getText());
304   DataSection = getELFSection("\t.data", true, SectionKind::getDataRel());
305   ReadOnlySection =
306     getELFSection("\t.rodata", false, SectionKind::getReadOnly());
307   TLSDataSection =
308     getELFSection("\t.tdata", false, SectionKind::getThreadData());
309   
310   TLSBSSSection = getELFSection("\t.tbss", false, 
311                                      SectionKind::getThreadBSS());
312
313   DataRelSection = getELFSection("\t.data.rel", false,
314                                       SectionKind::getDataRel());
315   DataRelLocalSection = getELFSection("\t.data.rel.local", false,
316                                    SectionKind::getDataRelLocal());
317   DataRelROSection = getELFSection("\t.data.rel.ro", false,
318                                 SectionKind::getReadOnlyWithRel());
319   DataRelROLocalSection =
320     getELFSection("\t.data.rel.ro.local", false,
321                        SectionKind::getReadOnlyWithRelLocal());
322     
323   MergeableConst4Section = getELFSection(".rodata.cst4", false,
324                                 SectionKind::getMergeableConst4());
325   MergeableConst8Section = getELFSection(".rodata.cst8", false,
326                                 SectionKind::getMergeableConst8());
327   MergeableConst16Section = getELFSection(".rodata.cst16", false,
328                                SectionKind::getMergeableConst16());
329
330   StaticCtorSection =
331     getELFSection(".ctors", false, SectionKind::getDataRel());
332   StaticDtorSection =
333     getELFSection(".dtors", false, SectionKind::getDataRel());
334   
335   // Exception Handling Sections.
336   
337   // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
338   // it contains relocatable pointers.  In PIC mode, this is probably a big
339   // runtime hit for C++ apps.  Either the contents of the LSDA need to be
340   // adjusted or this should be a data section.
341   LSDASection =
342     getELFSection(".gcc_except_table", false, SectionKind::getReadOnly());
343   EHFrameSection =
344     getELFSection(".eh_frame", false, SectionKind::getDataRel());
345   
346   // Debug Info Sections.
347   DwarfAbbrevSection = 
348     getELFSection(".debug_abbrev", false, SectionKind::getMetadata());
349   DwarfInfoSection = 
350     getELFSection(".debug_info", false, SectionKind::getMetadata());
351   DwarfLineSection = 
352     getELFSection(".debug_line", false, SectionKind::getMetadata());
353   DwarfFrameSection = 
354     getELFSection(".debug_frame", false, SectionKind::getMetadata());
355   DwarfPubNamesSection = 
356     getELFSection(".debug_pubnames", false, SectionKind::getMetadata());
357   DwarfPubTypesSection = 
358     getELFSection(".debug_pubtypes", false, SectionKind::getMetadata());
359   DwarfStrSection = 
360     getELFSection(".debug_str", false, SectionKind::getMetadata());
361   DwarfLocSection = 
362     getELFSection(".debug_loc", false, SectionKind::getMetadata());
363   DwarfARangesSection = 
364     getELFSection(".debug_aranges", false, SectionKind::getMetadata());
365   DwarfRangesSection = 
366     getELFSection(".debug_ranges", false, SectionKind::getMetadata());
367   DwarfMacroInfoSection = 
368     getELFSection(".debug_macinfo", false, SectionKind::getMetadata());
369 }
370
371
372 static SectionKind 
373 getELFKindForNamedSection(const char *Name, SectionKind K) {
374   if (Name[0] != '.') return K;
375   
376   // Some lame default implementation based on some magic section names.
377   if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
378       strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
379       strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
380       strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
381     return SectionKind::getBSS();
382   
383   if (strcmp(Name, ".tdata") == 0 ||
384       strncmp(Name, ".tdata.", 7) == 0 ||
385       strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
386       strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
387     return SectionKind::getThreadData();
388   
389   if (strcmp(Name, ".tbss") == 0 ||
390       strncmp(Name, ".tbss.", 6) == 0 ||
391       strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
392       strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
393     return SectionKind::getThreadBSS();
394   
395   return K;
396 }
397
398 const MCSection *TargetLoweringObjectFileELF::
399 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 
400                          Mangler *Mang, const TargetMachine &TM) const {
401   // Infer section flags from the section name if we can.
402   Kind = getELFKindForNamedSection(GV->getSection().c_str(), Kind);
403   
404   return getELFSection(GV->getSection().c_str(), false, Kind);
405 }
406       
407       
408       
409 void TargetLoweringObjectFileELF::
410 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
411   Str.push_back(',');
412   Str.push_back('"');
413   
414   if (!Kind.isMetadata())
415     Str.push_back('a');
416   if (Kind.isText())
417     Str.push_back('x');
418   if (Kind.isWriteable())
419     Str.push_back('w');
420   if (Kind.isMergeable1ByteCString() ||
421       Kind.isMergeable2ByteCString() ||
422       Kind.isMergeable4ByteCString() ||
423       Kind.isMergeableConst4() ||
424       Kind.isMergeableConst8() ||
425       Kind.isMergeableConst16())
426     Str.push_back('M');
427   if (Kind.isMergeable1ByteCString() ||
428       Kind.isMergeable2ByteCString() ||
429       Kind.isMergeable4ByteCString())
430     Str.push_back('S');
431   if (Kind.isThreadLocal())
432     Str.push_back('T');
433   
434   Str.push_back('"');
435   Str.push_back(',');
436   
437   // If comment string is '@', e.g. as on ARM - use '%' instead
438   if (AtIsCommentChar)
439     Str.push_back('%');
440   else
441     Str.push_back('@');
442   
443   const char *KindStr;
444   if (Kind.isBSS() || Kind.isThreadBSS())
445     KindStr = "nobits";
446   else
447     KindStr = "progbits";
448   
449   Str.append(KindStr, KindStr+strlen(KindStr));
450   
451   if (Kind.isMergeable1ByteCString()) {
452     Str.push_back(',');
453     Str.push_back('1');
454   } else if (Kind.isMergeable2ByteCString()) {
455     Str.push_back(',');
456     Str.push_back('2');
457   } else if (Kind.isMergeable4ByteCString()) {
458     Str.push_back(',');
459     Str.push_back('4');
460   } else if (Kind.isMergeableConst4()) {
461     Str.push_back(',');
462     Str.push_back('4');
463   } else if (Kind.isMergeableConst8()) {
464     Str.push_back(',');
465     Str.push_back('8');
466   } else if (Kind.isMergeableConst16()) {
467     Str.push_back(',');
468     Str.push_back('1');
469     Str.push_back('6');
470   }
471 }
472
473
474 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
475   if (Kind.isText())                 return ".gnu.linkonce.t.";
476   if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
477   
478   if (Kind.isThreadData())           return ".gnu.linkonce.td.";
479   if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
480   
481   if (Kind.isBSS())                  return ".gnu.linkonce.b.";
482   if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
483   if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
484   if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
485   if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
486   
487   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
488   return ".gnu.linkonce.d.rel.ro.";
489 }
490
491 const MCSection *TargetLoweringObjectFileELF::
492 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
493                        Mangler *Mang, const TargetMachine &TM) const {
494   
495   // If this global is linkonce/weak and the target handles this by emitting it
496   // into a 'uniqued' section name, create and return the section now.
497   if (GV->isWeakForLinker()) {
498     const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
499     std::string Name = Mang->makeNameProper(GV->getNameStr());
500     return getELFSection((Prefix+Name).c_str(), false, Kind);
501   }
502   
503   if (Kind.isText()) return TextSection;
504   
505   if (Kind.isMergeable1ByteCString() ||
506       Kind.isMergeable2ByteCString() ||
507       Kind.isMergeable4ByteCString()) {
508     
509     // We also need alignment here.
510     // FIXME: this is getting the alignment of the character, not the
511     // alignment of the global!
512     unsigned Align = 
513       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
514     
515     const char *SizeSpec = ".rodata.str1.";
516     if (Kind.isMergeable2ByteCString())
517       SizeSpec = ".rodata.str2.";
518     else if (Kind.isMergeable4ByteCString())
519       SizeSpec = ".rodata.str4.";
520     else
521       assert(Kind.isMergeable1ByteCString() && "unknown string width");
522     
523     
524     std::string Name = SizeSpec + utostr(Align);
525     return getELFSection(Name.c_str(), false, Kind);
526   }
527   
528   if (Kind.isMergeableConst()) {
529     if (Kind.isMergeableConst4())
530       return MergeableConst4Section;
531     if (Kind.isMergeableConst8())
532       return MergeableConst8Section;
533     if (Kind.isMergeableConst16())
534       return MergeableConst16Section;
535     return ReadOnlySection;  // .const
536   }
537   
538   if (Kind.isReadOnly())             return ReadOnlySection;
539   
540   if (Kind.isThreadData())           return TLSDataSection;
541   if (Kind.isThreadBSS())            return TLSBSSSection;
542   
543   if (Kind.isBSS())                  return BSSSection;
544   
545   if (Kind.isDataNoRel())            return DataSection;
546   if (Kind.isDataRelLocal())         return DataRelLocalSection;
547   if (Kind.isDataRel())              return DataRelSection;
548   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
549   
550   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
551   return DataRelROSection;
552 }
553
554 /// getSectionForConstant - Given a mergeable constant with the
555 /// specified size and relocation information, return a section that it
556 /// should be placed in.
557 const MCSection *TargetLoweringObjectFileELF::
558 getSectionForConstant(SectionKind Kind) const {
559   if (Kind.isMergeableConst4())
560     return MergeableConst4Section;
561   if (Kind.isMergeableConst8())
562     return MergeableConst8Section;
563   if (Kind.isMergeableConst16())
564     return MergeableConst16Section;
565   if (Kind.isReadOnly())
566     return ReadOnlySection;
567   
568   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
569   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
570   return DataRelROSection;
571 }
572
573 //===----------------------------------------------------------------------===//
574 //                                 MachO
575 //===----------------------------------------------------------------------===//
576
577
578 const MCSection *TargetLoweringObjectFileMachO::
579 getMachOSection(const char *Name, bool isDirective, SectionKind Kind) const {
580   if (MCSection *S = getContext().GetSection(Name))
581     return S;
582   return MCSection::Create(Name, isDirective, Kind, getContext());
583 }
584
585
586
587 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
588                                                const TargetMachine &TM) {
589   TargetLoweringObjectFile::Initialize(Ctx, TM);
590   TextSection = getMachOSection("\t.text", true, SectionKind::getText());
591   DataSection = getMachOSection("\t.data", true, SectionKind::getDataRel());
592   
593   CStringSection = getMachOSection("\t.cstring", true,
594                                    SectionKind::getMergeable1ByteCString());
595   UStringSection = getMachOSection("__TEXT,__ustring", false,
596                                    SectionKind::getMergeable2ByteCString());
597   FourByteConstantSection = getMachOSection("\t.literal4\n", true,
598                                             SectionKind::getMergeableConst4());
599   EightByteConstantSection = getMachOSection("\t.literal8\n", true,
600                                              SectionKind::getMergeableConst8());
601   
602   // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
603   // to using it in -static mode.
604   if (TM.getRelocationModel() != Reloc::Static &&
605       TM.getTargetData()->getPointerSize() == 32)
606     SixteenByteConstantSection = 
607       getMachOSection("\t.literal16\n", true, 
608                       SectionKind::getMergeableConst16());
609   else
610     SixteenByteConstantSection = 0;
611   
612   ReadOnlySection = getMachOSection("\t.const", true,
613                                     SectionKind::getReadOnly());
614   
615   TextCoalSection =
616     getMachOSection("\t__TEXT,__textcoal_nt,coalesced,pure_instructions",
617                     false, SectionKind::getText());
618   ConstTextCoalSection = getMachOSection("\t__TEXT,__const_coal,coalesced",
619                                          false, SectionKind::getText());
620   ConstDataCoalSection = getMachOSection("\t__DATA,__const_coal,coalesced",
621                                          false, SectionKind::getText());
622   ConstDataSection = getMachOSection("\t.const_data", true,
623                                      SectionKind::getReadOnlyWithRel());
624   DataCoalSection = getMachOSection("\t__DATA,__datacoal_nt,coalesced",
625                                     false, SectionKind::getDataRel());
626
627   if (TM.getRelocationModel() == Reloc::Static) {
628     StaticCtorSection =
629       getMachOSection(".constructor", true, SectionKind::getDataRel());
630     StaticDtorSection =
631       getMachOSection(".destructor", true, SectionKind::getDataRel());
632   } else {
633     StaticCtorSection =
634       getMachOSection(".mod_init_func", true, SectionKind::getDataRel());
635     StaticDtorSection =
636       getMachOSection(".mod_term_func", true, SectionKind::getDataRel());
637   }
638   
639   // Exception Handling.
640   LSDASection = getMachOSection("__DATA,__gcc_except_tab", false,
641                                 SectionKind::getDataRel());
642   EHFrameSection =
643     getMachOSection("__TEXT,__eh_frame,coalesced,no_toc+strip_static_syms"
644                     "+live_support", false, SectionKind::getReadOnly());
645
646   // Debug Information.
647   // FIXME: Don't use 'directive' syntax: need flags for debug/regular??
648   // FIXME: Need __DWARF segment.
649   DwarfAbbrevSection = 
650     getMachOSection(".section __DWARF,__debug_abbrev,regular,debug", true,
651                     SectionKind::getMetadata());
652   DwarfInfoSection =  
653     getMachOSection(".section __DWARF,__debug_info,regular,debug", true,
654                     SectionKind::getMetadata());
655   DwarfLineSection =  
656     getMachOSection(".section __DWARF,__debug_line,regular,debug", true,
657                     SectionKind::getMetadata());
658   DwarfFrameSection =  
659     getMachOSection(".section __DWARF,__debug_frame,regular,debug", true,
660                     SectionKind::getMetadata());
661   DwarfPubNamesSection =  
662     getMachOSection(".section __DWARF,__debug_pubnames,regular,debug", true,
663                     SectionKind::getMetadata());
664   DwarfPubTypesSection =  
665     getMachOSection(".section __DWARF,__debug_pubtypes,regular,debug", true,
666                     SectionKind::getMetadata());
667   DwarfStrSection =  
668     getMachOSection(".section __DWARF,__debug_str,regular,debug", true,
669                     SectionKind::getMetadata());
670   DwarfLocSection =  
671     getMachOSection(".section __DWARF,__debug_loc,regular,debug", true,
672                     SectionKind::getMetadata());
673   DwarfARangesSection =  
674     getMachOSection(".section __DWARF,__debug_aranges,regular,debug", true,
675                     SectionKind::getMetadata());
676   DwarfRangesSection =  
677     getMachOSection(".section __DWARF,__debug_ranges,regular,debug", true,
678                     SectionKind::getMetadata());
679   DwarfMacroInfoSection =  
680     getMachOSection(".section __DWARF,__debug_macinfo,regular,debug", true,
681                     SectionKind::getMetadata());
682   DwarfDebugInlineSection = 
683     getMachOSection(".section __DWARF,__debug_inlined,regular,debug", true,
684                     SectionKind::getMetadata());
685 }
686
687 const MCSection *TargetLoweringObjectFileMachO::
688 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 
689                          Mangler *Mang, const TargetMachine &TM) const {
690   return getMachOSection(GV->getSection().c_str(), false, Kind);
691 }
692
693 const MCSection *TargetLoweringObjectFileMachO::
694 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
695                        Mangler *Mang, const TargetMachine &TM) const {
696   assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
697   
698   if (Kind.isText())
699     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
700   
701   // If this is weak/linkonce, put this in a coalescable section, either in text
702   // or data depending on if it is writable.
703   if (GV->isWeakForLinker()) {
704     if (Kind.isReadOnly())
705       return ConstTextCoalSection;
706     return DataCoalSection;
707   }
708   
709   // FIXME: Alignment check should be handled by section classifier.
710   if (Kind.isMergeable1ByteCString() ||
711       Kind.isMergeable2ByteCString()) {
712     if (TM.getTargetData()->getPreferredAlignment(
713                                               cast<GlobalVariable>(GV)) < 32) {
714       if (Kind.isMergeable1ByteCString())
715         return CStringSection;
716       assert(Kind.isMergeable2ByteCString());
717       return UStringSection;
718     }
719   }
720   
721   if (Kind.isMergeableConst()) {
722     if (Kind.isMergeableConst4())
723       return FourByteConstantSection;
724     if (Kind.isMergeableConst8())
725       return EightByteConstantSection;
726     if (Kind.isMergeableConst16() && SixteenByteConstantSection)
727       return SixteenByteConstantSection;
728   }
729
730   // Otherwise, if it is readonly, but not something we can specially optimize,
731   // just drop it in .const.
732   if (Kind.isReadOnly())
733     return ReadOnlySection;
734
735   // If this is marked const, put it into a const section.  But if the dynamic
736   // linker needs to write to it, put it in the data segment.
737   if (Kind.isReadOnlyWithRel())
738     return ConstDataSection;
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())
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     const std::string &Name = Mang->getMangledName(GV);
775     if (Name[0] == 'L' || Name[0] == 'l')
776       return false;
777   }
778   
779   return true;
780 }
781
782
783 //===----------------------------------------------------------------------===//
784 //                                  COFF
785 //===----------------------------------------------------------------------===//
786
787
788 const MCSection *TargetLoweringObjectFileCOFF::
789 getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
790   if (MCSection *S = getContext().GetSection(Name))
791     return S;
792   return MCSection::Create(Name, isDirective, Kind, getContext());
793 }
794
795 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
796                                               const TargetMachine &TM) {
797   TargetLoweringObjectFile::Initialize(Ctx, TM);
798   TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
799   DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
800   StaticCtorSection =
801     getCOFFSection(".ctors", false, SectionKind::getDataRel());
802   StaticDtorSection =
803     getCOFFSection(".dtors", false, SectionKind::getDataRel());
804   
805   
806   // Debug info.
807   // FIXME: Don't use 'directive' mode here.
808   DwarfAbbrevSection =  
809     getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
810                    true, SectionKind::getMetadata());
811   DwarfInfoSection =    
812     getCOFFSection("\t.section\t.debug_info,\"dr\"",
813                    true, SectionKind::getMetadata());
814   DwarfLineSection =    
815     getCOFFSection("\t.section\t.debug_line,\"dr\"",
816                    true, SectionKind::getMetadata());
817   DwarfFrameSection =   
818     getCOFFSection("\t.section\t.debug_frame,\"dr\"",
819                    true, SectionKind::getMetadata());
820   DwarfPubNamesSection =
821     getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
822                    true, SectionKind::getMetadata());
823   DwarfPubTypesSection =
824     getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
825                    true, SectionKind::getMetadata());
826   DwarfStrSection =     
827     getCOFFSection("\t.section\t.debug_str,\"dr\"",
828                    true, SectionKind::getMetadata());
829   DwarfLocSection =     
830     getCOFFSection("\t.section\t.debug_loc,\"dr\"",
831                    true, SectionKind::getMetadata());
832   DwarfARangesSection = 
833     getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
834                    true, SectionKind::getMetadata());
835   DwarfRangesSection =  
836     getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
837                    true, SectionKind::getMetadata());
838   DwarfMacroInfoSection = 
839     getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
840                    true, SectionKind::getMetadata());
841 }
842
843 const MCSection *TargetLoweringObjectFileCOFF::
844 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, 
845                          Mangler *Mang, const TargetMachine &TM) const {
846   return getCOFFSection(GV->getSection().c_str(), false, Kind);
847 }
848
849
850 void TargetLoweringObjectFileCOFF::
851 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
852   // FIXME: Inefficient.
853   std::string Res = ",\"";
854   if (Kind.isText())
855     Res += 'x';
856   if (Kind.isWriteable())
857     Res += 'w';
858   Res += "\"";
859   
860   Str.append(Res.begin(), Res.end());
861 }
862
863 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
864   if (Kind.isText())
865     return ".text$linkonce";
866   if (Kind.isWriteable())
867     return ".data$linkonce";
868   return ".rdata$linkonce";
869 }
870
871
872 const MCSection *TargetLoweringObjectFileCOFF::
873 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
874                        Mangler *Mang, const TargetMachine &TM) const {
875   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
876   
877   // If this global is linkonce/weak and the target handles this by emitting it
878   // into a 'uniqued' section name, create and return the section now.
879   if (GV->isWeakForLinker()) {
880     const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
881     std::string Name = Mang->makeNameProper(GV->getNameStr());
882     return getCOFFSection((Prefix+Name).c_str(), false, Kind);
883   }
884   
885   if (Kind.isText())
886     return getTextSection();
887   
888   return getDataSection();
889 }
890