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