38ae71e67d6549226e95ab0aefd4a33abb82dca0
[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
43 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
44 }
45
46 static bool isSuitableForBSS(const GlobalVariable *GV) {
47   Constant *C = GV->getInitializer();
48   
49   // Must have zero initializer.
50   if (!C->isNullValue())
51     return false;
52   
53   // Leave constant zeros in readonly constant sections, so they can be shared.
54   if (GV->isConstant())
55     return false;
56   
57   // If the global has an explicit section specified, don't put it in BSS.
58   if (!GV->getSection().empty())
59     return false;
60   
61   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
62   if (NoZerosInBSS)
63     return false;
64   
65   // Otherwise, put it in BSS!
66   return true;
67 }
68
69 static bool isConstantString(const Constant *C) {
70   // First check: is we have constant array of i8 terminated with zero
71   const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
72   // Check, if initializer is a null-terminated string
73   if (CVA && CVA->isCString())
74     return true;
75
76   // Another possibility: [1 x i8] zeroinitializer
77   if (isa<ConstantAggregateZero>(C))
78     if (const ArrayType *Ty = dyn_cast<ArrayType>(C->getType()))
79       return (Ty->getElementType() == Type::Int8Ty &&
80               Ty->getNumElements() == 1);
81
82   return false;
83 }
84
85 /// SectionKindForGlobal - This is a top-level target-independent classifier for
86 /// a global variable.  Given an global variable and information from TM, it
87 /// classifies the global in a variety of ways that make various target
88 /// implementations simpler.  The target implementation is free to ignore this
89 /// extra info of course.
90 static SectionKind SectionKindForGlobal(const GlobalValue *GV,
91                                         const TargetMachine &TM) {
92   Reloc::Model ReloModel = TM.getRelocationModel();
93   
94   // Early exit - functions should be always in text sections.
95   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
96   if (GVar == 0)
97     return SectionKind::getText();
98
99   
100   // Handle thread-local data first.
101   if (GVar->isThreadLocal()) {
102     if (isSuitableForBSS(GVar))
103       return SectionKind::getThreadBSS();
104     return SectionKind::getThreadData();
105   }
106
107   // Variable can be easily put to BSS section.
108   if (isSuitableForBSS(GVar))
109     return SectionKind::getBSS();
110
111   Constant *C = GVar->getInitializer();
112   
113   // If the global is marked constant, we can put it into a mergable section,
114   // a mergable string section, or general .data if it contains relocations.
115   if (GVar->isConstant()) {
116     // If the initializer for the global contains something that requires a
117     // relocation, then we may have to drop this into a wriable data section
118     // even though it is marked const.
119     switch (C->getRelocationInfo()) {
120     default: llvm_unreachable("unknown relocation info kind");
121     case Constant::NoRelocation:
122       // If initializer is a null-terminated string, put it in a "cstring"
123       // section if the target has it.
124       if (isConstantString(C))
125         return SectionKind::getMergeableCString();
126       
127       // Otherwise, just drop it into a mergable constant section.  If we have
128       // a section for this size, use it, otherwise use the arbitrary sized
129       // mergable section.
130       switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
131       case 4:  return SectionKind::getMergeableConst4();
132       case 8:  return SectionKind::getMergeableConst8();
133       case 16: return SectionKind::getMergeableConst16();
134       default: return SectionKind::getMergeableConst();
135       }
136       
137     case Constant::LocalRelocation:
138       // In static relocation model, the linker will resolve all addresses, so
139       // the relocation entries will actually be constants by the time the app
140       // starts up.  However, we can't put this into a mergable section, because
141       // the linker doesn't take relocations into consideration when it tries to
142       // merge entries in the section.
143       if (ReloModel == Reloc::Static)
144         return SectionKind::getReadOnly();
145               
146       // Otherwise, the dynamic linker needs to fix it up, put it in the
147       // writable data.rel.local section.
148       return SectionKind::getReadOnlyWithRelLocal();
149               
150     case Constant::GlobalRelocations:
151       // In static relocation model, the linker will resolve all addresses, so
152       // the relocation entries will actually be constants by the time the app
153       // starts up.  However, we can't put this into a mergable section, because
154       // the linker doesn't take relocations into consideration when it tries to
155       // merge entries in the section.
156       if (ReloModel == Reloc::Static)
157         return SectionKind::getReadOnly();
158       
159       // Otherwise, the dynamic linker needs to fix it up, put it in the
160       // writable data.rel section.
161       return SectionKind::getReadOnlyWithRel();
162     }
163   }
164
165   // Okay, this isn't a constant.  If the initializer for the global is going
166   // to require a runtime relocation by the dynamic linker, put it into a more
167   // specific section to improve startup time of the app.  This coalesces these
168   // globals together onto fewer pages, improving the locality of the dynamic
169   // linker.
170   if (ReloModel == Reloc::Static)
171     return SectionKind::getDataNoRel();
172
173   switch (C->getRelocationInfo()) {
174   default: llvm_unreachable("unknown relocation info kind");
175   case Constant::NoRelocation:
176     return SectionKind::getDataNoRel();
177   case Constant::LocalRelocation:
178     return SectionKind::getDataRelLocal();
179   case Constant::GlobalRelocations:
180     return SectionKind::getDataRel();
181   }
182 }
183
184 /// SectionForGlobal - This method computes the appropriate section to emit
185 /// the specified global variable or function definition.  This should not
186 /// be passed external (or available externally) globals.
187 const MCSection *TargetLoweringObjectFile::
188 SectionForGlobal(const GlobalValue *GV, Mangler *Mang,
189                  const TargetMachine &TM) const {
190   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
191          "Can only be used for global definitions");
192   
193   SectionKind Kind = SectionKindForGlobal(GV, TM);
194   
195   // Select section name.
196   if (GV->hasSection()) {
197     // If the target has special section hacks for specifically named globals,
198     // return them now.
199     if (const MCSection *TS = getSpecialCasedSectionGlobals(GV, Mang, Kind))
200       return TS;
201     
202     // If the target has magic semantics for certain section names, make sure to
203     // pick up the flags.  This allows the user to write things with attribute
204     // section and still get the appropriate section flags printed.
205     Kind = getKindForNamedSection(GV->getSection().c_str(), Kind);
206     
207     return getOrCreateSection(GV->getSection().c_str(), false, Kind);
208   }
209
210   
211   // Use default section depending on the 'type' of global
212   return SelectSectionForGlobal(GV, Kind, Mang, TM);
213 }
214
215 // Lame default implementation. Calculate the section name for global.
216 const MCSection *
217 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
218                                                  SectionKind Kind,
219                                                  Mangler *Mang,
220                                                  const TargetMachine &TM) const{
221   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
222   
223   if (Kind.isText())
224     return getTextSection();
225   
226   if (Kind.isBSS() && BSSSection != 0)
227     return BSSSection;
228   
229   if (Kind.isReadOnly() && ReadOnlySection != 0)
230     return ReadOnlySection;
231
232   return getDataSection();
233 }
234
235 /// getSectionForConstant - Given a mergable constant with the
236 /// specified size and relocation information, return a section that it
237 /// should be placed in.
238 const MCSection *
239 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
240   if (Kind.isReadOnly() && ReadOnlySection != 0)
241     return ReadOnlySection;
242   
243   return DataSection;
244 }
245
246
247 const MCSection *TargetLoweringObjectFile::
248 getOrCreateSection(const char *Name, bool isDirective, SectionKind Kind) const {
249   if (MCSection *S = Ctx->GetSection(Name))
250     return S;
251   return MCSection::Create(Name, isDirective, Kind, *Ctx);
252 }
253
254
255
256 //===----------------------------------------------------------------------===//
257 //                                  ELF
258 //===----------------------------------------------------------------------===//
259
260 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
261                                              const TargetMachine &TM) {
262   TargetLoweringObjectFile::Initialize(Ctx, TM);
263   if (!HasCrazyBSS)
264     BSSSection = getOrCreateSection("\t.bss", true, SectionKind::getBSS());
265   else
266     // PPC/Linux doesn't support the .bss directive, it needs .section .bss.
267     // FIXME: Does .section .bss work everywhere??
268     // FIXME2: this should just be handle by the section printer.  We should get
269     // away from syntactic view of the sections and MCSection should just be a
270     // semantic view.
271     BSSSection = getOrCreateSection("\t.bss", false, SectionKind::getBSS());
272
273     
274   TextSection = getOrCreateSection("\t.text", true, SectionKind::getText());
275   DataSection = getOrCreateSection("\t.data", true, SectionKind::getDataRel());
276   ReadOnlySection =
277     getOrCreateSection("\t.rodata", false, SectionKind::getReadOnly());
278   TLSDataSection =
279     getOrCreateSection("\t.tdata", false, SectionKind::getThreadData());
280   CStringSection = getOrCreateSection("\t.rodata.str", true,
281                                SectionKind::getMergeableCString());
282
283   TLSBSSSection = getOrCreateSection("\t.tbss", false, 
284                                      SectionKind::getThreadBSS());
285
286   DataRelSection = getOrCreateSection("\t.data.rel", false,
287                                       SectionKind::getDataRel());
288   DataRelLocalSection = getOrCreateSection("\t.data.rel.local", false,
289                                    SectionKind::getDataRelLocal());
290   DataRelROSection = getOrCreateSection("\t.data.rel.ro", false,
291                                 SectionKind::getReadOnlyWithRel());
292   DataRelROLocalSection =
293     getOrCreateSection("\t.data.rel.ro.local", false,
294                        SectionKind::getReadOnlyWithRelLocal());
295     
296   MergeableConst4Section = getOrCreateSection(".rodata.cst4", false,
297                                 SectionKind::getMergeableConst4());
298   MergeableConst8Section = getOrCreateSection(".rodata.cst8", false,
299                                 SectionKind::getMergeableConst8());
300   MergeableConst16Section = getOrCreateSection(".rodata.cst16", false,
301                                SectionKind::getMergeableConst16());
302
303   StaticCtorSection =
304     getOrCreateSection(".ctors", false, SectionKind::getDataRel());
305   StaticDtorSection =
306     getOrCreateSection(".dtors", false, SectionKind::getDataRel());
307   
308   
309   // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
310   // it contains relocatable pointers.  In PIC mode, this is probably a big
311   // runtime hit for C++ apps.  Either the contents of the LSDA need to be
312   // adjusted or this should be a data section.
313   LSDASection =
314     getOrCreateSection(".gcc_except_table", false, SectionKind::getReadOnly());
315   EHFrameSection =
316     getOrCreateSection(".eh_frame", false, SectionKind::getDataRel());
317 }
318
319
320 SectionKind TargetLoweringObjectFileELF::
321 getKindForNamedSection(const char *Name, SectionKind K) const {
322   if (Name[0] != '.') return K;
323   
324   // Some lame default implementation based on some magic section names.
325   if (strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
326       strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
327       strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
328       strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
329     return SectionKind::getBSS();
330   
331   if (strcmp(Name, ".tdata") == 0 ||
332       strncmp(Name, ".tdata.", 7) == 0 ||
333       strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
334       strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
335     return SectionKind::getThreadData();
336   
337   if (strcmp(Name, ".tbss") == 0 ||
338       strncmp(Name, ".tbss.", 6) == 0 ||
339       strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
340       strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
341     return SectionKind::getThreadBSS();
342   
343   return K;
344 }
345
346 void TargetLoweringObjectFileELF::
347 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
348   Str.push_back(',');
349   Str.push_back('"');
350   
351   if (!Kind.isMetadata())
352     Str.push_back('a');
353   if (Kind.isText())
354     Str.push_back('x');
355   if (Kind.isWriteable())
356     Str.push_back('w');
357   if (Kind.isMergeableCString() ||
358       Kind.isMergeableConst4() ||
359       Kind.isMergeableConst8() ||
360       Kind.isMergeableConst16())
361     Str.push_back('M');
362   if (Kind.isMergeableCString())
363     Str.push_back('S');
364   if (Kind.isThreadLocal())
365     Str.push_back('T');
366   
367   Str.push_back('"');
368   Str.push_back(',');
369   
370   // If comment string is '@', e.g. as on ARM - use '%' instead
371   if (AtIsCommentChar)
372     Str.push_back('%');
373   else
374     Str.push_back('@');
375   
376   const char *KindStr;
377   if (Kind.isBSS() || Kind.isThreadBSS())
378     KindStr = "nobits";
379   else
380     KindStr = "progbits";
381   
382   Str.append(KindStr, KindStr+strlen(KindStr));
383   
384   if (Kind.isMergeableCString()) {
385     // TODO: Eventually handle multiple byte character strings.  For now, all
386     // mergable C strings are single byte.
387     Str.push_back(',');
388     Str.push_back('1');
389   } else if (Kind.isMergeableConst4()) {
390     Str.push_back(',');
391     Str.push_back('4');
392   } else if (Kind.isMergeableConst8()) {
393     Str.push_back(',');
394     Str.push_back('8');
395   } else if (Kind.isMergeableConst16()) {
396     Str.push_back(',');
397     Str.push_back('1');
398     Str.push_back('6');
399   }
400 }
401
402
403 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
404   if (Kind.isText())                 return ".gnu.linkonce.t.";
405   if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
406   
407   if (Kind.isThreadData())           return ".gnu.linkonce.td.";
408   if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
409   
410   if (Kind.isBSS())                  return ".gnu.linkonce.b.";
411   if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
412   if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
413   if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
414   if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
415   
416   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
417   return ".gnu.linkonce.d.rel.ro.";
418 }
419
420 const MCSection *TargetLoweringObjectFileELF::
421 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
422                        Mangler *Mang, const TargetMachine &TM) const {
423   
424   // If this global is linkonce/weak and the target handles this by emitting it
425   // into a 'uniqued' section name, create and return the section now.
426   if (GV->isWeakForLinker()) {
427     const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
428     std::string Name = Mang->makeNameProper(GV->getNameStr());
429     return getOrCreateSection((Prefix+Name).c_str(), false, Kind);
430   }
431   
432   if (Kind.isText()) return TextSection;
433   
434   if (Kind.isMergeableCString()) {
435    assert(CStringSection && "Should have string section prefix");
436     
437     // We also need alignment here.
438     // FIXME: this is getting the alignment of the character, not the
439     // alignment of the global!
440     unsigned Align = 
441       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
442     
443     std::string Name = CStringSection->getName() + "1." + utostr(Align);
444     return getOrCreateSection(Name.c_str(), false,
445                               SectionKind::getMergeableCString());
446   }
447   
448   if (Kind.isMergeableConst()) {
449     if (Kind.isMergeableConst4())
450       return MergeableConst4Section;
451     if (Kind.isMergeableConst8())
452       return MergeableConst8Section;
453     if (Kind.isMergeableConst16())
454       return MergeableConst16Section;
455     return ReadOnlySection;  // .const
456   }
457   
458   if (Kind.isReadOnly())             return ReadOnlySection;
459   
460   if (Kind.isThreadData())           return TLSDataSection;
461   if (Kind.isThreadBSS())            return TLSBSSSection;
462   
463   if (Kind.isBSS())                  return BSSSection;
464   
465   if (Kind.isDataNoRel())            return DataSection;
466   if (Kind.isDataRelLocal())         return DataRelLocalSection;
467   if (Kind.isDataRel())              return DataRelSection;
468   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
469   
470   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
471   return DataRelROSection;
472 }
473
474 /// getSectionForConstant - Given a mergeable constant with the
475 /// specified size and relocation information, return a section that it
476 /// should be placed in.
477 const MCSection *TargetLoweringObjectFileELF::
478 getSectionForConstant(SectionKind Kind) const {
479   if (Kind.isMergeableConst4())
480     return MergeableConst4Section;
481   if (Kind.isMergeableConst8())
482     return MergeableConst8Section;
483   if (Kind.isMergeableConst16())
484     return MergeableConst16Section;
485   if (Kind.isReadOnly())
486     return ReadOnlySection;
487   
488   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
489   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
490   return DataRelROSection;
491 }
492
493 //===----------------------------------------------------------------------===//
494 //                                 MachO
495 //===----------------------------------------------------------------------===//
496
497 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
498                                                const TargetMachine &TM) {
499   TargetLoweringObjectFile::Initialize(Ctx, TM);
500   TextSection = getOrCreateSection("\t.text", true,
501                                    SectionKind::getText());
502   DataSection = getOrCreateSection("\t.data", true, 
503                                    SectionKind::getDataRel());
504   
505   CStringSection = getOrCreateSection("\t.cstring", true,
506                                SectionKind::getMergeableCString());
507   FourByteConstantSection = getOrCreateSection("\t.literal4\n", true,
508                                 SectionKind::getMergeableConst4());
509   EightByteConstantSection = getOrCreateSection("\t.literal8\n", true,
510                                 SectionKind::getMergeableConst8());
511   
512   // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
513   // to using it in -static mode.
514   if (TM.getRelocationModel() != Reloc::Static &&
515       TM.getTargetData()->getPointerSize() == 32)
516     SixteenByteConstantSection = 
517       getOrCreateSection("\t.literal16\n", true, 
518                          SectionKind::getMergeableConst16());
519   else
520     SixteenByteConstantSection = 0;
521   
522   ReadOnlySection = getOrCreateSection("\t.const", true, 
523                                        SectionKind::getReadOnly());
524   
525   TextCoalSection =
526   getOrCreateSection("\t__TEXT,__textcoal_nt,coalesced,pure_instructions",
527                      false, SectionKind::getText());
528   ConstTextCoalSection = getOrCreateSection("\t__TEXT,__const_coal,coalesced",
529                                             false,
530                                            SectionKind::getText());
531   ConstDataCoalSection = getOrCreateSection("\t__DATA,__const_coal,coalesced",
532                                             false, 
533                                           SectionKind::getText());
534   ConstDataSection = getOrCreateSection("\t.const_data", true,
535                                 SectionKind::getReadOnlyWithRel());
536   DataCoalSection = getOrCreateSection("\t__DATA,__datacoal_nt,coalesced",
537                                        false,
538                                        SectionKind::getDataRel());
539
540   if (TM.getRelocationModel() == Reloc::Static) {
541     StaticCtorSection =
542       getOrCreateSection(".constructor", true, SectionKind::getDataRel());
543     StaticDtorSection =
544       getOrCreateSection(".destructor", true, SectionKind::getDataRel());
545   } else {
546     StaticCtorSection =
547       getOrCreateSection(".mod_init_func", true, SectionKind::getDataRel());
548     StaticDtorSection =
549       getOrCreateSection(".mod_term_func", true, SectionKind::getDataRel());
550   }
551   
552   LSDASection = getOrCreateSection("__DATA,__gcc_except_tab", false,
553                                    SectionKind::getDataRel());
554   EHFrameSection =
555     getOrCreateSection("__TEXT,__eh_frame,coalesced,no_toc+strip_static_syms"
556                        "+live_support", false, SectionKind::getReadOnly());
557 }
558
559 const MCSection *TargetLoweringObjectFileMachO::
560 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
561                        Mangler *Mang, const TargetMachine &TM) const {
562   assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
563   
564   if (Kind.isText())
565     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
566   
567   // If this is weak/linkonce, put this in a coalescable section, either in text
568   // or data depending on if it is writable.
569   if (GV->isWeakForLinker()) {
570     if (Kind.isReadOnly())
571       return ConstTextCoalSection;
572     return DataCoalSection;
573   }
574   
575   // FIXME: Alignment check should be handled by section classifier.
576   if (Kind.isMergeableCString()) {
577     Constant *C = cast<GlobalVariable>(GV)->getInitializer();
578     const Type *Ty = cast<ArrayType>(C->getType())->getElementType();
579     const TargetData &TD = *TM.getTargetData();
580     unsigned Size = TD.getTypeAllocSize(Ty);
581     if (Size) {
582       unsigned Align = TD.getPreferredAlignment(cast<GlobalVariable>(GV));
583       if (Align <= 32)
584         return CStringSection;
585     }
586     
587     return ReadOnlySection;
588   }
589   
590   if (Kind.isMergeableConst()) {
591     if (Kind.isMergeableConst4())
592       return FourByteConstantSection;
593     if (Kind.isMergeableConst8())
594       return EightByteConstantSection;
595     if (Kind.isMergeableConst16() && SixteenByteConstantSection)
596       return SixteenByteConstantSection;
597     return ReadOnlySection;  // .const
598   }
599   
600   // FIXME: ROData -> const in -static mode that is relocatable but they happen
601   // by the static linker.  Why not mergeable?
602   if (Kind.isReadOnly())
603     return ReadOnlySection;
604
605   // If this is marked const, put it into a const section.  But if the dynamic
606   // linker needs to write to it, put it in the data segment.
607   if (Kind.isReadOnlyWithRel())
608     return ConstDataSection;
609   
610   // Otherwise, just drop the variable in the normal data section.
611   return DataSection;
612 }
613
614 const MCSection *
615 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
616   // If this constant requires a relocation, we have to put it in the data
617   // segment, not in the text segment.
618   if (Kind.isDataRel())
619     return ConstDataSection;
620   
621   if (Kind.isMergeableConst4())
622     return FourByteConstantSection;
623   if (Kind.isMergeableConst8())
624     return EightByteConstantSection;
625   if (Kind.isMergeableConst16() && SixteenByteConstantSection)
626     return SixteenByteConstantSection;
627   return ReadOnlySection;  // .const
628 }
629
630 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
631 /// not to emit the UsedDirective for some symbols in llvm.used.
632 // FIXME: REMOVE this (rdar://7071300)
633 bool TargetLoweringObjectFileMachO::
634 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
635   /// On Darwin, internally linked data beginning with "L" or "l" does not have
636   /// the directive emitted (this occurs in ObjC metadata).
637   if (!GV) return false;
638     
639   // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
640   if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
641     // FIXME: ObjC metadata is currently emitted as internal symbols that have
642     // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
643     // this horrible hack can go away.
644     const std::string &Name = Mang->getMangledName(GV);
645     if (Name[0] == 'L' || Name[0] == 'l')
646       return false;
647   }
648   
649   return true;
650 }
651
652
653 //===----------------------------------------------------------------------===//
654 //                                  COFF
655 //===----------------------------------------------------------------------===//
656
657 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
658                                               const TargetMachine &TM) {
659   TargetLoweringObjectFile::Initialize(Ctx, TM);
660   TextSection = getOrCreateSection("\t.text", true,
661                                    SectionKind::getText());
662   DataSection = getOrCreateSection("\t.data", true,
663                                    SectionKind::getDataRel());
664   StaticCtorSection =
665     getOrCreateSection(".ctors", false, SectionKind::getDataRel());
666   StaticDtorSection =
667     getOrCreateSection(".dtors", false, SectionKind::getDataRel());
668 }
669
670 void TargetLoweringObjectFileCOFF::
671 getSectionFlagsAsString(SectionKind Kind, SmallVectorImpl<char> &Str) const {
672   // FIXME: Inefficient.
673   std::string Res = ",\"";
674   if (Kind.isText())
675     Res += 'x';
676   if (Kind.isWriteable())
677     Res += 'w';
678   Res += "\"";
679   
680   Str.append(Res.begin(), Res.end());
681 }
682
683 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
684   if (Kind.isText())
685     return ".text$linkonce";
686   if (Kind.isWriteable())
687     return ".data$linkonce";
688   return ".rdata$linkonce";
689 }
690
691
692 const MCSection *TargetLoweringObjectFileCOFF::
693 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
694                        Mangler *Mang, const TargetMachine &TM) const {
695   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
696   
697   // If this global is linkonce/weak and the target handles this by emitting it
698   // into a 'uniqued' section name, create and return the section now.
699   if (GV->isWeakForLinker()) {
700     const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
701     std::string Name = Mang->makeNameProper(GV->getNameStr());
702     return getOrCreateSection((Prefix+Name).c_str(), false, Kind);
703   }
704   
705   if (Kind.isText())
706     return getTextSection();
707   
708   return getDataSection();
709 }
710