1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements classes used to handle lowerings specific to common
11 // object file formats.
13 //===----------------------------------------------------------------------===//
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/MC/MCSymbol.h"
25 #include "llvm/Target/Mangler.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/StringExtras.h"
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
44 StaticCtorSection = 0;
45 StaticDtorSection = 0;
49 DwarfAbbrevSection = 0;
52 DwarfFrameSection = 0;
53 DwarfPubNamesSection = 0;
54 DwarfPubTypesSection = 0;
55 DwarfDebugInlineSection = 0;
58 DwarfARangesSection = 0;
59 DwarfRangesSection = 0;
60 DwarfMacroInfoSection = 0;
63 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
66 static bool isSuitableForBSS(const GlobalVariable *GV) {
67 Constant *C = GV->getInitializer();
69 // Must have zero initializer.
70 if (!C->isNullValue())
73 // Leave constant zeros in readonly constant sections, so they can be shared.
77 // If the global has an explicit section specified, don't put it in BSS.
78 if (!GV->getSection().empty())
81 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
85 // Otherwise, put it in BSS!
89 /// IsNullTerminatedString - Return true if the specified constant (which is
90 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
91 /// nul value and contains no other nuls in it.
92 static bool IsNullTerminatedString(const Constant *C) {
93 const ArrayType *ATy = cast<ArrayType>(C->getType());
95 // First check: is we have constant array of i8 terminated with zero
96 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
97 if (ATy->getNumElements() == 0) return false;
100 dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
101 if (Null == 0 || Null->getZExtValue() != 0)
102 return false; // Not null terminated.
104 // Verify that the null doesn't occur anywhere else in the string.
105 for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
106 // Reject constantexpr elements etc.
107 if (!isa<ConstantInt>(CVA->getOperand(i)) ||
108 CVA->getOperand(i) == Null)
113 // Another possibility: [1 x i8] zeroinitializer
114 if (isa<ConstantAggregateZero>(C))
115 return ATy->getNumElements() == 1;
120 /// getKindForGlobal - This is a top-level target-independent classifier for
121 /// a global variable. Given an global variable and information from TM, it
122 /// classifies the global in a variety of ways that make various target
123 /// implementations simpler. The target implementation is free to ignore this
124 /// extra info of course.
125 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
126 const TargetMachine &TM){
127 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
128 "Can only be used for global definitions");
130 Reloc::Model ReloModel = TM.getRelocationModel();
132 // Early exit - functions should be always in text sections.
133 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
135 return SectionKind::getText();
137 // Handle thread-local data first.
138 if (GVar->isThreadLocal()) {
139 if (isSuitableForBSS(GVar))
140 return SectionKind::getThreadBSS();
141 return SectionKind::getThreadData();
144 // Variables with common linkage always get classified as common.
145 if (GVar->hasCommonLinkage())
146 return SectionKind::getCommon();
148 // Variable can be easily put to BSS section.
149 if (isSuitableForBSS(GVar))
150 return SectionKind::getBSS();
152 Constant *C = GVar->getInitializer();
154 // If the global is marked constant, we can put it into a mergable section,
155 // a mergable string section, or general .data if it contains relocations.
156 if (GVar->isConstant()) {
157 // If the initializer for the global contains something that requires a
158 // relocation, then we may have to drop this into a wriable data section
159 // even though it is marked const.
160 switch (C->getRelocationInfo()) {
161 default: assert(0 && "unknown relocation info kind");
162 case Constant::NoRelocation:
163 // If initializer is a null-terminated string, put it in a "cstring"
164 // section of the right width.
165 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
166 if (const IntegerType *ITy =
167 dyn_cast<IntegerType>(ATy->getElementType())) {
168 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
169 ITy->getBitWidth() == 32) &&
170 IsNullTerminatedString(C)) {
171 if (ITy->getBitWidth() == 8)
172 return SectionKind::getMergeable1ByteCString();
173 if (ITy->getBitWidth() == 16)
174 return SectionKind::getMergeable2ByteCString();
176 assert(ITy->getBitWidth() == 32 && "Unknown width");
177 return SectionKind::getMergeable4ByteCString();
182 // Otherwise, just drop it into a mergable constant section. If we have
183 // a section for this size, use it, otherwise use the arbitrary sized
185 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
186 case 4: return SectionKind::getMergeableConst4();
187 case 8: return SectionKind::getMergeableConst8();
188 case 16: return SectionKind::getMergeableConst16();
189 default: return SectionKind::getMergeableConst();
192 case Constant::LocalRelocation:
193 // In static relocation model, the linker will resolve all addresses, so
194 // the relocation entries will actually be constants by the time the app
195 // starts up. However, we can't put this into a mergable section, because
196 // the linker doesn't take relocations into consideration when it tries to
197 // merge entries in the section.
198 if (ReloModel == Reloc::Static)
199 return SectionKind::getReadOnly();
201 // Otherwise, the dynamic linker needs to fix it up, put it in the
202 // writable data.rel.local section.
203 return SectionKind::getReadOnlyWithRelLocal();
205 case Constant::GlobalRelocations:
206 // In static relocation model, the linker will resolve all addresses, so
207 // the relocation entries will actually be constants by the time the app
208 // starts up. However, we can't put this into a mergable section, because
209 // the linker doesn't take relocations into consideration when it tries to
210 // merge entries in the section.
211 if (ReloModel == Reloc::Static)
212 return SectionKind::getReadOnly();
214 // Otherwise, the dynamic linker needs to fix it up, put it in the
215 // writable data.rel section.
216 return SectionKind::getReadOnlyWithRel();
220 // Okay, this isn't a constant. If the initializer for the global is going
221 // to require a runtime relocation by the dynamic linker, put it into a more
222 // specific section to improve startup time of the app. This coalesces these
223 // globals together onto fewer pages, improving the locality of the dynamic
225 if (ReloModel == Reloc::Static)
226 return SectionKind::getDataNoRel();
228 switch (C->getRelocationInfo()) {
229 default: assert(0 && "unknown relocation info kind");
230 case Constant::NoRelocation:
231 return SectionKind::getDataNoRel();
232 case Constant::LocalRelocation:
233 return SectionKind::getDataRelLocal();
234 case Constant::GlobalRelocations:
235 return SectionKind::getDataRel();
239 /// SectionForGlobal - This method computes the appropriate section to emit
240 /// the specified global variable or function definition. This should not
241 /// be passed external (or available externally) globals.
242 const MCSection *TargetLoweringObjectFile::
243 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
244 const TargetMachine &TM) const {
245 // Select section name.
246 if (GV->hasSection())
247 return getExplicitSectionGlobal(GV, Kind, Mang, TM);
250 // Use default section depending on the 'type' of global
251 return SelectSectionForGlobal(GV, Kind, Mang, TM);
255 // Lame default implementation. Calculate the section name for global.
257 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
260 const TargetMachine &TM) const{
261 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
264 return getTextSection();
266 if (Kind.isBSS() && BSSSection != 0)
269 if (Kind.isReadOnly() && ReadOnlySection != 0)
270 return ReadOnlySection;
272 return getDataSection();
275 /// getSectionForConstant - Given a mergable constant with the
276 /// specified size and relocation information, return a section that it
277 /// should be placed in.
279 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
280 if (Kind.isReadOnly() && ReadOnlySection != 0)
281 return ReadOnlySection;
286 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a
287 /// pc-relative reference to the specified global variable from exception
288 /// handling information. In addition to the symbol, this returns
291 /// IsIndirect - True if the returned symbol is actually a stub that contains
292 /// the address of the symbol, false if the symbol is the global itself.
294 /// IsPCRel - True if the symbol reference is already pc-relative, false if
295 /// the caller needs to subtract off the address of the reference from the
298 const MCExpr *TargetLoweringObjectFile::
299 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
300 MachineModuleInfo *MMI,
301 bool &IsIndirect, bool &IsPCRel) const {
302 // The generic implementation of this just returns a direct reference to the
307 // FIXME: Use GetGlobalValueSymbol.
308 SmallString<128> Name;
309 Mang->getNameWithPrefix(Name, GV, false);
310 return MCSymbolRefExpr::Create(Name.str(), getContext());
314 //===----------------------------------------------------------------------===//
316 //===----------------------------------------------------------------------===//
317 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
319 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
320 // If we have the section uniquing map, free it.
321 delete (ELFUniqueMapTy*)UniquingMap;
324 const MCSection *TargetLoweringObjectFileELF::
325 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
326 SectionKind Kind, bool IsExplicit) const {
327 if (UniquingMap == 0)
328 UniquingMap = new ELFUniqueMapTy();
329 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
331 // Do the lookup, if we have a hit, return it.
332 const MCSectionELF *&Entry = Map[Section];
333 if (Entry) return Entry;
335 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
339 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
340 const TargetMachine &TM) {
341 if (UniquingMap != 0)
342 ((ELFUniqueMapTy*)UniquingMap)->clear();
343 TargetLoweringObjectFile::Initialize(Ctx, TM);
346 getELFSection(".bss", MCSectionELF::SHT_NOBITS,
347 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
348 SectionKind::getBSS());
351 getELFSection(".text", MCSectionELF::SHT_PROGBITS,
352 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
353 SectionKind::getText());
356 getELFSection(".data", MCSectionELF::SHT_PROGBITS,
357 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
358 SectionKind::getDataRel());
361 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
362 MCSectionELF::SHF_ALLOC,
363 SectionKind::getReadOnly());
366 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
367 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
368 MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
371 getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
372 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
373 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
376 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
377 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
378 SectionKind::getDataRel());
380 DataRelLocalSection =
381 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
382 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
383 SectionKind::getDataRelLocal());
386 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
387 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
388 SectionKind::getReadOnlyWithRel());
390 DataRelROLocalSection =
391 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
392 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
393 SectionKind::getReadOnlyWithRelLocal());
395 MergeableConst4Section =
396 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
397 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
398 SectionKind::getMergeableConst4());
400 MergeableConst8Section =
401 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
402 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
403 SectionKind::getMergeableConst8());
405 MergeableConst16Section =
406 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
407 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
408 SectionKind::getMergeableConst16());
411 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
412 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
413 SectionKind::getDataRel());
416 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
417 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
418 SectionKind::getDataRel());
420 // Exception Handling Sections.
422 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
423 // it contains relocatable pointers. In PIC mode, this is probably a big
424 // runtime hit for C++ apps. Either the contents of the LSDA need to be
425 // adjusted or this should be a data section.
427 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
428 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
430 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
431 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
432 SectionKind::getDataRel());
434 // Debug Info Sections.
436 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
437 SectionKind::getMetadata());
439 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
440 SectionKind::getMetadata());
442 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
443 SectionKind::getMetadata());
445 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
446 SectionKind::getMetadata());
447 DwarfPubNamesSection =
448 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
449 SectionKind::getMetadata());
450 DwarfPubTypesSection =
451 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
452 SectionKind::getMetadata());
454 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
455 SectionKind::getMetadata());
457 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
458 SectionKind::getMetadata());
459 DwarfARangesSection =
460 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
461 SectionKind::getMetadata());
463 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
464 SectionKind::getMetadata());
465 DwarfMacroInfoSection =
466 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
467 SectionKind::getMetadata());
472 getELFKindForNamedSection(const char *Name, SectionKind K) {
473 if (Name[0] != '.') return K;
475 // Some lame default implementation based on some magic section names.
476 if (strcmp(Name, ".bss") == 0 ||
477 strncmp(Name, ".bss.", 5) == 0 ||
478 strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
479 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
480 strcmp(Name, ".sbss") == 0 ||
481 strncmp(Name, ".sbss.", 6) == 0 ||
482 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
483 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
484 return SectionKind::getBSS();
486 if (strcmp(Name, ".tdata") == 0 ||
487 strncmp(Name, ".tdata.", 7) == 0 ||
488 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
489 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
490 return SectionKind::getThreadData();
492 if (strcmp(Name, ".tbss") == 0 ||
493 strncmp(Name, ".tbss.", 6) == 0 ||
494 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
495 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
496 return SectionKind::getThreadBSS();
502 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
504 if (Name == ".init_array")
505 return MCSectionELF::SHT_INIT_ARRAY;
507 if (Name == ".fini_array")
508 return MCSectionELF::SHT_FINI_ARRAY;
510 if (Name == ".preinit_array")
511 return MCSectionELF::SHT_PREINIT_ARRAY;
513 if (K.isBSS() || K.isThreadBSS())
514 return MCSectionELF::SHT_NOBITS;
516 return MCSectionELF::SHT_PROGBITS;
521 getELFSectionFlags(SectionKind K) {
525 Flags |= MCSectionELF::SHF_ALLOC;
528 Flags |= MCSectionELF::SHF_EXECINSTR;
531 Flags |= MCSectionELF::SHF_WRITE;
533 if (K.isThreadLocal())
534 Flags |= MCSectionELF::SHF_TLS;
536 // K.isMergeableConst() is left out to honour PR4650
537 if (K.isMergeableCString() || K.isMergeableConst4() ||
538 K.isMergeableConst8() || K.isMergeableConst16())
539 Flags |= MCSectionELF::SHF_MERGE;
541 if (K.isMergeableCString())
542 Flags |= MCSectionELF::SHF_STRINGS;
548 const MCSection *TargetLoweringObjectFileELF::
549 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
550 Mangler *Mang, const TargetMachine &TM) const {
551 const char *SectionName = GV->getSection().c_str();
553 // Infer section flags from the section name if we can.
554 Kind = getELFKindForNamedSection(SectionName, Kind);
556 return getELFSection(SectionName,
557 getELFSectionType(SectionName, Kind),
558 getELFSectionFlags(Kind), Kind, true);
561 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
562 if (Kind.isText()) return ".gnu.linkonce.t.";
563 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
565 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
566 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
568 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
569 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
570 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
571 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
573 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
574 return ".gnu.linkonce.d.rel.ro.";
577 const MCSection *TargetLoweringObjectFileELF::
578 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
579 Mangler *Mang, const TargetMachine &TM) const {
581 // If this global is linkonce/weak and the target handles this by emitting it
582 // into a 'uniqued' section name, create and return the section now.
583 if (GV->isWeakForLinker() && !Kind.isCommon() && !Kind.isBSS()) {
584 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
585 SmallString<128> Name;
586 Name.append(Prefix, Prefix+strlen(Prefix));
587 Mang->getNameWithPrefix(Name, GV, false);
588 return getELFSection(Name.str(), getELFSectionType(Name.str(), Kind),
589 getELFSectionFlags(Kind), Kind);
592 if (Kind.isText()) return TextSection;
594 if (Kind.isMergeable1ByteCString() ||
595 Kind.isMergeable2ByteCString() ||
596 Kind.isMergeable4ByteCString()) {
598 // We also need alignment here.
599 // FIXME: this is getting the alignment of the character, not the
600 // alignment of the global!
602 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
604 const char *SizeSpec = ".rodata.str1.";
605 if (Kind.isMergeable2ByteCString())
606 SizeSpec = ".rodata.str2.";
607 else if (Kind.isMergeable4ByteCString())
608 SizeSpec = ".rodata.str4.";
610 assert(Kind.isMergeable1ByteCString() && "unknown string width");
613 std::string Name = SizeSpec + utostr(Align);
614 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS,
615 MCSectionELF::SHF_ALLOC |
616 MCSectionELF::SHF_MERGE |
617 MCSectionELF::SHF_STRINGS,
621 if (Kind.isMergeableConst()) {
622 if (Kind.isMergeableConst4() && MergeableConst4Section)
623 return MergeableConst4Section;
624 if (Kind.isMergeableConst8() && MergeableConst8Section)
625 return MergeableConst8Section;
626 if (Kind.isMergeableConst16() && MergeableConst16Section)
627 return MergeableConst16Section;
628 return ReadOnlySection; // .const
631 if (Kind.isReadOnly()) return ReadOnlySection;
633 if (Kind.isThreadData()) return TLSDataSection;
634 if (Kind.isThreadBSS()) return TLSBSSSection;
636 // Note: we claim that common symbols are put in BSSSection, but they are
637 // really emitted with the magic .comm directive, which creates a symbol table
638 // entry but not a section.
639 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
641 if (Kind.isDataNoRel()) return DataSection;
642 if (Kind.isDataRelLocal()) return DataRelLocalSection;
643 if (Kind.isDataRel()) return DataRelSection;
644 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
646 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
647 return DataRelROSection;
650 /// getSectionForConstant - Given a mergeable constant with the
651 /// specified size and relocation information, return a section that it
652 /// should be placed in.
653 const MCSection *TargetLoweringObjectFileELF::
654 getSectionForConstant(SectionKind Kind) const {
655 if (Kind.isMergeableConst4() && MergeableConst4Section)
656 return MergeableConst4Section;
657 if (Kind.isMergeableConst8() && MergeableConst8Section)
658 return MergeableConst8Section;
659 if (Kind.isMergeableConst16() && MergeableConst16Section)
660 return MergeableConst16Section;
661 if (Kind.isReadOnly())
662 return ReadOnlySection;
664 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
665 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
666 return DataRelROSection;
669 //===----------------------------------------------------------------------===//
671 //===----------------------------------------------------------------------===//
673 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
675 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
676 // If we have the MachO uniquing map, free it.
677 delete (MachOUniqueMapTy*)UniquingMap;
681 const MCSectionMachO *TargetLoweringObjectFileMachO::
682 getMachOSection(StringRef Segment, StringRef Section,
683 unsigned TypeAndAttributes,
684 unsigned Reserved2, SectionKind Kind) const {
685 // We unique sections by their segment/section pair. The returned section
686 // may not have the same flags as the requested section, if so this should be
687 // diagnosed by the client as an error.
689 // Create the map if it doesn't already exist.
690 if (UniquingMap == 0)
691 UniquingMap = new MachOUniqueMapTy();
692 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
694 // Form the name to look up.
695 SmallString<64> Name;
700 // Do the lookup, if we have a hit, return it.
701 const MCSectionMachO *&Entry = Map[Name.str()];
702 if (Entry) return Entry;
704 // Otherwise, return a new section.
705 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
706 Reserved2, Kind, getContext());
710 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
711 const TargetMachine &TM) {
712 if (UniquingMap != 0)
713 ((MachOUniqueMapTy*)UniquingMap)->clear();
714 TargetLoweringObjectFile::Initialize(Ctx, TM);
717 = getMachOSection("__TEXT", "__text",
718 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
719 SectionKind::getText());
721 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
723 CStringSection // .cstring
724 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
725 SectionKind::getMergeable1ByteCString());
727 = getMachOSection("__TEXT","__ustring", 0,
728 SectionKind::getMergeable2ByteCString());
729 FourByteConstantSection // .literal4
730 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
731 SectionKind::getMergeableConst4());
732 EightByteConstantSection // .literal8
733 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
734 SectionKind::getMergeableConst8());
736 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
737 // to using it in -static mode.
738 SixteenByteConstantSection = 0;
739 if (TM.getRelocationModel() != Reloc::Static &&
740 TM.getTargetData()->getPointerSize() == 32)
741 SixteenByteConstantSection = // .literal16
742 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
743 SectionKind::getMergeableConst16());
745 ReadOnlySection // .const
746 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
749 = getMachOSection("__TEXT", "__textcoal_nt",
750 MCSectionMachO::S_COALESCED |
751 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
752 SectionKind::getText());
754 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
755 SectionKind::getText());
757 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
758 SectionKind::getText());
760 = getMachOSection("__DATA","__common", MCSectionMachO::S_ZEROFILL,
761 SectionKind::getBSS());
762 ConstDataSection // .const_data
763 = getMachOSection("__DATA", "__const", 0,
764 SectionKind::getReadOnlyWithRel());
766 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
767 SectionKind::getDataRel());
770 LazySymbolPointerSection
771 = getMachOSection("__DATA", "__la_symbol_ptr",
772 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
773 SectionKind::getMetadata());
774 NonLazySymbolPointerSection
775 = getMachOSection("__DATA", "__nl_symbol_ptr",
776 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
777 SectionKind::getMetadata());
779 if (TM.getRelocationModel() == Reloc::Static) {
781 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
783 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
786 = getMachOSection("__DATA", "__mod_init_func",
787 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
788 SectionKind::getDataRel());
790 = getMachOSection("__DATA", "__mod_term_func",
791 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
792 SectionKind::getDataRel());
795 // Exception Handling.
796 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
797 SectionKind::getDataRel());
799 getMachOSection("__TEXT", "__eh_frame",
800 MCSectionMachO::S_COALESCED |
801 MCSectionMachO::S_ATTR_NO_TOC |
802 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
803 MCSectionMachO::S_ATTR_LIVE_SUPPORT,
804 SectionKind::getReadOnly());
806 // Debug Information.
808 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
809 SectionKind::getMetadata());
811 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
812 SectionKind::getMetadata());
814 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
815 SectionKind::getMetadata());
817 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
818 SectionKind::getMetadata());
819 DwarfPubNamesSection =
820 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
821 SectionKind::getMetadata());
822 DwarfPubTypesSection =
823 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
824 SectionKind::getMetadata());
826 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
827 SectionKind::getMetadata());
829 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
830 SectionKind::getMetadata());
831 DwarfARangesSection =
832 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
833 SectionKind::getMetadata());
835 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
836 SectionKind::getMetadata());
837 DwarfMacroInfoSection =
838 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
839 SectionKind::getMetadata());
840 DwarfDebugInlineSection =
841 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
842 SectionKind::getMetadata());
845 const MCSection *TargetLoweringObjectFileMachO::
846 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
847 Mangler *Mang, const TargetMachine &TM) const {
848 // Parse the section specifier and create it if valid.
849 StringRef Segment, Section;
850 unsigned TAA, StubSize;
851 std::string ErrorCode =
852 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
854 if (!ErrorCode.empty()) {
855 // If invalid, report the error with llvm_report_error.
856 llvm_report_error("Global variable '" + GV->getNameStr() +
857 "' has an invalid section specifier '" + GV->getSection()+
858 "': " + ErrorCode + ".");
859 // Fall back to dropping it into the data section.
864 const MCSectionMachO *S =
865 getMachOSection(Segment, Section, TAA, StubSize, Kind);
867 // Okay, now that we got the section, verify that the TAA & StubSize agree.
868 // If the user declared multiple globals with different section flags, we need
869 // to reject it here.
870 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
871 // If invalid, report the error with llvm_report_error.
872 llvm_report_error("Global variable '" + GV->getNameStr() +
873 "' section type or attributes does not match previous"
874 " section specifier");
880 const MCSection *TargetLoweringObjectFileMachO::
881 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
882 Mangler *Mang, const TargetMachine &TM) const {
883 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
886 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
888 // If this is weak/linkonce, put this in a coalescable section, either in text
889 // or data depending on if it is writable.
890 if (GV->isWeakForLinker()) {
891 if (Kind.isReadOnly())
892 return ConstTextCoalSection;
893 return DataCoalSection;
896 // FIXME: Alignment check should be handled by section classifier.
897 if (Kind.isMergeable1ByteCString() ||
898 Kind.isMergeable2ByteCString()) {
899 if (TM.getTargetData()->getPreferredAlignment(
900 cast<GlobalVariable>(GV)) < 32) {
901 if (Kind.isMergeable1ByteCString())
902 return CStringSection;
903 assert(Kind.isMergeable2ByteCString());
904 return UStringSection;
908 if (Kind.isMergeableConst()) {
909 if (Kind.isMergeableConst4())
910 return FourByteConstantSection;
911 if (Kind.isMergeableConst8())
912 return EightByteConstantSection;
913 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
914 return SixteenByteConstantSection;
917 // Otherwise, if it is readonly, but not something we can specially optimize,
918 // just drop it in .const.
919 if (Kind.isReadOnly())
920 return ReadOnlySection;
922 // If this is marked const, put it into a const section. But if the dynamic
923 // linker needs to write to it, put it in the data segment.
924 if (Kind.isReadOnlyWithRel())
925 return ConstDataSection;
927 // Put zero initialized globals with strong external linkage in the
928 // DATA, __common section with the .zerofill directive.
929 if (Kind.isBSS() && GV->hasExternalLinkage())
930 return DataCommonSection;
932 // Otherwise, just drop the variable in the normal data section.
937 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
938 // If this constant requires a relocation, we have to put it in the data
939 // segment, not in the text segment.
940 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
941 return ConstDataSection;
943 if (Kind.isMergeableConst4())
944 return FourByteConstantSection;
945 if (Kind.isMergeableConst8())
946 return EightByteConstantSection;
947 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
948 return SixteenByteConstantSection;
949 return ReadOnlySection; // .const
952 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
953 /// not to emit the UsedDirective for some symbols in llvm.used.
954 // FIXME: REMOVE this (rdar://7071300)
955 bool TargetLoweringObjectFileMachO::
956 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
957 /// On Darwin, internally linked data beginning with "L" or "l" does not have
958 /// the directive emitted (this occurs in ObjC metadata).
959 if (!GV) return false;
961 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
962 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
963 // FIXME: ObjC metadata is currently emitted as internal symbols that have
964 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
965 // this horrible hack can go away.
966 SmallString<64> Name;
967 Mang->getNameWithPrefix(Name, GV, false);
968 if (Name[0] == 'L' || Name[0] == 'l')
975 const MCExpr *TargetLoweringObjectFileMachO::
976 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
977 MachineModuleInfo *MMI,
978 bool &IsIndirect, bool &IsPCRel) const {
979 // The mach-o version of this method defaults to returning a stub reference.
983 SmallString<128> Name;
984 Mang->getNameWithPrefix(Name, GV, true);
985 Name += "$non_lazy_ptr";
986 return MCSymbolRefExpr::Create(Name.str(), getContext());
990 //===----------------------------------------------------------------------===//
992 //===----------------------------------------------------------------------===//
994 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
996 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
997 delete (COFFUniqueMapTy*)UniquingMap;
1001 const MCSection *TargetLoweringObjectFileCOFF::
1002 getCOFFSection(StringRef Name, bool isDirective, SectionKind Kind) const {
1003 // Create the map if it doesn't already exist.
1004 if (UniquingMap == 0)
1005 UniquingMap = new MachOUniqueMapTy();
1006 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
1008 // Do the lookup, if we have a hit, return it.
1009 const MCSectionCOFF *&Entry = Map[Name];
1010 if (Entry) return Entry;
1012 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
1015 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1016 const TargetMachine &TM) {
1017 if (UniquingMap != 0)
1018 ((COFFUniqueMapTy*)UniquingMap)->clear();
1019 TargetLoweringObjectFile::Initialize(Ctx, TM);
1020 TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
1021 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
1023 getCOFFSection(".ctors", false, SectionKind::getDataRel());
1025 getCOFFSection(".dtors", false, SectionKind::getDataRel());
1027 // FIXME: We're emitting LSDA info into a readonly section on COFF, even
1028 // though it contains relocatable pointers. In PIC mode, this is probably a
1029 // big runtime hit for C++ apps. Either the contents of the LSDA need to be
1030 // adjusted or this should be a data section.
1032 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
1034 getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
1037 // FIXME: Don't use 'directive' mode here.
1038 DwarfAbbrevSection =
1039 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
1040 true, SectionKind::getMetadata());
1042 getCOFFSection("\t.section\t.debug_info,\"dr\"",
1043 true, SectionKind::getMetadata());
1045 getCOFFSection("\t.section\t.debug_line,\"dr\"",
1046 true, SectionKind::getMetadata());
1048 getCOFFSection("\t.section\t.debug_frame,\"dr\"",
1049 true, SectionKind::getMetadata());
1050 DwarfPubNamesSection =
1051 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
1052 true, SectionKind::getMetadata());
1053 DwarfPubTypesSection =
1054 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
1055 true, SectionKind::getMetadata());
1057 getCOFFSection("\t.section\t.debug_str,\"dr\"",
1058 true, SectionKind::getMetadata());
1060 getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1061 true, SectionKind::getMetadata());
1062 DwarfARangesSection =
1063 getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1064 true, SectionKind::getMetadata());
1065 DwarfRangesSection =
1066 getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1067 true, SectionKind::getMetadata());
1068 DwarfMacroInfoSection =
1069 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1070 true, SectionKind::getMetadata());
1073 const MCSection *TargetLoweringObjectFileCOFF::
1074 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
1075 Mangler *Mang, const TargetMachine &TM) const {
1076 return getCOFFSection(GV->getSection().c_str(), false, Kind);
1079 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1081 return ".text$linkonce";
1082 if (Kind.isWriteable())
1083 return ".data$linkonce";
1084 return ".rdata$linkonce";
1088 const MCSection *TargetLoweringObjectFileCOFF::
1089 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1090 Mangler *Mang, const TargetMachine &TM) const {
1091 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1093 // If this global is linkonce/weak and the target handles this by emitting it
1094 // into a 'uniqued' section name, create and return the section now.
1095 if (GV->isWeakForLinker()) {
1096 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1097 SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
1098 Mang->getNameWithPrefix(Name, GV, false);
1099 return getCOFFSection(Name.str(), false, Kind);
1103 return getTextSection();
1105 return getDataSection();