1 //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.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/CodeGen/TargetLoweringObjectFileImpl.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCSectionCOFF.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Dwarf.h"
36 #include "llvm/Support/ELF.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Target/TargetLowering.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Target/TargetSubtargetInfo.h"
43 using namespace dwarf;
45 // Disabled by default because it hits bug 17350 in GNU ld (gold is fine)
47 EnableStructorCOMDAT("enable-structor-comdat", cl::Hidden,
48 cl::desc("Use comdats to keep only one copy of a "
49 "constructor/destructor invocation"),
52 //===----------------------------------------------------------------------===//
54 //===----------------------------------------------------------------------===//
56 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
57 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
58 MachineModuleInfo *MMI) const {
59 unsigned Encoding = getPersonalityEncoding();
60 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
61 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
62 TM.getSymbol(GV, Mang)->getName());
63 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
64 return TM.getSymbol(GV, Mang);
65 report_fatal_error("We do not support this DWARF encoding yet!");
68 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
69 const TargetMachine &TM,
70 const MCSymbol *Sym) const {
71 SmallString<64> NameData("DW.ref.");
72 NameData += Sym->getName();
73 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
74 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
75 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
76 StringRef Prefix = ".data.";
77 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
78 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
79 const MCSection *Sec = getContext().getELFSection(NameData,
82 SectionKind::getDataRel(),
84 unsigned Size = TM.getSubtargetImpl()->getDataLayout()->getPointerSize();
85 Streamer.SwitchSection(Sec);
86 Streamer.EmitValueToAlignment(
87 TM.getSubtargetImpl()->getDataLayout()->getPointerABIAlignment());
88 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
89 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
90 Streamer.EmitELFSize(Label, E);
91 Streamer.EmitLabel(Label);
93 Streamer.EmitSymbolValue(Sym, Size);
96 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
97 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
98 const TargetMachine &TM, MachineModuleInfo *MMI,
99 MCStreamer &Streamer) const {
101 if (Encoding & dwarf::DW_EH_PE_indirect) {
102 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
104 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
106 // Add information about the stub reference to ELFMMI so that the stub
107 // gets emitted by the asmprinter.
108 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
109 if (!StubSym.getPointer()) {
110 MCSymbol *Sym = TM.getSymbol(GV, Mang);
111 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
114 return TargetLoweringObjectFile::
115 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
116 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
119 return TargetLoweringObjectFile::
120 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
124 getELFKindForNamedSection(StringRef Name, SectionKind K) {
125 // N.B.: The defaults used in here are no the same ones used in MC.
126 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
127 // both gas and MC will produce a section with no flags. Given
128 // section(".eh_frame") gcc will produce:
130 // .section .eh_frame,"a",@progbits
131 if (Name.empty() || Name[0] != '.') return K;
133 // Some lame default implementation based on some magic section names.
134 if (Name == ".bss" ||
135 Name.startswith(".bss.") ||
136 Name.startswith(".gnu.linkonce.b.") ||
137 Name.startswith(".llvm.linkonce.b.") ||
139 Name.startswith(".sbss.") ||
140 Name.startswith(".gnu.linkonce.sb.") ||
141 Name.startswith(".llvm.linkonce.sb."))
142 return SectionKind::getBSS();
144 if (Name == ".tdata" ||
145 Name.startswith(".tdata.") ||
146 Name.startswith(".gnu.linkonce.td.") ||
147 Name.startswith(".llvm.linkonce.td."))
148 return SectionKind::getThreadData();
150 if (Name == ".tbss" ||
151 Name.startswith(".tbss.") ||
152 Name.startswith(".gnu.linkonce.tb.") ||
153 Name.startswith(".llvm.linkonce.tb."))
154 return SectionKind::getThreadBSS();
160 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
162 if (Name == ".init_array")
163 return ELF::SHT_INIT_ARRAY;
165 if (Name == ".fini_array")
166 return ELF::SHT_FINI_ARRAY;
168 if (Name == ".preinit_array")
169 return ELF::SHT_PREINIT_ARRAY;
171 if (K.isBSS() || K.isThreadBSS())
172 return ELF::SHT_NOBITS;
174 return ELF::SHT_PROGBITS;
179 getELFSectionFlags(SectionKind K) {
183 Flags |= ELF::SHF_ALLOC;
186 Flags |= ELF::SHF_EXECINSTR;
189 Flags |= ELF::SHF_WRITE;
191 if (K.isThreadLocal())
192 Flags |= ELF::SHF_TLS;
194 // K.isMergeableConst() is left out to honour PR4650
195 if (K.isMergeableCString() || K.isMergeableConst4() ||
196 K.isMergeableConst8() || K.isMergeableConst16())
197 Flags |= ELF::SHF_MERGE;
199 if (K.isMergeableCString())
200 Flags |= ELF::SHF_STRINGS;
205 static const Comdat *getELFComdat(const GlobalValue *GV) {
206 const Comdat *C = GV->getComdat();
210 if (C->getSelectionKind() != Comdat::Any)
211 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
212 C->getName() + "' cannot be lowered.");
217 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
218 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
219 const TargetMachine &TM) const {
220 StringRef SectionName = GV->getSection();
222 // Infer section flags from the section name if we can.
223 Kind = getELFKindForNamedSection(SectionName, Kind);
225 StringRef Group = "";
226 unsigned Flags = getELFSectionFlags(Kind);
227 if (const Comdat *C = getELFComdat(GV)) {
228 Group = C->getName();
229 Flags |= ELF::SHF_GROUP;
231 return getContext().getELFSection(SectionName,
232 getELFSectionType(SectionName, Kind), Flags,
233 Kind, /*EntrySize=*/0, Group);
236 /// getSectionPrefixForGlobal - Return the section prefix name used by options
237 /// FunctionsSections and DataSections.
238 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
239 if (Kind.isText()) return ".text.";
240 if (Kind.isReadOnly()) return ".rodata.";
241 if (Kind.isBSS()) return ".bss.";
243 if (Kind.isThreadData()) return ".tdata.";
244 if (Kind.isThreadBSS()) return ".tbss.";
246 if (Kind.isDataNoRel()) return ".data.";
247 if (Kind.isDataRelLocal()) return ".data.rel.local.";
248 if (Kind.isDataRel()) return ".data.rel.";
249 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
251 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
252 return ".data.rel.ro.";
255 const MCSection *TargetLoweringObjectFileELF::
256 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
257 Mangler &Mang, const TargetMachine &TM) const {
258 // If we have -ffunction-section or -fdata-section then we should emit the
259 // global value to a uniqued section specifically for it.
260 bool EmitUniquedSection;
262 EmitUniquedSection = TM.getFunctionSections();
264 EmitUniquedSection = TM.getDataSections();
266 // If this global is linkonce/weak and the target handles this by emitting it
267 // into a 'uniqued' section name, create and return the section now.
268 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
270 StringRef Prefix = getSectionPrefixForGlobal(Kind);
272 SmallString<128> Name(Prefix);
273 TM.getNameWithPrefix(Name, GV, Mang, true);
275 StringRef Group = "";
276 unsigned Flags = getELFSectionFlags(Kind);
277 if (GV->isWeakForLinker() || GV->hasComdat()) {
278 if (const Comdat *C = getELFComdat(GV))
279 Group = C->getName();
281 Group = Name.substr(Prefix.size());
282 Flags |= ELF::SHF_GROUP;
285 return getContext().getELFSection(Name.str(),
286 getELFSectionType(Name.str(), Kind),
287 Flags, Kind, 0, Group);
290 if (Kind.isText()) return TextSection;
292 if (Kind.isMergeable1ByteCString() ||
293 Kind.isMergeable2ByteCString() ||
294 Kind.isMergeable4ByteCString()) {
296 // We also need alignment here.
297 // FIXME: this is getting the alignment of the character, not the
298 // alignment of the global!
300 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
301 cast<GlobalVariable>(GV));
303 const char *SizeSpec = ".rodata.str1.";
304 if (Kind.isMergeable2ByteCString())
305 SizeSpec = ".rodata.str2.";
306 else if (Kind.isMergeable4ByteCString())
307 SizeSpec = ".rodata.str4.";
309 assert(Kind.isMergeable1ByteCString() && "unknown string width");
312 std::string Name = SizeSpec + utostr(Align);
313 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
320 if (Kind.isMergeableConst()) {
321 if (Kind.isMergeableConst4() && MergeableConst4Section)
322 return MergeableConst4Section;
323 if (Kind.isMergeableConst8() && MergeableConst8Section)
324 return MergeableConst8Section;
325 if (Kind.isMergeableConst16() && MergeableConst16Section)
326 return MergeableConst16Section;
327 return ReadOnlySection; // .const
330 if (Kind.isReadOnly()) return ReadOnlySection;
332 if (Kind.isThreadData()) return TLSDataSection;
333 if (Kind.isThreadBSS()) return TLSBSSSection;
335 // Note: we claim that common symbols are put in BSSSection, but they are
336 // really emitted with the magic .comm directive, which creates a symbol table
337 // entry but not a section.
338 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
340 if (Kind.isDataNoRel()) return DataSection;
341 if (Kind.isDataRelLocal()) return DataRelLocalSection;
342 if (Kind.isDataRel()) return DataRelSection;
343 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
345 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
346 return DataRelROSection;
349 /// getSectionForConstant - Given a mergeable constant with the
350 /// specified size and relocation information, return a section that it
351 /// should be placed in.
353 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
354 const Constant *C) const {
355 if (Kind.isMergeableConst4() && MergeableConst4Section)
356 return MergeableConst4Section;
357 if (Kind.isMergeableConst8() && MergeableConst8Section)
358 return MergeableConst8Section;
359 if (Kind.isMergeableConst16() && MergeableConst16Section)
360 return MergeableConst16Section;
361 if (Kind.isReadOnly())
362 return ReadOnlySection;
364 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
365 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
366 return DataRelROSection;
369 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
373 const MCSymbol *KeySym) {
374 if (!EnableStructorCOMDAT)
379 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
380 SectionKind Kind = SectionKind::getDataRel();
381 StringRef COMDAT = KeySym ? KeySym->getName() : "";
384 Flags |= ELF::SHF_GROUP;
388 Type = ELF::SHT_INIT_ARRAY;
389 Name = ".init_array";
391 Type = ELF::SHT_FINI_ARRAY;
392 Name = ".fini_array";
394 if (Priority != 65535) {
396 Name += utostr(Priority);
399 // The default scheme is .ctor / .dtor, so we have to invert the priority
405 if (Priority != 65535) {
407 Name += utostr(65535 - Priority);
409 Type = ELF::SHT_PROGBITS;
412 return Ctx.getELFSection(Name, Type, Flags, Kind, 0, COMDAT);
415 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
416 unsigned Priority, const MCSymbol *KeySym) const {
417 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
421 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
422 unsigned Priority, const MCSymbol *KeySym) const {
423 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
428 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
429 UseInitArray = UseInitArray_;
434 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
437 SectionKind::getDataRel());
439 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
442 SectionKind::getDataRel());
445 //===----------------------------------------------------------------------===//
447 //===----------------------------------------------------------------------===//
449 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
450 /// option string. Returns StringRef() if the option does not specify a library.
451 StringRef TargetLoweringObjectFileMachO::
452 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
453 const char *LibCmd = "-l";
454 if (LinkerOption.startswith(LibCmd))
455 return LinkerOption.substr(strlen(LibCmd));
459 /// emitModuleFlags - Perform code emission for module flags.
460 void TargetLoweringObjectFileMachO::
461 emitModuleFlags(MCStreamer &Streamer,
462 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
463 Mangler &Mang, const TargetMachine &TM) const {
464 unsigned VersionVal = 0;
465 unsigned ImageInfoFlags = 0;
466 MDNode *LinkerOptions = nullptr;
467 StringRef SectionVal;
469 for (ArrayRef<Module::ModuleFlagEntry>::iterator
470 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
471 const Module::ModuleFlagEntry &MFE = *i;
473 // Ignore flags with 'Require' behavior.
474 if (MFE.Behavior == Module::Require)
477 StringRef Key = MFE.Key->getString();
478 Value *Val = MFE.Val;
480 if (Key == "Objective-C Image Info Version") {
481 VersionVal = cast<ConstantInt>(Val)->getZExtValue();
482 } else if (Key == "Objective-C Garbage Collection" ||
483 Key == "Objective-C GC Only" ||
484 Key == "Objective-C Is Simulated") {
485 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
486 } else if (Key == "Objective-C Image Info Section") {
487 SectionVal = cast<MDString>(Val)->getString();
488 } else if (Key == "Linker Options") {
489 LinkerOptions = cast<MDNode>(Val);
493 // Emit the linker options if present.
495 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
496 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
497 SmallVector<std::string, 4> StrOptions;
499 // Convert to strings.
500 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
501 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
502 StrOptions.push_back(MDOption->getString());
505 Streamer.EmitLinkerOptions(StrOptions);
509 // The section is mandatory. If we don't have it, then we don't have GC info.
510 if (SectionVal.empty()) return;
512 StringRef Segment, Section;
513 unsigned TAA = 0, StubSize = 0;
515 std::string ErrorCode =
516 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
517 TAA, TAAParsed, StubSize);
518 if (!ErrorCode.empty())
519 // If invalid, report the error with report_fatal_error.
520 report_fatal_error("Invalid section specifier '" + Section + "': " +
524 const MCSectionMachO *S =
525 getContext().getMachOSection(Segment, Section, TAA, StubSize,
526 SectionKind::getDataNoRel());
527 Streamer.SwitchSection(S);
528 Streamer.EmitLabel(getContext().
529 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
530 Streamer.EmitIntValue(VersionVal, 4);
531 Streamer.EmitIntValue(ImageInfoFlags, 4);
532 Streamer.AddBlankLine();
535 static void checkMachOComdat(const GlobalValue *GV) {
536 const Comdat *C = GV->getComdat();
540 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
541 "' cannot be lowered.");
544 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
545 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
546 const TargetMachine &TM) const {
547 // Parse the section specifier and create it if valid.
548 StringRef Segment, Section;
549 unsigned TAA = 0, StubSize = 0;
552 checkMachOComdat(GV);
554 std::string ErrorCode =
555 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
556 TAA, TAAParsed, StubSize);
557 if (!ErrorCode.empty()) {
558 // If invalid, report the error with report_fatal_error.
559 report_fatal_error("Global variable '" + GV->getName() +
560 "' has an invalid section specifier '" +
561 GV->getSection() + "': " + ErrorCode + ".");
565 const MCSectionMachO *S =
566 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
568 // If TAA wasn't set by ParseSectionSpecifier() above,
569 // use the value returned by getMachOSection() as a default.
571 TAA = S->getTypeAndAttributes();
573 // Okay, now that we got the section, verify that the TAA & StubSize agree.
574 // If the user declared multiple globals with different section flags, we need
575 // to reject it here.
576 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
577 // If invalid, report the error with report_fatal_error.
578 report_fatal_error("Global variable '" + GV->getName() +
579 "' section type or attributes does not match previous"
580 " section specifier");
586 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
587 const MCSection &Section) const {
588 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
590 // Sections holding 1 byte strings are atomized based on the data
592 // Sections holding 2 byte strings require symbols in order to be
594 // There is no dedicated section for 4 byte strings.
595 if (SMO.getKind().isMergeable1ByteCString())
598 if (SMO.getSegmentName() == "__DATA" &&
599 SMO.getSectionName() == "__cfstring")
602 switch (SMO.getType()) {
606 // These sections are atomized at the element boundaries without using
608 case MachO::S_4BYTE_LITERALS:
609 case MachO::S_8BYTE_LITERALS:
610 case MachO::S_16BYTE_LITERALS:
611 case MachO::S_LITERAL_POINTERS:
612 case MachO::S_NON_LAZY_SYMBOL_POINTERS:
613 case MachO::S_LAZY_SYMBOL_POINTERS:
614 case MachO::S_MOD_INIT_FUNC_POINTERS:
615 case MachO::S_MOD_TERM_FUNC_POINTERS:
616 case MachO::S_INTERPOSING:
621 const MCSection *TargetLoweringObjectFileMachO::
622 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
623 Mangler &Mang, const TargetMachine &TM) const {
624 checkMachOComdat(GV);
626 // Handle thread local data.
627 if (Kind.isThreadBSS()) return TLSBSSSection;
628 if (Kind.isThreadData()) return TLSDataSection;
631 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
633 // If this is weak/linkonce, put this in a coalescable section, either in text
634 // or data depending on if it is writable.
635 if (GV->isWeakForLinker()) {
636 if (Kind.isReadOnly())
637 return ConstTextCoalSection;
638 return DataCoalSection;
641 // FIXME: Alignment check should be handled by section classifier.
642 if (Kind.isMergeable1ByteCString() &&
643 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
644 cast<GlobalVariable>(GV)) < 32)
645 return CStringSection;
647 // Do not put 16-bit arrays in the UString section if they have an
648 // externally visible label, this runs into issues with certain linker
650 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
651 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
652 cast<GlobalVariable>(GV)) < 32)
653 return UStringSection;
655 // With MachO only variables whose corresponding symbol starts with 'l' or
656 // 'L' can be merged, so we only try merging GVs with private linkage.
657 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
658 if (Kind.isMergeableConst4())
659 return FourByteConstantSection;
660 if (Kind.isMergeableConst8())
661 return EightByteConstantSection;
662 if (Kind.isMergeableConst16())
663 return SixteenByteConstantSection;
666 // Otherwise, if it is readonly, but not something we can specially optimize,
667 // just drop it in .const.
668 if (Kind.isReadOnly())
669 return ReadOnlySection;
671 // If this is marked const, put it into a const section. But if the dynamic
672 // linker needs to write to it, put it in the data segment.
673 if (Kind.isReadOnlyWithRel())
674 return ConstDataSection;
676 // Put zero initialized globals with strong external linkage in the
677 // DATA, __common section with the .zerofill directive.
678 if (Kind.isBSSExtern())
679 return DataCommonSection;
681 // Put zero initialized globals with local linkage in __DATA,__bss directive
682 // with the .zerofill directive (aka .lcomm).
683 if (Kind.isBSSLocal())
684 return DataBSSSection;
686 // Otherwise, just drop the variable in the normal data section.
691 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
692 const Constant *C) const {
693 // If this constant requires a relocation, we have to put it in the data
694 // segment, not in the text segment.
695 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
696 return ConstDataSection;
698 if (Kind.isMergeableConst4())
699 return FourByteConstantSection;
700 if (Kind.isMergeableConst8())
701 return EightByteConstantSection;
702 if (Kind.isMergeableConst16())
703 return SixteenByteConstantSection;
704 return ReadOnlySection; // .const
707 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
708 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
709 const TargetMachine &TM, MachineModuleInfo *MMI,
710 MCStreamer &Streamer) const {
711 // The mach-o version of this method defaults to returning a stub reference.
713 if (Encoding & DW_EH_PE_indirect) {
714 MachineModuleInfoMachO &MachOMMI =
715 MMI->getObjFileInfo<MachineModuleInfoMachO>();
718 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
720 // Add information about the stub reference to MachOMMI so that the stub
721 // gets emitted by the asmprinter.
722 MachineModuleInfoImpl::StubValueTy &StubSym =
723 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
724 MachOMMI.getGVStubEntry(SSym);
725 if (!StubSym.getPointer()) {
726 MCSymbol *Sym = TM.getSymbol(GV, Mang);
727 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
730 return TargetLoweringObjectFile::
731 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
732 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
735 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
739 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
740 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
741 MachineModuleInfo *MMI) const {
742 // The mach-o version of this method defaults to returning a stub reference.
743 MachineModuleInfoMachO &MachOMMI =
744 MMI->getObjFileInfo<MachineModuleInfoMachO>();
746 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
748 // Add information about the stub reference to MachOMMI so that the stub
749 // gets emitted by the asmprinter.
750 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
751 if (!StubSym.getPointer()) {
752 MCSymbol *Sym = TM.getSymbol(GV, Mang);
753 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
759 //===----------------------------------------------------------------------===//
761 //===----------------------------------------------------------------------===//
764 getCOFFSectionFlags(SectionKind K) {
769 COFF::IMAGE_SCN_MEM_DISCARDABLE;
772 COFF::IMAGE_SCN_MEM_EXECUTE |
773 COFF::IMAGE_SCN_MEM_READ |
774 COFF::IMAGE_SCN_CNT_CODE;
777 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
778 COFF::IMAGE_SCN_MEM_READ |
779 COFF::IMAGE_SCN_MEM_WRITE;
780 else if (K.isThreadLocal())
782 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
783 COFF::IMAGE_SCN_MEM_READ |
784 COFF::IMAGE_SCN_MEM_WRITE;
785 else if (K.isReadOnly())
787 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
788 COFF::IMAGE_SCN_MEM_READ;
789 else if (K.isWriteable())
791 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
792 COFF::IMAGE_SCN_MEM_READ |
793 COFF::IMAGE_SCN_MEM_WRITE;
798 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
799 const Comdat *C = GV->getComdat();
800 assert(C && "expected GV to have a Comdat!");
802 StringRef ComdatGVName = C->getName();
803 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
805 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
806 "' does not exist.");
808 if (ComdatGV->getComdat() != C)
809 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
810 "' is not a key for it's COMDAT.");
815 static int getSelectionForCOFF(const GlobalValue *GV) {
816 if (const Comdat *C = GV->getComdat()) {
817 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
818 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
819 ComdatKey = GA->getBaseObject();
820 if (ComdatKey == GV) {
821 switch (C->getSelectionKind()) {
823 return COFF::IMAGE_COMDAT_SELECT_ANY;
824 case Comdat::ExactMatch:
825 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
826 case Comdat::Largest:
827 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
828 case Comdat::NoDuplicates:
829 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
830 case Comdat::SameSize:
831 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
834 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
836 } else if (GV->isWeakForLinker()) {
837 return COFF::IMAGE_COMDAT_SELECT_ANY;
842 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
843 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
844 const TargetMachine &TM) const {
846 unsigned Characteristics = getCOFFSectionFlags(Kind);
847 StringRef Name = GV->getSection();
848 StringRef COMDATSymName = "";
849 if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) {
850 Selection = getSelectionForCOFF(GV);
851 const GlobalValue *ComdatGV;
852 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
853 ComdatGV = getComdatGVForCOFF(GV);
857 if (!ComdatGV->hasPrivateLinkage()) {
858 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
859 COMDATSymName = Sym->getName();
860 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
865 return getContext().getCOFFSection(Name,
872 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
877 if (Kind.isThreadLocal())
879 if (Kind.isWriteable())
885 const MCSection *TargetLoweringObjectFileCOFF::
886 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
887 Mangler &Mang, const TargetMachine &TM) const {
888 // If we have -ffunction-sections then we should emit the global value to a
889 // uniqued section specifically for it.
890 bool EmitUniquedSection;
892 EmitUniquedSection = TM.getFunctionSections();
894 EmitUniquedSection = TM.getDataSections();
896 // If this global is linkonce/weak and the target handles this by emitting it
897 // into a 'uniqued' section name, create and return the section now.
898 // Section names depend on the name of the symbol which is not feasible if the
899 // symbol has private linkage.
900 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
902 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
903 unsigned Characteristics = getCOFFSectionFlags(Kind);
905 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
906 int Selection = getSelectionForCOFF(GV);
908 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
909 const GlobalValue *ComdatGV;
911 ComdatGV = getComdatGVForCOFF(GV);
915 if (!ComdatGV->hasPrivateLinkage()) {
916 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
917 StringRef COMDATSymName = Sym->getName();
918 return getContext().getCOFFSection(Name, Characteristics, Kind,
919 COMDATSymName, Selection);
926 if (Kind.isThreadLocal())
927 return TLSDataSection;
929 if (Kind.isReadOnly())
930 return ReadOnlySection;
932 // Note: we claim that common symbols are put in BSSSection, but they are
933 // really emitted with the magic .comm directive, which creates a symbol table
934 // entry but not a section.
935 if (Kind.isBSS() || Kind.isCommon())
941 StringRef TargetLoweringObjectFileCOFF::
942 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
943 const char *LibCmd = "/DEFAULTLIB:";
944 if (LinkerOption.startswith(LibCmd))
945 return LinkerOption.substr(strlen(LibCmd));
949 void TargetLoweringObjectFileCOFF::
950 emitModuleFlags(MCStreamer &Streamer,
951 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
952 Mangler &Mang, const TargetMachine &TM) const {
953 MDNode *LinkerOptions = nullptr;
955 // Look for the "Linker Options" flag, since it's the only one we support.
956 for (ArrayRef<Module::ModuleFlagEntry>::iterator
957 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
958 const Module::ModuleFlagEntry &MFE = *i;
959 StringRef Key = MFE.Key->getString();
960 Value *Val = MFE.Val;
961 if (Key == "Linker Options") {
962 LinkerOptions = cast<MDNode>(Val);
969 // Emit the linker options to the linker .drectve section. According to the
970 // spec, this section is a space-separated string containing flags for linker.
971 const MCSection *Sec = getDrectveSection();
972 Streamer.SwitchSection(Sec);
973 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
974 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
975 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
976 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
977 StringRef Op = MDOption->getString();
978 // Lead with a space for consistency with our dllexport implementation.
979 std::string Escaped(" ");
980 if (Op.find(" ") != StringRef::npos) {
981 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
982 // how to escape quotes, but it probably uses this algorithm:
983 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
984 // FIXME: Reuse escaping code from Support/Windows/Program.inc
985 Escaped.push_back('\"');
987 Escaped.push_back('\"');
991 Streamer.EmitBytes(Escaped);
996 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
997 unsigned Priority, const MCSymbol *KeySym) const {
998 return getContext().getAssociativeCOFFSection(
999 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
1002 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1003 unsigned Priority, const MCSymbol *KeySym) const {
1004 return getContext().getAssociativeCOFFSection(
1005 cast<MCSectionCOFF>(StaticDtorSection), KeySym);