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 // Variable can be easily put to BSS section.
145 if (isSuitableForBSS(GVar))
146 return SectionKind::getBSS();
148 Constant *C = GVar->getInitializer();
150 // If the global is marked constant, we can put it into a mergable section,
151 // a mergable string section, or general .data if it contains relocations.
152 if (GVar->isConstant()) {
153 // If the initializer for the global contains something that requires a
154 // relocation, then we may have to drop this into a wriable data section
155 // even though it is marked const.
156 switch (C->getRelocationInfo()) {
157 default: assert(0 && "unknown relocation info kind");
158 case Constant::NoRelocation:
159 // If initializer is a null-terminated string, put it in a "cstring"
160 // section of the right width.
161 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
162 if (const IntegerType *ITy =
163 dyn_cast<IntegerType>(ATy->getElementType())) {
164 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
165 ITy->getBitWidth() == 32) &&
166 IsNullTerminatedString(C)) {
167 if (ITy->getBitWidth() == 8)
168 return SectionKind::getMergeable1ByteCString();
169 if (ITy->getBitWidth() == 16)
170 return SectionKind::getMergeable2ByteCString();
172 assert(ITy->getBitWidth() == 32 && "Unknown width");
173 return SectionKind::getMergeable4ByteCString();
178 // Otherwise, just drop it into a mergable constant section. If we have
179 // a section for this size, use it, otherwise use the arbitrary sized
181 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
182 case 4: return SectionKind::getMergeableConst4();
183 case 8: return SectionKind::getMergeableConst8();
184 case 16: return SectionKind::getMergeableConst16();
185 default: return SectionKind::getMergeableConst();
188 case Constant::LocalRelocation:
189 // In static relocation model, the linker will resolve all addresses, so
190 // the relocation entries will actually be constants by the time the app
191 // starts up. However, we can't put this into a mergable section, because
192 // the linker doesn't take relocations into consideration when it tries to
193 // merge entries in the section.
194 if (ReloModel == Reloc::Static)
195 return SectionKind::getReadOnly();
197 // Otherwise, the dynamic linker needs to fix it up, put it in the
198 // writable data.rel.local section.
199 return SectionKind::getReadOnlyWithRelLocal();
201 case Constant::GlobalRelocations:
202 // In static relocation model, the linker will resolve all addresses, so
203 // the relocation entries will actually be constants by the time the app
204 // starts up. However, we can't put this into a mergable section, because
205 // the linker doesn't take relocations into consideration when it tries to
206 // merge entries in the section.
207 if (ReloModel == Reloc::Static)
208 return SectionKind::getReadOnly();
210 // Otherwise, the dynamic linker needs to fix it up, put it in the
211 // writable data.rel section.
212 return SectionKind::getReadOnlyWithRel();
216 // Okay, this isn't a constant. If the initializer for the global is going
217 // to require a runtime relocation by the dynamic linker, put it into a more
218 // specific section to improve startup time of the app. This coalesces these
219 // globals together onto fewer pages, improving the locality of the dynamic
221 if (ReloModel == Reloc::Static)
222 return SectionKind::getDataNoRel();
224 switch (C->getRelocationInfo()) {
225 default: assert(0 && "unknown relocation info kind");
226 case Constant::NoRelocation:
227 return SectionKind::getDataNoRel();
228 case Constant::LocalRelocation:
229 return SectionKind::getDataRelLocal();
230 case Constant::GlobalRelocations:
231 return SectionKind::getDataRel();
235 /// SectionForGlobal - This method computes the appropriate section to emit
236 /// the specified global variable or function definition. This should not
237 /// be passed external (or available externally) globals.
238 const MCSection *TargetLoweringObjectFile::
239 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
240 const TargetMachine &TM) const {
241 // Select section name.
242 if (GV->hasSection())
243 return getExplicitSectionGlobal(GV, Kind, Mang, TM);
246 // Use default section depending on the 'type' of global
247 return SelectSectionForGlobal(GV, Kind, Mang, TM);
251 // Lame default implementation. Calculate the section name for global.
253 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
256 const TargetMachine &TM) const{
257 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
260 return getTextSection();
262 if (Kind.isBSS() && BSSSection != 0)
265 if (Kind.isReadOnly() && ReadOnlySection != 0)
266 return ReadOnlySection;
268 return getDataSection();
271 /// getSectionForConstant - Given a mergable constant with the
272 /// specified size and relocation information, return a section that it
273 /// should be placed in.
275 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
276 if (Kind.isReadOnly() && ReadOnlySection != 0)
277 return ReadOnlySection;
282 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a
283 /// pc-relative reference to the specified global variable from exception
284 /// handling information. In addition to the symbol, this returns
287 /// IsIndirect - True if the returned symbol is actually a stub that contains
288 /// the address of the symbol, false if the symbol is the global itself.
290 /// IsPCRel - True if the symbol reference is already pc-relative, false if
291 /// the caller needs to subtract off the address of the reference from the
294 const MCExpr *TargetLoweringObjectFile::
295 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
296 MachineModuleInfo *MMI,
297 bool &IsIndirect, bool &IsPCRel) const {
298 // The generic implementation of this just returns a direct reference to the
303 // FIXME: Use GetGlobalValueSymbol.
304 SmallString<128> Name;
305 Mang->getNameWithPrefix(Name, GV, false);
306 return MCSymbolRefExpr::Create(Name.str(), getContext());
310 //===----------------------------------------------------------------------===//
312 //===----------------------------------------------------------------------===//
313 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
315 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
316 // If we have the section uniquing map, free it.
317 delete (ELFUniqueMapTy*)UniquingMap;
320 const MCSection *TargetLoweringObjectFileELF::
321 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
322 SectionKind Kind, bool IsExplicit) const {
323 if (UniquingMap == 0)
324 UniquingMap = new ELFUniqueMapTy();
325 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
327 // Do the lookup, if we have a hit, return it.
328 const MCSectionELF *&Entry = Map[Section];
329 if (Entry) return Entry;
331 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
335 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
336 const TargetMachine &TM) {
337 if (UniquingMap != 0)
338 ((ELFUniqueMapTy*)UniquingMap)->clear();
339 TargetLoweringObjectFile::Initialize(Ctx, TM);
342 getELFSection(".bss", MCSectionELF::SHT_NOBITS,
343 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
344 SectionKind::getBSS());
347 getELFSection(".text", MCSectionELF::SHT_PROGBITS,
348 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
349 SectionKind::getText());
352 getELFSection(".data", MCSectionELF::SHT_PROGBITS,
353 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
354 SectionKind::getDataRel());
357 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
358 MCSectionELF::SHF_ALLOC,
359 SectionKind::getReadOnly());
362 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
363 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
364 MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
367 getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
368 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
369 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
372 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
373 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
374 SectionKind::getDataRel());
376 DataRelLocalSection =
377 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
378 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
379 SectionKind::getDataRelLocal());
382 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
383 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
384 SectionKind::getReadOnlyWithRel());
386 DataRelROLocalSection =
387 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
388 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
389 SectionKind::getReadOnlyWithRelLocal());
391 MergeableConst4Section =
392 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
393 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
394 SectionKind::getMergeableConst4());
396 MergeableConst8Section =
397 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
398 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
399 SectionKind::getMergeableConst8());
401 MergeableConst16Section =
402 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
403 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
404 SectionKind::getMergeableConst16());
407 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
408 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
409 SectionKind::getDataRel());
412 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
413 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
414 SectionKind::getDataRel());
416 // Exception Handling Sections.
418 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
419 // it contains relocatable pointers. In PIC mode, this is probably a big
420 // runtime hit for C++ apps. Either the contents of the LSDA need to be
421 // adjusted or this should be a data section.
423 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
424 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
426 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
427 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
428 SectionKind::getDataRel());
430 // Debug Info Sections.
432 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
433 SectionKind::getMetadata());
435 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
436 SectionKind::getMetadata());
438 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
439 SectionKind::getMetadata());
441 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
442 SectionKind::getMetadata());
443 DwarfPubNamesSection =
444 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
445 SectionKind::getMetadata());
446 DwarfPubTypesSection =
447 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
448 SectionKind::getMetadata());
450 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
451 SectionKind::getMetadata());
453 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
454 SectionKind::getMetadata());
455 DwarfARangesSection =
456 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
457 SectionKind::getMetadata());
459 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
460 SectionKind::getMetadata());
461 DwarfMacroInfoSection =
462 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
463 SectionKind::getMetadata());
468 getELFKindForNamedSection(const char *Name, SectionKind K) {
469 if (Name[0] != '.') return K;
471 // Some lame default implementation based on some magic section names.
472 if (strcmp(Name, ".bss") == 0 ||
473 strncmp(Name, ".bss.", 5) == 0 ||
474 strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
475 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
476 strcmp(Name, ".sbss") == 0 ||
477 strncmp(Name, ".sbss.", 6) == 0 ||
478 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
479 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
480 return SectionKind::getBSS();
482 if (strcmp(Name, ".tdata") == 0 ||
483 strncmp(Name, ".tdata.", 7) == 0 ||
484 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
485 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
486 return SectionKind::getThreadData();
488 if (strcmp(Name, ".tbss") == 0 ||
489 strncmp(Name, ".tbss.", 6) == 0 ||
490 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
491 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
492 return SectionKind::getThreadBSS();
498 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
500 if (Name == ".init_array")
501 return MCSectionELF::SHT_INIT_ARRAY;
503 if (Name == ".fini_array")
504 return MCSectionELF::SHT_FINI_ARRAY;
506 if (Name == ".preinit_array")
507 return MCSectionELF::SHT_PREINIT_ARRAY;
509 if (K.isBSS() || K.isThreadBSS())
510 return MCSectionELF::SHT_NOBITS;
512 return MCSectionELF::SHT_PROGBITS;
517 getELFSectionFlags(SectionKind K) {
521 Flags |= MCSectionELF::SHF_ALLOC;
524 Flags |= MCSectionELF::SHF_EXECINSTR;
527 Flags |= MCSectionELF::SHF_WRITE;
529 if (K.isThreadLocal())
530 Flags |= MCSectionELF::SHF_TLS;
532 // K.isMergeableConst() is left out to honour PR4650
533 if (K.isMergeableCString() || K.isMergeableConst4() ||
534 K.isMergeableConst8() || K.isMergeableConst16())
535 Flags |= MCSectionELF::SHF_MERGE;
537 if (K.isMergeableCString())
538 Flags |= MCSectionELF::SHF_STRINGS;
544 const MCSection *TargetLoweringObjectFileELF::
545 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
546 Mangler *Mang, const TargetMachine &TM) const {
547 const char *SectionName = GV->getSection().c_str();
549 // Infer section flags from the section name if we can.
550 Kind = getELFKindForNamedSection(SectionName, Kind);
552 return getELFSection(SectionName,
553 getELFSectionType(SectionName, Kind),
554 getELFSectionFlags(Kind), Kind, true);
557 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
558 if (Kind.isText()) return ".gnu.linkonce.t.";
559 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
561 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
562 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
564 if (Kind.isBSS()) return ".gnu.linkonce.b.";
565 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
566 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
567 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
568 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
570 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
571 return ".gnu.linkonce.d.rel.ro.";
574 const MCSection *TargetLoweringObjectFileELF::
575 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
576 Mangler *Mang, const TargetMachine &TM) const {
578 // If this global is linkonce/weak and the target handles this by emitting it
579 // into a 'uniqued' section name, create and return the section now.
580 if (GV->isWeakForLinker()) {
581 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
582 SmallString<128> Name;
583 Name.append(Prefix, Prefix+strlen(Prefix));
584 Mang->getNameWithPrefix(Name, GV, false);
585 return getELFSection(Name.str(), getELFSectionType(Name.str(), Kind),
586 getELFSectionFlags(Kind), Kind);
589 if (Kind.isText()) return TextSection;
591 if (Kind.isMergeable1ByteCString() ||
592 Kind.isMergeable2ByteCString() ||
593 Kind.isMergeable4ByteCString()) {
595 // We also need alignment here.
596 // FIXME: this is getting the alignment of the character, not the
597 // alignment of the global!
599 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
601 const char *SizeSpec = ".rodata.str1.";
602 if (Kind.isMergeable2ByteCString())
603 SizeSpec = ".rodata.str2.";
604 else if (Kind.isMergeable4ByteCString())
605 SizeSpec = ".rodata.str4.";
607 assert(Kind.isMergeable1ByteCString() && "unknown string width");
610 std::string Name = SizeSpec + utostr(Align);
611 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS,
612 MCSectionELF::SHF_ALLOC |
613 MCSectionELF::SHF_MERGE |
614 MCSectionELF::SHF_STRINGS,
618 if (Kind.isMergeableConst()) {
619 if (Kind.isMergeableConst4() && MergeableConst4Section)
620 return MergeableConst4Section;
621 if (Kind.isMergeableConst8() && MergeableConst8Section)
622 return MergeableConst8Section;
623 if (Kind.isMergeableConst16() && MergeableConst16Section)
624 return MergeableConst16Section;
625 return ReadOnlySection; // .const
628 if (Kind.isReadOnly()) return ReadOnlySection;
630 if (Kind.isThreadData()) return TLSDataSection;
631 if (Kind.isThreadBSS()) return TLSBSSSection;
633 if (Kind.isBSS()) return BSSSection;
635 if (Kind.isDataNoRel()) return DataSection;
636 if (Kind.isDataRelLocal()) return DataRelLocalSection;
637 if (Kind.isDataRel()) return DataRelSection;
638 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
640 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
641 return DataRelROSection;
644 /// getSectionForConstant - Given a mergeable constant with the
645 /// specified size and relocation information, return a section that it
646 /// should be placed in.
647 const MCSection *TargetLoweringObjectFileELF::
648 getSectionForConstant(SectionKind Kind) const {
649 if (Kind.isMergeableConst4() && MergeableConst4Section)
650 return MergeableConst4Section;
651 if (Kind.isMergeableConst8() && MergeableConst8Section)
652 return MergeableConst8Section;
653 if (Kind.isMergeableConst16() && MergeableConst16Section)
654 return MergeableConst16Section;
655 if (Kind.isReadOnly())
656 return ReadOnlySection;
658 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
659 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
660 return DataRelROSection;
663 //===----------------------------------------------------------------------===//
665 //===----------------------------------------------------------------------===//
667 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
669 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
670 // If we have the MachO uniquing map, free it.
671 delete (MachOUniqueMapTy*)UniquingMap;
675 const MCSectionMachO *TargetLoweringObjectFileMachO::
676 getMachOSection(StringRef Segment, StringRef Section,
677 unsigned TypeAndAttributes,
678 unsigned Reserved2, SectionKind Kind) const {
679 // We unique sections by their segment/section pair. The returned section
680 // may not have the same flags as the requested section, if so this should be
681 // diagnosed by the client as an error.
683 // Create the map if it doesn't already exist.
684 if (UniquingMap == 0)
685 UniquingMap = new MachOUniqueMapTy();
686 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
688 // Form the name to look up.
689 SmallString<64> Name;
694 // Do the lookup, if we have a hit, return it.
695 const MCSectionMachO *&Entry = Map[Name.str()];
696 if (Entry) return Entry;
698 // Otherwise, return a new section.
699 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
700 Reserved2, Kind, getContext());
704 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
705 const TargetMachine &TM) {
706 if (UniquingMap != 0)
707 ((MachOUniqueMapTy*)UniquingMap)->clear();
708 TargetLoweringObjectFile::Initialize(Ctx, TM);
711 = getMachOSection("__TEXT", "__text",
712 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
713 SectionKind::getText());
715 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
717 CStringSection // .cstring
718 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
719 SectionKind::getMergeable1ByteCString());
721 = getMachOSection("__TEXT","__ustring", 0,
722 SectionKind::getMergeable2ByteCString());
723 FourByteConstantSection // .literal4
724 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
725 SectionKind::getMergeableConst4());
726 EightByteConstantSection // .literal8
727 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
728 SectionKind::getMergeableConst8());
730 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
731 // to using it in -static mode.
732 SixteenByteConstantSection = 0;
733 if (TM.getRelocationModel() != Reloc::Static &&
734 TM.getTargetData()->getPointerSize() == 32)
735 SixteenByteConstantSection = // .literal16
736 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
737 SectionKind::getMergeableConst16());
739 ReadOnlySection // .const
740 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
743 = getMachOSection("__TEXT", "__textcoal_nt",
744 MCSectionMachO::S_COALESCED |
745 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
746 SectionKind::getText());
748 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
749 SectionKind::getText());
751 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
752 SectionKind::getText());
753 ConstDataSection // .const_data
754 = getMachOSection("__DATA", "__const", 0,
755 SectionKind::getReadOnlyWithRel());
757 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
758 SectionKind::getDataRel());
761 LazySymbolPointerSection
762 = getMachOSection("__DATA", "__la_symbol_ptr",
763 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
764 SectionKind::getMetadata());
765 NonLazySymbolPointerSection
766 = getMachOSection("__DATA", "__nl_symbol_ptr",
767 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
768 SectionKind::getMetadata());
770 if (TM.getRelocationModel() == Reloc::Static) {
772 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
774 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
777 = getMachOSection("__DATA", "__mod_init_func",
778 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
779 SectionKind::getDataRel());
781 = getMachOSection("__DATA", "__mod_term_func",
782 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
783 SectionKind::getDataRel());
786 // Exception Handling.
787 LSDASection = getMachOSection("__DATA", "__gcc_except_tab", 0,
788 SectionKind::getDataRel());
790 getMachOSection("__TEXT", "__eh_frame",
791 MCSectionMachO::S_COALESCED |
792 MCSectionMachO::S_ATTR_NO_TOC |
793 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
794 MCSectionMachO::S_ATTR_LIVE_SUPPORT,
795 SectionKind::getReadOnly());
797 // Debug Information.
799 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
800 SectionKind::getMetadata());
802 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
803 SectionKind::getMetadata());
805 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
806 SectionKind::getMetadata());
808 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
809 SectionKind::getMetadata());
810 DwarfPubNamesSection =
811 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
812 SectionKind::getMetadata());
813 DwarfPubTypesSection =
814 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
815 SectionKind::getMetadata());
817 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
818 SectionKind::getMetadata());
820 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
821 SectionKind::getMetadata());
822 DwarfARangesSection =
823 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
824 SectionKind::getMetadata());
826 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
827 SectionKind::getMetadata());
828 DwarfMacroInfoSection =
829 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
830 SectionKind::getMetadata());
831 DwarfDebugInlineSection =
832 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
833 SectionKind::getMetadata());
836 const MCSection *TargetLoweringObjectFileMachO::
837 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
838 Mangler *Mang, const TargetMachine &TM) const {
839 // Parse the section specifier and create it if valid.
840 StringRef Segment, Section;
841 unsigned TAA, StubSize;
842 std::string ErrorCode =
843 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
845 if (!ErrorCode.empty()) {
846 // If invalid, report the error with llvm_report_error.
847 llvm_report_error("Global variable '" + GV->getNameStr() +
848 "' has an invalid section specifier '" + GV->getSection()+
849 "': " + ErrorCode + ".");
850 // Fall back to dropping it into the data section.
855 const MCSectionMachO *S =
856 getMachOSection(Segment, Section, TAA, StubSize, Kind);
858 // Okay, now that we got the section, verify that the TAA & StubSize agree.
859 // If the user declared multiple globals with different section flags, we need
860 // to reject it here.
861 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
862 // If invalid, report the error with llvm_report_error.
863 llvm_report_error("Global variable '" + GV->getNameStr() +
864 "' section type or attributes does not match previous"
865 " section specifier");
871 const MCSection *TargetLoweringObjectFileMachO::
872 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
873 Mangler *Mang, const TargetMachine &TM) const {
874 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
877 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
879 // If this is weak/linkonce, put this in a coalescable section, either in text
880 // or data depending on if it is writable.
881 if (GV->isWeakForLinker()) {
882 if (Kind.isReadOnly())
883 return ConstTextCoalSection;
884 return DataCoalSection;
887 // FIXME: Alignment check should be handled by section classifier.
888 if (Kind.isMergeable1ByteCString() ||
889 Kind.isMergeable2ByteCString()) {
890 if (TM.getTargetData()->getPreferredAlignment(
891 cast<GlobalVariable>(GV)) < 32) {
892 if (Kind.isMergeable1ByteCString())
893 return CStringSection;
894 assert(Kind.isMergeable2ByteCString());
895 return UStringSection;
899 if (Kind.isMergeableConst()) {
900 if (Kind.isMergeableConst4())
901 return FourByteConstantSection;
902 if (Kind.isMergeableConst8())
903 return EightByteConstantSection;
904 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
905 return SixteenByteConstantSection;
908 // Otherwise, if it is readonly, but not something we can specially optimize,
909 // just drop it in .const.
910 if (Kind.isReadOnly())
911 return ReadOnlySection;
913 // If this is marked const, put it into a const section. But if the dynamic
914 // linker needs to write to it, put it in the data segment.
915 if (Kind.isReadOnlyWithRel())
916 return ConstDataSection;
918 // Otherwise, just drop the variable in the normal data section.
923 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
924 // If this constant requires a relocation, we have to put it in the data
925 // segment, not in the text segment.
926 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
927 return ConstDataSection;
929 if (Kind.isMergeableConst4())
930 return FourByteConstantSection;
931 if (Kind.isMergeableConst8())
932 return EightByteConstantSection;
933 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
934 return SixteenByteConstantSection;
935 return ReadOnlySection; // .const
938 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
939 /// not to emit the UsedDirective for some symbols in llvm.used.
940 // FIXME: REMOVE this (rdar://7071300)
941 bool TargetLoweringObjectFileMachO::
942 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
943 /// On Darwin, internally linked data beginning with "L" or "l" does not have
944 /// the directive emitted (this occurs in ObjC metadata).
945 if (!GV) return false;
947 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
948 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
949 // FIXME: ObjC metadata is currently emitted as internal symbols that have
950 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
951 // this horrible hack can go away.
952 SmallString<64> Name;
953 Mang->getNameWithPrefix(Name, GV, false);
954 if (Name[0] == 'L' || Name[0] == 'l')
961 const MCExpr *TargetLoweringObjectFileMachO::
962 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
963 MachineModuleInfo *MMI,
964 bool &IsIndirect, bool &IsPCRel) const {
965 // The mach-o version of this method defaults to returning a stub reference.
969 SmallString<128> Name;
970 Mang->getNameWithPrefix(Name, GV, true);
971 Name += "$non_lazy_ptr";
972 return MCSymbolRefExpr::Create(Name.str(), getContext());
976 //===----------------------------------------------------------------------===//
978 //===----------------------------------------------------------------------===//
980 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
982 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
983 delete (COFFUniqueMapTy*)UniquingMap;
987 const MCSection *TargetLoweringObjectFileCOFF::
988 getCOFFSection(StringRef Name, bool isDirective, SectionKind Kind) const {
989 // Create the map if it doesn't already exist.
990 if (UniquingMap == 0)
991 UniquingMap = new MachOUniqueMapTy();
992 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
994 // Do the lookup, if we have a hit, return it.
995 const MCSectionCOFF *&Entry = Map[Name];
996 if (Entry) return Entry;
998 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
1001 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1002 const TargetMachine &TM) {
1003 if (UniquingMap != 0)
1004 ((COFFUniqueMapTy*)UniquingMap)->clear();
1005 TargetLoweringObjectFile::Initialize(Ctx, TM);
1006 TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
1007 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
1009 getCOFFSection(".ctors", false, SectionKind::getDataRel());
1011 getCOFFSection(".dtors", false, SectionKind::getDataRel());
1013 // FIXME: We're emitting LSDA info into a readonly section on COFF, even
1014 // though it contains relocatable pointers. In PIC mode, this is probably a
1015 // big runtime hit for C++ apps. Either the contents of the LSDA need to be
1016 // adjusted or this should be a data section.
1018 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
1020 getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
1023 // FIXME: Don't use 'directive' mode here.
1024 DwarfAbbrevSection =
1025 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
1026 true, SectionKind::getMetadata());
1028 getCOFFSection("\t.section\t.debug_info,\"dr\"",
1029 true, SectionKind::getMetadata());
1031 getCOFFSection("\t.section\t.debug_line,\"dr\"",
1032 true, SectionKind::getMetadata());
1034 getCOFFSection("\t.section\t.debug_frame,\"dr\"",
1035 true, SectionKind::getMetadata());
1036 DwarfPubNamesSection =
1037 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
1038 true, SectionKind::getMetadata());
1039 DwarfPubTypesSection =
1040 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
1041 true, SectionKind::getMetadata());
1043 getCOFFSection("\t.section\t.debug_str,\"dr\"",
1044 true, SectionKind::getMetadata());
1046 getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1047 true, SectionKind::getMetadata());
1048 DwarfARangesSection =
1049 getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1050 true, SectionKind::getMetadata());
1051 DwarfRangesSection =
1052 getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1053 true, SectionKind::getMetadata());
1054 DwarfMacroInfoSection =
1055 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1056 true, SectionKind::getMetadata());
1059 const MCSection *TargetLoweringObjectFileCOFF::
1060 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
1061 Mangler *Mang, const TargetMachine &TM) const {
1062 return getCOFFSection(GV->getSection().c_str(), false, Kind);
1065 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1067 return ".text$linkonce";
1068 if (Kind.isWriteable())
1069 return ".data$linkonce";
1070 return ".rdata$linkonce";
1074 const MCSection *TargetLoweringObjectFileCOFF::
1075 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1076 Mangler *Mang, const TargetMachine &TM) const {
1077 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1079 // If this global is linkonce/weak and the target handles this by emitting it
1080 // into a 'uniqued' section name, create and return the section now.
1081 if (GV->isWeakForLinker()) {
1082 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1083 SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
1084 Mang->getNameWithPrefix(Name, GV, false);
1085 return getCOFFSection(Name.str(), false, Kind);
1089 return getTextSection();
1091 return getDataSection();