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/Dwarf.h"
35 #include "llvm/Support/ELF.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
42 using namespace dwarf;
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
49 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
50 MachineModuleInfo *MMI) const {
51 unsigned Encoding = getPersonalityEncoding();
52 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
53 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
54 TM.getSymbol(GV, Mang)->getName());
55 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
56 return TM.getSymbol(GV, Mang);
57 report_fatal_error("We do not support this DWARF encoding yet!");
60 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
61 const TargetMachine &TM,
62 const MCSymbol *Sym) const {
63 SmallString<64> NameData("DW.ref.");
64 NameData += Sym->getName();
65 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
66 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
67 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
68 StringRef Prefix = ".data.";
69 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
70 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
71 const MCSection *Sec = getContext().getELFSection(NameData,
75 unsigned Size = TM.getDataLayout()->getPointerSize();
76 Streamer.SwitchSection(Sec);
77 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
78 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
79 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
80 Streamer.EmitELFSize(Label, E);
81 Streamer.EmitLabel(Label);
83 Streamer.EmitSymbolValue(Sym, Size);
86 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
87 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
88 const TargetMachine &TM, MachineModuleInfo *MMI,
89 MCStreamer &Streamer) const {
91 if (Encoding & dwarf::DW_EH_PE_indirect) {
92 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
94 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
96 // Add information about the stub reference to ELFMMI so that the stub
97 // gets emitted by the asmprinter.
98 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
99 if (!StubSym.getPointer()) {
100 MCSymbol *Sym = TM.getSymbol(GV, Mang);
101 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
104 return TargetLoweringObjectFile::
105 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
106 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
109 return TargetLoweringObjectFile::
110 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
114 getELFKindForNamedSection(StringRef Name, SectionKind K) {
115 // N.B.: The defaults used in here are no the same ones used in MC.
116 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
117 // both gas and MC will produce a section with no flags. Given
118 // section(".eh_frame") gcc will produce:
120 // .section .eh_frame,"a",@progbits
121 if (Name.empty() || Name[0] != '.') return K;
123 // Some lame default implementation based on some magic section names.
124 if (Name == ".bss" ||
125 Name.startswith(".bss.") ||
126 Name.startswith(".gnu.linkonce.b.") ||
127 Name.startswith(".llvm.linkonce.b.") ||
129 Name.startswith(".sbss.") ||
130 Name.startswith(".gnu.linkonce.sb.") ||
131 Name.startswith(".llvm.linkonce.sb."))
132 return SectionKind::getBSS();
134 if (Name == ".tdata" ||
135 Name.startswith(".tdata.") ||
136 Name.startswith(".gnu.linkonce.td.") ||
137 Name.startswith(".llvm.linkonce.td."))
138 return SectionKind::getThreadData();
140 if (Name == ".tbss" ||
141 Name.startswith(".tbss.") ||
142 Name.startswith(".gnu.linkonce.tb.") ||
143 Name.startswith(".llvm.linkonce.tb."))
144 return SectionKind::getThreadBSS();
150 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
152 if (Name == ".init_array")
153 return ELF::SHT_INIT_ARRAY;
155 if (Name == ".fini_array")
156 return ELF::SHT_FINI_ARRAY;
158 if (Name == ".preinit_array")
159 return ELF::SHT_PREINIT_ARRAY;
161 if (K.isBSS() || K.isThreadBSS())
162 return ELF::SHT_NOBITS;
164 return ELF::SHT_PROGBITS;
169 getELFSectionFlags(SectionKind K, bool InCOMDAT) {
173 Flags |= ELF::SHF_ALLOC;
176 Flags |= ELF::SHF_EXECINSTR;
179 Flags |= ELF::SHF_WRITE;
181 if (K.isThreadLocal())
182 Flags |= ELF::SHF_TLS;
184 // FIXME: There is nothing in ELF preventing an SHF_MERGE from being
185 // in a comdat. We just avoid it for now because we don't print
186 // those .sections correctly.
187 if (!InCOMDAT && (K.isMergeableCString() || K.isMergeableConst()))
188 Flags |= ELF::SHF_MERGE;
190 if (K.isMergeableCString())
191 Flags |= ELF::SHF_STRINGS;
196 static const Comdat *getELFComdat(const GlobalValue *GV) {
197 const Comdat *C = GV->getComdat();
201 if (C->getSelectionKind() != Comdat::Any)
202 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
203 C->getName() + "' cannot be lowered.");
208 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
209 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
210 const TargetMachine &TM) const {
211 StringRef SectionName = GV->getSection();
213 // Infer section flags from the section name if we can.
214 Kind = getELFKindForNamedSection(SectionName, Kind);
216 StringRef Group = "";
217 unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
218 if (const Comdat *C = getELFComdat(GV)) {
219 Group = C->getName();
220 Flags |= ELF::SHF_GROUP;
222 return getContext().getELFSection(SectionName,
223 getELFSectionType(SectionName, Kind), Flags,
224 /*EntrySize=*/0, Group);
227 /// Return the section prefix name used by options FunctionsSections and
229 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
232 if (Kind.isReadOnly())
236 if (Kind.isThreadData())
238 if (Kind.isThreadBSS())
240 if (Kind.isDataNoRel())
242 if (Kind.isDataRelLocal())
243 return ".data.rel.local.";
244 if (Kind.isDataRel())
246 if (Kind.isReadOnlyWithRelLocal())
247 return ".data.rel.ro.local.";
248 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
249 return ".data.rel.ro.";
252 const MCSection *TargetLoweringObjectFileELF::
253 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
254 Mangler &Mang, const TargetMachine &TM) const {
255 unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
257 // If we have -ffunction-section or -fdata-section then we should emit the
258 // global value to a uniqued section specifically for it.
259 bool EmitUniquedSection = false;
260 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
262 EmitUniquedSection = TM.getFunctionSections();
264 EmitUniquedSection = TM.getDataSections();
267 if (EmitUniquedSection || GV->hasComdat()) {
268 StringRef Prefix = getSectionPrefixForGlobal(Kind);
270 SmallString<128> Name(Prefix);
271 TM.getNameWithPrefix(Name, GV, Mang, true);
273 StringRef Group = "";
274 if (const Comdat *C = getELFComdat(GV)) {
275 Flags |= ELF::SHF_GROUP;
276 Group = C->getName();
279 return getContext().getELFSection(
280 Name.str(), getELFSectionType(Name.str(), Kind), Flags, 0, Group);
283 if (Kind.isText()) return TextSection;
285 if (Kind.isMergeableCString()) {
287 // We also need alignment here.
288 // FIXME: this is getting the alignment of the character, not the
289 // alignment of the global!
291 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
293 unsigned EntrySize = 1;
294 if (Kind.isMergeable2ByteCString())
296 else if (Kind.isMergeable4ByteCString())
299 assert(Kind.isMergeable1ByteCString() && "unknown string width");
301 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
302 std::string Name = SizeSpec + utostr(Align);
303 return getContext().getELFSection(
304 Name, ELF::SHT_PROGBITS,
305 ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize, "");
308 if (Kind.isMergeableConst()) {
309 if (Kind.isMergeableConst4() && MergeableConst4Section)
310 return MergeableConst4Section;
311 if (Kind.isMergeableConst8() && MergeableConst8Section)
312 return MergeableConst8Section;
313 if (Kind.isMergeableConst16() && MergeableConst16Section)
314 return MergeableConst16Section;
315 return ReadOnlySection; // .const
318 if (Kind.isReadOnly()) return ReadOnlySection;
320 if (Kind.isThreadData()) return TLSDataSection;
321 if (Kind.isThreadBSS()) return TLSBSSSection;
323 // Note: we claim that common symbols are put in BSSSection, but they are
324 // really emitted with the magic .comm directive, which creates a symbol table
325 // entry but not a section.
326 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
328 if (Kind.isDataNoRel()) return DataSection;
329 if (Kind.isDataRelLocal()) return DataRelLocalSection;
330 if (Kind.isDataRel()) return DataRelSection;
331 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
333 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
334 return DataRelROSection;
337 const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
338 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
339 // If the function can be removed, produce a unique section so that
340 // the table doesn't prevent the removal.
341 const Comdat *C = F.getComdat();
342 bool EmitUniqueSection = TM.getFunctionSections() || C;
343 if (!EmitUniqueSection)
344 return ReadOnlySection;
346 SmallString<128> Name(".rodata.");
347 TM.getNameWithPrefix(Name, &F, Mang, true);
349 unsigned Flags = ELF::SHF_ALLOC;
350 StringRef Group = "";
352 Flags |= ELF::SHF_GROUP;
353 Group = C->getName();
356 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags, 0, Group);
359 /// getSectionForConstant - Given a mergeable constant with the
360 /// specified size and relocation information, return a section that it
361 /// should be placed in.
363 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
364 const Constant *C) const {
365 if (Kind.isMergeableConst4() && MergeableConst4Section)
366 return MergeableConst4Section;
367 if (Kind.isMergeableConst8() && MergeableConst8Section)
368 return MergeableConst8Section;
369 if (Kind.isMergeableConst16() && MergeableConst16Section)
370 return MergeableConst16Section;
371 if (Kind.isReadOnly())
372 return ReadOnlySection;
374 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
375 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
376 return DataRelROSection;
379 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
383 const MCSymbol *KeySym) {
386 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
387 StringRef COMDAT = KeySym ? KeySym->getName() : "";
390 Flags |= ELF::SHF_GROUP;
394 Type = ELF::SHT_INIT_ARRAY;
395 Name = ".init_array";
397 Type = ELF::SHT_FINI_ARRAY;
398 Name = ".fini_array";
400 if (Priority != 65535) {
402 Name += utostr(Priority);
405 // The default scheme is .ctor / .dtor, so we have to invert the priority
411 if (Priority != 65535) {
413 Name += utostr(65535 - Priority);
415 Type = ELF::SHT_PROGBITS;
418 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
421 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
422 unsigned Priority, const MCSymbol *KeySym) const {
423 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
427 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
428 unsigned Priority, const MCSymbol *KeySym) const {
429 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
434 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
435 UseInitArray = UseInitArray_;
439 StaticCtorSection = getContext().getELFSection(
440 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
441 StaticDtorSection = getContext().getELFSection(
442 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
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 Metadata *Val = MFE.Val;
480 if (Key == "Objective-C Image Info Version") {
481 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
482 } else if (Key == "Objective-C Garbage Collection" ||
483 Key == "Objective-C GC Only" ||
484 Key == "Objective-C Is Simulated" ||
485 Key == "Objective-C Image Swift Version") {
486 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
487 } else if (Key == "Objective-C Image Info Section") {
488 SectionVal = cast<MDString>(Val)->getString();
489 } else if (Key == "Linker Options") {
490 LinkerOptions = cast<MDNode>(Val);
494 // Emit the linker options if present.
496 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
497 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
498 SmallVector<std::string, 4> StrOptions;
500 // Convert to strings.
501 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
502 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
503 StrOptions.push_back(MDOption->getString());
506 Streamer.EmitLinkerOptions(StrOptions);
510 // The section is mandatory. If we don't have it, then we don't have GC info.
511 if (SectionVal.empty()) return;
513 StringRef Segment, Section;
514 unsigned TAA = 0, StubSize = 0;
516 std::string ErrorCode =
517 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
518 TAA, TAAParsed, StubSize);
519 if (!ErrorCode.empty())
520 // If invalid, report the error with report_fatal_error.
521 report_fatal_error("Invalid section specifier '" + Section + "': " +
525 const MCSectionMachO *S =
526 getContext().getMachOSection(Segment, Section, TAA, StubSize,
527 SectionKind::getDataNoRel());
528 Streamer.SwitchSection(S);
529 Streamer.EmitLabel(getContext().
530 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
531 Streamer.EmitIntValue(VersionVal, 4);
532 Streamer.EmitIntValue(ImageInfoFlags, 4);
533 Streamer.AddBlankLine();
536 static void checkMachOComdat(const GlobalValue *GV) {
537 const Comdat *C = GV->getComdat();
541 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
542 "' cannot be lowered.");
545 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
546 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
547 const TargetMachine &TM) const {
548 // Parse the section specifier and create it if valid.
549 StringRef Segment, Section;
550 unsigned TAA = 0, StubSize = 0;
553 checkMachOComdat(GV);
555 std::string ErrorCode =
556 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
557 TAA, TAAParsed, StubSize);
558 if (!ErrorCode.empty()) {
559 // If invalid, report the error with report_fatal_error.
560 report_fatal_error("Global variable '" + GV->getName() +
561 "' has an invalid section specifier '" +
562 GV->getSection() + "': " + ErrorCode + ".");
566 const MCSectionMachO *S =
567 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
569 // If TAA wasn't set by ParseSectionSpecifier() above,
570 // use the value returned by getMachOSection() as a default.
572 TAA = S->getTypeAndAttributes();
574 // Okay, now that we got the section, verify that the TAA & StubSize agree.
575 // If the user declared multiple globals with different section flags, we need
576 // to reject it here.
577 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
578 // If invalid, report the error with report_fatal_error.
579 report_fatal_error("Global variable '" + GV->getName() +
580 "' section type or attributes does not match previous"
581 " section specifier");
587 const MCSection *TargetLoweringObjectFileMachO::
588 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
589 Mangler &Mang, const TargetMachine &TM) const {
590 checkMachOComdat(GV);
592 // Handle thread local data.
593 if (Kind.isThreadBSS()) return TLSBSSSection;
594 if (Kind.isThreadData()) return TLSDataSection;
597 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
599 // If this is weak/linkonce, put this in a coalescable section, either in text
600 // or data depending on if it is writable.
601 if (GV->isWeakForLinker()) {
602 if (Kind.isReadOnly())
603 return ConstTextCoalSection;
604 return DataCoalSection;
607 // FIXME: Alignment check should be handled by section classifier.
608 if (Kind.isMergeable1ByteCString() &&
609 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
610 return CStringSection;
612 // Do not put 16-bit arrays in the UString section if they have an
613 // externally visible label, this runs into issues with certain linker
615 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
616 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
617 return UStringSection;
619 // With MachO only variables whose corresponding symbol starts with 'l' or
620 // 'L' can be merged, so we only try merging GVs with private linkage.
621 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
622 if (Kind.isMergeableConst4())
623 return FourByteConstantSection;
624 if (Kind.isMergeableConst8())
625 return EightByteConstantSection;
626 if (Kind.isMergeableConst16())
627 return SixteenByteConstantSection;
630 // Otherwise, if it is readonly, but not something we can specially optimize,
631 // just drop it in .const.
632 if (Kind.isReadOnly())
633 return ReadOnlySection;
635 // If this is marked const, put it into a const section. But if the dynamic
636 // linker needs to write to it, put it in the data segment.
637 if (Kind.isReadOnlyWithRel())
638 return ConstDataSection;
640 // Put zero initialized globals with strong external linkage in the
641 // DATA, __common section with the .zerofill directive.
642 if (Kind.isBSSExtern())
643 return DataCommonSection;
645 // Put zero initialized globals with local linkage in __DATA,__bss directive
646 // with the .zerofill directive (aka .lcomm).
647 if (Kind.isBSSLocal())
648 return DataBSSSection;
650 // Otherwise, just drop the variable in the normal data section.
655 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
656 const Constant *C) const {
657 // If this constant requires a relocation, we have to put it in the data
658 // segment, not in the text segment.
659 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
660 return ConstDataSection;
662 if (Kind.isMergeableConst4())
663 return FourByteConstantSection;
664 if (Kind.isMergeableConst8())
665 return EightByteConstantSection;
666 if (Kind.isMergeableConst16())
667 return SixteenByteConstantSection;
668 return ReadOnlySection; // .const
671 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
672 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
673 const TargetMachine &TM, MachineModuleInfo *MMI,
674 MCStreamer &Streamer) const {
675 // The mach-o version of this method defaults to returning a stub reference.
677 if (Encoding & DW_EH_PE_indirect) {
678 MachineModuleInfoMachO &MachOMMI =
679 MMI->getObjFileInfo<MachineModuleInfoMachO>();
682 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
684 // Add information about the stub reference to MachOMMI so that the stub
685 // gets emitted by the asmprinter.
686 MachineModuleInfoImpl::StubValueTy &StubSym =
687 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
688 MachOMMI.getGVStubEntry(SSym);
689 if (!StubSym.getPointer()) {
690 MCSymbol *Sym = TM.getSymbol(GV, Mang);
691 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
694 return TargetLoweringObjectFile::
695 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
696 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
699 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
703 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
704 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
705 MachineModuleInfo *MMI) const {
706 // The mach-o version of this method defaults to returning a stub reference.
707 MachineModuleInfoMachO &MachOMMI =
708 MMI->getObjFileInfo<MachineModuleInfoMachO>();
710 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
712 // Add information about the stub reference to MachOMMI so that the stub
713 // gets emitted by the asmprinter.
714 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
715 if (!StubSym.getPointer()) {
716 MCSymbol *Sym = TM.getSymbol(GV, Mang);
717 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
723 //===----------------------------------------------------------------------===//
725 //===----------------------------------------------------------------------===//
728 getCOFFSectionFlags(SectionKind K) {
733 COFF::IMAGE_SCN_MEM_DISCARDABLE;
736 COFF::IMAGE_SCN_MEM_EXECUTE |
737 COFF::IMAGE_SCN_MEM_READ |
738 COFF::IMAGE_SCN_CNT_CODE;
741 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
742 COFF::IMAGE_SCN_MEM_READ |
743 COFF::IMAGE_SCN_MEM_WRITE;
744 else if (K.isThreadLocal())
746 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
747 COFF::IMAGE_SCN_MEM_READ |
748 COFF::IMAGE_SCN_MEM_WRITE;
749 else if (K.isReadOnly() || K.isReadOnlyWithRel())
751 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
752 COFF::IMAGE_SCN_MEM_READ;
753 else if (K.isWriteable())
755 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
756 COFF::IMAGE_SCN_MEM_READ |
757 COFF::IMAGE_SCN_MEM_WRITE;
762 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
763 const Comdat *C = GV->getComdat();
764 assert(C && "expected GV to have a Comdat!");
766 StringRef ComdatGVName = C->getName();
767 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
769 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
770 "' does not exist.");
772 if (ComdatGV->getComdat() != C)
773 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
774 "' is not a key for its COMDAT.");
779 static int getSelectionForCOFF(const GlobalValue *GV) {
780 if (const Comdat *C = GV->getComdat()) {
781 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
782 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
783 ComdatKey = GA->getBaseObject();
784 if (ComdatKey == GV) {
785 switch (C->getSelectionKind()) {
787 return COFF::IMAGE_COMDAT_SELECT_ANY;
788 case Comdat::ExactMatch:
789 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
790 case Comdat::Largest:
791 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
792 case Comdat::NoDuplicates:
793 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
794 case Comdat::SameSize:
795 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
798 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
800 } else if (GV->isWeakForLinker()) {
801 return COFF::IMAGE_COMDAT_SELECT_ANY;
806 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
807 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
808 const TargetMachine &TM) const {
810 unsigned Characteristics = getCOFFSectionFlags(Kind);
811 StringRef Name = GV->getSection();
812 StringRef COMDATSymName = "";
813 if (GV->hasComdat()) {
814 Selection = getSelectionForCOFF(GV);
815 const GlobalValue *ComdatGV;
816 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
817 ComdatGV = getComdatGVForCOFF(GV);
821 if (!ComdatGV->hasPrivateLinkage()) {
822 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
823 COMDATSymName = Sym->getName();
824 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
829 return getContext().getCOFFSection(Name,
836 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
841 if (Kind.isThreadLocal())
843 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
849 const MCSection *TargetLoweringObjectFileCOFF::
850 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
851 Mangler &Mang, const TargetMachine &TM) const {
852 // If we have -ffunction-sections then we should emit the global value to a
853 // uniqued section specifically for it.
854 bool EmitUniquedSection;
856 EmitUniquedSection = TM.getFunctionSections();
858 EmitUniquedSection = TM.getDataSections();
860 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
861 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
862 unsigned Characteristics = getCOFFSectionFlags(Kind);
864 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
865 int Selection = getSelectionForCOFF(GV);
867 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
868 const GlobalValue *ComdatGV;
870 ComdatGV = getComdatGVForCOFF(GV);
874 if (!ComdatGV->hasPrivateLinkage()) {
875 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
876 StringRef COMDATSymName = Sym->getName();
877 return getContext().getCOFFSection(Name, Characteristics, Kind,
878 COMDATSymName, Selection);
885 if (Kind.isThreadLocal())
886 return TLSDataSection;
888 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
889 return ReadOnlySection;
891 // Note: we claim that common symbols are put in BSSSection, but they are
892 // really emitted with the magic .comm directive, which creates a symbol table
893 // entry but not a section.
894 if (Kind.isBSS() || Kind.isCommon())
900 StringRef TargetLoweringObjectFileCOFF::
901 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
902 const char *LibCmd = "/DEFAULTLIB:";
903 if (LinkerOption.startswith(LibCmd))
904 return LinkerOption.substr(strlen(LibCmd));
908 void TargetLoweringObjectFileCOFF::
909 emitModuleFlags(MCStreamer &Streamer,
910 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
911 Mangler &Mang, const TargetMachine &TM) const {
912 MDNode *LinkerOptions = nullptr;
914 // Look for the "Linker Options" flag, since it's the only one we support.
915 for (ArrayRef<Module::ModuleFlagEntry>::iterator
916 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
917 const Module::ModuleFlagEntry &MFE = *i;
918 StringRef Key = MFE.Key->getString();
919 Metadata *Val = MFE.Val;
920 if (Key == "Linker Options") {
921 LinkerOptions = cast<MDNode>(Val);
928 // Emit the linker options to the linker .drectve section. According to the
929 // spec, this section is a space-separated string containing flags for linker.
930 const MCSection *Sec = getDrectveSection();
931 Streamer.SwitchSection(Sec);
932 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
933 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
934 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
935 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
936 // Lead with a space for consistency with our dllexport implementation.
937 std::string Directive(" ");
938 Directive.append(MDOption->getString());
939 Streamer.EmitBytes(Directive);
944 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
945 unsigned Priority, const MCSymbol *KeySym) const {
946 return getContext().getAssociativeCOFFSection(
947 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
950 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
951 unsigned Priority, const MCSymbol *KeySym) const {
952 return getContext().getAssociativeCOFFSection(
953 cast<MCSectionCOFF>(StaticDtorSection), KeySym);