--- Reverse-merging r82282 into '.':
[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/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCSectionMachO.h"
23 #include "llvm/MC/MCSectionELF.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
30 using namespace llvm;
31
32 //===----------------------------------------------------------------------===//
33 //                              Generic Code
34 //===----------------------------------------------------------------------===//
35
36 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
37   TextSection = 0;
38   DataSection = 0;
39   BSSSection = 0;
40   ReadOnlySection = 0;
41   StaticCtorSection = 0;
42   StaticDtorSection = 0;
43   LSDASection = 0;
44   EHFrameSection = 0;
45
46   DwarfAbbrevSection = 0;
47   DwarfInfoSection = 0;
48   DwarfLineSection = 0;
49   DwarfFrameSection = 0;
50   DwarfPubNamesSection = 0;
51   DwarfPubTypesSection = 0;
52   DwarfDebugInlineSection = 0;
53   DwarfStrSection = 0;
54   DwarfLocSection = 0;
55   DwarfARangesSection = 0;
56   DwarfRangesSection = 0;
57   DwarfMacroInfoSection = 0;
58 }
59
60 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
61 }
62
63 static bool isSuitableForBSS(const GlobalVariable *GV) {
64   Constant *C = GV->getInitializer();
65
66   // Must have zero initializer.
67   if (!C->isNullValue())
68     return false;
69
70   // Leave constant zeros in readonly constant sections, so they can be shared.
71   if (GV->isConstant())
72     return false;
73
74   // If the global has an explicit section specified, don't put it in BSS.
75   if (!GV->getSection().empty())
76     return false;
77
78   // If -nozero-initialized-in-bss is specified, don't ever use BSS.
79   if (NoZerosInBSS)
80     return false;
81
82   // Otherwise, put it in BSS!
83   return true;
84 }
85
86 /// IsNullTerminatedString - Return true if the specified constant (which is
87 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
88 /// nul value and contains no other nuls in it.
89 static bool IsNullTerminatedString(const Constant *C) {
90   const ArrayType *ATy = cast<ArrayType>(C->getType());
91
92   // First check: is we have constant array of i8 terminated with zero
93   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
94     if (ATy->getNumElements() == 0) return false;
95
96     ConstantInt *Null =
97       dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
98     if (Null == 0 || Null->getZExtValue() != 0)
99       return false; // Not null terminated.
100
101     // Verify that the null doesn't occur anywhere else in the string.
102     for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
103       // Reject constantexpr elements etc.
104       if (!isa<ConstantInt>(CVA->getOperand(i)) ||
105           CVA->getOperand(i) == Null)
106         return false;
107     return true;
108   }
109
110   // Another possibility: [1 x i8] zeroinitializer
111   if (isa<ConstantAggregateZero>(C))
112     return ATy->getNumElements() == 1;
113
114   return false;
115 }
116
117 /// getKindForGlobal - This is a top-level target-independent classifier for
118 /// a global variable.  Given an global variable and information from TM, it
119 /// classifies the global in a variety of ways that make various target
120 /// implementations simpler.  The target implementation is free to ignore this
121 /// extra info of course.
122 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
123                                                        const TargetMachine &TM){
124   assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
125          "Can only be used for global definitions");
126
127   Reloc::Model ReloModel = TM.getRelocationModel();
128
129   // Early exit - functions should be always in text sections.
130   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
131   if (GVar == 0)
132     return SectionKind::getText();
133
134   // Handle thread-local data first.
135   if (GVar->isThreadLocal()) {
136     if (isSuitableForBSS(GVar))
137       return SectionKind::getThreadBSS();
138     return SectionKind::getThreadData();
139   }
140
141   // Variable can be easily put to BSS section.
142   if (isSuitableForBSS(GVar))
143     return SectionKind::getBSS();
144
145   Constant *C = GVar->getInitializer();
146
147   // If the global is marked constant, we can put it into a mergable section,
148   // a mergable string section, or general .data if it contains relocations.
149   if (GVar->isConstant()) {
150     // If the initializer for the global contains something that requires a
151     // relocation, then we may have to drop this into a wriable data section
152     // even though it is marked const.
153     switch (C->getRelocationInfo()) {
154     default: llvm_unreachable("unknown relocation info kind");
155     case Constant::NoRelocation:
156       // If initializer is a null-terminated string, put it in a "cstring"
157       // section of the right width.
158       if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
159         if (const IntegerType *ITy =
160               dyn_cast<IntegerType>(ATy->getElementType())) {
161           if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
162                ITy->getBitWidth() == 32) &&
163               IsNullTerminatedString(C)) {
164             if (ITy->getBitWidth() == 8)
165               return SectionKind::getMergeable1ByteCString();
166             if (ITy->getBitWidth() == 16)
167               return SectionKind::getMergeable2ByteCString();
168
169             assert(ITy->getBitWidth() == 32 && "Unknown width");
170             return SectionKind::getMergeable4ByteCString();
171           }
172         }
173       }
174
175       // Otherwise, just drop it into a mergable constant section.  If we have
176       // a section for this size, use it, otherwise use the arbitrary sized
177       // mergable section.
178       switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
179       case 4:  return SectionKind::getMergeableConst4();
180       case 8:  return SectionKind::getMergeableConst8();
181       case 16: return SectionKind::getMergeableConst16();
182       default: return SectionKind::getMergeableConst();
183       }
184
185     case Constant::LocalRelocation:
186       // In static relocation model, the linker will resolve all addresses, so
187       // the relocation entries will actually be constants by the time the app
188       // starts up.  However, we can't put this into a mergable section, because
189       // the linker doesn't take relocations into consideration when it tries to
190       // merge entries in the section.
191       if (ReloModel == Reloc::Static)
192         return SectionKind::getReadOnly();
193
194       // Otherwise, the dynamic linker needs to fix it up, put it in the
195       // writable data.rel.local section.
196       return SectionKind::getReadOnlyWithRelLocal();
197
198     case Constant::GlobalRelocations:
199       // In static relocation model, the linker will resolve all addresses, so
200       // the relocation entries will actually be constants by the time the app
201       // starts up.  However, we can't put this into a mergable section, because
202       // the linker doesn't take relocations into consideration when it tries to
203       // merge entries in the section.
204       if (ReloModel == Reloc::Static)
205         return SectionKind::getReadOnly();
206
207       // Otherwise, the dynamic linker needs to fix it up, put it in the
208       // writable data.rel section.
209       return SectionKind::getReadOnlyWithRel();
210     }
211   }
212
213   // Okay, this isn't a constant.  If the initializer for the global is going
214   // to require a runtime relocation by the dynamic linker, put it into a more
215   // specific section to improve startup time of the app.  This coalesces these
216   // globals together onto fewer pages, improving the locality of the dynamic
217   // linker.
218   if (ReloModel == Reloc::Static)
219     return SectionKind::getDataNoRel();
220
221   switch (C->getRelocationInfo()) {
222   default: llvm_unreachable("unknown relocation info kind");
223   case Constant::NoRelocation:
224     return SectionKind::getDataNoRel();
225   case Constant::LocalRelocation:
226     return SectionKind::getDataRelLocal();
227   case Constant::GlobalRelocations:
228     return SectionKind::getDataRel();
229   }
230 }
231
232 /// SectionForGlobal - This method computes the appropriate section to emit
233 /// the specified global variable or function definition.  This should not
234 /// be passed external (or available externally) globals.
235 const MCSection *TargetLoweringObjectFile::
236 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
237                  const TargetMachine &TM) const {
238   // Select section name.
239   if (GV->hasSection())
240     return getExplicitSectionGlobal(GV, Kind, Mang, TM);
241
242
243   // Use default section depending on the 'type' of global
244   return SelectSectionForGlobal(GV, Kind, Mang, TM);
245 }
246
247
248 // Lame default implementation. Calculate the section name for global.
249 const MCSection *
250 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
251                                                  SectionKind Kind,
252                                                  Mangler *Mang,
253                                                  const TargetMachine &TM) const{
254   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
255
256   if (Kind.isText())
257     return getTextSection();
258
259   if (Kind.isBSS() && BSSSection != 0)
260     return BSSSection;
261
262   if (Kind.isReadOnly() && ReadOnlySection != 0)
263     return ReadOnlySection;
264
265   return getDataSection();
266 }
267
268 /// getSectionForConstant - Given a mergable constant with the
269 /// specified size and relocation information, return a section that it
270 /// should be placed in.
271 const MCSection *
272 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
273   if (Kind.isReadOnly() && ReadOnlySection != 0)
274     return ReadOnlySection;
275
276   return DataSection;
277 }
278
279 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a
280 /// pc-relative reference to the specified global variable from exception
281 /// handling information.  In addition to the symbol, this returns
282 /// by-reference:
283 ///
284 /// IsIndirect - True if the returned symbol is actually a stub that contains
285 ///    the address of the symbol, false if the symbol is the global itself.
286 ///
287 /// IsPCRel - True if the symbol reference is already pc-relative, false if
288 ///    the caller needs to subtract off the address of the reference from the
289 ///    symbol.
290 ///
291 const MCExpr *TargetLoweringObjectFile::
292 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
293                                  MachineModuleInfo *MMI,
294                                  bool &IsIndirect, bool &IsPCRel) const {
295   // The generic implementation of this just returns a direct reference to the
296   // symbol.
297   IsIndirect = false;
298   IsPCRel    = false;
299   
300   SmallString<128> Name;
301   Mang->getNameWithPrefix(Name, GV, false);
302   return MCSymbolRefExpr::Create(Name.str(), getContext());
303 }
304
305
306 //===----------------------------------------------------------------------===//
307 //                                  ELF
308 //===----------------------------------------------------------------------===//
309 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
310
311 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
312   // If we have the section uniquing map, free it.
313   delete (ELFUniqueMapTy*)UniquingMap;
314 }
315
316 const MCSection *TargetLoweringObjectFileELF::
317 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
318               SectionKind Kind, bool IsExplicit) const {
319   if (UniquingMap == 0)
320     UniquingMap = new ELFUniqueMapTy();
321   ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
322
323   // Do the lookup, if we have a hit, return it.
324   const MCSectionELF *&Entry = Map[Section];
325   if (Entry) return Entry;
326
327   return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
328                                       getContext());
329 }
330
331 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
332                                              const TargetMachine &TM) {
333   if (UniquingMap != 0)
334     ((ELFUniqueMapTy*)UniquingMap)->clear();
335   TargetLoweringObjectFile::Initialize(Ctx, TM);
336
337   BSSSection =
338     getELFSection(".bss", MCSectionELF::SHT_NOBITS,
339                   MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
340                   SectionKind::getBSS());
341
342   TextSection =
343     getELFSection(".text", MCSectionELF::SHT_PROGBITS,
344                   MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
345                   SectionKind::getText());
346
347   DataSection =
348     getELFSection(".data", MCSectionELF::SHT_PROGBITS,
349                   MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
350                   SectionKind::getDataRel());
351
352   ReadOnlySection =
353     getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
354                   MCSectionELF::SHF_ALLOC,
355                   SectionKind::getReadOnly());
356
357   TLSDataSection =
358     getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
359                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
360                   MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
361
362   TLSBSSSection =
363     getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
364                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
365                   MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
366
367   DataRelSection =
368     getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
369                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
370                   SectionKind::getDataRel());
371
372   DataRelLocalSection =
373     getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
374                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
375                   SectionKind::getDataRelLocal());
376
377   DataRelROSection =
378     getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
379                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
380                   SectionKind::getReadOnlyWithRel());
381
382   DataRelROLocalSection =
383     getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
384                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
385                   SectionKind::getReadOnlyWithRelLocal());
386
387   MergeableConst4Section =
388     getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
389                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
390                   SectionKind::getMergeableConst4());
391
392   MergeableConst8Section =
393     getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
394                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
395                   SectionKind::getMergeableConst8());
396
397   MergeableConst16Section =
398     getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
399                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
400                   SectionKind::getMergeableConst16());
401
402   StaticCtorSection =
403     getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
404                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
405                   SectionKind::getDataRel());
406
407   StaticDtorSection =
408     getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
409                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
410                   SectionKind::getDataRel());
411
412   // Exception Handling Sections.
413
414   // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
415   // it contains relocatable pointers.  In PIC mode, this is probably a big
416   // runtime hit for C++ apps.  Either the contents of the LSDA need to be
417   // adjusted or this should be a data section.
418   LSDASection =
419     getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
420                   MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
421   EHFrameSection =
422     getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
423                   MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
424                   SectionKind::getDataRel());
425
426   // Debug Info Sections.
427   DwarfAbbrevSection =
428     getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
429                   SectionKind::getMetadata());
430   DwarfInfoSection =
431     getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
432                   SectionKind::getMetadata());
433   DwarfLineSection =
434     getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
435                   SectionKind::getMetadata());
436   DwarfFrameSection =
437     getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
438                   SectionKind::getMetadata());
439   DwarfPubNamesSection =
440     getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
441                   SectionKind::getMetadata());
442   DwarfPubTypesSection =
443     getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
444                   SectionKind::getMetadata());
445   DwarfStrSection =
446     getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
447                   SectionKind::getMetadata());
448   DwarfLocSection =
449     getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
450                   SectionKind::getMetadata());
451   DwarfARangesSection =
452     getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
453                   SectionKind::getMetadata());
454   DwarfRangesSection =
455     getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
456                   SectionKind::getMetadata());
457   DwarfMacroInfoSection =
458     getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
459                   SectionKind::getMetadata());
460 }
461
462
463 static SectionKind
464 getELFKindForNamedSection(const char *Name, SectionKind K) {
465   if (Name[0] != '.') return K;
466
467   // Some lame default implementation based on some magic section names.
468   if (strcmp(Name, ".bss") == 0 ||
469       strncmp(Name, ".bss.", 5) == 0 ||
470       strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
471       strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
472       strcmp(Name, ".sbss") == 0 ||
473       strncmp(Name, ".sbss.", 6) == 0 ||
474       strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
475       strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
476     return SectionKind::getBSS();
477
478   if (strcmp(Name, ".tdata") == 0 ||
479       strncmp(Name, ".tdata.", 7) == 0 ||
480       strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
481       strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
482     return SectionKind::getThreadData();
483
484   if (strcmp(Name, ".tbss") == 0 ||
485       strncmp(Name, ".tbss.", 6) == 0 ||
486       strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
487       strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
488     return SectionKind::getThreadBSS();
489
490   return K;
491 }
492
493
494 static unsigned
495 getELFSectionType(const char *Name, SectionKind K) {
496
497   if (strcmp(Name, ".init_array") == 0)
498     return MCSectionELF::SHT_INIT_ARRAY;
499
500   if (strcmp(Name, ".fini_array") == 0)
501     return MCSectionELF::SHT_FINI_ARRAY;
502
503   if (strcmp(Name, ".preinit_array") == 0)
504     return MCSectionELF::SHT_PREINIT_ARRAY;
505
506   if (K.isBSS() || K.isThreadBSS())
507     return MCSectionELF::SHT_NOBITS;
508
509   return MCSectionELF::SHT_PROGBITS;
510 }
511
512
513 static unsigned
514 getELFSectionFlags(SectionKind K) {
515   unsigned Flags = 0;
516
517   if (!K.isMetadata())
518     Flags |= MCSectionELF::SHF_ALLOC;
519
520   if (K.isText())
521     Flags |= MCSectionELF::SHF_EXECINSTR;
522
523   if (K.isWriteable())
524     Flags |= MCSectionELF::SHF_WRITE;
525
526   if (K.isThreadLocal())
527     Flags |= MCSectionELF::SHF_TLS;
528
529   // K.isMergeableConst() is left out to honour PR4650
530   if (K.isMergeableCString() || K.isMergeableConst4() ||
531       K.isMergeableConst8() || K.isMergeableConst16())
532     Flags |= MCSectionELF::SHF_MERGE;
533
534   if (K.isMergeableCString())
535     Flags |= MCSectionELF::SHF_STRINGS;
536
537   return Flags;
538 }
539
540
541 const MCSection *TargetLoweringObjectFileELF::
542 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
543                          Mangler *Mang, const TargetMachine &TM) const {
544   const char *SectionName = GV->getSection().c_str();
545
546   // Infer section flags from the section name if we can.
547   Kind = getELFKindForNamedSection(SectionName, Kind);
548
549   return getELFSection(SectionName,
550                        getELFSectionType(SectionName, Kind),
551                        getELFSectionFlags(Kind), Kind, true);
552 }
553
554 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
555   if (Kind.isText())                 return ".gnu.linkonce.t.";
556   if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
557
558   if (Kind.isThreadData())           return ".gnu.linkonce.td.";
559   if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
560
561   if (Kind.isBSS())                  return ".gnu.linkonce.b.";
562   if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
563   if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
564   if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
565   if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
566
567   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
568   return ".gnu.linkonce.d.rel.ro.";
569 }
570
571 const MCSection *TargetLoweringObjectFileELF::
572 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
573                        Mangler *Mang, const TargetMachine &TM) const {
574
575   // If this global is linkonce/weak and the target handles this by emitting it
576   // into a 'uniqued' section name, create and return the section now.
577   if (GV->isWeakForLinker()) {
578     const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
579     std::string Name = Mang->makeNameProper(GV->getNameStr());
580
581     return getELFSection((Prefix+Name).c_str(),
582                          getELFSectionType((Prefix+Name).c_str(), Kind),
583                          getELFSectionFlags(Kind),
584                          Kind);
585   }
586
587   if (Kind.isText()) return TextSection;
588
589   if (Kind.isMergeable1ByteCString() ||
590       Kind.isMergeable2ByteCString() ||
591       Kind.isMergeable4ByteCString()) {
592
593     // We also need alignment here.
594     // FIXME: this is getting the alignment of the character, not the
595     // alignment of the global!
596     unsigned Align =
597       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
598
599     const char *SizeSpec = ".rodata.str1.";
600     if (Kind.isMergeable2ByteCString())
601       SizeSpec = ".rodata.str2.";
602     else if (Kind.isMergeable4ByteCString())
603       SizeSpec = ".rodata.str4.";
604     else
605       assert(Kind.isMergeable1ByteCString() && "unknown string width");
606
607
608     std::string Name = SizeSpec + utostr(Align);
609     return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS,
610                          MCSectionELF::SHF_ALLOC |
611                          MCSectionELF::SHF_MERGE |
612                          MCSectionELF::SHF_STRINGS,
613                          Kind);
614   }
615
616   if (Kind.isMergeableConst()) {
617     if (Kind.isMergeableConst4() && MergeableConst4Section)
618       return MergeableConst4Section;
619     if (Kind.isMergeableConst8() && MergeableConst8Section)
620       return MergeableConst8Section;
621     if (Kind.isMergeableConst16() && MergeableConst16Section)
622       return MergeableConst16Section;
623     return ReadOnlySection;  // .const
624   }
625
626   if (Kind.isReadOnly())             return ReadOnlySection;
627
628   if (Kind.isThreadData())           return TLSDataSection;
629   if (Kind.isThreadBSS())            return TLSBSSSection;
630
631   if (Kind.isBSS())                  return BSSSection;
632
633   if (Kind.isDataNoRel())            return DataSection;
634   if (Kind.isDataRelLocal())         return DataRelLocalSection;
635   if (Kind.isDataRel())              return DataRelSection;
636   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
637
638   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
639   return DataRelROSection;
640 }
641
642 /// getSectionForConstant - Given a mergeable constant with the
643 /// specified size and relocation information, return a section that it
644 /// should be placed in.
645 const MCSection *TargetLoweringObjectFileELF::
646 getSectionForConstant(SectionKind Kind) const {
647   if (Kind.isMergeableConst4() && MergeableConst4Section)
648     return MergeableConst4Section;
649   if (Kind.isMergeableConst8() && MergeableConst8Section)
650     return MergeableConst8Section;
651   if (Kind.isMergeableConst16() && MergeableConst16Section)
652     return MergeableConst16Section;
653   if (Kind.isReadOnly())
654     return ReadOnlySection;
655
656   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
657   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
658   return DataRelROSection;
659 }
660
661 //===----------------------------------------------------------------------===//
662 //                                 MachO
663 //===----------------------------------------------------------------------===//
664
665 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
666
667 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
668   // If we have the MachO uniquing map, free it.
669   delete (MachOUniqueMapTy*)UniquingMap;
670 }
671
672
673 const MCSectionMachO *TargetLoweringObjectFileMachO::
674 getMachOSection(const StringRef &Segment, const StringRef &Section,
675                 unsigned TypeAndAttributes,
676                 unsigned Reserved2, SectionKind Kind) const {
677   // We unique sections by their segment/section pair.  The returned section
678   // may not have the same flags as the requested section, if so this should be
679   // diagnosed by the client as an error.
680
681   // Create the map if it doesn't already exist.
682   if (UniquingMap == 0)
683     UniquingMap = new MachOUniqueMapTy();
684   MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
685
686   // Form the name to look up.
687   SmallString<64> Name;
688   Name += Segment;
689   Name.push_back(',');
690   Name += Section;
691
692   // Do the lookup, if we have a hit, return it.
693   const MCSectionMachO *&Entry = Map[Name.str()];
694   if (Entry) return Entry;
695
696   // Otherwise, return a new section.
697   return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
698                                         Reserved2, Kind, getContext());
699 }
700
701
702 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
703                                                const TargetMachine &TM) {
704   if (UniquingMap != 0)
705     ((MachOUniqueMapTy*)UniquingMap)->clear();
706   TargetLoweringObjectFile::Initialize(Ctx, TM);
707
708   TextSection // .text
709     = getMachOSection("__TEXT", "__text",
710                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
711                       SectionKind::getText());
712   DataSection // .data
713     = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
714
715   CStringSection // .cstring
716     = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
717                       SectionKind::getMergeable1ByteCString());
718   UStringSection
719     = getMachOSection("__TEXT","__ustring", 0,
720                       SectionKind::getMergeable2ByteCString());
721   FourByteConstantSection // .literal4
722     = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
723                       SectionKind::getMergeableConst4());
724   EightByteConstantSection // .literal8
725     = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
726                       SectionKind::getMergeableConst8());
727
728   // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
729   // to using it in -static mode.
730   SixteenByteConstantSection = 0;
731   if (TM.getRelocationModel() != Reloc::Static &&
732       TM.getTargetData()->getPointerSize() == 32)
733     SixteenByteConstantSection =   // .literal16
734       getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
735                       SectionKind::getMergeableConst16());
736
737   ReadOnlySection  // .const
738     = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
739
740   TextCoalSection
741     = getMachOSection("__TEXT", "__textcoal_nt",
742                       MCSectionMachO::S_COALESCED |
743                       MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
744                       SectionKind::getText());
745   ConstTextCoalSection
746     = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
747                       SectionKind::getText());
748   ConstDataCoalSection
749     = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
750                       SectionKind::getText());
751   ConstDataSection  // .const_data
752     = getMachOSection("__DATA", "__const", 0,
753                       SectionKind::getReadOnlyWithRel());
754   DataCoalSection
755     = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
756                       SectionKind::getDataRel());
757
758
759   LazySymbolPointerSection
760     = getMachOSection("__DATA", "__la_symbol_ptr",
761                       MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
762                       SectionKind::getMetadata());
763   NonLazySymbolPointerSection
764     = getMachOSection("__DATA", "__nl_symbol_ptr",
765                       MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
766                       SectionKind::getMetadata());
767
768   if (TM.getRelocationModel() == Reloc::Static) {
769     StaticCtorSection
770       = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
771     StaticDtorSection
772       = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
773   } else {
774     StaticCtorSection
775       = getMachOSection("__DATA", "__mod_init_func",
776                         MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
777                         SectionKind::getDataRel());
778     StaticDtorSection
779       = getMachOSection("__DATA", "__mod_term_func",
780                         MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
781                         SectionKind::getDataRel());
782   }
783
784   // Exception Handling.
785   LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
786                                 SectionKind::getDataRel());
787   EHFrameSection =
788     getMachOSection("__TEXT", "__eh_frame",
789                     MCSectionMachO::S_COALESCED |
790                     MCSectionMachO::S_ATTR_NO_TOC |
791                     MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
792                     MCSectionMachO::S_ATTR_LIVE_SUPPORT,
793                     SectionKind::getReadOnly());
794
795   // Debug Information.
796   DwarfAbbrevSection =
797     getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
798                     SectionKind::getMetadata());
799   DwarfInfoSection =
800     getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
801                     SectionKind::getMetadata());
802   DwarfLineSection =
803     getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
804                     SectionKind::getMetadata());
805   DwarfFrameSection =
806     getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
807                     SectionKind::getMetadata());
808   DwarfPubNamesSection =
809     getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
810                     SectionKind::getMetadata());
811   DwarfPubTypesSection =
812     getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
813                     SectionKind::getMetadata());
814   DwarfStrSection =
815     getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
816                     SectionKind::getMetadata());
817   DwarfLocSection =
818     getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
819                     SectionKind::getMetadata());
820   DwarfARangesSection =
821     getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
822                     SectionKind::getMetadata());
823   DwarfRangesSection =
824     getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
825                     SectionKind::getMetadata());
826   DwarfMacroInfoSection =
827     getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
828                     SectionKind::getMetadata());
829   DwarfDebugInlineSection =
830     getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
831                     SectionKind::getMetadata());
832 }
833
834 const MCSection *TargetLoweringObjectFileMachO::
835 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
836                          Mangler *Mang, const TargetMachine &TM) const {
837   // Parse the section specifier and create it if valid.
838   StringRef Segment, Section;
839   unsigned TAA, StubSize;
840   std::string ErrorCode =
841     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
842                                           TAA, StubSize);
843   if (!ErrorCode.empty()) {
844     // If invalid, report the error with llvm_report_error.
845     llvm_report_error("Global variable '" + GV->getNameStr() +
846                       "' has an invalid section specifier '" + GV->getSection()+
847                       "': " + ErrorCode + ".");
848     // Fall back to dropping it into the data section.
849     return DataSection;
850   }
851
852   // Get the section.
853   const MCSectionMachO *S =
854     getMachOSection(Segment, Section, TAA, StubSize, Kind);
855
856   // Okay, now that we got the section, verify that the TAA & StubSize agree.
857   // If the user declared multiple globals with different section flags, we need
858   // to reject it here.
859   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
860     // If invalid, report the error with llvm_report_error.
861     llvm_report_error("Global variable '" + GV->getNameStr() +
862                       "' section type or attributes does not match previous"
863                       " section specifier");
864   }
865
866   return S;
867 }
868
869 const MCSection *TargetLoweringObjectFileMachO::
870 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
871                        Mangler *Mang, const TargetMachine &TM) const {
872   assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
873
874   if (Kind.isText())
875     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
876
877   // If this is weak/linkonce, put this in a coalescable section, either in text
878   // or data depending on if it is writable.
879   if (GV->isWeakForLinker()) {
880     if (Kind.isReadOnly())
881       return ConstTextCoalSection;
882     return DataCoalSection;
883   }
884
885   // FIXME: Alignment check should be handled by section classifier.
886   if (Kind.isMergeable1ByteCString() ||
887       Kind.isMergeable2ByteCString()) {
888     if (TM.getTargetData()->getPreferredAlignment(
889                                               cast<GlobalVariable>(GV)) < 32) {
890       if (Kind.isMergeable1ByteCString())
891         return CStringSection;
892       assert(Kind.isMergeable2ByteCString());
893       return UStringSection;
894     }
895   }
896
897   if (Kind.isMergeableConst()) {
898     if (Kind.isMergeableConst4())
899       return FourByteConstantSection;
900     if (Kind.isMergeableConst8())
901       return EightByteConstantSection;
902     if (Kind.isMergeableConst16() && SixteenByteConstantSection)
903       return SixteenByteConstantSection;
904   }
905
906   // Otherwise, if it is readonly, but not something we can specially optimize,
907   // just drop it in .const.
908   if (Kind.isReadOnly())
909     return ReadOnlySection;
910
911   // If this is marked const, put it into a const section.  But if the dynamic
912   // linker needs to write to it, put it in the data segment.
913   if (Kind.isReadOnlyWithRel())
914     return ConstDataSection;
915
916   // Otherwise, just drop the variable in the normal data section.
917   return DataSection;
918 }
919
920 const MCSection *
921 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
922   // If this constant requires a relocation, we have to put it in the data
923   // segment, not in the text segment.
924   if (Kind.isDataRel())
925     return ConstDataSection;
926
927   if (Kind.isMergeableConst4())
928     return FourByteConstantSection;
929   if (Kind.isMergeableConst8())
930     return EightByteConstantSection;
931   if (Kind.isMergeableConst16() && SixteenByteConstantSection)
932     return SixteenByteConstantSection;
933   return ReadOnlySection;  // .const
934 }
935
936 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
937 /// not to emit the UsedDirective for some symbols in llvm.used.
938 // FIXME: REMOVE this (rdar://7071300)
939 bool TargetLoweringObjectFileMachO::
940 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
941   /// On Darwin, internally linked data beginning with "L" or "l" does not have
942   /// the directive emitted (this occurs in ObjC metadata).
943   if (!GV) return false;
944
945   // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
946   if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
947     // FIXME: ObjC metadata is currently emitted as internal symbols that have
948     // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
949     // this horrible hack can go away.
950     const std::string &Name = Mang->getMangledName(GV);
951     if (Name[0] == 'L' || Name[0] == 'l')
952       return false;
953   }
954
955   return true;
956 }
957
958 const MCExpr *TargetLoweringObjectFileMachO::
959 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
960                                  MachineModuleInfo *MMI,
961                                  bool &IsIndirect, bool &IsPCRel) const {
962   // The mach-o version of this method defaults to returning a stub reference.
963   IsIndirect = true;
964   IsPCRel    = false;
965   
966   SmallString<128> Name;
967   Mang->getNameWithPrefix(Name, GV, true);
968   Name += "$non_lazy_ptr";
969   return MCSymbolRefExpr::Create(Name.str(), getContext());
970 }
971
972
973 //===----------------------------------------------------------------------===//
974 //                                  COFF
975 //===----------------------------------------------------------------------===//
976
977 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
978
979 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
980   delete (COFFUniqueMapTy*)UniquingMap;
981 }
982
983
984 const MCSection *TargetLoweringObjectFileCOFF::
985 getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
986   // Create the map if it doesn't already exist.
987   if (UniquingMap == 0)
988     UniquingMap = new MachOUniqueMapTy();
989   COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
990
991   // Do the lookup, if we have a hit, return it.
992   const MCSectionCOFF *&Entry = Map[Name];
993   if (Entry) return Entry;
994
995   return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
996 }
997
998 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
999                                               const TargetMachine &TM) {
1000   if (UniquingMap != 0)
1001     ((COFFUniqueMapTy*)UniquingMap)->clear();
1002   TargetLoweringObjectFile::Initialize(Ctx, TM);
1003   TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
1004   DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
1005   StaticCtorSection =
1006     getCOFFSection(".ctors", false, SectionKind::getDataRel());
1007   StaticDtorSection =
1008     getCOFFSection(".dtors", false, SectionKind::getDataRel());
1009
1010   // FIXME: We're emitting LSDA info into a readonly section on COFF, even
1011   // though it contains relocatable pointers.  In PIC mode, this is probably a
1012   // big runtime hit for C++ apps.  Either the contents of the LSDA need to be
1013   // adjusted or this should be a data section.
1014   LSDASection =
1015     getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
1016   EHFrameSection =
1017     getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
1018
1019   // Debug info.
1020   // FIXME: Don't use 'directive' mode here.
1021   DwarfAbbrevSection =
1022     getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
1023                    true, SectionKind::getMetadata());
1024   DwarfInfoSection =
1025     getCOFFSection("\t.section\t.debug_info,\"dr\"",
1026                    true, SectionKind::getMetadata());
1027   DwarfLineSection =
1028     getCOFFSection("\t.section\t.debug_line,\"dr\"",
1029                    true, SectionKind::getMetadata());
1030   DwarfFrameSection =
1031     getCOFFSection("\t.section\t.debug_frame,\"dr\"",
1032                    true, SectionKind::getMetadata());
1033   DwarfPubNamesSection =
1034     getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
1035                    true, SectionKind::getMetadata());
1036   DwarfPubTypesSection =
1037     getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
1038                    true, SectionKind::getMetadata());
1039   DwarfStrSection =
1040     getCOFFSection("\t.section\t.debug_str,\"dr\"",
1041                    true, SectionKind::getMetadata());
1042   DwarfLocSection =
1043     getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1044                    true, SectionKind::getMetadata());
1045   DwarfARangesSection =
1046     getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1047                    true, SectionKind::getMetadata());
1048   DwarfRangesSection =
1049     getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1050                    true, SectionKind::getMetadata());
1051   DwarfMacroInfoSection =
1052     getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1053                    true, SectionKind::getMetadata());
1054 }
1055
1056 const MCSection *TargetLoweringObjectFileCOFF::
1057 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
1058                          Mangler *Mang, const TargetMachine &TM) const {
1059   return getCOFFSection(GV->getSection().c_str(), false, Kind);
1060 }
1061
1062 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1063   if (Kind.isText())
1064     return ".text$linkonce";
1065   if (Kind.isWriteable())
1066     return ".data$linkonce";
1067   return ".rdata$linkonce";
1068 }
1069
1070
1071 const MCSection *TargetLoweringObjectFileCOFF::
1072 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1073                        Mangler *Mang, const TargetMachine &TM) const {
1074   assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1075
1076   // If this global is linkonce/weak and the target handles this by emitting it
1077   // into a 'uniqued' section name, create and return the section now.
1078   if (GV->isWeakForLinker()) {
1079     const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1080     std::string Name = Mang->makeNameProper(GV->getNameStr());
1081     return getCOFFSection((Prefix+Name).c_str(), false, Kind);
1082   }
1083
1084   if (Kind.isText())
1085     return getTextSection();
1086
1087   return getDataSection();
1088 }
1089