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/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
41 StaticCtorSection = 0;
42 StaticDtorSection = 0;
46 DwarfAbbrevSection = 0;
49 DwarfFrameSection = 0;
50 DwarfPubNamesSection = 0;
51 DwarfPubTypesSection = 0;
52 DwarfDebugInlineSection = 0;
55 DwarfARangesSection = 0;
56 DwarfRangesSection = 0;
57 DwarfMacroInfoSection = 0;
60 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
63 static bool isSuitableForBSS(const GlobalVariable *GV) {
64 Constant *C = GV->getInitializer();
66 // Must have zero initializer.
67 if (!C->isNullValue())
70 // Leave constant zeros in readonly constant sections, so they can be shared.
74 // If the global has an explicit section specified, don't put it in BSS.
75 if (!GV->getSection().empty())
78 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
82 // Otherwise, put it in BSS!
86 /// IsNullTerminatedString - Return true if the specified constant (which is
87 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
88 /// nul value and contains no other nuls in it.
89 static bool IsNullTerminatedString(const Constant *C) {
90 const ArrayType *ATy = cast<ArrayType>(C->getType());
92 // First check: is we have constant array of i8 terminated with zero
93 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
94 if (ATy->getNumElements() == 0) return false;
97 dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
98 if (Null == 0 || Null->getZExtValue() != 0)
99 return false; // Not null terminated.
101 // Verify that the null doesn't occur anywhere else in the string.
102 for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
103 // Reject constantexpr elements etc.
104 if (!isa<ConstantInt>(CVA->getOperand(i)) ||
105 CVA->getOperand(i) == Null)
110 // Another possibility: [1 x i8] zeroinitializer
111 if (isa<ConstantAggregateZero>(C))
112 return ATy->getNumElements() == 1;
117 /// getKindForGlobal - This is a top-level target-independent classifier for
118 /// a global variable. Given an global variable and information from TM, it
119 /// classifies the global in a variety of ways that make various target
120 /// implementations simpler. The target implementation is free to ignore this
121 /// extra info of course.
122 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
123 const TargetMachine &TM){
124 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
125 "Can only be used for global definitions");
127 Reloc::Model ReloModel = TM.getRelocationModel();
129 // Early exit - functions should be always in text sections.
130 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
132 return SectionKind::getText();
134 // Handle thread-local data first.
135 if (GVar->isThreadLocal()) {
136 if (isSuitableForBSS(GVar))
137 return SectionKind::getThreadBSS();
138 return SectionKind::getThreadData();
141 // Variable can be easily put to BSS section.
142 if (isSuitableForBSS(GVar))
143 return SectionKind::getBSS();
145 Constant *C = GVar->getInitializer();
147 // If the global is marked constant, we can put it into a mergable section,
148 // a mergable string section, or general .data if it contains relocations.
149 if (GVar->isConstant()) {
150 // If the initializer for the global contains something that requires a
151 // relocation, then we may have to drop this into a wriable data section
152 // even though it is marked const.
153 switch (C->getRelocationInfo()) {
154 default: llvm_unreachable("unknown relocation info kind");
155 case Constant::NoRelocation:
156 // If initializer is a null-terminated string, put it in a "cstring"
157 // section of the right width.
158 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
159 if (const IntegerType *ITy =
160 dyn_cast<IntegerType>(ATy->getElementType())) {
161 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
162 ITy->getBitWidth() == 32) &&
163 IsNullTerminatedString(C)) {
164 if (ITy->getBitWidth() == 8)
165 return SectionKind::getMergeable1ByteCString();
166 if (ITy->getBitWidth() == 16)
167 return SectionKind::getMergeable2ByteCString();
169 assert(ITy->getBitWidth() == 32 && "Unknown width");
170 return SectionKind::getMergeable4ByteCString();
175 // Otherwise, just drop it into a mergable constant section. If we have
176 // a section for this size, use it, otherwise use the arbitrary sized
178 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
179 case 4: return SectionKind::getMergeableConst4();
180 case 8: return SectionKind::getMergeableConst8();
181 case 16: return SectionKind::getMergeableConst16();
182 default: return SectionKind::getMergeableConst();
185 case Constant::LocalRelocation:
186 // In static relocation model, the linker will resolve all addresses, so
187 // the relocation entries will actually be constants by the time the app
188 // starts up. However, we can't put this into a mergable section, because
189 // the linker doesn't take relocations into consideration when it tries to
190 // merge entries in the section.
191 if (ReloModel == Reloc::Static)
192 return SectionKind::getReadOnly();
194 // Otherwise, the dynamic linker needs to fix it up, put it in the
195 // writable data.rel.local section.
196 return SectionKind::getReadOnlyWithRelLocal();
198 case Constant::GlobalRelocations:
199 // In static relocation model, the linker will resolve all addresses, so
200 // the relocation entries will actually be constants by the time the app
201 // starts up. However, we can't put this into a mergable section, because
202 // the linker doesn't take relocations into consideration when it tries to
203 // merge entries in the section.
204 if (ReloModel == Reloc::Static)
205 return SectionKind::getReadOnly();
207 // Otherwise, the dynamic linker needs to fix it up, put it in the
208 // writable data.rel section.
209 return SectionKind::getReadOnlyWithRel();
213 // Okay, this isn't a constant. If the initializer for the global is going
214 // to require a runtime relocation by the dynamic linker, put it into a more
215 // specific section to improve startup time of the app. This coalesces these
216 // globals together onto fewer pages, improving the locality of the dynamic
218 if (ReloModel == Reloc::Static)
219 return SectionKind::getDataNoRel();
221 switch (C->getRelocationInfo()) {
222 default: llvm_unreachable("unknown relocation info kind");
223 case Constant::NoRelocation:
224 return SectionKind::getDataNoRel();
225 case Constant::LocalRelocation:
226 return SectionKind::getDataRelLocal();
227 case Constant::GlobalRelocations:
228 return SectionKind::getDataRel();
232 /// SectionForGlobal - This method computes the appropriate section to emit
233 /// the specified global variable or function definition. This should not
234 /// be passed external (or available externally) globals.
235 const MCSection *TargetLoweringObjectFile::
236 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
237 const TargetMachine &TM) const {
238 // Select section name.
239 if (GV->hasSection())
240 return getExplicitSectionGlobal(GV, Kind, Mang, TM);
243 // Use default section depending on the 'type' of global
244 return SelectSectionForGlobal(GV, Kind, Mang, TM);
248 // Lame default implementation. Calculate the section name for global.
250 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
253 const TargetMachine &TM) const{
254 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
257 return getTextSection();
259 if (Kind.isBSS() && BSSSection != 0)
262 if (Kind.isReadOnly() && ReadOnlySection != 0)
263 return ReadOnlySection;
265 return getDataSection();
268 /// getSectionForConstant - Given a mergable constant with the
269 /// specified size and relocation information, return a section that it
270 /// should be placed in.
272 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
273 if (Kind.isReadOnly() && ReadOnlySection != 0)
274 return ReadOnlySection;
279 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a
280 /// pc-relative reference to the specified global variable from exception
281 /// handling information. In addition to the symbol, this returns
284 /// IsIndirect - True if the returned symbol is actually a stub that contains
285 /// the address of the symbol, false if the symbol is the global itself.
287 /// IsPCRel - True if the symbol reference is already pc-relative, false if
288 /// the caller needs to subtract off the address of the reference from the
291 const MCExpr *TargetLoweringObjectFile::
292 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
293 bool &IsIndirect, bool &IsPCRel) const {
294 // The generic implementation of this just returns a direct reference to the
299 SmallString<128> Name;
300 Mang->getNameWithPrefix(Name, GV, false);
301 return MCSymbolRefExpr::Create(Name.str(), getContext());
305 //===----------------------------------------------------------------------===//
307 //===----------------------------------------------------------------------===//
308 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
310 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
311 // If we have the section uniquing map, free it.
312 delete (ELFUniqueMapTy*)UniquingMap;
315 const MCSection *TargetLoweringObjectFileELF::
316 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
317 SectionKind Kind, bool IsExplicit) const {
318 if (UniquingMap == 0)
319 UniquingMap = new ELFUniqueMapTy();
320 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
322 // Do the lookup, if we have a hit, return it.
323 const MCSectionELF *&Entry = Map[Section];
324 if (Entry) return Entry;
326 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
330 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
331 const TargetMachine &TM) {
332 if (UniquingMap != 0)
333 ((ELFUniqueMapTy*)UniquingMap)->clear();
334 TargetLoweringObjectFile::Initialize(Ctx, TM);
337 getELFSection(".bss", MCSectionELF::SHT_NOBITS,
338 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
339 SectionKind::getBSS());
342 getELFSection(".text", MCSectionELF::SHT_PROGBITS,
343 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
344 SectionKind::getText());
347 getELFSection(".data", MCSectionELF::SHT_PROGBITS,
348 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
349 SectionKind::getDataRel());
352 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
353 MCSectionELF::SHF_ALLOC,
354 SectionKind::getReadOnly());
357 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
358 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
359 MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
362 getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
363 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
364 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
367 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
368 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
369 SectionKind::getDataRel());
371 DataRelLocalSection =
372 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
373 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
374 SectionKind::getDataRelLocal());
377 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
378 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
379 SectionKind::getReadOnlyWithRel());
381 DataRelROLocalSection =
382 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
383 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
384 SectionKind::getReadOnlyWithRelLocal());
386 MergeableConst4Section =
387 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
388 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
389 SectionKind::getMergeableConst4());
391 MergeableConst8Section =
392 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
393 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
394 SectionKind::getMergeableConst8());
396 MergeableConst16Section =
397 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
398 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
399 SectionKind::getMergeableConst16());
402 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
403 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
404 SectionKind::getDataRel());
407 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
408 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
409 SectionKind::getDataRel());
411 // Exception Handling Sections.
413 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
414 // it contains relocatable pointers. In PIC mode, this is probably a big
415 // runtime hit for C++ apps. Either the contents of the LSDA need to be
416 // adjusted or this should be a data section.
418 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
419 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
421 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
422 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
423 SectionKind::getDataRel());
425 // Debug Info Sections.
427 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
428 SectionKind::getMetadata());
430 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
431 SectionKind::getMetadata());
433 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
434 SectionKind::getMetadata());
436 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
437 SectionKind::getMetadata());
438 DwarfPubNamesSection =
439 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
440 SectionKind::getMetadata());
441 DwarfPubTypesSection =
442 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
443 SectionKind::getMetadata());
445 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
446 SectionKind::getMetadata());
448 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
449 SectionKind::getMetadata());
450 DwarfARangesSection =
451 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
452 SectionKind::getMetadata());
454 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
455 SectionKind::getMetadata());
456 DwarfMacroInfoSection =
457 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
458 SectionKind::getMetadata());
463 getELFKindForNamedSection(const char *Name, SectionKind K) {
464 if (Name[0] != '.') return K;
466 // Some lame default implementation based on some magic section names.
467 if (strcmp(Name, ".bss") == 0 ||
468 strncmp(Name, ".bss.", 5) == 0 ||
469 strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
470 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
471 strcmp(Name, ".sbss") == 0 ||
472 strncmp(Name, ".sbss.", 6) == 0 ||
473 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
474 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
475 return SectionKind::getBSS();
477 if (strcmp(Name, ".tdata") == 0 ||
478 strncmp(Name, ".tdata.", 7) == 0 ||
479 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
480 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
481 return SectionKind::getThreadData();
483 if (strcmp(Name, ".tbss") == 0 ||
484 strncmp(Name, ".tbss.", 6) == 0 ||
485 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
486 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
487 return SectionKind::getThreadBSS();
494 getELFSectionType(const char *Name, SectionKind K) {
496 if (strcmp(Name, ".init_array") == 0)
497 return MCSectionELF::SHT_INIT_ARRAY;
499 if (strcmp(Name, ".fini_array") == 0)
500 return MCSectionELF::SHT_FINI_ARRAY;
502 if (strcmp(Name, ".preinit_array") == 0)
503 return MCSectionELF::SHT_PREINIT_ARRAY;
505 if (K.isBSS() || K.isThreadBSS())
506 return MCSectionELF::SHT_NOBITS;
508 return MCSectionELF::SHT_PROGBITS;
513 getELFSectionFlags(SectionKind K) {
517 Flags |= MCSectionELF::SHF_ALLOC;
520 Flags |= MCSectionELF::SHF_EXECINSTR;
523 Flags |= MCSectionELF::SHF_WRITE;
525 if (K.isThreadLocal())
526 Flags |= MCSectionELF::SHF_TLS;
528 // K.isMergeableConst() is left out to honour PR4650
529 if (K.isMergeableCString() || K.isMergeableConst4() ||
530 K.isMergeableConst8() || K.isMergeableConst16())
531 Flags |= MCSectionELF::SHF_MERGE;
533 if (K.isMergeableCString())
534 Flags |= MCSectionELF::SHF_STRINGS;
540 const MCSection *TargetLoweringObjectFileELF::
541 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
542 Mangler *Mang, const TargetMachine &TM) const {
543 const char *SectionName = GV->getSection().c_str();
545 // Infer section flags from the section name if we can.
546 Kind = getELFKindForNamedSection(SectionName, Kind);
548 return getELFSection(SectionName,
549 getELFSectionType(SectionName, Kind),
550 getELFSectionFlags(Kind), Kind, true);
553 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
554 if (Kind.isText()) return ".gnu.linkonce.t.";
555 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
557 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
558 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
560 if (Kind.isBSS()) return ".gnu.linkonce.b.";
561 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
562 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
563 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
564 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
566 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
567 return ".gnu.linkonce.d.rel.ro.";
570 const MCSection *TargetLoweringObjectFileELF::
571 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
572 Mangler *Mang, const TargetMachine &TM) const {
574 // If this global is linkonce/weak and the target handles this by emitting it
575 // into a 'uniqued' section name, create and return the section now.
576 if (GV->isWeakForLinker()) {
577 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
578 std::string Name = Mang->makeNameProper(GV->getNameStr());
580 return getELFSection((Prefix+Name).c_str(),
581 getELFSectionType((Prefix+Name).c_str(), Kind),
582 getELFSectionFlags(Kind),
586 if (Kind.isText()) return TextSection;
588 if (Kind.isMergeable1ByteCString() ||
589 Kind.isMergeable2ByteCString() ||
590 Kind.isMergeable4ByteCString()) {
592 // We also need alignment here.
593 // FIXME: this is getting the alignment of the character, not the
594 // alignment of the global!
596 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
598 const char *SizeSpec = ".rodata.str1.";
599 if (Kind.isMergeable2ByteCString())
600 SizeSpec = ".rodata.str2.";
601 else if (Kind.isMergeable4ByteCString())
602 SizeSpec = ".rodata.str4.";
604 assert(Kind.isMergeable1ByteCString() && "unknown string width");
607 std::string Name = SizeSpec + utostr(Align);
608 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS,
609 MCSectionELF::SHF_ALLOC |
610 MCSectionELF::SHF_MERGE |
611 MCSectionELF::SHF_STRINGS,
615 if (Kind.isMergeableConst()) {
616 if (Kind.isMergeableConst4() && MergeableConst4Section)
617 return MergeableConst4Section;
618 if (Kind.isMergeableConst8() && MergeableConst8Section)
619 return MergeableConst8Section;
620 if (Kind.isMergeableConst16() && MergeableConst16Section)
621 return MergeableConst16Section;
622 return ReadOnlySection; // .const
625 if (Kind.isReadOnly()) return ReadOnlySection;
627 if (Kind.isThreadData()) return TLSDataSection;
628 if (Kind.isThreadBSS()) return TLSBSSSection;
630 if (Kind.isBSS()) return BSSSection;
632 if (Kind.isDataNoRel()) return DataSection;
633 if (Kind.isDataRelLocal()) return DataRelLocalSection;
634 if (Kind.isDataRel()) return DataRelSection;
635 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
637 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
638 return DataRelROSection;
641 /// getSectionForConstant - Given a mergeable constant with the
642 /// specified size and relocation information, return a section that it
643 /// should be placed in.
644 const MCSection *TargetLoweringObjectFileELF::
645 getSectionForConstant(SectionKind Kind) const {
646 if (Kind.isMergeableConst4() && MergeableConst4Section)
647 return MergeableConst4Section;
648 if (Kind.isMergeableConst8() && MergeableConst8Section)
649 return MergeableConst8Section;
650 if (Kind.isMergeableConst16() && MergeableConst16Section)
651 return MergeableConst16Section;
652 if (Kind.isReadOnly())
653 return ReadOnlySection;
655 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
656 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
657 return DataRelROSection;
660 //===----------------------------------------------------------------------===//
662 //===----------------------------------------------------------------------===//
664 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
666 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
667 // If we have the MachO uniquing map, free it.
668 delete (MachOUniqueMapTy*)UniquingMap;
672 const MCSectionMachO *TargetLoweringObjectFileMachO::
673 getMachOSection(const StringRef &Segment, const StringRef &Section,
674 unsigned TypeAndAttributes,
675 unsigned Reserved2, SectionKind Kind) const {
676 // We unique sections by their segment/section pair. The returned section
677 // may not have the same flags as the requested section, if so this should be
678 // diagnosed by the client as an error.
680 // Create the map if it doesn't already exist.
681 if (UniquingMap == 0)
682 UniquingMap = new MachOUniqueMapTy();
683 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
685 // Form the name to look up.
686 SmallString<64> Name;
691 // Do the lookup, if we have a hit, return it.
692 const MCSectionMachO *&Entry = Map[Name.str()];
693 if (Entry) return Entry;
695 // Otherwise, return a new section.
696 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
697 Reserved2, Kind, getContext());
701 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
702 const TargetMachine &TM) {
703 if (UniquingMap != 0)
704 ((MachOUniqueMapTy*)UniquingMap)->clear();
705 TargetLoweringObjectFile::Initialize(Ctx, TM);
708 = getMachOSection("__TEXT", "__text",
709 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
710 SectionKind::getText());
712 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
714 CStringSection // .cstring
715 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
716 SectionKind::getMergeable1ByteCString());
718 = getMachOSection("__TEXT","__ustring", 0,
719 SectionKind::getMergeable2ByteCString());
720 FourByteConstantSection // .literal4
721 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
722 SectionKind::getMergeableConst4());
723 EightByteConstantSection // .literal8
724 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
725 SectionKind::getMergeableConst8());
727 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
728 // to using it in -static mode.
729 SixteenByteConstantSection = 0;
730 if (TM.getRelocationModel() != Reloc::Static &&
731 TM.getTargetData()->getPointerSize() == 32)
732 SixteenByteConstantSection = // .literal16
733 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
734 SectionKind::getMergeableConst16());
736 ReadOnlySection // .const
737 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
740 = getMachOSection("__TEXT", "__textcoal_nt",
741 MCSectionMachO::S_COALESCED |
742 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
743 SectionKind::getText());
745 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
746 SectionKind::getText());
748 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
749 SectionKind::getText());
750 ConstDataSection // .const_data
751 = getMachOSection("__DATA", "__const", 0,
752 SectionKind::getReadOnlyWithRel());
754 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
755 SectionKind::getDataRel());
758 LazySymbolPointerSection
759 = getMachOSection("__DATA", "__la_symbol_ptr",
760 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
761 SectionKind::getMetadata());
762 NonLazySymbolPointerSection
763 = getMachOSection("__DATA", "__nl_symbol_ptr",
764 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
765 SectionKind::getMetadata());
767 if (TM.getRelocationModel() == Reloc::Static) {
769 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
771 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
774 = getMachOSection("__DATA", "__mod_init_func",
775 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
776 SectionKind::getDataRel());
778 = getMachOSection("__DATA", "__mod_term_func",
779 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
780 SectionKind::getDataRel());
783 // Exception Handling.
784 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
785 SectionKind::getDataRel());
787 getMachOSection("__TEXT", "__eh_frame",
788 MCSectionMachO::S_COALESCED |
789 MCSectionMachO::S_ATTR_NO_TOC |
790 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
791 MCSectionMachO::S_ATTR_LIVE_SUPPORT,
792 SectionKind::getReadOnly());
794 // Debug Information.
796 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
797 SectionKind::getMetadata());
799 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
800 SectionKind::getMetadata());
802 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
803 SectionKind::getMetadata());
805 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
806 SectionKind::getMetadata());
807 DwarfPubNamesSection =
808 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
809 SectionKind::getMetadata());
810 DwarfPubTypesSection =
811 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
812 SectionKind::getMetadata());
814 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
815 SectionKind::getMetadata());
817 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
818 SectionKind::getMetadata());
819 DwarfARangesSection =
820 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
821 SectionKind::getMetadata());
823 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
824 SectionKind::getMetadata());
825 DwarfMacroInfoSection =
826 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
827 SectionKind::getMetadata());
828 DwarfDebugInlineSection =
829 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
830 SectionKind::getMetadata());
833 const MCSection *TargetLoweringObjectFileMachO::
834 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
835 Mangler *Mang, const TargetMachine &TM) const {
836 // Parse the section specifier and create it if valid.
837 StringRef Segment, Section;
838 unsigned TAA, StubSize;
839 std::string ErrorCode =
840 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
842 if (!ErrorCode.empty()) {
843 // If invalid, report the error with llvm_report_error.
844 llvm_report_error("Global variable '" + GV->getNameStr() +
845 "' has an invalid section specifier '" + GV->getSection()+
846 "': " + ErrorCode + ".");
847 // Fall back to dropping it into the data section.
852 const MCSectionMachO *S =
853 getMachOSection(Segment, Section, TAA, StubSize, Kind);
855 // Okay, now that we got the section, verify that the TAA & StubSize agree.
856 // If the user declared multiple globals with different section flags, we need
857 // to reject it here.
858 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
859 // If invalid, report the error with llvm_report_error.
860 llvm_report_error("Global variable '" + GV->getNameStr() +
861 "' section type or attributes does not match previous"
862 " section specifier");
868 const MCSection *TargetLoweringObjectFileMachO::
869 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
870 Mangler *Mang, const TargetMachine &TM) const {
871 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
874 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
876 // If this is weak/linkonce, put this in a coalescable section, either in text
877 // or data depending on if it is writable.
878 if (GV->isWeakForLinker()) {
879 if (Kind.isReadOnly())
880 return ConstTextCoalSection;
881 return DataCoalSection;
884 // FIXME: Alignment check should be handled by section classifier.
885 if (Kind.isMergeable1ByteCString() ||
886 Kind.isMergeable2ByteCString()) {
887 if (TM.getTargetData()->getPreferredAlignment(
888 cast<GlobalVariable>(GV)) < 32) {
889 if (Kind.isMergeable1ByteCString())
890 return CStringSection;
891 assert(Kind.isMergeable2ByteCString());
892 return UStringSection;
896 if (Kind.isMergeableConst()) {
897 if (Kind.isMergeableConst4())
898 return FourByteConstantSection;
899 if (Kind.isMergeableConst8())
900 return EightByteConstantSection;
901 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
902 return SixteenByteConstantSection;
905 // Otherwise, if it is readonly, but not something we can specially optimize,
906 // just drop it in .const.
907 if (Kind.isReadOnly())
908 return ReadOnlySection;
910 // If this is marked const, put it into a const section. But if the dynamic
911 // linker needs to write to it, put it in the data segment.
912 if (Kind.isReadOnlyWithRel())
913 return ConstDataSection;
915 // Otherwise, just drop the variable in the normal data section.
920 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
921 // If this constant requires a relocation, we have to put it in the data
922 // segment, not in the text segment.
923 if (Kind.isDataRel())
924 return ConstDataSection;
926 if (Kind.isMergeableConst4())
927 return FourByteConstantSection;
928 if (Kind.isMergeableConst8())
929 return EightByteConstantSection;
930 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
931 return SixteenByteConstantSection;
932 return ReadOnlySection; // .const
935 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
936 /// not to emit the UsedDirective for some symbols in llvm.used.
937 // FIXME: REMOVE this (rdar://7071300)
938 bool TargetLoweringObjectFileMachO::
939 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
940 /// On Darwin, internally linked data beginning with "L" or "l" does not have
941 /// the directive emitted (this occurs in ObjC metadata).
942 if (!GV) return false;
944 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
945 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
946 // FIXME: ObjC metadata is currently emitted as internal symbols that have
947 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
948 // this horrible hack can go away.
949 const std::string &Name = Mang->getMangledName(GV);
950 if (Name[0] == 'L' || Name[0] == 'l')
957 const MCExpr *TargetLoweringObjectFileMachO::
958 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
959 bool &IsIndirect, bool &IsPCRel) const {
960 // The mach-o version of this method defaults to returning a stub reference.
964 SmallString<128> Name;
965 Mang->getNameWithPrefix(Name, GV, true);
966 Name += "$non_lazy_ptr";
967 return MCSymbolRefExpr::Create(Name.str(), getContext());
971 //===----------------------------------------------------------------------===//
973 //===----------------------------------------------------------------------===//
975 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
977 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
978 delete (COFFUniqueMapTy*)UniquingMap;
982 const MCSection *TargetLoweringObjectFileCOFF::
983 getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
984 // Create the map if it doesn't already exist.
985 if (UniquingMap == 0)
986 UniquingMap = new MachOUniqueMapTy();
987 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
989 // Do the lookup, if we have a hit, return it.
990 const MCSectionCOFF *&Entry = Map[Name];
991 if (Entry) return Entry;
993 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
996 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
997 const TargetMachine &TM) {
998 if (UniquingMap != 0)
999 ((COFFUniqueMapTy*)UniquingMap)->clear();
1000 TargetLoweringObjectFile::Initialize(Ctx, TM);
1001 TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
1002 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
1004 getCOFFSection(".ctors", false, SectionKind::getDataRel());
1006 getCOFFSection(".dtors", false, SectionKind::getDataRel());
1008 // FIXME: We're emitting LSDA info into a readonly section on COFF, even
1009 // though it contains relocatable pointers. In PIC mode, this is probably a
1010 // big runtime hit for C++ apps. Either the contents of the LSDA need to be
1011 // adjusted or this should be a data section.
1013 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
1015 getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
1018 // FIXME: Don't use 'directive' mode here.
1019 DwarfAbbrevSection =
1020 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
1021 true, SectionKind::getMetadata());
1023 getCOFFSection("\t.section\t.debug_info,\"dr\"",
1024 true, SectionKind::getMetadata());
1026 getCOFFSection("\t.section\t.debug_line,\"dr\"",
1027 true, SectionKind::getMetadata());
1029 getCOFFSection("\t.section\t.debug_frame,\"dr\"",
1030 true, SectionKind::getMetadata());
1031 DwarfPubNamesSection =
1032 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
1033 true, SectionKind::getMetadata());
1034 DwarfPubTypesSection =
1035 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
1036 true, SectionKind::getMetadata());
1038 getCOFFSection("\t.section\t.debug_str,\"dr\"",
1039 true, SectionKind::getMetadata());
1041 getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1042 true, SectionKind::getMetadata());
1043 DwarfARangesSection =
1044 getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1045 true, SectionKind::getMetadata());
1046 DwarfRangesSection =
1047 getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1048 true, SectionKind::getMetadata());
1049 DwarfMacroInfoSection =
1050 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1051 true, SectionKind::getMetadata());
1054 const MCSection *TargetLoweringObjectFileCOFF::
1055 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
1056 Mangler *Mang, const TargetMachine &TM) const {
1057 return getCOFFSection(GV->getSection().c_str(), false, Kind);
1060 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1062 return ".text$linkonce";
1063 if (Kind.isWriteable())
1064 return ".data$linkonce";
1065 return ".rdata$linkonce";
1069 const MCSection *TargetLoweringObjectFileCOFF::
1070 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1071 Mangler *Mang, const TargetMachine &TM) const {
1072 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1074 // If this global is linkonce/weak and the target handles this by emitting it
1075 // into a 'uniqued' section name, create and return the section now.
1076 if (GV->isWeakForLinker()) {
1077 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1078 std::string Name = Mang->makeNameProper(GV->getNameStr());
1079 return getCOFFSection((Prefix+Name).c_str(), false, Kind);
1083 return getTextSection();
1085 return getDataSection();