TargetLoweringObjectFile.cpp revision a07b7504050e10508144b294b2c7996fe8794e0c
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
496getELFSectionType(const char *Name, SectionKind K) {
497
498  if (strcmp(Name, ".init_array") == 0)
499    return MCSectionELF::SHT_INIT_ARRAY;
500
501  if (strcmp(Name, ".fini_array") == 0)
502    return MCSectionELF::SHT_FINI_ARRAY;
503
504  if (strcmp(Name, ".preinit_array") == 0)
505    return MCSectionELF::SHT_PREINIT_ARRAY;
506
507  if (K.isBSS() || K.isThreadBSS())
508    return MCSectionELF::SHT_NOBITS;
509
510  return MCSectionELF::SHT_PROGBITS;
511}
512
513
514static unsigned
515getELFSectionFlags(SectionKind K) {
516  unsigned Flags = 0;
517
518  if (!K.isMetadata())
519    Flags |= MCSectionELF::SHF_ALLOC;
520
521  if (K.isText())
522    Flags |= MCSectionELF::SHF_EXECINSTR;
523
524  if (K.isWriteable())
525    Flags |= MCSectionELF::SHF_WRITE;
526
527  if (K.isThreadLocal())
528    Flags |= MCSectionELF::SHF_TLS;
529
530  // K.isMergeableConst() is left out to honour PR4650
531  if (K.isMergeableCString() || K.isMergeableConst4() ||
532      K.isMergeableConst8() || K.isMergeableConst16())
533    Flags |= MCSectionELF::SHF_MERGE;
534
535  if (K.isMergeableCString())
536    Flags |= MCSectionELF::SHF_STRINGS;
537
538  return Flags;
539}
540
541
542const MCSection *TargetLoweringObjectFileELF::
543getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
544                         Mangler *Mang, const TargetMachine &TM) const {
545  const char *SectionName = GV->getSection().c_str();
546
547  // Infer section flags from the section name if we can.
548  Kind = getELFKindForNamedSection(SectionName, Kind);
549
550  return getELFSection(SectionName,
551                       getELFSectionType(SectionName, Kind),
552                       getELFSectionFlags(Kind), Kind, true);
553}
554
555static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
556  if (Kind.isText())                 return ".gnu.linkonce.t.";
557  if (Kind.isReadOnly())             return ".gnu.linkonce.r.";
558
559  if (Kind.isThreadData())           return ".gnu.linkonce.td.";
560  if (Kind.isThreadBSS())            return ".gnu.linkonce.tb.";
561
562  if (Kind.isBSS())                  return ".gnu.linkonce.b.";
563  if (Kind.isDataNoRel())            return ".gnu.linkonce.d.";
564  if (Kind.isDataRelLocal())         return ".gnu.linkonce.d.rel.local.";
565  if (Kind.isDataRel())              return ".gnu.linkonce.d.rel.";
566  if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
567
568  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
569  return ".gnu.linkonce.d.rel.ro.";
570}
571
572const MCSection *TargetLoweringObjectFileELF::
573SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
574                       Mangler *Mang, const TargetMachine &TM) const {
575
576  // If this global is linkonce/weak and the target handles this by emitting it
577  // into a 'uniqued' section name, create and return the section now.
578  if (GV->isWeakForLinker()) {
579    const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
580    std::string Name = Mang->makeNameProper(GV->getNameStr());
581
582    return getELFSection((Prefix+Name).c_str(),
583                         getELFSectionType((Prefix+Name).c_str(), Kind),
584                         getELFSectionFlags(Kind),
585                         Kind);
586  }
587
588  if (Kind.isText()) return TextSection;
589
590  if (Kind.isMergeable1ByteCString() ||
591      Kind.isMergeable2ByteCString() ||
592      Kind.isMergeable4ByteCString()) {
593
594    // We also need alignment here.
595    // FIXME: this is getting the alignment of the character, not the
596    // alignment of the global!
597    unsigned Align =
598      TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
599
600    const char *SizeSpec = ".rodata.str1.";
601    if (Kind.isMergeable2ByteCString())
602      SizeSpec = ".rodata.str2.";
603    else if (Kind.isMergeable4ByteCString())
604      SizeSpec = ".rodata.str4.";
605    else
606      assert(Kind.isMergeable1ByteCString() && "unknown string width");
607
608
609    std::string Name = SizeSpec + utostr(Align);
610    return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS,
611                         MCSectionELF::SHF_ALLOC |
612                         MCSectionELF::SHF_MERGE |
613                         MCSectionELF::SHF_STRINGS,
614                         Kind);
615  }
616
617  if (Kind.isMergeableConst()) {
618    if (Kind.isMergeableConst4() && MergeableConst4Section)
619      return MergeableConst4Section;
620    if (Kind.isMergeableConst8() && MergeableConst8Section)
621      return MergeableConst8Section;
622    if (Kind.isMergeableConst16() && MergeableConst16Section)
623      return MergeableConst16Section;
624    return ReadOnlySection;  // .const
625  }
626
627  if (Kind.isReadOnly())             return ReadOnlySection;
628
629  if (Kind.isThreadData())           return TLSDataSection;
630  if (Kind.isThreadBSS())            return TLSBSSSection;
631
632  if (Kind.isBSS())                  return BSSSection;
633
634  if (Kind.isDataNoRel())            return DataSection;
635  if (Kind.isDataRelLocal())         return DataRelLocalSection;
636  if (Kind.isDataRel())              return DataRelSection;
637  if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
638
639  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
640  return DataRelROSection;
641}
642
643/// getSectionForConstant - Given a mergeable constant with the
644/// specified size and relocation information, return a section that it
645/// should be placed in.
646const MCSection *TargetLoweringObjectFileELF::
647getSectionForConstant(SectionKind Kind) const {
648  if (Kind.isMergeableConst4() && MergeableConst4Section)
649    return MergeableConst4Section;
650  if (Kind.isMergeableConst8() && MergeableConst8Section)
651    return MergeableConst8Section;
652  if (Kind.isMergeableConst16() && MergeableConst16Section)
653    return MergeableConst16Section;
654  if (Kind.isReadOnly())
655    return ReadOnlySection;
656
657  if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
658  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
659  return DataRelROSection;
660}
661
662//===----------------------------------------------------------------------===//
663//                                 MachO
664//===----------------------------------------------------------------------===//
665
666typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
667
668TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
669  // If we have the MachO uniquing map, free it.
670  delete (MachOUniqueMapTy*)UniquingMap;
671}
672
673
674const MCSectionMachO *TargetLoweringObjectFileMachO::
675getMachOSection(StringRef Segment, StringRef Section,
676                unsigned TypeAndAttributes,
677                unsigned Reserved2, SectionKind Kind) const {
678  // We unique sections by their segment/section pair.  The returned section
679  // may not have the same flags as the requested section, if so this should be
680  // diagnosed by the client as an error.
681
682  // Create the map if it doesn't already exist.
683  if (UniquingMap == 0)
684    UniquingMap = new MachOUniqueMapTy();
685  MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
686
687  // Form the name to look up.
688  SmallString<64> Name;
689  Name += Segment;
690  Name.push_back(',');
691  Name += Section;
692
693  // Do the lookup, if we have a hit, return it.
694  const MCSectionMachO *&Entry = Map[Name.str()];
695  if (Entry) return Entry;
696
697  // Otherwise, return a new section.
698  return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
699                                        Reserved2, Kind, getContext());
700}
701
702
703void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
704                                               const TargetMachine &TM) {
705  if (UniquingMap != 0)
706    ((MachOUniqueMapTy*)UniquingMap)->clear();
707  TargetLoweringObjectFile::Initialize(Ctx, TM);
708
709  TextSection // .text
710    = getMachOSection("__TEXT", "__text",
711                      MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
712                      SectionKind::getText());
713  DataSection // .data
714    = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
715
716  CStringSection // .cstring
717    = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
718                      SectionKind::getMergeable1ByteCString());
719  UStringSection
720    = getMachOSection("__TEXT","__ustring", 0,
721                      SectionKind::getMergeable2ByteCString());
722  FourByteConstantSection // .literal4
723    = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
724                      SectionKind::getMergeableConst4());
725  EightByteConstantSection // .literal8
726    = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
727                      SectionKind::getMergeableConst8());
728
729  // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
730  // to using it in -static mode.
731  SixteenByteConstantSection = 0;
732  if (TM.getRelocationModel() != Reloc::Static &&
733      TM.getTargetData()->getPointerSize() == 32)
734    SixteenByteConstantSection =   // .literal16
735      getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
736                      SectionKind::getMergeableConst16());
737
738  ReadOnlySection  // .const
739    = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
740
741  TextCoalSection
742    = getMachOSection("__TEXT", "__textcoal_nt",
743                      MCSectionMachO::S_COALESCED |
744                      MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
745                      SectionKind::getText());
746  ConstTextCoalSection
747    = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
748                      SectionKind::getText());
749  ConstDataCoalSection
750    = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
751                      SectionKind::getText());
752  ConstDataSection  // .const_data
753    = getMachOSection("__DATA", "__const", 0,
754                      SectionKind::getReadOnlyWithRel());
755  DataCoalSection
756    = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
757                      SectionKind::getDataRel());
758
759
760  LazySymbolPointerSection
761    = getMachOSection("__DATA", "__la_symbol_ptr",
762                      MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
763                      SectionKind::getMetadata());
764  NonLazySymbolPointerSection
765    = getMachOSection("__DATA", "__nl_symbol_ptr",
766                      MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
767                      SectionKind::getMetadata());
768
769  if (TM.getRelocationModel() == Reloc::Static) {
770    StaticCtorSection
771      = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
772    StaticDtorSection
773      = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
774  } else {
775    StaticCtorSection
776      = getMachOSection("__DATA", "__mod_init_func",
777                        MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
778                        SectionKind::getDataRel());
779    StaticDtorSection
780      = getMachOSection("__DATA", "__mod_term_func",
781                        MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
782                        SectionKind::getDataRel());
783  }
784
785  // Exception Handling.
786  LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
787                                SectionKind::getDataRel());
788  EHFrameSection =
789    getMachOSection("__TEXT", "__eh_frame",
790                    MCSectionMachO::S_COALESCED |
791                    MCSectionMachO::S_ATTR_NO_TOC |
792                    MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
793                    MCSectionMachO::S_ATTR_LIVE_SUPPORT,
794                    SectionKind::getReadOnly());
795
796  // Debug Information.
797  DwarfAbbrevSection =
798    getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
799                    SectionKind::getMetadata());
800  DwarfInfoSection =
801    getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
802                    SectionKind::getMetadata());
803  DwarfLineSection =
804    getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
805                    SectionKind::getMetadata());
806  DwarfFrameSection =
807    getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
808                    SectionKind::getMetadata());
809  DwarfPubNamesSection =
810    getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
811                    SectionKind::getMetadata());
812  DwarfPubTypesSection =
813    getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
814                    SectionKind::getMetadata());
815  DwarfStrSection =
816    getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
817                    SectionKind::getMetadata());
818  DwarfLocSection =
819    getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
820                    SectionKind::getMetadata());
821  DwarfARangesSection =
822    getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
823                    SectionKind::getMetadata());
824  DwarfRangesSection =
825    getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
826                    SectionKind::getMetadata());
827  DwarfMacroInfoSection =
828    getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
829                    SectionKind::getMetadata());
830  DwarfDebugInlineSection =
831    getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
832                    SectionKind::getMetadata());
833}
834
835const MCSection *TargetLoweringObjectFileMachO::
836getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
837                         Mangler *Mang, const TargetMachine &TM) const {
838  // Parse the section specifier and create it if valid.
839  StringRef Segment, Section;
840  unsigned TAA, StubSize;
841  std::string ErrorCode =
842    MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
843                                          TAA, StubSize);
844  if (!ErrorCode.empty()) {
845    // If invalid, report the error with llvm_report_error.
846    llvm_report_error("Global variable '" + GV->getNameStr() +
847                      "' has an invalid section specifier '" + GV->getSection()+
848                      "': " + ErrorCode + ".");
849    // Fall back to dropping it into the data section.
850    return DataSection;
851  }
852
853  // Get the section.
854  const MCSectionMachO *S =
855    getMachOSection(Segment, Section, TAA, StubSize, Kind);
856
857  // Okay, now that we got the section, verify that the TAA & StubSize agree.
858  // If the user declared multiple globals with different section flags, we need
859  // to reject it here.
860  if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
861    // If invalid, report the error with llvm_report_error.
862    llvm_report_error("Global variable '" + GV->getNameStr() +
863                      "' section type or attributes does not match previous"
864                      " section specifier");
865  }
866
867  return S;
868}
869
870const MCSection *TargetLoweringObjectFileMachO::
871SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
872                       Mangler *Mang, const TargetMachine &TM) const {
873  assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
874
875  if (Kind.isText())
876    return GV->isWeakForLinker() ? TextCoalSection : TextSection;
877
878  // If this is weak/linkonce, put this in a coalescable section, either in text
879  // or data depending on if it is writable.
880  if (GV->isWeakForLinker()) {
881    if (Kind.isReadOnly())
882      return ConstTextCoalSection;
883    return DataCoalSection;
884  }
885
886  // FIXME: Alignment check should be handled by section classifier.
887  if (Kind.isMergeable1ByteCString() ||
888      Kind.isMergeable2ByteCString()) {
889    if (TM.getTargetData()->getPreferredAlignment(
890                                              cast<GlobalVariable>(GV)) < 32) {
891      if (Kind.isMergeable1ByteCString())
892        return CStringSection;
893      assert(Kind.isMergeable2ByteCString());
894      return UStringSection;
895    }
896  }
897
898  if (Kind.isMergeableConst()) {
899    if (Kind.isMergeableConst4())
900      return FourByteConstantSection;
901    if (Kind.isMergeableConst8())
902      return EightByteConstantSection;
903    if (Kind.isMergeableConst16() && SixteenByteConstantSection)
904      return SixteenByteConstantSection;
905  }
906
907  // Otherwise, if it is readonly, but not something we can specially optimize,
908  // just drop it in .const.
909  if (Kind.isReadOnly())
910    return ReadOnlySection;
911
912  // If this is marked const, put it into a const section.  But if the dynamic
913  // linker needs to write to it, put it in the data segment.
914  if (Kind.isReadOnlyWithRel())
915    return ConstDataSection;
916
917  // Otherwise, just drop the variable in the normal data section.
918  return DataSection;
919}
920
921const MCSection *
922TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
923  // If this constant requires a relocation, we have to put it in the data
924  // segment, not in the text segment.
925  if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
926    return ConstDataSection;
927
928  if (Kind.isMergeableConst4())
929    return FourByteConstantSection;
930  if (Kind.isMergeableConst8())
931    return EightByteConstantSection;
932  if (Kind.isMergeableConst16() && SixteenByteConstantSection)
933    return SixteenByteConstantSection;
934  return ReadOnlySection;  // .const
935}
936
937/// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
938/// not to emit the UsedDirective for some symbols in llvm.used.
939// FIXME: REMOVE this (rdar://7071300)
940bool TargetLoweringObjectFileMachO::
941shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
942  /// On Darwin, internally linked data beginning with "L" or "l" does not have
943  /// the directive emitted (this occurs in ObjC metadata).
944  if (!GV) return false;
945
946  // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
947  if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
948    // FIXME: ObjC metadata is currently emitted as internal symbols that have
949    // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
950    // this horrible hack can go away.
951    const std::string &Name = Mang->getMangledName(GV);
952    if (Name[0] == 'L' || Name[0] == 'l')
953      return false;
954  }
955
956  return true;
957}
958
959const MCExpr *TargetLoweringObjectFileMachO::
960getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
961                                 MachineModuleInfo *MMI,
962                                 bool &IsIndirect, bool &IsPCRel) const {
963  // The mach-o version of this method defaults to returning a stub reference.
964  IsIndirect = true;
965  IsPCRel    = false;
966
967  SmallString<128> Name;
968  Mang->getNameWithPrefix(Name, GV, true);
969  Name += "$non_lazy_ptr";
970  return MCSymbolRefExpr::Create(Name.str(), getContext());
971}
972
973
974//===----------------------------------------------------------------------===//
975//                                  COFF
976//===----------------------------------------------------------------------===//
977
978typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
979
980TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
981  delete (COFFUniqueMapTy*)UniquingMap;
982}
983
984
985const MCSection *TargetLoweringObjectFileCOFF::
986getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
987  // Create the map if it doesn't already exist.
988  if (UniquingMap == 0)
989    UniquingMap = new MachOUniqueMapTy();
990  COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
991
992  // Do the lookup, if we have a hit, return it.
993  const MCSectionCOFF *&Entry = Map[Name];
994  if (Entry) return Entry;
995
996  return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
997}
998
999void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1000                                              const TargetMachine &TM) {
1001  if (UniquingMap != 0)
1002    ((COFFUniqueMapTy*)UniquingMap)->clear();
1003  TargetLoweringObjectFile::Initialize(Ctx, TM);
1004  TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
1005  DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
1006  StaticCtorSection =
1007    getCOFFSection(".ctors", false, SectionKind::getDataRel());
1008  StaticDtorSection =
1009    getCOFFSection(".dtors", false, SectionKind::getDataRel());
1010
1011  // FIXME: We're emitting LSDA info into a readonly section on COFF, even
1012  // though it contains relocatable pointers.  In PIC mode, this is probably a
1013  // big runtime hit for C++ apps.  Either the contents of the LSDA need to be
1014  // adjusted or this should be a data section.
1015  LSDASection =
1016    getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
1017  EHFrameSection =
1018    getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
1019
1020  // Debug info.
1021  // FIXME: Don't use 'directive' mode here.
1022  DwarfAbbrevSection =
1023    getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
1024                   true, SectionKind::getMetadata());
1025  DwarfInfoSection =
1026    getCOFFSection("\t.section\t.debug_info,\"dr\"",
1027                   true, SectionKind::getMetadata());
1028  DwarfLineSection =
1029    getCOFFSection("\t.section\t.debug_line,\"dr\"",
1030                   true, SectionKind::getMetadata());
1031  DwarfFrameSection =
1032    getCOFFSection("\t.section\t.debug_frame,\"dr\"",
1033                   true, SectionKind::getMetadata());
1034  DwarfPubNamesSection =
1035    getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
1036                   true, SectionKind::getMetadata());
1037  DwarfPubTypesSection =
1038    getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
1039                   true, SectionKind::getMetadata());
1040  DwarfStrSection =
1041    getCOFFSection("\t.section\t.debug_str,\"dr\"",
1042                   true, SectionKind::getMetadata());
1043  DwarfLocSection =
1044    getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1045                   true, SectionKind::getMetadata());
1046  DwarfARangesSection =
1047    getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1048                   true, SectionKind::getMetadata());
1049  DwarfRangesSection =
1050    getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1051                   true, SectionKind::getMetadata());
1052  DwarfMacroInfoSection =
1053    getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1054                   true, SectionKind::getMetadata());
1055}
1056
1057const MCSection *TargetLoweringObjectFileCOFF::
1058getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
1059                         Mangler *Mang, const TargetMachine &TM) const {
1060  return getCOFFSection(GV->getSection().c_str(), false, Kind);
1061}
1062
1063static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1064  if (Kind.isText())
1065    return ".text$linkonce";
1066  if (Kind.isWriteable())
1067    return ".data$linkonce";
1068  return ".rdata$linkonce";
1069}
1070
1071
1072const MCSection *TargetLoweringObjectFileCOFF::
1073SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1074                       Mangler *Mang, const TargetMachine &TM) const {
1075  assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1076
1077  // If this global is linkonce/weak and the target handles this by emitting it
1078  // into a 'uniqued' section name, create and return the section now.
1079  if (GV->isWeakForLinker()) {
1080    const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1081    std::string Name = Mang->makeNameProper(GV->getNameStr());
1082    return getCOFFSection((Prefix+Name).c_str(), false, Kind);
1083  }
1084
1085  if (Kind.isText())
1086    return getTextSection();
1087
1088  return getDataSection();
1089}
1090
1091