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/MC/MCValue.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 //===----------------------------------------------------------------------===//
47 //===----------------------------------------------------------------------===//
49 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
50 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
51 MachineModuleInfo *MMI) const {
52 unsigned Encoding = getPersonalityEncoding();
53 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
54 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
55 TM.getSymbol(GV, Mang)->getName());
56 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
57 return TM.getSymbol(GV, Mang);
58 report_fatal_error("We do not support this DWARF encoding yet!");
61 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
62 const TargetMachine &TM,
63 const MCSymbol *Sym) const {
64 SmallString<64> NameData("DW.ref.");
65 NameData += Sym->getName();
66 MCSymbol *Label = getContext().getOrCreateSymbol(NameData);
67 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
68 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
69 StringRef Prefix = ".data.";
70 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
71 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
72 MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
73 Flags, 0, Label->getName());
74 unsigned Size = TM.getDataLayout()->getPointerSize();
75 Streamer.SwitchSection(Sec);
76 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
77 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
78 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
79 Streamer.EmitELFSize(Label, E);
80 Streamer.EmitLabel(Label);
82 Streamer.EmitSymbolValue(Sym, Size);
85 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
86 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
87 const TargetMachine &TM, MachineModuleInfo *MMI,
88 MCStreamer &Streamer) const {
90 if (Encoding & dwarf::DW_EH_PE_indirect) {
91 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
93 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
95 // Add information about the stub reference to ELFMMI so that the stub
96 // gets emitted by the asmprinter.
97 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
98 if (!StubSym.getPointer()) {
99 MCSymbol *Sym = TM.getSymbol(GV, Mang);
100 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
103 return TargetLoweringObjectFile::
104 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
105 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
108 return TargetLoweringObjectFile::
109 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
113 getELFKindForNamedSection(StringRef Name, SectionKind K) {
114 // N.B.: The defaults used in here are no the same ones used in MC.
115 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
116 // both gas and MC will produce a section with no flags. Given
117 // section(".eh_frame") gcc will produce:
119 // .section .eh_frame,"a",@progbits
120 if (Name.empty() || Name[0] != '.') return K;
122 // Some lame default implementation based on some magic section names.
123 if (Name == ".bss" ||
124 Name.startswith(".bss.") ||
125 Name.startswith(".gnu.linkonce.b.") ||
126 Name.startswith(".llvm.linkonce.b.") ||
128 Name.startswith(".sbss.") ||
129 Name.startswith(".gnu.linkonce.sb.") ||
130 Name.startswith(".llvm.linkonce.sb."))
131 return SectionKind::getBSS();
133 if (Name == ".tdata" ||
134 Name.startswith(".tdata.") ||
135 Name.startswith(".gnu.linkonce.td.") ||
136 Name.startswith(".llvm.linkonce.td."))
137 return SectionKind::getThreadData();
139 if (Name == ".tbss" ||
140 Name.startswith(".tbss.") ||
141 Name.startswith(".gnu.linkonce.tb.") ||
142 Name.startswith(".llvm.linkonce.tb."))
143 return SectionKind::getThreadBSS();
149 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
151 if (Name == ".init_array")
152 return ELF::SHT_INIT_ARRAY;
154 if (Name == ".fini_array")
155 return ELF::SHT_FINI_ARRAY;
157 if (Name == ".preinit_array")
158 return ELF::SHT_PREINIT_ARRAY;
160 if (K.isBSS() || K.isThreadBSS())
161 return ELF::SHT_NOBITS;
163 return ELF::SHT_PROGBITS;
166 static unsigned getELFSectionFlags(SectionKind K) {
170 Flags |= ELF::SHF_ALLOC;
173 Flags |= ELF::SHF_EXECINSTR;
176 Flags |= ELF::SHF_WRITE;
178 if (K.isThreadLocal())
179 Flags |= ELF::SHF_TLS;
181 if (K.isMergeableCString() || K.isMergeableConst())
182 Flags |= ELF::SHF_MERGE;
184 if (K.isMergeableCString())
185 Flags |= ELF::SHF_STRINGS;
190 static const Comdat *getELFComdat(const GlobalValue *GV) {
191 const Comdat *C = GV->getComdat();
195 if (C->getSelectionKind() != Comdat::Any)
196 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
197 C->getName() + "' cannot be lowered.");
202 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
203 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
204 const TargetMachine &TM) const {
205 StringRef SectionName = GV->getSection();
207 // Infer section flags from the section name if we can.
208 Kind = getELFKindForNamedSection(SectionName, Kind);
210 StringRef Group = "";
211 unsigned Flags = getELFSectionFlags(Kind);
212 if (const Comdat *C = getELFComdat(GV)) {
213 Group = C->getName();
214 Flags |= ELF::SHF_GROUP;
216 return getContext().getELFSection(SectionName,
217 getELFSectionType(SectionName, Kind), Flags,
218 /*EntrySize=*/0, Group);
221 /// Return the section prefix name used by options FunctionsSections and
223 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
226 if (Kind.isReadOnly())
230 if (Kind.isThreadData())
232 if (Kind.isThreadBSS())
234 if (Kind.isDataNoRel())
236 if (Kind.isDataRelLocal())
237 return ".data.rel.local";
238 if (Kind.isDataRel())
240 if (Kind.isReadOnlyWithRelLocal())
241 return ".data.rel.ro.local";
242 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
243 return ".data.rel.ro";
246 static MCSectionELF *
247 selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
248 SectionKind Kind, Mangler &Mang,
249 const TargetMachine &TM, bool EmitUniqueSection,
250 unsigned Flags, unsigned *NextUniqueID) {
251 unsigned EntrySize = 0;
252 if (Kind.isMergeableCString()) {
253 if (Kind.isMergeable2ByteCString()) {
255 } else if (Kind.isMergeable4ByteCString()) {
259 assert(Kind.isMergeable1ByteCString() && "unknown string width");
261 } else if (Kind.isMergeableConst()) {
262 if (Kind.isMergeableConst4()) {
264 } else if (Kind.isMergeableConst8()) {
267 assert(Kind.isMergeableConst16() && "unknown data width");
272 StringRef Group = "";
273 if (const Comdat *C = getELFComdat(GV)) {
274 Flags |= ELF::SHF_GROUP;
275 Group = C->getName();
278 bool UniqueSectionNames = TM.getUniqueSectionNames();
279 SmallString<128> Name;
280 if (Kind.isMergeableCString()) {
281 // We also need alignment here.
282 // FIXME: this is getting the alignment of the character, not the
283 // alignment of the global!
285 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
287 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
288 Name = SizeSpec + utostr(Align);
289 } else if (Kind.isMergeableConst()) {
290 Name = ".rodata.cst";
291 Name += utostr(EntrySize);
293 Name = getSectionPrefixForGlobal(Kind);
296 if (EmitUniqueSection && UniqueSectionNames) {
298 TM.getNameWithPrefix(Name, GV, Mang, true);
300 unsigned UniqueID = ~0;
301 if (EmitUniqueSection && !UniqueSectionNames) {
302 UniqueID = *NextUniqueID;
305 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
306 EntrySize, Group, UniqueID);
309 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
310 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
311 const TargetMachine &TM) const {
312 unsigned Flags = getELFSectionFlags(Kind);
314 // If we have -ffunction-section or -fdata-section then we should emit the
315 // global value to a uniqued section specifically for it.
316 bool EmitUniqueSection = false;
317 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
319 EmitUniqueSection = TM.getFunctionSections();
321 EmitUniqueSection = TM.getDataSections();
323 EmitUniqueSection |= GV->hasComdat();
325 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
326 EmitUniqueSection, Flags, &NextUniqueID);
329 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
330 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
331 // If the function can be removed, produce a unique section so that
332 // the table doesn't prevent the removal.
333 const Comdat *C = F.getComdat();
334 bool EmitUniqueSection = TM.getFunctionSections() || C;
335 if (!EmitUniqueSection)
336 return ReadOnlySection;
338 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
339 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
343 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
344 bool UsesLabelDifference, const Function &F) const {
345 // We can always create relative relocations, so use another section
346 // that can be marked non-executable.
350 /// Given a mergeable constant with the specified size and relocation
351 /// information, return a section that it 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 MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
370 bool IsCtor, unsigned Priority,
371 const MCSymbol *KeySym) {
374 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
375 StringRef COMDAT = KeySym ? KeySym->getName() : "";
378 Flags |= ELF::SHF_GROUP;
382 Type = ELF::SHT_INIT_ARRAY;
383 Name = ".init_array";
385 Type = ELF::SHT_FINI_ARRAY;
386 Name = ".fini_array";
388 if (Priority != 65535) {
390 Name += utostr(Priority);
393 // The default scheme is .ctor / .dtor, so we have to invert the priority
399 if (Priority != 65535) {
401 Name += utostr(65535 - Priority);
403 Type = ELF::SHT_PROGBITS;
406 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
409 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
410 unsigned Priority, const MCSymbol *KeySym) const {
411 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
415 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
416 unsigned Priority, const MCSymbol *KeySym) const {
417 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
422 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
423 UseInitArray = UseInitArray_;
427 StaticCtorSection = getContext().getELFSection(
428 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
429 StaticDtorSection = getContext().getELFSection(
430 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
433 //===----------------------------------------------------------------------===//
435 //===----------------------------------------------------------------------===//
437 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
438 : TargetLoweringObjectFile() {
439 SupportIndirectSymViaGOTPCRel = true;
442 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
443 /// option string. Returns StringRef() if the option does not specify a library.
444 StringRef TargetLoweringObjectFileMachO::
445 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
446 const char *LibCmd = "-l";
447 if (LinkerOption.startswith(LibCmd))
448 return LinkerOption.substr(strlen(LibCmd));
452 /// emitModuleFlags - Perform code emission for module flags.
453 void TargetLoweringObjectFileMachO::
454 emitModuleFlags(MCStreamer &Streamer,
455 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
456 Mangler &Mang, const TargetMachine &TM) const {
457 unsigned VersionVal = 0;
458 unsigned ImageInfoFlags = 0;
459 MDNode *LinkerOptions = nullptr;
460 StringRef SectionVal;
462 for (ArrayRef<Module::ModuleFlagEntry>::iterator
463 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
464 const Module::ModuleFlagEntry &MFE = *i;
466 // Ignore flags with 'Require' behavior.
467 if (MFE.Behavior == Module::Require)
470 StringRef Key = MFE.Key->getString();
471 Metadata *Val = MFE.Val;
473 if (Key == "Objective-C Image Info Version") {
474 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
475 } else if (Key == "Objective-C Garbage Collection" ||
476 Key == "Objective-C GC Only" ||
477 Key == "Objective-C Is Simulated" ||
478 Key == "Objective-C Image Swift Version") {
479 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
480 } else if (Key == "Objective-C Image Info Section") {
481 SectionVal = cast<MDString>(Val)->getString();
482 } else if (Key == "Linker Options") {
483 LinkerOptions = cast<MDNode>(Val);
487 // Emit the linker options if present.
489 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
490 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
491 SmallVector<std::string, 4> StrOptions;
493 // Convert to strings.
494 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
495 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
496 StrOptions.push_back(MDOption->getString());
499 Streamer.EmitLinkerOptions(StrOptions);
503 // The section is mandatory. If we don't have it, then we don't have GC info.
504 if (SectionVal.empty()) return;
506 StringRef Segment, Section;
507 unsigned TAA = 0, StubSize = 0;
509 std::string ErrorCode =
510 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
511 TAA, TAAParsed, StubSize);
512 if (!ErrorCode.empty())
513 // If invalid, report the error with report_fatal_error.
514 report_fatal_error("Invalid section specifier '" + Section + "': " +
518 MCSectionMachO *S = getContext().getMachOSection(
519 Segment, Section, TAA, StubSize, SectionKind::getDataNoRel());
520 Streamer.SwitchSection(S);
521 Streamer.EmitLabel(getContext().
522 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
523 Streamer.EmitIntValue(VersionVal, 4);
524 Streamer.EmitIntValue(ImageInfoFlags, 4);
525 Streamer.AddBlankLine();
528 static void checkMachOComdat(const GlobalValue *GV) {
529 const Comdat *C = GV->getComdat();
533 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
534 "' cannot be lowered.");
537 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
538 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
539 const TargetMachine &TM) const {
540 // Parse the section specifier and create it if valid.
541 StringRef Segment, Section;
542 unsigned TAA = 0, StubSize = 0;
545 checkMachOComdat(GV);
547 std::string ErrorCode =
548 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
549 TAA, TAAParsed, StubSize);
550 if (!ErrorCode.empty()) {
551 // If invalid, report the error with report_fatal_error.
552 report_fatal_error("Global variable '" + GV->getName() +
553 "' has an invalid section specifier '" +
554 GV->getSection() + "': " + ErrorCode + ".");
559 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
561 // If TAA wasn't set by ParseSectionSpecifier() above,
562 // use the value returned by getMachOSection() as a default.
564 TAA = S->getTypeAndAttributes();
566 // Okay, now that we got the section, verify that the TAA & StubSize agree.
567 // If the user declared multiple globals with different section flags, we need
568 // to reject it here.
569 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
570 // If invalid, report the error with report_fatal_error.
571 report_fatal_error("Global variable '" + GV->getName() +
572 "' section type or attributes does not match previous"
573 " section specifier");
579 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
580 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
581 const TargetMachine &TM) const {
582 checkMachOComdat(GV);
584 // Handle thread local data.
585 if (Kind.isThreadBSS()) return TLSBSSSection;
586 if (Kind.isThreadData()) return TLSDataSection;
589 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
591 // If this is weak/linkonce, put this in a coalescable section, either in text
592 // or data depending on if it is writable.
593 if (GV->isWeakForLinker()) {
594 if (Kind.isReadOnly())
595 return ConstTextCoalSection;
596 return DataCoalSection;
599 // FIXME: Alignment check should be handled by section classifier.
600 if (Kind.isMergeable1ByteCString() &&
601 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
602 return CStringSection;
604 // Do not put 16-bit arrays in the UString section if they have an
605 // externally visible label, this runs into issues with certain linker
607 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
608 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
609 return UStringSection;
611 // With MachO only variables whose corresponding symbol starts with 'l' or
612 // 'L' can be merged, so we only try merging GVs with private linkage.
613 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
614 if (Kind.isMergeableConst4())
615 return FourByteConstantSection;
616 if (Kind.isMergeableConst8())
617 return EightByteConstantSection;
618 if (Kind.isMergeableConst16())
619 return SixteenByteConstantSection;
622 // Otherwise, if it is readonly, but not something we can specially optimize,
623 // just drop it in .const.
624 if (Kind.isReadOnly())
625 return ReadOnlySection;
627 // If this is marked const, put it into a const section. But if the dynamic
628 // linker needs to write to it, put it in the data segment.
629 if (Kind.isReadOnlyWithRel())
630 return ConstDataSection;
632 // Put zero initialized globals with strong external linkage in the
633 // DATA, __common section with the .zerofill directive.
634 if (Kind.isBSSExtern())
635 return DataCommonSection;
637 // Put zero initialized globals with local linkage in __DATA,__bss directive
638 // with the .zerofill directive (aka .lcomm).
639 if (Kind.isBSSLocal())
640 return DataBSSSection;
642 // Otherwise, just drop the variable in the normal data section.
647 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
648 const Constant *C) const {
649 // If this constant requires a relocation, we have to put it in the data
650 // segment, not in the text segment.
651 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
652 return ConstDataSection;
654 if (Kind.isMergeableConst4())
655 return FourByteConstantSection;
656 if (Kind.isMergeableConst8())
657 return EightByteConstantSection;
658 if (Kind.isMergeableConst16())
659 return SixteenByteConstantSection;
660 return ReadOnlySection; // .const
663 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
664 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
665 const TargetMachine &TM, MachineModuleInfo *MMI,
666 MCStreamer &Streamer) const {
667 // The mach-o version of this method defaults to returning a stub reference.
669 if (Encoding & DW_EH_PE_indirect) {
670 MachineModuleInfoMachO &MachOMMI =
671 MMI->getObjFileInfo<MachineModuleInfoMachO>();
674 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
676 // Add information about the stub reference to MachOMMI so that the stub
677 // gets emitted by the asmprinter.
678 MachineModuleInfoImpl::StubValueTy &StubSym =
679 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
680 MachOMMI.getGVStubEntry(SSym);
681 if (!StubSym.getPointer()) {
682 MCSymbol *Sym = TM.getSymbol(GV, Mang);
683 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
686 return TargetLoweringObjectFile::
687 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
688 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
691 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
695 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
696 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
697 MachineModuleInfo *MMI) const {
698 // The mach-o version of this method defaults to returning a stub reference.
699 MachineModuleInfoMachO &MachOMMI =
700 MMI->getObjFileInfo<MachineModuleInfoMachO>();
702 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
704 // Add information about the stub reference to MachOMMI so that the stub
705 // gets emitted by the asmprinter.
706 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
707 if (!StubSym.getPointer()) {
708 MCSymbol *Sym = TM.getSymbol(GV, Mang);
709 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
715 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
716 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
717 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
718 // Although MachO 32-bit targets do not explictly have a GOTPCREL relocation
719 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
720 // through a non_lazy_ptr stub instead. One advantage is that it allows the
721 // computation of deltas to final external symbols. Example:
727 // .long _extgotequiv-_delta
729 // is transformed to:
732 // .long L_extfoo$non_lazy_ptr-(_delta+0)
734 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
735 // L_extfoo$non_lazy_ptr:
736 // .indirect_symbol _extfoo
739 MachineModuleInfoMachO &MachOMMI =
740 MMI->getObjFileInfo<MachineModuleInfoMachO>();
741 MCContext &Ctx = getContext();
743 // The offset must consider the original displacement from the base symbol
744 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
745 Offset = -MV.getConstant();
746 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
748 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
749 // non_lazy_ptr stubs.
750 SmallString<128> Name;
751 StringRef Suffix = "$non_lazy_ptr";
752 Name += DL->getPrivateGlobalPrefix();
753 Name += Sym->getName();
755 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
757 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
758 if (!StubSym.getPointer())
759 StubSym = MachineModuleInfoImpl::
760 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
762 const MCExpr *BSymExpr =
763 MCSymbolRefExpr::Create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
765 MCSymbolRefExpr::Create(Stub, MCSymbolRefExpr::VK_None, Ctx);
768 return MCBinaryExpr::CreateSub(LHS, BSymExpr, Ctx);
771 MCBinaryExpr::CreateAdd(BSymExpr, MCConstantExpr::Create(Offset, Ctx), Ctx);
772 return MCBinaryExpr::CreateSub(LHS, RHS, Ctx);
775 //===----------------------------------------------------------------------===//
777 //===----------------------------------------------------------------------===//
780 getCOFFSectionFlags(SectionKind K) {
785 COFF::IMAGE_SCN_MEM_DISCARDABLE;
788 COFF::IMAGE_SCN_MEM_EXECUTE |
789 COFF::IMAGE_SCN_MEM_READ |
790 COFF::IMAGE_SCN_CNT_CODE;
793 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
794 COFF::IMAGE_SCN_MEM_READ |
795 COFF::IMAGE_SCN_MEM_WRITE;
796 else if (K.isThreadLocal())
798 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
799 COFF::IMAGE_SCN_MEM_READ |
800 COFF::IMAGE_SCN_MEM_WRITE;
801 else if (K.isReadOnly() || K.isReadOnlyWithRel())
803 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
804 COFF::IMAGE_SCN_MEM_READ;
805 else if (K.isWriteable())
807 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
808 COFF::IMAGE_SCN_MEM_READ |
809 COFF::IMAGE_SCN_MEM_WRITE;
814 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
815 const Comdat *C = GV->getComdat();
816 assert(C && "expected GV to have a Comdat!");
818 StringRef ComdatGVName = C->getName();
819 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
821 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
822 "' does not exist.");
824 if (ComdatGV->getComdat() != C)
825 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
826 "' is not a key for its COMDAT.");
831 static int getSelectionForCOFF(const GlobalValue *GV) {
832 if (const Comdat *C = GV->getComdat()) {
833 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
834 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
835 ComdatKey = GA->getBaseObject();
836 if (ComdatKey == GV) {
837 switch (C->getSelectionKind()) {
839 return COFF::IMAGE_COMDAT_SELECT_ANY;
840 case Comdat::ExactMatch:
841 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
842 case Comdat::Largest:
843 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
844 case Comdat::NoDuplicates:
845 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
846 case Comdat::SameSize:
847 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
850 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
852 } else if (GV->isWeakForLinker()) {
853 return COFF::IMAGE_COMDAT_SELECT_ANY;
858 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
859 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
860 const TargetMachine &TM) const {
862 unsigned Characteristics = getCOFFSectionFlags(Kind);
863 StringRef Name = GV->getSection();
864 StringRef COMDATSymName = "";
865 if (GV->hasComdat()) {
866 Selection = getSelectionForCOFF(GV);
867 const GlobalValue *ComdatGV;
868 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
869 ComdatGV = getComdatGVForCOFF(GV);
873 if (!ComdatGV->hasPrivateLinkage()) {
874 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
875 COMDATSymName = Sym->getName();
876 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
881 return getContext().getCOFFSection(Name,
888 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
893 if (Kind.isThreadLocal())
895 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
900 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
901 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
902 const TargetMachine &TM) const {
903 // If we have -ffunction-sections then we should emit the global value to a
904 // uniqued section specifically for it.
905 bool EmitUniquedSection;
907 EmitUniquedSection = TM.getFunctionSections();
909 EmitUniquedSection = TM.getDataSections();
911 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
912 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
913 unsigned Characteristics = getCOFFSectionFlags(Kind);
915 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
916 int Selection = getSelectionForCOFF(GV);
918 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
919 const GlobalValue *ComdatGV;
921 ComdatGV = getComdatGVForCOFF(GV);
925 if (!ComdatGV->hasPrivateLinkage()) {
926 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
927 StringRef COMDATSymName = Sym->getName();
928 return getContext().getCOFFSection(Name, Characteristics, Kind,
929 COMDATSymName, Selection);
931 SmallString<256> TmpData;
932 getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true, Mang, TM);
933 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
941 if (Kind.isThreadLocal())
942 return TLSDataSection;
944 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
945 return ReadOnlySection;
947 // Note: we claim that common symbols are put in BSSSection, but they are
948 // really emitted with the magic .comm directive, which creates a symbol table
949 // entry but not a section.
950 if (Kind.isBSS() || Kind.isCommon())
956 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
957 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
958 bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
959 if (GV->hasPrivateLinkage() &&
960 ((isa<Function>(GV) && TM.getFunctionSections()) ||
961 (isa<GlobalVariable>(GV) && TM.getDataSections())))
962 CannotUsePrivateLabel = true;
964 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
967 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
968 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
969 // If the function can be removed, produce a unique section so that
970 // the table doesn't prevent the removal.
971 const Comdat *C = F.getComdat();
972 bool EmitUniqueSection = TM.getFunctionSections() || C;
973 if (!EmitUniqueSection)
974 return ReadOnlySection;
976 // FIXME: we should produce a symbol for F instead.
977 if (F.hasPrivateLinkage())
978 return ReadOnlySection;
980 MCSymbol *Sym = TM.getSymbol(&F, Mang);
981 StringRef COMDATSymName = Sym->getName();
983 SectionKind Kind = SectionKind::getReadOnly();
984 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
985 unsigned Characteristics = getCOFFSectionFlags(Kind);
986 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
988 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
989 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
992 StringRef TargetLoweringObjectFileCOFF::
993 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
994 const char *LibCmd = "/DEFAULTLIB:";
995 if (LinkerOption.startswith(LibCmd))
996 return LinkerOption.substr(strlen(LibCmd));
1000 void TargetLoweringObjectFileCOFF::
1001 emitModuleFlags(MCStreamer &Streamer,
1002 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1003 Mangler &Mang, const TargetMachine &TM) const {
1004 MDNode *LinkerOptions = nullptr;
1006 // Look for the "Linker Options" flag, since it's the only one we support.
1007 for (ArrayRef<Module::ModuleFlagEntry>::iterator
1008 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1009 const Module::ModuleFlagEntry &MFE = *i;
1010 StringRef Key = MFE.Key->getString();
1011 Metadata *Val = MFE.Val;
1012 if (Key == "Linker Options") {
1013 LinkerOptions = cast<MDNode>(Val);
1020 // Emit the linker options to the linker .drectve section. According to the
1021 // spec, this section is a space-separated string containing flags for linker.
1022 MCSection *Sec = getDrectveSection();
1023 Streamer.SwitchSection(Sec);
1024 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1025 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1026 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1027 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
1028 // Lead with a space for consistency with our dllexport implementation.
1029 std::string Directive(" ");
1030 Directive.append(MDOption->getString());
1031 Streamer.EmitBytes(Directive);
1036 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1037 unsigned Priority, const MCSymbol *KeySym) const {
1038 return getContext().getAssociativeCOFFSection(
1039 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
1042 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1043 unsigned Priority, const MCSymbol *KeySym) const {
1044 return getContext().getAssociativeCOFFSection(
1045 cast<MCSectionCOFF>(StaticDtorSection), KeySym);