1 //===-- llvm/Target/TargetLoweringObjectFile.cpp - Object File Info -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements classes used to handle lowerings specific to common
11 // object file formats.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Target/TargetLoweringObjectFile.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/MC/MCContext.h"
21 #include "llvm/MC/MCExpr.h"
22 #include "llvm/MC/MCSectionMachO.h"
23 #include "llvm/MC/MCSectionELF.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetOptions.h"
27 #include "llvm/Support/Mangler.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringExtras.h"
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 TargetLoweringObjectFile::TargetLoweringObjectFile() : Ctx(0) {
41 StaticCtorSection
= 0;
42 StaticDtorSection
= 0;
46 DwarfAbbrevSection
= 0;
49 DwarfFrameSection
= 0;
50 DwarfPubNamesSection
= 0;
51 DwarfPubTypesSection
= 0;
52 DwarfDebugInlineSection
= 0;
55 DwarfARangesSection
= 0;
56 DwarfRangesSection
= 0;
57 DwarfMacroInfoSection
= 0;
60 TargetLoweringObjectFile::~TargetLoweringObjectFile() {
63 static bool isSuitableForBSS(const GlobalVariable
*GV
) {
64 Constant
*C
= GV
->getInitializer();
66 // Must have zero initializer.
67 if (!C
->isNullValue())
70 // Leave constant zeros in readonly constant sections, so they can be shared.
74 // If the global has an explicit section specified, don't put it in BSS.
75 if (!GV
->getSection().empty())
78 // If -nozero-initialized-in-bss is specified, don't ever use BSS.
82 // Otherwise, put it in BSS!
86 /// IsNullTerminatedString - Return true if the specified constant (which is
87 /// known to have a type that is an array of 1/2/4 byte elements) ends with a
88 /// nul value and contains no other nuls in it.
89 static bool IsNullTerminatedString(const Constant
*C
) {
90 const ArrayType
*ATy
= cast
<ArrayType
>(C
->getType());
92 // First check: is we have constant array of i8 terminated with zero
93 if (const ConstantArray
*CVA
= dyn_cast
<ConstantArray
>(C
)) {
94 if (ATy
->getNumElements() == 0) return false;
97 dyn_cast
<ConstantInt
>(CVA
->getOperand(ATy
->getNumElements()-1));
98 if (Null
== 0 || Null
->getZExtValue() != 0)
99 return false; // Not null terminated.
101 // Verify that the null doesn't occur anywhere else in the string.
102 for (unsigned i
= 0, e
= ATy
->getNumElements()-1; i
!= e
; ++i
)
103 // Reject constantexpr elements etc.
104 if (!isa
<ConstantInt
>(CVA
->getOperand(i
)) ||
105 CVA
->getOperand(i
) == Null
)
110 // Another possibility: [1 x i8] zeroinitializer
111 if (isa
<ConstantAggregateZero
>(C
))
112 return ATy
->getNumElements() == 1;
117 /// getKindForGlobal - This is a top-level target-independent classifier for
118 /// a global variable. Given an global variable and information from TM, it
119 /// classifies the global in a variety of ways that make various target
120 /// implementations simpler. The target implementation is free to ignore this
121 /// extra info of course.
122 SectionKind
TargetLoweringObjectFile::getKindForGlobal(const GlobalValue
*GV
,
123 const TargetMachine
&TM
){
124 assert(!GV
->isDeclaration() && !GV
->hasAvailableExternallyLinkage() &&
125 "Can only be used for global definitions");
127 Reloc::Model ReloModel
= TM
.getRelocationModel();
129 // Early exit - functions should be always in text sections.
130 const GlobalVariable
*GVar
= dyn_cast
<GlobalVariable
>(GV
);
132 return SectionKind::getText();
134 // Handle thread-local data first.
135 if (GVar
->isThreadLocal()) {
136 if (isSuitableForBSS(GVar
))
137 return SectionKind::getThreadBSS();
138 return SectionKind::getThreadData();
141 // Variable can be easily put to BSS section.
142 if (isSuitableForBSS(GVar
))
143 return SectionKind::getBSS();
145 Constant
*C
= GVar
->getInitializer();
147 // If the global is marked constant, we can put it into a mergable section,
148 // a mergable string section, or general .data if it contains relocations.
149 if (GVar
->isConstant()) {
150 // If the initializer for the global contains something that requires a
151 // relocation, then we may have to drop this into a wriable data section
152 // even though it is marked const.
153 switch (C
->getRelocationInfo()) {
154 default: llvm_unreachable("unknown relocation info kind");
155 case Constant::NoRelocation
:
156 // If initializer is a null-terminated string, put it in a "cstring"
157 // section of the right width.
158 if (const ArrayType
*ATy
= dyn_cast
<ArrayType
>(C
->getType())) {
159 if (const IntegerType
*ITy
=
160 dyn_cast
<IntegerType
>(ATy
->getElementType())) {
161 if ((ITy
->getBitWidth() == 8 || ITy
->getBitWidth() == 16 ||
162 ITy
->getBitWidth() == 32) &&
163 IsNullTerminatedString(C
)) {
164 if (ITy
->getBitWidth() == 8)
165 return SectionKind::getMergeable1ByteCString();
166 if (ITy
->getBitWidth() == 16)
167 return SectionKind::getMergeable2ByteCString();
169 assert(ITy
->getBitWidth() == 32 && "Unknown width");
170 return SectionKind::getMergeable4ByteCString();
175 // Otherwise, just drop it into a mergable constant section. If we have
176 // a section for this size, use it, otherwise use the arbitrary sized
178 switch (TM
.getTargetData()->getTypeAllocSize(C
->getType())) {
179 case 4: return SectionKind::getMergeableConst4();
180 case 8: return SectionKind::getMergeableConst8();
181 case 16: return SectionKind::getMergeableConst16();
182 default: return SectionKind::getMergeableConst();
185 case Constant::LocalRelocation
:
186 // In static relocation model, the linker will resolve all addresses, so
187 // the relocation entries will actually be constants by the time the app
188 // starts up. However, we can't put this into a mergable section, because
189 // the linker doesn't take relocations into consideration when it tries to
190 // merge entries in the section.
191 if (ReloModel
== Reloc::Static
)
192 return SectionKind::getReadOnly();
194 // Otherwise, the dynamic linker needs to fix it up, put it in the
195 // writable data.rel.local section.
196 return SectionKind::getReadOnlyWithRelLocal();
198 case Constant::GlobalRelocations
:
199 // In static relocation model, the linker will resolve all addresses, so
200 // the relocation entries will actually be constants by the time the app
201 // starts up. However, we can't put this into a mergable section, because
202 // the linker doesn't take relocations into consideration when it tries to
203 // merge entries in the section.
204 if (ReloModel
== Reloc::Static
)
205 return SectionKind::getReadOnly();
207 // Otherwise, the dynamic linker needs to fix it up, put it in the
208 // writable data.rel section.
209 return SectionKind::getReadOnlyWithRel();
213 // Okay, this isn't a constant. If the initializer for the global is going
214 // to require a runtime relocation by the dynamic linker, put it into a more
215 // specific section to improve startup time of the app. This coalesces these
216 // globals together onto fewer pages, improving the locality of the dynamic
218 if (ReloModel
== Reloc::Static
)
219 return SectionKind::getDataNoRel();
221 switch (C
->getRelocationInfo()) {
222 default: llvm_unreachable("unknown relocation info kind");
223 case Constant::NoRelocation
:
224 return SectionKind::getDataNoRel();
225 case Constant::LocalRelocation
:
226 return SectionKind::getDataRelLocal();
227 case Constant::GlobalRelocations
:
228 return SectionKind::getDataRel();
232 /// SectionForGlobal - This method computes the appropriate section to emit
233 /// the specified global variable or function definition. This should not
234 /// be passed external (or available externally) globals.
235 const MCSection
*TargetLoweringObjectFile::
236 SectionForGlobal(const GlobalValue
*GV
, SectionKind Kind
, Mangler
*Mang
,
237 const TargetMachine
&TM
) const {
238 // Select section name.
239 if (GV
->hasSection())
240 return getExplicitSectionGlobal(GV
, Kind
, Mang
, TM
);
243 // Use default section depending on the 'type' of global
244 return SelectSectionForGlobal(GV
, Kind
, Mang
, TM
);
248 // Lame default implementation. Calculate the section name for global.
250 TargetLoweringObjectFile::SelectSectionForGlobal(const GlobalValue
*GV
,
253 const TargetMachine
&TM
) const{
254 assert(!Kind
.isThreadLocal() && "Doesn't support TLS");
257 return getTextSection();
259 if (Kind
.isBSS() && BSSSection
!= 0)
262 if (Kind
.isReadOnly() && ReadOnlySection
!= 0)
263 return ReadOnlySection
;
265 return getDataSection();
268 /// getSectionForConstant - Given a mergable constant with the
269 /// specified size and relocation information, return a section that it
270 /// should be placed in.
272 TargetLoweringObjectFile::getSectionForConstant(SectionKind Kind
) const {
273 if (Kind
.isReadOnly() && ReadOnlySection
!= 0)
274 return ReadOnlySection
;
279 /// getSymbolForDwarfGlobalReference - Return an MCExpr to use for a
280 /// pc-relative reference to the specified global variable from exception
281 /// handling information. In addition to the symbol, this returns
284 /// IsIndirect - True if the returned symbol is actually a stub that contains
285 /// the address of the symbol, false if the symbol is the global itself.
287 /// IsPCRel - True if the symbol reference is already pc-relative, false if
288 /// the caller needs to subtract off the address of the reference from the
291 const MCExpr
*TargetLoweringObjectFile::
292 getSymbolForDwarfGlobalReference(const GlobalValue
*GV
, Mangler
*Mang
,
293 MachineModuleInfo
*MMI
,
294 bool &IsIndirect
, bool &IsPCRel
) const {
295 // The generic implementation of this just returns a direct reference to the
300 SmallString
<128> Name
;
301 Mang
->getNameWithPrefix(Name
, GV
, false);
302 return MCSymbolRefExpr::Create(Name
.str(), getContext());
306 //===----------------------------------------------------------------------===//
308 //===----------------------------------------------------------------------===//
309 typedef StringMap
<const MCSectionELF
*> ELFUniqueMapTy
;
311 TargetLoweringObjectFileELF::~TargetLoweringObjectFileELF() {
312 // If we have the section uniquing map, free it.
313 delete (ELFUniqueMapTy
*)UniquingMap
;
316 const MCSection
*TargetLoweringObjectFileELF::
317 getELFSection(StringRef Section
, unsigned Type
, unsigned Flags
,
318 SectionKind Kind
, bool IsExplicit
) const {
319 if (UniquingMap
== 0)
320 UniquingMap
= new ELFUniqueMapTy();
321 ELFUniqueMapTy
&Map
= *(ELFUniqueMapTy
*)UniquingMap
;
323 // Do the lookup, if we have a hit, return it.
324 const MCSectionELF
*&Entry
= Map
[Section
];
325 if (Entry
) return Entry
;
327 return Entry
= MCSectionELF::Create(Section
, Type
, Flags
, Kind
, IsExplicit
,
331 void TargetLoweringObjectFileELF::Initialize(MCContext
&Ctx
,
332 const TargetMachine
&TM
) {
333 if (UniquingMap
!= 0)
334 ((ELFUniqueMapTy
*)UniquingMap
)->clear();
335 TargetLoweringObjectFile::Initialize(Ctx
, TM
);
338 getELFSection(".bss", MCSectionELF::SHT_NOBITS
,
339 MCSectionELF::SHF_WRITE
| MCSectionELF::SHF_ALLOC
,
340 SectionKind::getBSS());
343 getELFSection(".text", MCSectionELF::SHT_PROGBITS
,
344 MCSectionELF::SHF_EXECINSTR
| MCSectionELF::SHF_ALLOC
,
345 SectionKind::getText());
348 getELFSection(".data", MCSectionELF::SHT_PROGBITS
,
349 MCSectionELF::SHF_WRITE
| MCSectionELF::SHF_ALLOC
,
350 SectionKind::getDataRel());
353 getELFSection(".rodata", MCSectionELF::SHT_PROGBITS
,
354 MCSectionELF::SHF_ALLOC
,
355 SectionKind::getReadOnly());
358 getELFSection(".tdata", MCSectionELF::SHT_PROGBITS
,
359 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_TLS
|
360 MCSectionELF::SHF_WRITE
, SectionKind::getThreadData());
363 getELFSection(".tbss", MCSectionELF::SHT_NOBITS
,
364 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_TLS
|
365 MCSectionELF::SHF_WRITE
, SectionKind::getThreadBSS());
368 getELFSection(".data.rel", MCSectionELF::SHT_PROGBITS
,
369 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_WRITE
,
370 SectionKind::getDataRel());
372 DataRelLocalSection
=
373 getELFSection(".data.rel.local", MCSectionELF::SHT_PROGBITS
,
374 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_WRITE
,
375 SectionKind::getDataRelLocal());
378 getELFSection(".data.rel.ro", MCSectionELF::SHT_PROGBITS
,
379 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_WRITE
,
380 SectionKind::getReadOnlyWithRel());
382 DataRelROLocalSection
=
383 getELFSection(".data.rel.ro.local", MCSectionELF::SHT_PROGBITS
,
384 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_WRITE
,
385 SectionKind::getReadOnlyWithRelLocal());
387 MergeableConst4Section
=
388 getELFSection(".rodata.cst4", MCSectionELF::SHT_PROGBITS
,
389 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_MERGE
,
390 SectionKind::getMergeableConst4());
392 MergeableConst8Section
=
393 getELFSection(".rodata.cst8", MCSectionELF::SHT_PROGBITS
,
394 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_MERGE
,
395 SectionKind::getMergeableConst8());
397 MergeableConst16Section
=
398 getELFSection(".rodata.cst16", MCSectionELF::SHT_PROGBITS
,
399 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_MERGE
,
400 SectionKind::getMergeableConst16());
403 getELFSection(".ctors", MCSectionELF::SHT_PROGBITS
,
404 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_WRITE
,
405 SectionKind::getDataRel());
408 getELFSection(".dtors", MCSectionELF::SHT_PROGBITS
,
409 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_WRITE
,
410 SectionKind::getDataRel());
412 // Exception Handling Sections.
414 // FIXME: We're emitting LSDA info into a readonly section on ELF, even though
415 // it contains relocatable pointers. In PIC mode, this is probably a big
416 // runtime hit for C++ apps. Either the contents of the LSDA need to be
417 // adjusted or this should be a data section.
419 getELFSection(".gcc_except_table", MCSectionELF::SHT_PROGBITS
,
420 MCSectionELF::SHF_ALLOC
, SectionKind::getReadOnly());
422 getELFSection(".eh_frame", MCSectionELF::SHT_PROGBITS
,
423 MCSectionELF::SHF_ALLOC
| MCSectionELF::SHF_WRITE
,
424 SectionKind::getDataRel());
426 // Debug Info Sections.
428 getELFSection(".debug_abbrev", MCSectionELF::SHT_PROGBITS
, 0,
429 SectionKind::getMetadata());
431 getELFSection(".debug_info", MCSectionELF::SHT_PROGBITS
, 0,
432 SectionKind::getMetadata());
434 getELFSection(".debug_line", MCSectionELF::SHT_PROGBITS
, 0,
435 SectionKind::getMetadata());
437 getELFSection(".debug_frame", MCSectionELF::SHT_PROGBITS
, 0,
438 SectionKind::getMetadata());
439 DwarfPubNamesSection
=
440 getELFSection(".debug_pubnames", MCSectionELF::SHT_PROGBITS
, 0,
441 SectionKind::getMetadata());
442 DwarfPubTypesSection
=
443 getELFSection(".debug_pubtypes", MCSectionELF::SHT_PROGBITS
, 0,
444 SectionKind::getMetadata());
446 getELFSection(".debug_str", MCSectionELF::SHT_PROGBITS
, 0,
447 SectionKind::getMetadata());
449 getELFSection(".debug_loc", MCSectionELF::SHT_PROGBITS
, 0,
450 SectionKind::getMetadata());
451 DwarfARangesSection
=
452 getELFSection(".debug_aranges", MCSectionELF::SHT_PROGBITS
, 0,
453 SectionKind::getMetadata());
455 getELFSection(".debug_ranges", MCSectionELF::SHT_PROGBITS
, 0,
456 SectionKind::getMetadata());
457 DwarfMacroInfoSection
=
458 getELFSection(".debug_macinfo", MCSectionELF::SHT_PROGBITS
, 0,
459 SectionKind::getMetadata());
464 getELFKindForNamedSection(const char *Name
, SectionKind K
) {
465 if (Name
[0] != '.') return K
;
467 // Some lame default implementation based on some magic section names.
468 if (strcmp(Name
, ".bss") == 0 ||
469 strncmp(Name
, ".bss.", 5) == 0 ||
470 strncmp(Name
, ".gnu.linkonce.b.", 16) == 0 ||
471 strncmp(Name
, ".llvm.linkonce.b.", 17) == 0 ||
472 strcmp(Name
, ".sbss") == 0 ||
473 strncmp(Name
, ".sbss.", 6) == 0 ||
474 strncmp(Name
, ".gnu.linkonce.sb.", 17) == 0 ||
475 strncmp(Name
, ".llvm.linkonce.sb.", 18) == 0)
476 return SectionKind::getBSS();
478 if (strcmp(Name
, ".tdata") == 0 ||
479 strncmp(Name
, ".tdata.", 7) == 0 ||
480 strncmp(Name
, ".gnu.linkonce.td.", 17) == 0 ||
481 strncmp(Name
, ".llvm.linkonce.td.", 18) == 0)
482 return SectionKind::getThreadData();
484 if (strcmp(Name
, ".tbss") == 0 ||
485 strncmp(Name
, ".tbss.", 6) == 0 ||
486 strncmp(Name
, ".gnu.linkonce.tb.", 17) == 0 ||
487 strncmp(Name
, ".llvm.linkonce.tb.", 18) == 0)
488 return SectionKind::getThreadBSS();
495 getELFSectionType(const char *Name
, SectionKind K
) {
497 if (strcmp(Name
, ".init_array") == 0)
498 return MCSectionELF::SHT_INIT_ARRAY
;
500 if (strcmp(Name
, ".fini_array") == 0)
501 return MCSectionELF::SHT_FINI_ARRAY
;
503 if (strcmp(Name
, ".preinit_array") == 0)
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 std::string Name
= Mang
->makeNameProper(GV
->getNameStr());
581 return getELFSection((Prefix
+Name
).c_str(),
582 getELFSectionType((Prefix
+Name
).c_str(), Kind
),
583 getELFSectionFlags(Kind
),
587 if (Kind
.isText()) return TextSection
;
589 if (Kind
.isMergeable1ByteCString() ||
590 Kind
.isMergeable2ByteCString() ||
591 Kind
.isMergeable4ByteCString()) {
593 // We also need alignment here.
594 // FIXME: this is getting the alignment of the character, not the
595 // alignment of the global!
597 TM
.getTargetData()->getPreferredAlignment(cast
<GlobalVariable
>(GV
));
599 const char *SizeSpec
= ".rodata.str1.";
600 if (Kind
.isMergeable2ByteCString())
601 SizeSpec
= ".rodata.str2.";
602 else if (Kind
.isMergeable4ByteCString())
603 SizeSpec
= ".rodata.str4.";
605 assert(Kind
.isMergeable1ByteCString() && "unknown string width");
608 std::string Name
= SizeSpec
+ utostr(Align
);
609 return getELFSection(Name
.c_str(), MCSectionELF::SHT_PROGBITS
,
610 MCSectionELF::SHF_ALLOC
|
611 MCSectionELF::SHF_MERGE
|
612 MCSectionELF::SHF_STRINGS
,
616 if (Kind
.isMergeableConst()) {
617 if (Kind
.isMergeableConst4() && MergeableConst4Section
)
618 return MergeableConst4Section
;
619 if (Kind
.isMergeableConst8() && MergeableConst8Section
)
620 return MergeableConst8Section
;
621 if (Kind
.isMergeableConst16() && MergeableConst16Section
)
622 return MergeableConst16Section
;
623 return ReadOnlySection
; // .const
626 if (Kind
.isReadOnly()) return ReadOnlySection
;
628 if (Kind
.isThreadData()) return TLSDataSection
;
629 if (Kind
.isThreadBSS()) return TLSBSSSection
;
631 if (Kind
.isBSS()) return BSSSection
;
633 if (Kind
.isDataNoRel()) return DataSection
;
634 if (Kind
.isDataRelLocal()) return DataRelLocalSection
;
635 if (Kind
.isDataRel()) return DataRelSection
;
636 if (Kind
.isReadOnlyWithRelLocal()) return DataRelROLocalSection
;
638 assert(Kind
.isReadOnlyWithRel() && "Unknown section kind");
639 return DataRelROSection
;
642 /// getSectionForConstant - Given a mergeable constant with the
643 /// specified size and relocation information, return a section that it
644 /// should be placed in.
645 const MCSection
*TargetLoweringObjectFileELF::
646 getSectionForConstant(SectionKind Kind
) const {
647 if (Kind
.isMergeableConst4() && MergeableConst4Section
)
648 return MergeableConst4Section
;
649 if (Kind
.isMergeableConst8() && MergeableConst8Section
)
650 return MergeableConst8Section
;
651 if (Kind
.isMergeableConst16() && MergeableConst16Section
)
652 return MergeableConst16Section
;
653 if (Kind
.isReadOnly())
654 return ReadOnlySection
;
656 if (Kind
.isReadOnlyWithRelLocal()) return DataRelROLocalSection
;
657 assert(Kind
.isReadOnlyWithRel() && "Unknown section kind");
658 return DataRelROSection
;
661 //===----------------------------------------------------------------------===//
663 //===----------------------------------------------------------------------===//
665 typedef StringMap
<const MCSectionMachO
*> MachOUniqueMapTy
;
667 TargetLoweringObjectFileMachO::~TargetLoweringObjectFileMachO() {
668 // If we have the MachO uniquing map, free it.
669 delete (MachOUniqueMapTy
*)UniquingMap
;
673 const MCSectionMachO
*TargetLoweringObjectFileMachO::
674 getMachOSection(const StringRef
&Segment
, const StringRef
&Section
,
675 unsigned TypeAndAttributes
,
676 unsigned Reserved2
, SectionKind Kind
) const {
677 // We unique sections by their segment/section pair. The returned section
678 // may not have the same flags as the requested section, if so this should be
679 // diagnosed by the client as an error.
681 // Create the map if it doesn't already exist.
682 if (UniquingMap
== 0)
683 UniquingMap
= new MachOUniqueMapTy();
684 MachOUniqueMapTy
&Map
= *(MachOUniqueMapTy
*)UniquingMap
;
686 // Form the name to look up.
687 SmallString
<64> Name
;
692 // Do the lookup, if we have a hit, return it.
693 const MCSectionMachO
*&Entry
= Map
[Name
.str()];
694 if (Entry
) return Entry
;
696 // Otherwise, return a new section.
697 return Entry
= MCSectionMachO::Create(Segment
, Section
, TypeAndAttributes
,
698 Reserved2
, Kind
, getContext());
702 void TargetLoweringObjectFileMachO::Initialize(MCContext
&Ctx
,
703 const TargetMachine
&TM
) {
704 if (UniquingMap
!= 0)
705 ((MachOUniqueMapTy
*)UniquingMap
)->clear();
706 TargetLoweringObjectFile::Initialize(Ctx
, TM
);
709 = getMachOSection("__TEXT", "__text",
710 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS
,
711 SectionKind::getText());
713 = getMachOSection("__DATA", "__data", 0, SectionKind::getDataRel());
715 CStringSection
// .cstring
716 = getMachOSection("__TEXT", "__cstring", MCSectionMachO::S_CSTRING_LITERALS
,
717 SectionKind::getMergeable1ByteCString());
719 = getMachOSection("__TEXT","__ustring", 0,
720 SectionKind::getMergeable2ByteCString());
721 FourByteConstantSection
// .literal4
722 = getMachOSection("__TEXT", "__literal4", MCSectionMachO::S_4BYTE_LITERALS
,
723 SectionKind::getMergeableConst4());
724 EightByteConstantSection
// .literal8
725 = getMachOSection("__TEXT", "__literal8", MCSectionMachO::S_8BYTE_LITERALS
,
726 SectionKind::getMergeableConst8());
728 // ld_classic doesn't support .literal16 in 32-bit mode, and ld64 falls back
729 // to using it in -static mode.
730 SixteenByteConstantSection
= 0;
731 if (TM
.getRelocationModel() != Reloc::Static
&&
732 TM
.getTargetData()->getPointerSize() == 32)
733 SixteenByteConstantSection
= // .literal16
734 getMachOSection("__TEXT", "__literal16",MCSectionMachO::S_16BYTE_LITERALS
,
735 SectionKind::getMergeableConst16());
737 ReadOnlySection
// .const
738 = getMachOSection("__TEXT", "__const", 0, SectionKind::getReadOnly());
741 = getMachOSection("__TEXT", "__textcoal_nt",
742 MCSectionMachO::S_COALESCED
|
743 MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS
,
744 SectionKind::getText());
746 = getMachOSection("__TEXT", "__const_coal", MCSectionMachO::S_COALESCED
,
747 SectionKind::getText());
749 = getMachOSection("__DATA","__const_coal", MCSectionMachO::S_COALESCED
,
750 SectionKind::getText());
751 ConstDataSection
// .const_data
752 = getMachOSection("__DATA", "__const", 0,
753 SectionKind::getReadOnlyWithRel());
755 = getMachOSection("__DATA","__datacoal_nt", MCSectionMachO::S_COALESCED
,
756 SectionKind::getDataRel());
759 LazySymbolPointerSection
760 = getMachOSection("__DATA", "__la_symbol_ptr",
761 MCSectionMachO::S_LAZY_SYMBOL_POINTERS
,
762 SectionKind::getMetadata());
763 NonLazySymbolPointerSection
764 = getMachOSection("__DATA", "__nl_symbol_ptr",
765 MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS
,
766 SectionKind::getMetadata());
768 if (TM
.getRelocationModel() == Reloc::Static
) {
770 = getMachOSection("__TEXT", "__constructor", 0,SectionKind::getDataRel());
772 = getMachOSection("__TEXT", "__destructor", 0, SectionKind::getDataRel());
775 = getMachOSection("__DATA", "__mod_init_func",
776 MCSectionMachO::S_MOD_INIT_FUNC_POINTERS
,
777 SectionKind::getDataRel());
779 = getMachOSection("__DATA", "__mod_term_func",
780 MCSectionMachO::S_MOD_TERM_FUNC_POINTERS
,
781 SectionKind::getDataRel());
784 // Exception Handling.
785 LSDASection
= getMachOSection("__DATA", "__gcc_except_tab", 0,
786 SectionKind::getDataRel());
788 getMachOSection("__TEXT", "__eh_frame",
789 MCSectionMachO::S_COALESCED
|
790 MCSectionMachO::S_ATTR_NO_TOC
|
791 MCSectionMachO::S_ATTR_STRIP_STATIC_SYMS
|
792 MCSectionMachO::S_ATTR_LIVE_SUPPORT
,
793 SectionKind::getReadOnly());
795 // Debug Information.
797 getMachOSection("__DWARF", "__debug_abbrev", MCSectionMachO::S_ATTR_DEBUG
,
798 SectionKind::getMetadata());
800 getMachOSection("__DWARF", "__debug_info", MCSectionMachO::S_ATTR_DEBUG
,
801 SectionKind::getMetadata());
803 getMachOSection("__DWARF", "__debug_line", MCSectionMachO::S_ATTR_DEBUG
,
804 SectionKind::getMetadata());
806 getMachOSection("__DWARF", "__debug_frame", MCSectionMachO::S_ATTR_DEBUG
,
807 SectionKind::getMetadata());
808 DwarfPubNamesSection
=
809 getMachOSection("__DWARF", "__debug_pubnames", MCSectionMachO::S_ATTR_DEBUG
,
810 SectionKind::getMetadata());
811 DwarfPubTypesSection
=
812 getMachOSection("__DWARF", "__debug_pubtypes", MCSectionMachO::S_ATTR_DEBUG
,
813 SectionKind::getMetadata());
815 getMachOSection("__DWARF", "__debug_str", MCSectionMachO::S_ATTR_DEBUG
,
816 SectionKind::getMetadata());
818 getMachOSection("__DWARF", "__debug_loc", MCSectionMachO::S_ATTR_DEBUG
,
819 SectionKind::getMetadata());
820 DwarfARangesSection
=
821 getMachOSection("__DWARF", "__debug_aranges", MCSectionMachO::S_ATTR_DEBUG
,
822 SectionKind::getMetadata());
824 getMachOSection("__DWARF", "__debug_ranges", MCSectionMachO::S_ATTR_DEBUG
,
825 SectionKind::getMetadata());
826 DwarfMacroInfoSection
=
827 getMachOSection("__DWARF", "__debug_macinfo", MCSectionMachO::S_ATTR_DEBUG
,
828 SectionKind::getMetadata());
829 DwarfDebugInlineSection
=
830 getMachOSection("__DWARF", "__debug_inlined", MCSectionMachO::S_ATTR_DEBUG
,
831 SectionKind::getMetadata());
834 const MCSection
*TargetLoweringObjectFileMachO::
835 getExplicitSectionGlobal(const GlobalValue
*GV
, SectionKind Kind
,
836 Mangler
*Mang
, const TargetMachine
&TM
) const {
837 // Parse the section specifier and create it if valid.
838 StringRef Segment
, Section
;
839 unsigned TAA
, StubSize
;
840 std::string ErrorCode
=
841 MCSectionMachO::ParseSectionSpecifier(GV
->getSection(), Segment
, Section
,
843 if (!ErrorCode
.empty()) {
844 // If invalid, report the error with llvm_report_error.
845 llvm_report_error("Global variable '" + GV
->getNameStr() +
846 "' has an invalid section specifier '" + GV
->getSection()+
847 "': " + ErrorCode
+ ".");
848 // Fall back to dropping it into the data section.
853 const MCSectionMachO
*S
=
854 getMachOSection(Segment
, Section
, TAA
, StubSize
, Kind
);
856 // Okay, now that we got the section, verify that the TAA & StubSize agree.
857 // If the user declared multiple globals with different section flags, we need
858 // to reject it here.
859 if (S
->getTypeAndAttributes() != TAA
|| S
->getStubSize() != StubSize
) {
860 // If invalid, report the error with llvm_report_error.
861 llvm_report_error("Global variable '" + GV
->getNameStr() +
862 "' section type or attributes does not match previous"
863 " section specifier");
869 const MCSection
*TargetLoweringObjectFileMachO::
870 SelectSectionForGlobal(const GlobalValue
*GV
, SectionKind Kind
,
871 Mangler
*Mang
, const TargetMachine
&TM
) const {
872 assert(!Kind
.isThreadLocal() && "Darwin doesn't support TLS");
875 return GV
->isWeakForLinker() ? TextCoalSection
: TextSection
;
877 // If this is weak/linkonce, put this in a coalescable section, either in text
878 // or data depending on if it is writable.
879 if (GV
->isWeakForLinker()) {
880 if (Kind
.isReadOnly())
881 return ConstTextCoalSection
;
882 return DataCoalSection
;
885 // FIXME: Alignment check should be handled by section classifier.
886 if (Kind
.isMergeable1ByteCString() ||
887 Kind
.isMergeable2ByteCString()) {
888 if (TM
.getTargetData()->getPreferredAlignment(
889 cast
<GlobalVariable
>(GV
)) < 32) {
890 if (Kind
.isMergeable1ByteCString())
891 return CStringSection
;
892 assert(Kind
.isMergeable2ByteCString());
893 return UStringSection
;
897 if (Kind
.isMergeableConst()) {
898 if (Kind
.isMergeableConst4())
899 return FourByteConstantSection
;
900 if (Kind
.isMergeableConst8())
901 return EightByteConstantSection
;
902 if (Kind
.isMergeableConst16() && SixteenByteConstantSection
)
903 return SixteenByteConstantSection
;
906 // Otherwise, if it is readonly, but not something we can specially optimize,
907 // just drop it in .const.
908 if (Kind
.isReadOnly())
909 return ReadOnlySection
;
911 // If this is marked const, put it into a const section. But if the dynamic
912 // linker needs to write to it, put it in the data segment.
913 if (Kind
.isReadOnlyWithRel())
914 return ConstDataSection
;
916 // Otherwise, just drop the variable in the normal data section.
921 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind
) const {
922 // If this constant requires a relocation, we have to put it in the data
923 // segment, not in the text segment.
924 if (Kind
.isDataRel())
925 return ConstDataSection
;
927 if (Kind
.isMergeableConst4())
928 return FourByteConstantSection
;
929 if (Kind
.isMergeableConst8())
930 return EightByteConstantSection
;
931 if (Kind
.isMergeableConst16() && SixteenByteConstantSection
)
932 return SixteenByteConstantSection
;
933 return ReadOnlySection
; // .const
936 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
937 /// not to emit the UsedDirective for some symbols in llvm.used.
938 // FIXME: REMOVE this (rdar://7071300)
939 bool TargetLoweringObjectFileMachO::
940 shouldEmitUsedDirectiveFor(const GlobalValue
*GV
, Mangler
*Mang
) const {
941 /// On Darwin, internally linked data beginning with "L" or "l" does not have
942 /// the directive emitted (this occurs in ObjC metadata).
943 if (!GV
) return false;
945 // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
946 if (GV
->hasLocalLinkage() && !isa
<Function
>(GV
)) {
947 // FIXME: ObjC metadata is currently emitted as internal symbols that have
948 // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
949 // this horrible hack can go away.
950 const std::string
&Name
= Mang
->getMangledName(GV
);
951 if (Name
[0] == 'L' || Name
[0] == 'l')
958 const MCExpr
*TargetLoweringObjectFileMachO::
959 getSymbolForDwarfGlobalReference(const GlobalValue
*GV
, Mangler
*Mang
,
960 MachineModuleInfo
*MMI
,
961 bool &IsIndirect
, bool &IsPCRel
) const {
962 // The mach-o version of this method defaults to returning a stub reference.
966 SmallString
<128> Name
;
967 Mang
->getNameWithPrefix(Name
, GV
, true);
968 Name
+= "$non_lazy_ptr";
969 return MCSymbolRefExpr::Create(Name
.str(), getContext());
973 //===----------------------------------------------------------------------===//
975 //===----------------------------------------------------------------------===//
977 typedef StringMap
<const MCSectionCOFF
*> COFFUniqueMapTy
;
979 TargetLoweringObjectFileCOFF::~TargetLoweringObjectFileCOFF() {
980 delete (COFFUniqueMapTy
*)UniquingMap
;
984 const MCSection
*TargetLoweringObjectFileCOFF::
985 getCOFFSection(const char *Name
, bool isDirective
, SectionKind Kind
) const {
986 // Create the map if it doesn't already exist.
987 if (UniquingMap
== 0)
988 UniquingMap
= new MachOUniqueMapTy();
989 COFFUniqueMapTy
&Map
= *(COFFUniqueMapTy
*)UniquingMap
;
991 // Do the lookup, if we have a hit, return it.
992 const MCSectionCOFF
*&Entry
= Map
[Name
];
993 if (Entry
) return Entry
;
995 return Entry
= MCSectionCOFF::Create(Name
, isDirective
, Kind
, getContext());
998 void TargetLoweringObjectFileCOFF::Initialize(MCContext
&Ctx
,
999 const TargetMachine
&TM
) {
1000 if (UniquingMap
!= 0)
1001 ((COFFUniqueMapTy
*)UniquingMap
)->clear();
1002 TargetLoweringObjectFile::Initialize(Ctx
, TM
);
1003 TextSection
= getCOFFSection("\t.text", true, SectionKind::getText());
1004 DataSection
= getCOFFSection("\t.data", true, SectionKind::getDataRel());
1006 getCOFFSection(".ctors", false, SectionKind::getDataRel());
1008 getCOFFSection(".dtors", false, SectionKind::getDataRel());
1010 // FIXME: We're emitting LSDA info into a readonly section on COFF, even
1011 // though it contains relocatable pointers. In PIC mode, this is probably a
1012 // big runtime hit for C++ apps. Either the contents of the LSDA need to be
1013 // adjusted or this should be a data section.
1015 getCOFFSection(".gcc_except_table", false, SectionKind::getReadOnly());
1017 getCOFFSection(".eh_frame", false, SectionKind::getDataRel());
1020 // FIXME: Don't use 'directive' mode here.
1021 DwarfAbbrevSection
=
1022 getCOFFSection("\t.section\t.debug_abbrev,\"dr\"",
1023 true, SectionKind::getMetadata());
1025 getCOFFSection("\t.section\t.debug_info,\"dr\"",
1026 true, SectionKind::getMetadata());
1028 getCOFFSection("\t.section\t.debug_line,\"dr\"",
1029 true, SectionKind::getMetadata());
1031 getCOFFSection("\t.section\t.debug_frame,\"dr\"",
1032 true, SectionKind::getMetadata());
1033 DwarfPubNamesSection
=
1034 getCOFFSection("\t.section\t.debug_pubnames,\"dr\"",
1035 true, SectionKind::getMetadata());
1036 DwarfPubTypesSection
=
1037 getCOFFSection("\t.section\t.debug_pubtypes,\"dr\"",
1038 true, SectionKind::getMetadata());
1040 getCOFFSection("\t.section\t.debug_str,\"dr\"",
1041 true, SectionKind::getMetadata());
1043 getCOFFSection("\t.section\t.debug_loc,\"dr\"",
1044 true, SectionKind::getMetadata());
1045 DwarfARangesSection
=
1046 getCOFFSection("\t.section\t.debug_aranges,\"dr\"",
1047 true, SectionKind::getMetadata());
1048 DwarfRangesSection
=
1049 getCOFFSection("\t.section\t.debug_ranges,\"dr\"",
1050 true, SectionKind::getMetadata());
1051 DwarfMacroInfoSection
=
1052 getCOFFSection("\t.section\t.debug_macinfo,\"dr\"",
1053 true, SectionKind::getMetadata());
1056 const MCSection
*TargetLoweringObjectFileCOFF::
1057 getExplicitSectionGlobal(const GlobalValue
*GV
, SectionKind Kind
,
1058 Mangler
*Mang
, const TargetMachine
&TM
) const {
1059 return getCOFFSection(GV
->getSection().c_str(), false, Kind
);
1062 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind
) {
1064 return ".text$linkonce";
1065 if (Kind
.isWriteable())
1066 return ".data$linkonce";
1067 return ".rdata$linkonce";
1071 const MCSection
*TargetLoweringObjectFileCOFF::
1072 SelectSectionForGlobal(const GlobalValue
*GV
, SectionKind Kind
,
1073 Mangler
*Mang
, const TargetMachine
&TM
) const {
1074 assert(!Kind
.isThreadLocal() && "Doesn't support TLS");
1076 // If this global is linkonce/weak and the target handles this by emitting it
1077 // into a 'uniqued' section name, create and return the section now.
1078 if (GV
->isWeakForLinker()) {
1079 const char *Prefix
= getCOFFSectionPrefixForUniqueGlobal(Kind
);
1080 std::string Name
= Mang
->makeNameProper(GV
->getNameStr());
1081 return getCOFFSection((Prefix
+Name
).c_str(), false, Kind
);
1085 return getTextSection();
1087 return getDataSection();