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/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCSectionCOFF.h"
31 #include "llvm/MC/MCSectionELF.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbolELF.h"
35 #include "llvm/MC/MCValue.h"
36 #include "llvm/Support/COFF.h"
37 #include "llvm/Support/Dwarf.h"
38 #include "llvm/Support/ELF.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/raw_ostream.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Target/TargetSubtargetInfo.h"
45 using namespace dwarf;
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
52 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
53 MachineModuleInfo *MMI) const {
54 unsigned Encoding = getPersonalityEncoding();
55 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
56 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
57 TM.getSymbol(GV, Mang)->getName());
58 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
59 return TM.getSymbol(GV, Mang);
60 report_fatal_error("We do not support this DWARF encoding yet!");
63 void TargetLoweringObjectFileELF::emitPersonalityValue(
64 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
65 SmallString<64> NameData("DW.ref.");
66 NameData += Sym->getName();
68 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
69 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
70 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
71 StringRef Prefix = ".data.";
72 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
73 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
74 MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
75 Flags, 0, Label->getName());
76 unsigned Size = DL.getPointerSize();
77 Streamer.SwitchSection(Sec);
78 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
79 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
80 const MCExpr *E = MCConstantExpr::create(Size, getContext());
81 Streamer.emitELFSize(Label, E);
82 Streamer.EmitLabel(Label);
84 Streamer.EmitSymbolValue(Sym, Size);
87 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
88 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
89 const TargetMachine &TM, MachineModuleInfo *MMI,
90 MCStreamer &Streamer) const {
92 if (Encoding & dwarf::DW_EH_PE_indirect) {
93 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
95 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
97 // Add information about the stub reference to ELFMMI so that the stub
98 // gets emitted by the asmprinter.
99 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
100 if (!StubSym.getPointer()) {
101 MCSymbol *Sym = TM.getSymbol(GV, Mang);
102 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
105 return TargetLoweringObjectFile::
106 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
107 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
110 return TargetLoweringObjectFile::
111 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
115 getELFKindForNamedSection(StringRef Name, SectionKind K) {
116 // N.B.: The defaults used in here are no the same ones used in MC.
117 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
118 // both gas and MC will produce a section with no flags. Given
119 // section(".eh_frame") gcc will produce:
121 // .section .eh_frame,"a",@progbits
122 if (Name.empty() || Name[0] != '.') return K;
124 // Some lame default implementation based on some magic section names.
125 if (Name == ".bss" ||
126 Name.startswith(".bss.") ||
127 Name.startswith(".gnu.linkonce.b.") ||
128 Name.startswith(".llvm.linkonce.b.") ||
130 Name.startswith(".sbss.") ||
131 Name.startswith(".gnu.linkonce.sb.") ||
132 Name.startswith(".llvm.linkonce.sb."))
133 return SectionKind::getBSS();
135 if (Name == ".tdata" ||
136 Name.startswith(".tdata.") ||
137 Name.startswith(".gnu.linkonce.td.") ||
138 Name.startswith(".llvm.linkonce.td."))
139 return SectionKind::getThreadData();
141 if (Name == ".tbss" ||
142 Name.startswith(".tbss.") ||
143 Name.startswith(".gnu.linkonce.tb.") ||
144 Name.startswith(".llvm.linkonce.tb."))
145 return SectionKind::getThreadBSS();
151 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
153 if (Name == ".init_array")
154 return ELF::SHT_INIT_ARRAY;
156 if (Name == ".fini_array")
157 return ELF::SHT_FINI_ARRAY;
159 if (Name == ".preinit_array")
160 return ELF::SHT_PREINIT_ARRAY;
162 if (K.isBSS() || K.isThreadBSS())
163 return ELF::SHT_NOBITS;
165 return ELF::SHT_PROGBITS;
168 static unsigned getELFSectionFlags(SectionKind K) {
172 Flags |= ELF::SHF_ALLOC;
175 Flags |= ELF::SHF_EXECINSTR;
178 Flags |= ELF::SHF_WRITE;
180 if (K.isThreadLocal())
181 Flags |= ELF::SHF_TLS;
183 if (K.isMergeableCString() || K.isMergeableConst())
184 Flags |= ELF::SHF_MERGE;
186 if (K.isMergeableCString())
187 Flags |= ELF::SHF_STRINGS;
192 static const Comdat *getELFComdat(const GlobalValue *GV) {
193 const Comdat *C = GV->getComdat();
197 if (C->getSelectionKind() != Comdat::Any)
198 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
199 C->getName() + "' cannot be lowered.");
204 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
205 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
206 const TargetMachine &TM) const {
207 StringRef SectionName = GV->getSection();
209 // Infer section flags from the section name if we can.
210 Kind = getELFKindForNamedSection(SectionName, Kind);
212 StringRef Group = "";
213 unsigned Flags = getELFSectionFlags(Kind);
214 if (const Comdat *C = getELFComdat(GV)) {
215 Group = C->getName();
216 Flags |= ELF::SHF_GROUP;
218 return getContext().getELFSection(SectionName,
219 getELFSectionType(SectionName, Kind), Flags,
220 /*EntrySize=*/0, Group);
223 /// Return the section prefix name used by options FunctionsSections and
225 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
228 if (Kind.isReadOnly())
232 if (Kind.isThreadData())
234 if (Kind.isThreadBSS())
236 if (Kind.isDataNoRel())
238 if (Kind.isDataRel())
240 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
241 return ".data.rel.ro";
244 static MCSectionELF *
245 selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
246 SectionKind Kind, Mangler &Mang,
247 const TargetMachine &TM, bool EmitUniqueSection,
248 unsigned Flags, unsigned *NextUniqueID) {
249 unsigned EntrySize = 0;
250 if (Kind.isMergeableCString()) {
251 if (Kind.isMergeable2ByteCString()) {
253 } else if (Kind.isMergeable4ByteCString()) {
257 assert(Kind.isMergeable1ByteCString() && "unknown string width");
259 } else if (Kind.isMergeableConst()) {
260 if (Kind.isMergeableConst4()) {
262 } else if (Kind.isMergeableConst8()) {
265 assert(Kind.isMergeableConst16() && "unknown data width");
270 StringRef Group = "";
271 if (const Comdat *C = getELFComdat(GV)) {
272 Flags |= ELF::SHF_GROUP;
273 Group = C->getName();
276 bool UniqueSectionNames = TM.getUniqueSectionNames();
277 SmallString<128> Name;
278 if (Kind.isMergeableCString()) {
279 // We also need alignment here.
280 // FIXME: this is getting the alignment of the character, not the
281 // alignment of the global!
282 unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
283 cast<GlobalVariable>(GV));
285 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
286 Name = SizeSpec + utostr(Align);
287 } else if (Kind.isMergeableConst()) {
288 Name = ".rodata.cst";
289 Name += utostr(EntrySize);
291 Name = getSectionPrefixForGlobal(Kind);
294 if (EmitUniqueSection && UniqueSectionNames) {
296 TM.getNameWithPrefix(Name, GV, Mang, true);
298 unsigned UniqueID = ~0;
299 if (EmitUniqueSection && !UniqueSectionNames) {
300 UniqueID = *NextUniqueID;
303 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
304 EntrySize, Group, UniqueID);
307 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
308 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
309 const TargetMachine &TM) const {
310 unsigned Flags = getELFSectionFlags(Kind);
312 // If we have -ffunction-section or -fdata-section then we should emit the
313 // global value to a uniqued section specifically for it.
314 bool EmitUniqueSection = false;
315 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
317 EmitUniqueSection = TM.getFunctionSections();
319 EmitUniqueSection = TM.getDataSections();
321 EmitUniqueSection |= GV->hasComdat();
323 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
324 EmitUniqueSection, Flags, &NextUniqueID);
327 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
328 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
329 // If the function can be removed, produce a unique section so that
330 // the table doesn't prevent the removal.
331 const Comdat *C = F.getComdat();
332 bool EmitUniqueSection = TM.getFunctionSections() || C;
333 if (!EmitUniqueSection)
334 return ReadOnlySection;
336 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
337 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
341 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
342 bool UsesLabelDifference, const Function &F) const {
343 // We can always create relative relocations, so use another section
344 // that can be marked non-executable.
348 /// Given a mergeable constant with the specified size and relocation
349 /// information, return a section that it should be placed in.
350 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
351 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
352 if (Kind.isMergeableConst4() && MergeableConst4Section)
353 return MergeableConst4Section;
354 if (Kind.isMergeableConst8() && MergeableConst8Section)
355 return MergeableConst8Section;
356 if (Kind.isMergeableConst16() && MergeableConst16Section)
357 return MergeableConst16Section;
358 if (Kind.isReadOnly())
359 return ReadOnlySection;
361 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
362 return DataRelROSection;
365 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
366 bool IsCtor, unsigned Priority,
367 const MCSymbol *KeySym) {
370 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
371 StringRef COMDAT = KeySym ? KeySym->getName() : "";
374 Flags |= ELF::SHF_GROUP;
378 Type = ELF::SHT_INIT_ARRAY;
379 Name = ".init_array";
381 Type = ELF::SHT_FINI_ARRAY;
382 Name = ".fini_array";
384 if (Priority != 65535) {
386 Name += utostr(Priority);
389 // The default scheme is .ctor / .dtor, so we have to invert the priority
395 if (Priority != 65535) {
397 Name += utostr(65535 - Priority);
399 Type = ELF::SHT_PROGBITS;
402 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
405 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
406 unsigned Priority, const MCSymbol *KeySym) const {
407 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
411 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
412 unsigned Priority, const MCSymbol *KeySym) const {
413 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
418 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
419 UseInitArray = UseInitArray_;
423 StaticCtorSection = getContext().getELFSection(
424 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
425 StaticDtorSection = getContext().getELFSection(
426 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
429 //===----------------------------------------------------------------------===//
431 //===----------------------------------------------------------------------===//
433 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
434 : TargetLoweringObjectFile() {
435 SupportIndirectSymViaGOTPCRel = true;
438 /// emitModuleFlags - Perform code emission for module flags.
439 void TargetLoweringObjectFileMachO::
440 emitModuleFlags(MCStreamer &Streamer,
441 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
442 Mangler &Mang, const TargetMachine &TM) const {
443 unsigned VersionVal = 0;
444 unsigned ImageInfoFlags = 0;
445 MDNode *LinkerOptions = nullptr;
446 StringRef SectionVal;
448 for (ArrayRef<Module::ModuleFlagEntry>::iterator
449 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
450 const Module::ModuleFlagEntry &MFE = *i;
452 // Ignore flags with 'Require' behavior.
453 if (MFE.Behavior == Module::Require)
456 StringRef Key = MFE.Key->getString();
457 Metadata *Val = MFE.Val;
459 if (Key == "Objective-C Image Info Version") {
460 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
461 } else if (Key == "Objective-C Garbage Collection" ||
462 Key == "Objective-C GC Only" ||
463 Key == "Objective-C Is Simulated" ||
464 Key == "Objective-C Image Swift Version") {
465 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
466 } else if (Key == "Objective-C Image Info Section") {
467 SectionVal = cast<MDString>(Val)->getString();
468 } else if (Key == "Linker Options") {
469 LinkerOptions = cast<MDNode>(Val);
473 // Emit the linker options if present.
475 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
476 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
477 SmallVector<std::string, 4> StrOptions;
479 // Convert to strings.
480 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
481 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
482 StrOptions.push_back(MDOption->getString());
485 Streamer.EmitLinkerOptions(StrOptions);
489 // The section is mandatory. If we don't have it, then we don't have GC info.
490 if (SectionVal.empty()) return;
492 StringRef Segment, Section;
493 unsigned TAA = 0, StubSize = 0;
495 std::string ErrorCode =
496 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
497 TAA, TAAParsed, StubSize);
498 if (!ErrorCode.empty())
499 // If invalid, report the error with report_fatal_error.
500 report_fatal_error("Invalid section specifier '" + Section + "': " +
504 MCSectionMachO *S = getContext().getMachOSection(
505 Segment, Section, TAA, StubSize, SectionKind::getDataNoRel());
506 Streamer.SwitchSection(S);
507 Streamer.EmitLabel(getContext().
508 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
509 Streamer.EmitIntValue(VersionVal, 4);
510 Streamer.EmitIntValue(ImageInfoFlags, 4);
511 Streamer.AddBlankLine();
514 static void checkMachOComdat(const GlobalValue *GV) {
515 const Comdat *C = GV->getComdat();
519 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
520 "' cannot be lowered.");
523 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
524 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
525 const TargetMachine &TM) const {
526 // Parse the section specifier and create it if valid.
527 StringRef Segment, Section;
528 unsigned TAA = 0, StubSize = 0;
531 checkMachOComdat(GV);
533 std::string ErrorCode =
534 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
535 TAA, TAAParsed, StubSize);
536 if (!ErrorCode.empty()) {
537 // If invalid, report the error with report_fatal_error.
538 report_fatal_error("Global variable '" + GV->getName() +
539 "' has an invalid section specifier '" +
540 GV->getSection() + "': " + ErrorCode + ".");
545 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
547 // If TAA wasn't set by ParseSectionSpecifier() above,
548 // use the value returned by getMachOSection() as a default.
550 TAA = S->getTypeAndAttributes();
552 // Okay, now that we got the section, verify that the TAA & StubSize agree.
553 // If the user declared multiple globals with different section flags, we need
554 // to reject it here.
555 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
556 // If invalid, report the error with report_fatal_error.
557 report_fatal_error("Global variable '" + GV->getName() +
558 "' section type or attributes does not match previous"
559 " section specifier");
565 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
566 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
567 const TargetMachine &TM) const {
568 checkMachOComdat(GV);
570 // Handle thread local data.
571 if (Kind.isThreadBSS()) return TLSBSSSection;
572 if (Kind.isThreadData()) return TLSDataSection;
575 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
577 // If this is weak/linkonce, put this in a coalescable section, either in text
578 // or data depending on if it is writable.
579 if (GV->isWeakForLinker()) {
580 if (Kind.isReadOnly())
581 return ConstTextCoalSection;
582 return DataCoalSection;
585 // FIXME: Alignment check should be handled by section classifier.
586 if (Kind.isMergeable1ByteCString() &&
587 GV->getParent()->getDataLayout().getPreferredAlignment(
588 cast<GlobalVariable>(GV)) < 32)
589 return CStringSection;
591 // Do not put 16-bit arrays in the UString section if they have an
592 // externally visible label, this runs into issues with certain linker
594 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
595 GV->getParent()->getDataLayout().getPreferredAlignment(
596 cast<GlobalVariable>(GV)) < 32)
597 return UStringSection;
599 // With MachO only variables whose corresponding symbol starts with 'l' or
600 // 'L' can be merged, so we only try merging GVs with private linkage.
601 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
602 if (Kind.isMergeableConst4())
603 return FourByteConstantSection;
604 if (Kind.isMergeableConst8())
605 return EightByteConstantSection;
606 if (Kind.isMergeableConst16())
607 return SixteenByteConstantSection;
610 // Otherwise, if it is readonly, but not something we can specially optimize,
611 // just drop it in .const.
612 if (Kind.isReadOnly())
613 return ReadOnlySection;
615 // If this is marked const, put it into a const section. But if the dynamic
616 // linker needs to write to it, put it in the data segment.
617 if (Kind.isReadOnlyWithRel())
618 return ConstDataSection;
620 // Put zero initialized globals with strong external linkage in the
621 // DATA, __common section with the .zerofill directive.
622 if (Kind.isBSSExtern())
623 return DataCommonSection;
625 // Put zero initialized globals with local linkage in __DATA,__bss directive
626 // with the .zerofill directive (aka .lcomm).
627 if (Kind.isBSSLocal())
628 return DataBSSSection;
630 // Otherwise, just drop the variable in the normal data section.
634 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
635 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
636 // If this constant requires a relocation, we have to put it in the data
637 // segment, not in the text segment.
638 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
639 return ConstDataSection;
641 if (Kind.isMergeableConst4())
642 return FourByteConstantSection;
643 if (Kind.isMergeableConst8())
644 return EightByteConstantSection;
645 if (Kind.isMergeableConst16())
646 return SixteenByteConstantSection;
647 return ReadOnlySection; // .const
650 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
651 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
652 const TargetMachine &TM, MachineModuleInfo *MMI,
653 MCStreamer &Streamer) const {
654 // The mach-o version of this method defaults to returning a stub reference.
656 if (Encoding & DW_EH_PE_indirect) {
657 MachineModuleInfoMachO &MachOMMI =
658 MMI->getObjFileInfo<MachineModuleInfoMachO>();
661 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
663 // Add information about the stub reference to MachOMMI so that the stub
664 // gets emitted by the asmprinter.
665 MachineModuleInfoImpl::StubValueTy &StubSym =
666 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
667 MachOMMI.getGVStubEntry(SSym);
668 if (!StubSym.getPointer()) {
669 MCSymbol *Sym = TM.getSymbol(GV, Mang);
670 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
673 return TargetLoweringObjectFile::
674 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
675 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
678 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
682 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
683 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
684 MachineModuleInfo *MMI) const {
685 // The mach-o version of this method defaults to returning a stub reference.
686 MachineModuleInfoMachO &MachOMMI =
687 MMI->getObjFileInfo<MachineModuleInfoMachO>();
689 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
691 // Add information about the stub reference to MachOMMI so that the stub
692 // gets emitted by the asmprinter.
693 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
694 if (!StubSym.getPointer()) {
695 MCSymbol *Sym = TM.getSymbol(GV, Mang);
696 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
702 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
703 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
704 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
705 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
706 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
707 // through a non_lazy_ptr stub instead. One advantage is that it allows the
708 // computation of deltas to final external symbols. Example:
714 // .long _extgotequiv-_delta
716 // is transformed to:
719 // .long L_extfoo$non_lazy_ptr-(_delta+0)
721 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
722 // L_extfoo$non_lazy_ptr:
723 // .indirect_symbol _extfoo
726 MachineModuleInfoMachO &MachOMMI =
727 MMI->getObjFileInfo<MachineModuleInfoMachO>();
728 MCContext &Ctx = getContext();
730 // The offset must consider the original displacement from the base symbol
731 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
732 Offset = -MV.getConstant();
733 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
735 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
736 // non_lazy_ptr stubs.
737 SmallString<128> Name;
738 StringRef Suffix = "$non_lazy_ptr";
739 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
740 Name += Sym->getName();
742 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
744 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
745 if (!StubSym.getPointer())
746 StubSym = MachineModuleInfoImpl::
747 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
749 const MCExpr *BSymExpr =
750 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
752 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
755 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
758 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
759 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
762 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
763 const MCSection &Section) {
764 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
767 // If it is not dead stripped, it is safe to use private labels.
768 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
769 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
775 void TargetLoweringObjectFileMachO::getNameWithPrefix(
776 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
777 const TargetMachine &TM) const {
778 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
779 const MCSection *TheSection = SectionForGlobal(GV, GVKind, Mang, TM);
780 bool CannotUsePrivateLabel =
781 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
782 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
785 //===----------------------------------------------------------------------===//
787 //===----------------------------------------------------------------------===//
790 getCOFFSectionFlags(SectionKind K) {
795 COFF::IMAGE_SCN_MEM_DISCARDABLE;
798 COFF::IMAGE_SCN_MEM_EXECUTE |
799 COFF::IMAGE_SCN_MEM_READ |
800 COFF::IMAGE_SCN_CNT_CODE;
803 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
804 COFF::IMAGE_SCN_MEM_READ |
805 COFF::IMAGE_SCN_MEM_WRITE;
806 else if (K.isThreadLocal())
808 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
809 COFF::IMAGE_SCN_MEM_READ |
810 COFF::IMAGE_SCN_MEM_WRITE;
811 else if (K.isReadOnly() || K.isReadOnlyWithRel())
813 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
814 COFF::IMAGE_SCN_MEM_READ;
815 else if (K.isWriteable())
817 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
818 COFF::IMAGE_SCN_MEM_READ |
819 COFF::IMAGE_SCN_MEM_WRITE;
824 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
825 const Comdat *C = GV->getComdat();
826 assert(C && "expected GV to have a Comdat!");
828 StringRef ComdatGVName = C->getName();
829 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
831 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
832 "' does not exist.");
834 if (ComdatGV->getComdat() != C)
835 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
836 "' is not a key for its COMDAT.");
841 static int getSelectionForCOFF(const GlobalValue *GV) {
842 if (const Comdat *C = GV->getComdat()) {
843 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
844 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
845 ComdatKey = GA->getBaseObject();
846 if (ComdatKey == GV) {
847 switch (C->getSelectionKind()) {
849 return COFF::IMAGE_COMDAT_SELECT_ANY;
850 case Comdat::ExactMatch:
851 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
852 case Comdat::Largest:
853 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
854 case Comdat::NoDuplicates:
855 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
856 case Comdat::SameSize:
857 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
860 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
866 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
867 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
868 const TargetMachine &TM) const {
870 unsigned Characteristics = getCOFFSectionFlags(Kind);
871 StringRef Name = GV->getSection();
872 StringRef COMDATSymName = "";
873 if (GV->hasComdat()) {
874 Selection = getSelectionForCOFF(GV);
875 const GlobalValue *ComdatGV;
876 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
877 ComdatGV = getComdatGVForCOFF(GV);
881 if (!ComdatGV->hasPrivateLinkage()) {
882 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
883 COMDATSymName = Sym->getName();
884 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
889 return getContext().getCOFFSection(Name,
896 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
901 if (Kind.isThreadLocal())
903 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
908 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
909 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
910 const TargetMachine &TM) const {
911 // If we have -ffunction-sections then we should emit the global value to a
912 // uniqued section specifically for it.
913 bool EmitUniquedSection;
915 EmitUniquedSection = TM.getFunctionSections();
917 EmitUniquedSection = TM.getDataSections();
919 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
920 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
921 unsigned Characteristics = getCOFFSectionFlags(Kind);
923 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
924 int Selection = getSelectionForCOFF(GV);
926 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
927 const GlobalValue *ComdatGV;
929 ComdatGV = getComdatGVForCOFF(GV);
933 if (!ComdatGV->hasPrivateLinkage()) {
934 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
935 StringRef COMDATSymName = Sym->getName();
936 return getContext().getCOFFSection(Name, Characteristics, Kind,
937 COMDATSymName, Selection);
939 SmallString<256> TmpData;
940 Mang.getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
941 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
949 if (Kind.isThreadLocal())
950 return TLSDataSection;
952 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
953 return ReadOnlySection;
955 // Note: we claim that common symbols are put in BSSSection, but they are
956 // really emitted with the magic .comm directive, which creates a symbol table
957 // entry but not a section.
958 if (Kind.isBSS() || Kind.isCommon())
964 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
965 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
966 const TargetMachine &TM) const {
967 bool CannotUsePrivateLabel = false;
968 if (GV->hasPrivateLinkage() &&
969 ((isa<Function>(GV) && TM.getFunctionSections()) ||
970 (isa<GlobalVariable>(GV) && TM.getDataSections())))
971 CannotUsePrivateLabel = true;
973 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
976 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
977 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
978 // If the function can be removed, produce a unique section so that
979 // the table doesn't prevent the removal.
980 const Comdat *C = F.getComdat();
981 bool EmitUniqueSection = TM.getFunctionSections() || C;
982 if (!EmitUniqueSection)
983 return ReadOnlySection;
985 // FIXME: we should produce a symbol for F instead.
986 if (F.hasPrivateLinkage())
987 return ReadOnlySection;
989 MCSymbol *Sym = TM.getSymbol(&F, Mang);
990 StringRef COMDATSymName = Sym->getName();
992 SectionKind Kind = SectionKind::getReadOnly();
993 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
994 unsigned Characteristics = getCOFFSectionFlags(Kind);
995 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
997 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
998 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
1001 void TargetLoweringObjectFileCOFF::
1002 emitModuleFlags(MCStreamer &Streamer,
1003 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1004 Mangler &Mang, const TargetMachine &TM) const {
1005 MDNode *LinkerOptions = nullptr;
1007 // Look for the "Linker Options" flag, since it's the only one we support.
1008 for (ArrayRef<Module::ModuleFlagEntry>::iterator
1009 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1010 const Module::ModuleFlagEntry &MFE = *i;
1011 StringRef Key = MFE.Key->getString();
1012 Metadata *Val = MFE.Val;
1013 if (Key == "Linker Options") {
1014 LinkerOptions = cast<MDNode>(Val);
1021 // Emit the linker options to the linker .drectve section. According to the
1022 // spec, this section is a space-separated string containing flags for linker.
1023 MCSection *Sec = getDrectveSection();
1024 Streamer.SwitchSection(Sec);
1025 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1026 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1027 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1028 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
1029 // Lead with a space for consistency with our dllexport implementation.
1030 std::string Directive(" ");
1031 Directive.append(MDOption->getString());
1032 Streamer.EmitBytes(Directive);
1037 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1038 unsigned Priority, const MCSymbol *KeySym) const {
1039 return getContext().getAssociativeCOFFSection(
1040 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
1043 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1044 unsigned Priority, const MCSymbol *KeySym) const {
1045 return getContext().getAssociativeCOFFSection(
1046 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
1049 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1050 raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
1051 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1054 const Triple &TT = getTargetTriple();
1056 if (TT.isKnownWindowsMSVCEnvironment())
1061 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1063 raw_string_ostream FlagOS(Flag);
1064 Mang.getNameWithPrefix(FlagOS, GV, false);
1066 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
1067 OS << Flag.substr(1);
1071 Mang.getNameWithPrefix(OS, GV, false);
1074 if (!GV->getValueType()->isFunctionTy()) {
1075 if (TT.isKnownWindowsMSVCEnvironment())