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