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/ErrorHandling.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/StringExtras.h"
33 //===----------------------------------------------------------------------===//
35 //===----------------------------------------------------------------------===//
37 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
42 StaticCtorSection = 0;
43 StaticDtorSection = 0;
47 DwarfAbbrevSection = 0;
50 DwarfFrameSection = 0;
51 DwarfPubNamesSection = 0;
52 DwarfPubTypesSection = 0;
53 DwarfDebugInlineSection = 0;
56 DwarfARangesSection = 0;
57 DwarfRangesSection = 0;
58 DwarfMacroInfoSection = 0;
61 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
64 static bool isSuitableForBSS(const GlobalVariable *GV) {
65 Constant *C = GV->getInitializer();
67 // Must have zero initializer.
68 if (!C->isNullValue())
71 // Leave constant zeros in readonly constant sections, so they can be shared.
75 // If the global has an explicit section specified, don't put it in BSS.
76 if (!GV->getSection().empty())
79 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
83 // Otherwise, put it in BSS!
87 /// IsNullTerminatedString - Return true if the specified constant (which is
88 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
89 /// nul value and contains no other nuls in it.
90 static bool IsNullTerminatedString(const Constant *C) {
91 const ArrayType *ATy = cast<ArrayType>(C->getType());
93 // First check: is we have constant array of i8 terminated with zero
94 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(C)) {
95 if (ATy->getNumElements() == 0) return false;
98 dyn_cast<ConstantInt>(CVA->getOperand(ATy->getNumElements()-1));
99 if (Null == 0 || Null->getZExtValue() != 0)
100 return false; // Not null terminated.
102 // Verify that the null doesn't occur anywhere else in the string.
103 for (unsigned i = 0, e = ATy->getNumElements()-1; i != e; ++i)
104 // Reject constantexpr elements etc.
105 if (!isa<ConstantInt>(CVA->getOperand(i)) ||
106 CVA->getOperand(i) == Null)
111 // Another possibility: [1 x i8] zeroinitializer
112 if (isa<ConstantAggregateZero>(C))
113 return ATy->getNumElements() == 1;
118 /// getKindForGlobal - This is a top-level target-independent classifier for
119 /// a global variable. Given an global variable and information from TM, it
120 /// classifies the global in a variety of ways that make various target
121 /// implementations simpler. The target implementation is free to ignore this
122 /// extra info of course.
123 SectionKind TargetLoweringObjectFile::getKindForGlobal(const GlobalValue *GV,
124 const TargetMachine &TM){
125 assert(!GV->isDeclaration() && !GV->hasAvailableExternallyLinkage() &&
126 "Can only be used for global definitions");
128 Reloc::Model ReloModel = TM.getRelocationModel();
130 // Early exit - functions should be always in text sections.
131 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
133 return SectionKind::getText();
135 // Handle thread-local data first.
136 if (GVar->isThreadLocal()) {
137 if (isSuitableForBSS(GVar))
138 return SectionKind::getThreadBSS();
139 return SectionKind::getThreadData();
142 // Variable can be easily put to BSS section.
143 if (isSuitableForBSS(GVar))
144 return SectionKind::getBSS();
146 Constant *C = GVar->getInitializer();
148 // If the global is marked constant, we can put it into a mergable section,
149 // a mergable string section, or general .data if it contains relocations.
150 if (GVar->isConstant()) {
151 // If the initializer for the global contains something that requires a
152 // relocation, then we may have to drop this into a wriable data section
153 // even though it is marked const.
154 switch (C->getRelocationInfo()) {
155 default: assert(0 && "unknown relocation info kind");
156 case Constant::NoRelocation:
157 // If initializer is a null-terminated string, put it in a "cstring"
158 // section of the right width.
159 if (const ArrayType *ATy = dyn_cast<ArrayType>(C->getType())) {
160 if (const IntegerType *ITy =
161 dyn_cast<IntegerType>(ATy->getElementType())) {
162 if ((ITy->getBitWidth() == 8 || ITy->getBitWidth() == 16 ||
163 ITy->getBitWidth() == 32) &&
164 IsNullTerminatedString(C)) {
165 if (ITy->getBitWidth() == 8)
166 return SectionKind::getMergeable1ByteCString();
167 if (ITy->getBitWidth() == 16)
168 return SectionKind::getMergeable2ByteCString();
170 assert(ITy->getBitWidth() == 32 && "Unknown width");
171 return SectionKind::getMergeable4ByteCString();
176 // Otherwise, just drop it into a mergable constant section. If we have
177 // a section for this size, use it, otherwise use the arbitrary sized
179 switch (TM.getTargetData()->getTypeAllocSize(C->getType())) {
180 case 4: return SectionKind::getMergeableConst4();
181 case 8: return SectionKind::getMergeableConst8();
182 case 16: return SectionKind::getMergeableConst16();
183 default: return SectionKind::getMergeableConst();
186 case Constant::LocalRelocation:
187 // In static relocation model, the linker will resolve all addresses, so
188 // the relocation entries will actually be constants by the time the app
189 // starts up. However, we can't put this into a mergable section, because
190 // the linker doesn't take relocations into consideration when it tries to
191 // merge entries in the section.
192 if (ReloModel == Reloc::Static)
193 return SectionKind::getReadOnly();
195 // Otherwise, the dynamic linker needs to fix it up, put it in the
196 // writable data.rel.local section.
197 return SectionKind::getReadOnlyWithRelLocal();
199 case Constant::GlobalRelocations:
200 // In static relocation model, the linker will resolve all addresses, so
201 // the relocation entries will actually be constants by the time the app
202 // starts up. However, we can't put this into a mergable section, because
203 // the linker doesn't take relocations into consideration when it tries to
204 // merge entries in the section.
205 if (ReloModel == Reloc::Static)
206 return SectionKind::getReadOnly();
208 // Otherwise, the dynamic linker needs to fix it up, put it in the
209 // writable data.rel section.
210 return SectionKind::getReadOnlyWithRel();
214 // Okay, this isn't a constant. If the initializer for the global is going
215 // to require a runtime relocation by the dynamic linker, put it into a more
216 // specific section to improve startup time of the app. This coalesces these
217 // globals together onto fewer pages, improving the locality of the dynamic
219 if (ReloModel == Reloc::Static)
220 return SectionKind::getDataNoRel();
222 switch (C->getRelocationInfo()) {
223 default: assert(0 && "unknown relocation info kind");
224 case Constant::NoRelocation:
225 return SectionKind::getDataNoRel();
226 case Constant::LocalRelocation:
227 return SectionKind::getDataRelLocal();
228 case Constant::GlobalRelocations:
229 return SectionKind::getDataRel();
233 /// SectionForGlobal - This method computes the appropriate section to emit
234 /// the specified global variable or function definition. This should not
235 /// be passed external (or available externally) globals.
236 const MCSection *TargetLoweringObjectFile::
237 SectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang,
238 const TargetMachine &TM) const {
239 // Select section name.
240 if (GV->hasSection())
241 return getExplicitSectionGlobal(GV, Kind, Mang, TM);
244 // Use default section depending on the 'type' of global
245 return SelectSectionForGlobal(GV, Kind, Mang, TM);
249 // Lame default implementation. Calculate the section name for global.
251 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue *GV,
254 const TargetMachine &TM) const{
255 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
258 return getTextSection();
260 if (Kind.isBSS() && BSSSection != 0)
263 if (Kind.isReadOnly() && ReadOnlySection != 0)
264 return ReadOnlySection;
266 return getDataSection();
269 /// getSectionForConstant - Given a mergable constant with the
270 /// specified size and relocation information, return a section that it
271 /// should be placed in.
273 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind) const {
274 if (Kind.isReadOnly() && ReadOnlySection != 0)
275 return ReadOnlySection;
280 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a
281 /// pc-relative reference to the specified global variable from exception
282 /// handling information. In addition to the symbol, this returns
285 /// IsIndirect - True if the returned symbol is actually a stub that contains
286 /// the address of the symbol, false if the symbol is the global itself.
288 /// IsPCRel - True if the symbol reference is already pc-relative, false if
289 /// the caller needs to subtract off the address of the reference from the
292 const MCExpr *TargetLoweringObjectFile::
293 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
294 MachineModuleInfo *MMI,
295 bool &IsIndirect, bool &IsPCRel) const {
296 // The generic implementation of this just returns a direct reference to the
301 SmallString<128> Name;
302 Mang->getNameWithPrefix(Name, GV, false);
303 return MCSymbolRefExpr::Create(Name.str(), getContext());
307 //===----------------------------------------------------------------------===//
309 //===----------------------------------------------------------------------===//
310 typedef StringMap<const MCSectionELF*> ELFUniqueMapTy;
312 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
313 // If we have the section uniquing map, free it.
314 delete (ELFUniqueMapTy*)UniquingMap;
317 const MCSection *TargetLoweringObjectFileELF::
318 getELFSection(StringRef Section, unsigned Type, unsigned Flags,
319 SectionKind Kind, bool IsExplicit) const {
320 if (UniquingMap == 0)
321 UniquingMap = new ELFUniqueMapTy();
322 ELFUniqueMapTy &Map = *(ELFUniqueMapTy*)UniquingMap;
324 // Do the lookup, if we have a hit, return it.
325 const MCSectionELF *&Entry = Map[Section];
326 if (Entry) return Entry;
328 return Entry = MCSectionELF::Create(Section, Type, Flags, Kind, IsExplicit,
332 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
333 const TargetMachine &TM) {
334 if (UniquingMap != 0)
335 ((ELFUniqueMapTy*)UniquingMap)->clear();
336 TargetLoweringObjectFile::Initialize(Ctx, TM);
339 getELFSection(".bss", MCSectionELF::SHT_NOBITS,
340 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
341 SectionKind::getBSS());
344 getELFSection(".text", MCSectionELF::SHT_PROGBITS,
345 MCSectionELF::SHF_EXECINSTR | MCSectionELF::SHF_ALLOC,
346 SectionKind::getText());
349 getELFSection(".data", MCSectionELF::SHT_PROGBITS,
350 MCSectionELF::SHF_WRITE | MCSectionELF::SHF_ALLOC,
351 SectionKind::getDataRel());
354 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS,
355 MCSectionELF::SHF_ALLOC,
356 SectionKind::getReadOnly());
359 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS,
360 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
361 MCSectionELF::SHF_WRITE, SectionKind::getThreadData());
364 getELFSection(".tbss", MCSectionELF::SHT_NOBITS,
365 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_TLS |
366 MCSectionELF::SHF_WRITE, SectionKind::getThreadBSS());
369 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS,
370 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
371 SectionKind::getDataRel());
373 DataRelLocalSection =
374 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS,
375 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
376 SectionKind::getDataRelLocal());
379 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS,
380 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
381 SectionKind::getReadOnlyWithRel());
383 DataRelROLocalSection =
384 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS,
385 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
386 SectionKind::getReadOnlyWithRelLocal());
388 MergeableConst4Section =
389 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS,
390 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
391 SectionKind::getMergeableConst4());
393 MergeableConst8Section =
394 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS,
395 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
396 SectionKind::getMergeableConst8());
398 MergeableConst16Section =
399 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS,
400 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_MERGE,
401 SectionKind::getMergeableConst16());
404 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS,
405 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
406 SectionKind::getDataRel());
409 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS,
410 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
411 SectionKind::getDataRel());
413 // Exception Handling Sections.
415 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
416 // it contains relocatable pointers. In PIC mode, this is probably a big
417 // runtime hit for C++ apps. Either the contents of the LSDA need to be
418 // adjusted or this should be a data section.
420 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS,
421 MCSectionELF::SHF_ALLOC, SectionKind::getReadOnly());
423 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS,
424 MCSectionELF::SHF_ALLOC | MCSectionELF::SHF_WRITE,
425 SectionKind::getDataRel());
427 // Debug Info Sections.
429 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS, 0,
430 SectionKind::getMetadata());
432 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS, 0,
433 SectionKind::getMetadata());
435 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS, 0,
436 SectionKind::getMetadata());
438 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS, 0,
439 SectionKind::getMetadata());
440 DwarfPubNamesSection =
441 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS, 0,
442 SectionKind::getMetadata());
443 DwarfPubTypesSection =
444 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS, 0,
445 SectionKind::getMetadata());
447 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS, 0,
448 SectionKind::getMetadata());
450 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS, 0,
451 SectionKind::getMetadata());
452 DwarfARangesSection =
453 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS, 0,
454 SectionKind::getMetadata());
456 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS, 0,
457 SectionKind::getMetadata());
458 DwarfMacroInfoSection =
459 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS, 0,
460 SectionKind::getMetadata());
465 getELFKindForNamedSection(const char *Name, SectionKind K) {
466 if (Name[0] != '.') return K;
468 // Some lame default implementation based on some magic section names.
469 if (strcmp(Name, ".bss") == 0 ||
470 strncmp(Name, ".bss.", 5) == 0 ||
471 strncmp(Name, ".gnu.linkonce.b.", 16) == 0 ||
472 strncmp(Name, ".llvm.linkonce.b.", 17) == 0 ||
473 strcmp(Name, ".sbss") == 0 ||
474 strncmp(Name, ".sbss.", 6) == 0 ||
475 strncmp(Name, ".gnu.linkonce.sb.", 17) == 0 ||
476 strncmp(Name, ".llvm.linkonce.sb.", 18) == 0)
477 return SectionKind::getBSS();
479 if (strcmp(Name, ".tdata") == 0 ||
480 strncmp(Name, ".tdata.", 7) == 0 ||
481 strncmp(Name, ".gnu.linkonce.td.", 17) == 0 ||
482 strncmp(Name, ".llvm.linkonce.td.", 18) == 0)
483 return SectionKind::getThreadData();
485 if (strcmp(Name, ".tbss") == 0 ||
486 strncmp(Name, ".tbss.", 6) == 0 ||
487 strncmp(Name, ".gnu.linkonce.tb.", 17) == 0 ||
488 strncmp(Name, ".llvm.linkonce.tb.", 18) == 0)
489 return SectionKind::getThreadBSS();
496 getELFSectionType(const char *Name, SectionKind K) {
498 if (strcmp(Name, ".init_array") == 0)
499 return MCSectionELF::SHT_INIT_ARRAY;
501 if (strcmp(Name, ".fini_array") == 0)
502 return MCSectionELF::SHT_FINI_ARRAY;
504 if (strcmp(Name, ".preinit_array") == 0)
505 return MCSectionELF::SHT_PREINIT_ARRAY;
507 if (K.isBSS() || K.isThreadBSS())
508 return MCSectionELF::SHT_NOBITS;
510 return MCSectionELF::SHT_PROGBITS;
515 getELFSectionFlags(SectionKind K) {
519 Flags |= MCSectionELF::SHF_ALLOC;
522 Flags |= MCSectionELF::SHF_EXECINSTR;
525 Flags |= MCSectionELF::SHF_WRITE;
527 if (K.isThreadLocal())
528 Flags |= MCSectionELF::SHF_TLS;
530 // K.isMergeableConst() is left out to honour PR4650
531 if (K.isMergeableCString() || K.isMergeableConst4() ||
532 K.isMergeableConst8() || K.isMergeableConst16())
533 Flags |= MCSectionELF::SHF_MERGE;
535 if (K.isMergeableCString())
536 Flags |= MCSectionELF::SHF_STRINGS;
542 const MCSection *TargetLoweringObjectFileELF::
543 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
544 Mangler *Mang, const TargetMachine &TM) const {
545 const char *SectionName = GV->getSection().c_str();
547 // Infer section flags from the section name if we can.
548 Kind = getELFKindForNamedSection(SectionName, Kind);
550 return getELFSection(SectionName,
551 getELFSectionType(SectionName, Kind),
552 getELFSectionFlags(Kind), Kind, true);
555 static const char *getSectionPrefixForUniqueGlobal(SectionKind Kind) {
556 if (Kind.isText()) return ".gnu.linkonce.t.";
557 if (Kind.isReadOnly()) return ".gnu.linkonce.r.";
559 if (Kind.isThreadData()) return ".gnu.linkonce.td.";
560 if (Kind.isThreadBSS()) return ".gnu.linkonce.tb.";
562 if (Kind.isBSS()) return ".gnu.linkonce.b.";
563 if (Kind.isDataNoRel()) return ".gnu.linkonce.d.";
564 if (Kind.isDataRelLocal()) return ".gnu.linkonce.d.rel.local.";
565 if (Kind.isDataRel()) return ".gnu.linkonce.d.rel.";
566 if (Kind.isReadOnlyWithRelLocal()) return ".gnu.linkonce.d.rel.ro.local.";
568 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
569 return ".gnu.linkonce.d.rel.ro.";
572 const MCSection *TargetLoweringObjectFileELF::
573 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
574 Mangler *Mang, const TargetMachine &TM) const {
576 // If this global is linkonce/weak and the target handles this by emitting it
577 // into a 'uniqued' section name, create and return the section now.
578 if (GV->isWeakForLinker()) {
579 const char *Prefix = getSectionPrefixForUniqueGlobal(Kind);
580 std::string Name = Mang->makeNameProper(GV->getNameStr());
582 return getELFSection((Prefix+Name).c_str(),
583 getELFSectionType((Prefix+Name).c_str(), Kind),
584 getELFSectionFlags(Kind),
588 if (Kind.isText()) return TextSection;
590 if (Kind.isMergeable1ByteCString() ||
591 Kind.isMergeable2ByteCString() ||
592 Kind.isMergeable4ByteCString()) {
594 // We also need alignment here.
595 // FIXME: this is getting the alignment of the character, not the
596 // alignment of the global!
598 TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
600 const char *SizeSpec = ".rodata.str1.";
601 if (Kind.isMergeable2ByteCString())
602 SizeSpec = ".rodata.str2.";
603 else if (Kind.isMergeable4ByteCString())
604 SizeSpec = ".rodata.str4.";
606 assert(Kind.isMergeable1ByteCString() && "unknown string width");
609 std::string Name = SizeSpec + utostr(Align);
610 return getELFSection(Name.c_str(), MCSectionELF::SHT_PROGBITS,
611 MCSectionELF::SHF_ALLOC |
612 MCSectionELF::SHF_MERGE |
613 MCSectionELF::SHF_STRINGS,
617 if (Kind.isMergeableConst()) {
618 if (Kind.isMergeableConst4() && MergeableConst4Section)
619 return MergeableConst4Section;
620 if (Kind.isMergeableConst8() && MergeableConst8Section)
621 return MergeableConst8Section;
622 if (Kind.isMergeableConst16() && MergeableConst16Section)
623 return MergeableConst16Section;
624 return ReadOnlySection; // .const
627 if (Kind.isReadOnly()) return ReadOnlySection;
629 if (Kind.isThreadData()) return TLSDataSection;
630 if (Kind.isThreadBSS()) return TLSBSSSection;
632 if (Kind.isBSS()) return BSSSection;
634 if (Kind.isDataNoRel()) return DataSection;
635 if (Kind.isDataRelLocal()) return DataRelLocalSection;
636 if (Kind.isDataRel()) return DataRelSection;
637 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
639 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
640 return DataRelROSection;
643 /// getSectionForConstant - Given a mergeable constant with the
644 /// specified size and relocation information, return a section that it
645 /// should be placed in.
646 const MCSection *TargetLoweringObjectFileELF::
647 getSectionForConstant(SectionKind Kind) const {
648 if (Kind.isMergeableConst4() && MergeableConst4Section)
649 return MergeableConst4Section;
650 if (Kind.isMergeableConst8() && MergeableConst8Section)
651 return MergeableConst8Section;
652 if (Kind.isMergeableConst16() && MergeableConst16Section)
653 return MergeableConst16Section;
654 if (Kind.isReadOnly())
655 return ReadOnlySection;
657 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
658 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
659 return DataRelROSection;
662 //===----------------------------------------------------------------------===//
664 //===----------------------------------------------------------------------===//
666 typedef StringMap<const MCSectionMachO*> MachOUniqueMapTy;
668 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
669 // If we have the MachO uniquing map, free it.
670 delete (MachOUniqueMapTy*)UniquingMap;
674 const MCSectionMachO *TargetLoweringObjectFileMachO::
675 getMachOSection(StringRef Segment, StringRef Section,
676 unsigned TypeAndAttributes,
677 unsigned Reserved2, SectionKind Kind) const {
678 // We unique sections by their segment/section pair. The returned section
679 // may not have the same flags as the requested section, if so this should be
680 // diagnosed by the client as an error.
682 // Create the map if it doesn't already exist.
683 if (UniquingMap == 0)
684 UniquingMap = new MachOUniqueMapTy();
685 MachOUniqueMapTy &Map = *(MachOUniqueMapTy*)UniquingMap;
687 // Form the name to look up.
688 SmallString<64> Name;
693 // Do the lookup, if we have a hit, return it.
694 const MCSectionMachO *&Entry = Map[Name.str()];
695 if (Entry) return Entry;
697 // Otherwise, return a new section.
698 return Entry = MCSectionMachO::Create(Segment, Section, TypeAndAttributes,
699 Reserved2, Kind, getContext());
703 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
704 const TargetMachine &TM) {
705 if (UniquingMap != 0)
706 ((MachOUniqueMapTy*)UniquingMap)->clear();
707 TargetLoweringObjectFile::Initialize(Ctx, TM);
710 = getMachOSection("__TEXT", "__text",
711 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
712 SectionKind::getText());
714 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
716 CStringSection // .cstring
717 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS,
718 SectionKind::getMergeable1ByteCString());
720 = getMachOSection("__TEXT","__ustring", 0,
721 SectionKind::getMergeable2ByteCString());
722 FourByteConstantSection // .literal4
723 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS,
724 SectionKind::getMergeableConst4());
725 EightByteConstantSection // .literal8
726 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS,
727 SectionKind::getMergeableConst8());
729 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
730 // to using it in -static mode.
731 SixteenByteConstantSection = 0;
732 if (TM.getRelocationModel() != Reloc::Static &&
733 TM.getTargetData()->getPointerSize() == 32)
734 SixteenByteConstantSection = // .literal16
735 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS,
736 SectionKind::getMergeableConst16());
738 ReadOnlySection // .const
739 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
742 = getMachOSection("__TEXT", "__textcoal_nt",
743 MCSectionMachO::S_COALESCED |
744 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
745 SectionKind::getText());
747 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED,
748 SectionKind::getText());
750 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED,
751 SectionKind::getText());
752 ConstDataSection // .const_data
753 = getMachOSection("__DATA", "__const", 0,
754 SectionKind::getReadOnlyWithRel());
756 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED,
757 SectionKind::getDataRel());
760 LazySymbolPointerSection
761 = getMachOSection("__DATA", "__la_symbol_ptr",
762 MCSectionMachO::S_LAZY_SYMBOL_POINTERS,
763 SectionKind::getMetadata());
764 NonLazySymbolPointerSection
765 = getMachOSection("__DATA", "__nl_symbol_ptr",
766 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
767 SectionKind::getMetadata());
769 if (TM.getRelocationModel() == Reloc::Static) {
771 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
773 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
776 = getMachOSection("__DATA", "__mod_init_func",
777 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS,
778 SectionKind::getDataRel());
780 = getMachOSection("__DATA", "__mod_term_func",
781 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS,
782 SectionKind::getDataRel());
785 // Exception Handling.
786 LSDASection = getMachOSection("__TEXT", "__gcc_except_tab", 0,
787 SectionKind::getReadOnlyWithRel());
789 getMachOSection("__TEXT", "__eh_frame",
790 MCSectionMachO::S_COALESCED |
791 MCSectionMachO::S_ATTR_NO_TOC |
792 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS |
793 MCSectionMachO::S_ATTR_LIVE_SUPPORT,
794 SectionKind::getReadOnly());
796 // Debug Information.
798 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG,
799 SectionKind::getMetadata());
801 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG,
802 SectionKind::getMetadata());
804 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG,
805 SectionKind::getMetadata());
807 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG,
808 SectionKind::getMetadata());
809 DwarfPubNamesSection =
810 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG,
811 SectionKind::getMetadata());
812 DwarfPubTypesSection =
813 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG,
814 SectionKind::getMetadata());
816 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG,
817 SectionKind::getMetadata());
819 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG,
820 SectionKind::getMetadata());
821 DwarfARangesSection =
822 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG,
823 SectionKind::getMetadata());
825 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG,
826 SectionKind::getMetadata());
827 DwarfMacroInfoSection =
828 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG,
829 SectionKind::getMetadata());
830 DwarfDebugInlineSection =
831 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG,
832 SectionKind::getMetadata());
835 const MCSection *TargetLoweringObjectFileMachO::
836 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
837 Mangler *Mang, const TargetMachine &TM) const {
838 // Parse the section specifier and create it if valid.
839 StringRef Segment, Section;
840 unsigned TAA, StubSize;
841 std::string ErrorCode =
842 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
844 if (!ErrorCode.empty()) {
845 // If invalid, report the error with llvm_report_error.
846 llvm_report_error("Global variable '" + GV->getNameStr() +
847 "' has an invalid section specifier '" + GV->getSection()+
848 "': " + ErrorCode + ".");
849 // Fall back to dropping it into the data section.
854 const MCSectionMachO *S =
855 getMachOSection(Segment, Section, TAA, StubSize, Kind);
857 // Okay, now that we got the section, verify that the TAA & StubSize agree.
858 // If the user declared multiple globals with different section flags, we need
859 // to reject it here.
860 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
861 // If invalid, report the error with llvm_report_error.
862 llvm_report_error("Global variable '" + GV->getNameStr() +
863 "' section type or attributes does not match previous"
864 " section specifier");
870 const MCSection *TargetLoweringObjectFileMachO::
871 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
872 Mangler *Mang, const TargetMachine &TM) const {
873 assert(!Kind.isThreadLocal() && "Darwin doesn't support TLS");
876 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
878 // If this is weak/linkonce, put this in a coalescable section, either in text
879 // or data depending on if it is writable.
880 if (GV->isWeakForLinker()) {
881 if (Kind.isReadOnly())
882 return ConstTextCoalSection;
883 return DataCoalSection;
886 // FIXME: Alignment check should be handled by section classifier.
887 if (Kind.isMergeable1ByteCString() ||
888 Kind.isMergeable2ByteCString()) {
889 if (TM.getTargetData()->getPreferredAlignment(
890 cast<GlobalVariable>(GV)) < 32) {
891 if (Kind.isMergeable1ByteCString())
892 return CStringSection;
893 assert(Kind.isMergeable2ByteCString());
894 return UStringSection;
898 if (Kind.isMergeableConst()) {
899 if (Kind.isMergeableConst4())
900 return FourByteConstantSection;
901 if (Kind.isMergeableConst8())
902 return EightByteConstantSection;
903 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
904 return SixteenByteConstantSection;
907 // Otherwise, if it is readonly, but not something we can specially optimize,
908 // just drop it in .const.
909 if (Kind.isReadOnly())
910 return ReadOnlySection;
912 // If this is marked const, put it into a const section. But if the dynamic
913 // linker needs to write to it, put it in the data segment.
914 if (Kind.isReadOnlyWithRel())
915 return ConstDataSection;
917 // Otherwise, just drop the variable in the normal data section.
922 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
923 // If this constant requires a relocation, we have to put it in the data
924 // segment, not in the text segment.
925 if (Kind.isDataRel())
926 return ConstDataSection;
928 if (Kind.isMergeableConst4())
929 return FourByteConstantSection;
930 if (Kind.isMergeableConst8())
931 return EightByteConstantSection;
932 if (Kind.isMergeableConst16() && SixteenByteConstantSection)
933 return SixteenByteConstantSection;
934 return ReadOnlySection; // .const
937 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
938 /// not to emit the UsedDirective for some symbols in llvm.used.
939 // FIXME: REMOVE this (rdar://7071300)
940 bool TargetLoweringObjectFileMachO::
941 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
942 /// On Darwin, internally linked data beginning with "L" or "l" does not have
943 /// the directive emitted (this occurs in ObjC metadata).
944 if (!GV) return false;
946 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
947 if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
948 // FIXME: ObjC metadata is currently emitted as internal symbols that have
949 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
950 // this horrible hack can go away.
951 const std::string &Name = Mang->getMangledName(GV);
952 if (Name[0] == 'L' || Name[0] == 'l')
959 const MCExpr *TargetLoweringObjectFileMachO::
960 getSymbolForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
961 MachineModuleInfo *MMI,
962 bool &IsIndirect, bool &IsPCRel) const {
963 // The mach-o version of this method defaults to returning a stub reference.
967 SmallString<128> Name;
968 Mang->getNameWithPrefix(Name, GV, true);
969 Name += "$non_lazy_ptr";
970 return MCSymbolRefExpr::Create(Name.str(), getContext());
974 //===----------------------------------------------------------------------===//
976 //===----------------------------------------------------------------------===//
978 typedef StringMap<const MCSectionCOFF*> COFFUniqueMapTy;
980 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
981 delete (COFFUniqueMapTy*)UniquingMap;
985 const MCSection *TargetLoweringObjectFileCOFF::
986 getCOFFSection(const char *Name, bool isDirective, SectionKind Kind) const {
987 // Create the map if it doesn't already exist.
988 if (UniquingMap == 0)
989 UniquingMap = new MachOUniqueMapTy();
990 COFFUniqueMapTy &Map = *(COFFUniqueMapTy*)UniquingMap;
992 // Do the lookup, if we have a hit, return it.
993 const MCSectionCOFF *&Entry = Map[Name];
994 if (Entry) return Entry;
996 return Entry = MCSectionCOFF::Create(Name, isDirective, Kind, getContext());
999 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1000 const TargetMachine &TM) {
1001 if (UniquingMap != 0)
1002 ((COFFUniqueMapTy*)UniquingMap)->clear();
1003 TargetLoweringObjectFile::Initialize(Ctx, TM);
1004 TextSection = getCOFFSection("\t.text", true, SectionKind::getText());
1005 DataSection = getCOFFSection("\t.data", true, SectionKind::getDataRel());
1007 getCOFFSection(".ctors", false, SectionKind::getDataRel());
1009 getCOFFSection(".dtors", false, SectionKind::getDataRel());
1011 // FIXME: We're emitting LSDA info into a readonly section on COFF, even
1012 // though it contains relocatable pointers. In PIC mode, this is probably a
1013 // big runtime hit for C++ apps. Either the contents of the LSDA need to be
1014 // adjusted or this should be a data section.
1016 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
1018 getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
1021 // FIXME: Don't use 'directive' mode here.
1022 DwarfAbbrevSection =
1023 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
1024 true, SectionKind::getMetadata());
1026 getCOFFSection("\t.section\t.debug_info,\"dr\"",
1027 true, SectionKind::getMetadata());
1029 getCOFFSection("\t.section\t.debug_line,\"dr\"",
1030 true, SectionKind::getMetadata());
1032 getCOFFSection("\t.section\t.debug_frame,\"dr\"",
1033 true, SectionKind::getMetadata());
1034 DwarfPubNamesSection =
1035 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
1036 true, SectionKind::getMetadata());
1037 DwarfPubTypesSection =
1038 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
1039 true, SectionKind::getMetadata());
1041 getCOFFSection("\t.section\t.debug_str,\"dr\"",
1042 true, SectionKind::getMetadata());
1044 getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1045 true, SectionKind::getMetadata());
1046 DwarfARangesSection =
1047 getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1048 true, SectionKind::getMetadata());
1049 DwarfRangesSection =
1050 getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1051 true, SectionKind::getMetadata());
1052 DwarfMacroInfoSection =
1053 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1054 true, SectionKind::getMetadata());
1057 const MCSection *TargetLoweringObjectFileCOFF::
1058 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
1059 Mangler *Mang, const TargetMachine &TM) const {
1060 return getCOFFSection(GV->getSection().c_str(), false, Kind);
1063 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
1065 return ".text$linkonce";
1066 if (Kind.isWriteable())
1067 return ".data$linkonce";
1068 return ".rdata$linkonce";
1072 const MCSection *TargetLoweringObjectFileCOFF::
1073 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
1074 Mangler *Mang, const TargetMachine &TM) const {
1075 assert(!Kind.isThreadLocal() && "Doesn't support TLS");
1077 // If this global is linkonce/weak and the target handles this by emitting it
1078 // into a 'uniqued' section name, create and return the section now.
1079 if (GV->isWeakForLinker()) {
1080 const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
1081 std::string Name = Mang->makeNameProper(GV->getNameStr());
1082 return getCOFFSection((Prefix+Name).c_str(), false, Kind);
1086 return getTextSection();
1088 return getDataSection();