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/MCSymbolELF.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();
67 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
68 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
69 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
70 StringRef Prefix = ".data.";
71 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
72 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
73 MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
74 Flags, 0, Label->getName());
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;
167 static unsigned getELFSectionFlags(SectionKind K) {
171 Flags |= ELF::SHF_ALLOC;
174 Flags |= ELF::SHF_EXECINSTR;
177 Flags |= ELF::SHF_WRITE;
179 if (K.isThreadLocal())
180 Flags |= ELF::SHF_TLS;
182 if (K.isMergeableCString() || K.isMergeableConst())
183 Flags |= ELF::SHF_MERGE;
185 if (K.isMergeableCString())
186 Flags |= ELF::SHF_STRINGS;
191 static const Comdat *getELFComdat(const GlobalValue *GV) {
192 const Comdat *C = GV->getComdat();
196 if (C->getSelectionKind() != Comdat::Any)
197 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
198 C->getName() + "' cannot be lowered.");
203 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
204 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
205 const TargetMachine &TM) const {
206 StringRef SectionName = GV->getSection();
208 // Infer section flags from the section name if we can.
209 Kind = getELFKindForNamedSection(SectionName, Kind);
211 StringRef Group = "";
212 unsigned Flags = getELFSectionFlags(Kind);
213 if (const Comdat *C = getELFComdat(GV)) {
214 Group = C->getName();
215 Flags |= ELF::SHF_GROUP;
217 return getContext().getELFSection(SectionName,
218 getELFSectionType(SectionName, Kind), Flags,
219 /*EntrySize=*/0, Group);
222 /// Return the section prefix name used by options FunctionsSections and
224 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
227 if (Kind.isReadOnly())
231 if (Kind.isThreadData())
233 if (Kind.isThreadBSS())
235 if (Kind.isDataNoRel())
237 if (Kind.isDataRelLocal())
238 return ".data.rel.local";
239 if (Kind.isDataRel())
241 if (Kind.isReadOnlyWithRelLocal())
242 return ".data.rel.ro.local";
243 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
244 return ".data.rel.ro";
247 static MCSectionELF *
248 selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
249 SectionKind Kind, Mangler &Mang,
250 const TargetMachine &TM, bool EmitUniqueSection,
251 unsigned Flags, unsigned *NextUniqueID) {
252 unsigned EntrySize = 0;
253 if (Kind.isMergeableCString()) {
254 if (Kind.isMergeable2ByteCString()) {
256 } else if (Kind.isMergeable4ByteCString()) {
260 assert(Kind.isMergeable1ByteCString() && "unknown string width");
262 } else if (Kind.isMergeableConst()) {
263 if (Kind.isMergeableConst4()) {
265 } else if (Kind.isMergeableConst8()) {
268 assert(Kind.isMergeableConst16() && "unknown data width");
273 StringRef Group = "";
274 if (const Comdat *C = getELFComdat(GV)) {
275 Flags |= ELF::SHF_GROUP;
276 Group = C->getName();
279 bool UniqueSectionNames = TM.getUniqueSectionNames();
280 SmallString<128> Name;
281 if (Kind.isMergeableCString()) {
282 // We also need alignment here.
283 // FIXME: this is getting the alignment of the character, not the
284 // alignment of the global!
286 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
288 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
289 Name = SizeSpec + utostr(Align);
290 } else if (Kind.isMergeableConst()) {
291 Name = ".rodata.cst";
292 Name += utostr(EntrySize);
294 Name = getSectionPrefixForGlobal(Kind);
297 if (EmitUniqueSection && UniqueSectionNames) {
299 TM.getNameWithPrefix(Name, GV, Mang, true);
301 unsigned UniqueID = ~0;
302 if (EmitUniqueSection && !UniqueSectionNames) {
303 UniqueID = *NextUniqueID;
306 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
307 EntrySize, Group, UniqueID);
310 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
311 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
312 const TargetMachine &TM) const {
313 unsigned Flags = getELFSectionFlags(Kind);
315 // If we have -ffunction-section or -fdata-section then we should emit the
316 // global value to a uniqued section specifically for it.
317 bool EmitUniqueSection = false;
318 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
320 EmitUniqueSection = TM.getFunctionSections();
322 EmitUniqueSection = TM.getDataSections();
324 EmitUniqueSection |= GV->hasComdat();
326 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
327 EmitUniqueSection, Flags, &NextUniqueID);
330 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
331 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
332 // If the function can be removed, produce a unique section so that
333 // the table doesn't prevent the removal.
334 const Comdat *C = F.getComdat();
335 bool EmitUniqueSection = TM.getFunctionSections() || C;
336 if (!EmitUniqueSection)
337 return ReadOnlySection;
339 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
340 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
344 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
345 bool UsesLabelDifference, const Function &F) const {
346 // We can always create relative relocations, so use another section
347 // that can be marked non-executable.
351 /// Given a mergeable constant with the specified size and relocation
352 /// information, return a section that it should be placed in.
354 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
355 const Constant *C) const {
356 if (Kind.isMergeableConst4() && MergeableConst4Section)
357 return MergeableConst4Section;
358 if (Kind.isMergeableConst8() && MergeableConst8Section)
359 return MergeableConst8Section;
360 if (Kind.isMergeableConst16() && MergeableConst16Section)
361 return MergeableConst16Section;
362 if (Kind.isReadOnly())
363 return ReadOnlySection;
365 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
366 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
367 return DataRelROSection;
370 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
371 bool IsCtor, unsigned Priority,
372 const MCSymbol *KeySym) {
375 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
376 StringRef COMDAT = KeySym ? KeySym->getName() : "";
379 Flags |= ELF::SHF_GROUP;
383 Type = ELF::SHT_INIT_ARRAY;
384 Name = ".init_array";
386 Type = ELF::SHT_FINI_ARRAY;
387 Name = ".fini_array";
389 if (Priority != 65535) {
391 Name += utostr(Priority);
394 // The default scheme is .ctor / .dtor, so we have to invert the priority
400 if (Priority != 65535) {
402 Name += utostr(65535 - Priority);
404 Type = ELF::SHT_PROGBITS;
407 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
410 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
411 unsigned Priority, const MCSymbol *KeySym) const {
412 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
416 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
417 unsigned Priority, const MCSymbol *KeySym) const {
418 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
423 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
424 UseInitArray = UseInitArray_;
428 StaticCtorSection = getContext().getELFSection(
429 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
430 StaticDtorSection = getContext().getELFSection(
431 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
434 //===----------------------------------------------------------------------===//
436 //===----------------------------------------------------------------------===//
438 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
439 : TargetLoweringObjectFile() {
440 SupportIndirectSymViaGOTPCRel = true;
443 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
444 /// option string. Returns StringRef() if the option does not specify a library.
445 StringRef TargetLoweringObjectFileMachO::
446 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
447 const char *LibCmd = "-l";
448 if (LinkerOption.startswith(LibCmd))
449 return LinkerOption.substr(strlen(LibCmd));
453 /// emitModuleFlags - Perform code emission for module flags.
454 void TargetLoweringObjectFileMachO::
455 emitModuleFlags(MCStreamer &Streamer,
456 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
457 Mangler &Mang, const TargetMachine &TM) const {
458 unsigned VersionVal = 0;
459 unsigned ImageInfoFlags = 0;
460 MDNode *LinkerOptions = nullptr;
461 StringRef SectionVal;
463 for (ArrayRef<Module::ModuleFlagEntry>::iterator
464 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
465 const Module::ModuleFlagEntry &MFE = *i;
467 // Ignore flags with 'Require' behavior.
468 if (MFE.Behavior == Module::Require)
471 StringRef Key = MFE.Key->getString();
472 Metadata *Val = MFE.Val;
474 if (Key == "Objective-C Image Info Version") {
475 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
476 } else if (Key == "Objective-C Garbage Collection" ||
477 Key == "Objective-C GC Only" ||
478 Key == "Objective-C Is Simulated" ||
479 Key == "Objective-C Image Swift Version") {
480 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
481 } else if (Key == "Objective-C Image Info Section") {
482 SectionVal = cast<MDString>(Val)->getString();
483 } else if (Key == "Linker Options") {
484 LinkerOptions = cast<MDNode>(Val);
488 // Emit the linker options if present.
490 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
491 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
492 SmallVector<std::string, 4> StrOptions;
494 // Convert to strings.
495 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
496 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
497 StrOptions.push_back(MDOption->getString());
500 Streamer.EmitLinkerOptions(StrOptions);
504 // The section is mandatory. If we don't have it, then we don't have GC info.
505 if (SectionVal.empty()) return;
507 StringRef Segment, Section;
508 unsigned TAA = 0, StubSize = 0;
510 std::string ErrorCode =
511 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
512 TAA, TAAParsed, StubSize);
513 if (!ErrorCode.empty())
514 // If invalid, report the error with report_fatal_error.
515 report_fatal_error("Invalid section specifier '" + Section + "': " +
519 MCSectionMachO *S = getContext().getMachOSection(
520 Segment, Section, TAA, StubSize, SectionKind::getDataNoRel());
521 Streamer.SwitchSection(S);
522 Streamer.EmitLabel(getContext().
523 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
524 Streamer.EmitIntValue(VersionVal, 4);
525 Streamer.EmitIntValue(ImageInfoFlags, 4);
526 Streamer.AddBlankLine();
529 static void checkMachOComdat(const GlobalValue *GV) {
530 const Comdat *C = GV->getComdat();
534 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
535 "' cannot be lowered.");
538 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
539 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
540 const TargetMachine &TM) const {
541 // Parse the section specifier and create it if valid.
542 StringRef Segment, Section;
543 unsigned TAA = 0, StubSize = 0;
546 checkMachOComdat(GV);
548 std::string ErrorCode =
549 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
550 TAA, TAAParsed, StubSize);
551 if (!ErrorCode.empty()) {
552 // If invalid, report the error with report_fatal_error.
553 report_fatal_error("Global variable '" + GV->getName() +
554 "' has an invalid section specifier '" +
555 GV->getSection() + "': " + ErrorCode + ".");
560 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
562 // If TAA wasn't set by ParseSectionSpecifier() above,
563 // use the value returned by getMachOSection() as a default.
565 TAA = S->getTypeAndAttributes();
567 // Okay, now that we got the section, verify that the TAA & StubSize agree.
568 // If the user declared multiple globals with different section flags, we need
569 // to reject it here.
570 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
571 // If invalid, report the error with report_fatal_error.
572 report_fatal_error("Global variable '" + GV->getName() +
573 "' section type or attributes does not match previous"
574 " section specifier");
580 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
581 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
582 const TargetMachine &TM) const {
583 checkMachOComdat(GV);
585 // Handle thread local data.
586 if (Kind.isThreadBSS()) return TLSBSSSection;
587 if (Kind.isThreadData()) return TLSDataSection;
590 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
592 // If this is weak/linkonce, put this in a coalescable section, either in text
593 // or data depending on if it is writable.
594 if (GV->isWeakForLinker()) {
595 if (Kind.isReadOnly())
596 return ConstTextCoalSection;
597 return DataCoalSection;
600 // FIXME: Alignment check should be handled by section classifier.
601 if (Kind.isMergeable1ByteCString() &&
602 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
603 return CStringSection;
605 // Do not put 16-bit arrays in the UString section if they have an
606 // externally visible label, this runs into issues with certain linker
608 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
609 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
610 return UStringSection;
612 // With MachO only variables whose corresponding symbol starts with 'l' or
613 // 'L' can be merged, so we only try merging GVs with private linkage.
614 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
615 if (Kind.isMergeableConst4())
616 return FourByteConstantSection;
617 if (Kind.isMergeableConst8())
618 return EightByteConstantSection;
619 if (Kind.isMergeableConst16())
620 return SixteenByteConstantSection;
623 // Otherwise, if it is readonly, but not something we can specially optimize,
624 // just drop it in .const.
625 if (Kind.isReadOnly())
626 return ReadOnlySection;
628 // If this is marked const, put it into a const section. But if the dynamic
629 // linker needs to write to it, put it in the data segment.
630 if (Kind.isReadOnlyWithRel())
631 return ConstDataSection;
633 // Put zero initialized globals with strong external linkage in the
634 // DATA, __common section with the .zerofill directive.
635 if (Kind.isBSSExtern())
636 return DataCommonSection;
638 // Put zero initialized globals with local linkage in __DATA,__bss directive
639 // with the .zerofill directive (aka .lcomm).
640 if (Kind.isBSSLocal())
641 return DataBSSSection;
643 // Otherwise, just drop the variable in the normal data section.
648 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
649 const Constant *C) const {
650 // If this constant requires a relocation, we have to put it in the data
651 // segment, not in the text segment.
652 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
653 return ConstDataSection;
655 if (Kind.isMergeableConst4())
656 return FourByteConstantSection;
657 if (Kind.isMergeableConst8())
658 return EightByteConstantSection;
659 if (Kind.isMergeableConst16())
660 return SixteenByteConstantSection;
661 return ReadOnlySection; // .const
664 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
665 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
666 const TargetMachine &TM, MachineModuleInfo *MMI,
667 MCStreamer &Streamer) const {
668 // The mach-o version of this method defaults to returning a stub reference.
670 if (Encoding & DW_EH_PE_indirect) {
671 MachineModuleInfoMachO &MachOMMI =
672 MMI->getObjFileInfo<MachineModuleInfoMachO>();
675 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
677 // Add information about the stub reference to MachOMMI so that the stub
678 // gets emitted by the asmprinter.
679 MachineModuleInfoImpl::StubValueTy &StubSym =
680 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
681 MachOMMI.getGVStubEntry(SSym);
682 if (!StubSym.getPointer()) {
683 MCSymbol *Sym = TM.getSymbol(GV, Mang);
684 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
687 return TargetLoweringObjectFile::
688 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
689 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
692 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
696 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
697 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
698 MachineModuleInfo *MMI) const {
699 // The mach-o version of this method defaults to returning a stub reference.
700 MachineModuleInfoMachO &MachOMMI =
701 MMI->getObjFileInfo<MachineModuleInfoMachO>();
703 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
705 // Add information about the stub reference to MachOMMI so that the stub
706 // gets emitted by the asmprinter.
707 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
708 if (!StubSym.getPointer()) {
709 MCSymbol *Sym = TM.getSymbol(GV, Mang);
710 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
716 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
717 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
718 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
719 // Although MachO 32-bit targets do not explictly have a GOTPCREL relocation
720 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
721 // through a non_lazy_ptr stub instead. One advantage is that it allows the
722 // computation of deltas to final external symbols. Example:
728 // .long _extgotequiv-_delta
730 // is transformed to:
733 // .long L_extfoo$non_lazy_ptr-(_delta+0)
735 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
736 // L_extfoo$non_lazy_ptr:
737 // .indirect_symbol _extfoo
740 MachineModuleInfoMachO &MachOMMI =
741 MMI->getObjFileInfo<MachineModuleInfoMachO>();
742 MCContext &Ctx = getContext();
744 // The offset must consider the original displacement from the base symbol
745 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
746 Offset = -MV.getConstant();
747 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
749 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
750 // non_lazy_ptr stubs.
751 SmallString<128> Name;
752 StringRef Suffix = "$non_lazy_ptr";
753 Name += DL->getPrivateGlobalPrefix();
754 Name += Sym->getName();
756 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
758 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
759 if (!StubSym.getPointer())
760 StubSym = MachineModuleInfoImpl::
761 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
763 const MCExpr *BSymExpr =
764 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
766 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
769 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
772 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
773 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
776 //===----------------------------------------------------------------------===//
778 //===----------------------------------------------------------------------===//
781 getCOFFSectionFlags(SectionKind K) {
786 COFF::IMAGE_SCN_MEM_DISCARDABLE;
789 COFF::IMAGE_SCN_MEM_EXECUTE |
790 COFF::IMAGE_SCN_MEM_READ |
791 COFF::IMAGE_SCN_CNT_CODE;
794 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
795 COFF::IMAGE_SCN_MEM_READ |
796 COFF::IMAGE_SCN_MEM_WRITE;
797 else if (K.isThreadLocal())
799 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
800 COFF::IMAGE_SCN_MEM_READ |
801 COFF::IMAGE_SCN_MEM_WRITE;
802 else if (K.isReadOnly() || K.isReadOnlyWithRel())
804 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
805 COFF::IMAGE_SCN_MEM_READ;
806 else if (K.isWriteable())
808 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
809 COFF::IMAGE_SCN_MEM_READ |
810 COFF::IMAGE_SCN_MEM_WRITE;
815 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
816 const Comdat *C = GV->getComdat();
817 assert(C && "expected GV to have a Comdat!");
819 StringRef ComdatGVName = C->getName();
820 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
822 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
823 "' does not exist.");
825 if (ComdatGV->getComdat() != C)
826 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
827 "' is not a key for its COMDAT.");
832 static int getSelectionForCOFF(const GlobalValue *GV) {
833 if (const Comdat *C = GV->getComdat()) {
834 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
835 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
836 ComdatKey = GA->getBaseObject();
837 if (ComdatKey == GV) {
838 switch (C->getSelectionKind()) {
840 return COFF::IMAGE_COMDAT_SELECT_ANY;
841 case Comdat::ExactMatch:
842 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
843 case Comdat::Largest:
844 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
845 case Comdat::NoDuplicates:
846 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
847 case Comdat::SameSize:
848 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
851 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
853 } else if (GV->isWeakForLinker()) {
854 return COFF::IMAGE_COMDAT_SELECT_ANY;
859 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
860 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
861 const TargetMachine &TM) const {
863 unsigned Characteristics = getCOFFSectionFlags(Kind);
864 StringRef Name = GV->getSection();
865 StringRef COMDATSymName = "";
866 if (GV->hasComdat()) {
867 Selection = getSelectionForCOFF(GV);
868 const GlobalValue *ComdatGV;
869 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
870 ComdatGV = getComdatGVForCOFF(GV);
874 if (!ComdatGV->hasPrivateLinkage()) {
875 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
876 COMDATSymName = Sym->getName();
877 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
882 return getContext().getCOFFSection(Name,
889 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
894 if (Kind.isThreadLocal())
896 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
901 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
902 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
903 const TargetMachine &TM) const {
904 // If we have -ffunction-sections then we should emit the global value to a
905 // uniqued section specifically for it.
906 bool EmitUniquedSection;
908 EmitUniquedSection = TM.getFunctionSections();
910 EmitUniquedSection = TM.getDataSections();
912 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
913 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
914 unsigned Characteristics = getCOFFSectionFlags(Kind);
916 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
917 int Selection = getSelectionForCOFF(GV);
919 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
920 const GlobalValue *ComdatGV;
922 ComdatGV = getComdatGVForCOFF(GV);
926 if (!ComdatGV->hasPrivateLinkage()) {
927 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
928 StringRef COMDATSymName = Sym->getName();
929 return getContext().getCOFFSection(Name, Characteristics, Kind,
930 COMDATSymName, Selection);
932 SmallString<256> TmpData;
933 getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true, Mang, TM);
934 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
942 if (Kind.isThreadLocal())
943 return TLSDataSection;
945 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
946 return ReadOnlySection;
948 // Note: we claim that common symbols are put in BSSSection, but they are
949 // really emitted with the magic .comm directive, which creates a symbol table
950 // entry but not a section.
951 if (Kind.isBSS() || Kind.isCommon())
957 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
958 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
959 bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
960 if (GV->hasPrivateLinkage() &&
961 ((isa<Function>(GV) && TM.getFunctionSections()) ||
962 (isa<GlobalVariable>(GV) && TM.getDataSections())))
963 CannotUsePrivateLabel = true;
965 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
968 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
969 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
970 // If the function can be removed, produce a unique section so that
971 // the table doesn't prevent the removal.
972 const Comdat *C = F.getComdat();
973 bool EmitUniqueSection = TM.getFunctionSections() || C;
974 if (!EmitUniqueSection)
975 return ReadOnlySection;
977 // FIXME: we should produce a symbol for F instead.
978 if (F.hasPrivateLinkage())
979 return ReadOnlySection;
981 MCSymbol *Sym = TM.getSymbol(&F, Mang);
982 StringRef COMDATSymName = Sym->getName();
984 SectionKind Kind = SectionKind::getReadOnly();
985 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
986 unsigned Characteristics = getCOFFSectionFlags(Kind);
987 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
989 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
990 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
993 StringRef TargetLoweringObjectFileCOFF::
994 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
995 const char *LibCmd = "/DEFAULTLIB:";
996 if (LinkerOption.startswith(LibCmd))
997 return LinkerOption.substr(strlen(LibCmd));
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);