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(
62 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
63 SmallString<64> NameData("DW.ref.");
64 NameData += Sym->getName();
66 cast<MCSymbolELF>(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 = DL.getPointerSize();
75 Streamer.SwitchSection(Sec);
76 Streamer.EmitValueToAlignment(DL.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!
284 unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
285 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.
352 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
353 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
354 if (Kind.isMergeableConst4() && MergeableConst4Section)
355 return MergeableConst4Section;
356 if (Kind.isMergeableConst8() && MergeableConst8Section)
357 return MergeableConst8Section;
358 if (Kind.isMergeableConst16() && MergeableConst16Section)
359 return MergeableConst16Section;
360 if (Kind.isReadOnly())
361 return ReadOnlySection;
363 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
364 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
365 return DataRelROSection;
368 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
369 bool IsCtor, unsigned Priority,
370 const MCSymbol *KeySym) {
373 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
374 StringRef COMDAT = KeySym ? KeySym->getName() : "";
377 Flags |= ELF::SHF_GROUP;
381 Type = ELF::SHT_INIT_ARRAY;
382 Name = ".init_array";
384 Type = ELF::SHT_FINI_ARRAY;
385 Name = ".fini_array";
387 if (Priority != 65535) {
389 Name += utostr(Priority);
392 // The default scheme is .ctor / .dtor, so we have to invert the priority
398 if (Priority != 65535) {
400 Name += utostr(65535 - Priority);
402 Type = ELF::SHT_PROGBITS;
405 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
408 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
409 unsigned Priority, const MCSymbol *KeySym) const {
410 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
414 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
415 unsigned Priority, const MCSymbol *KeySym) const {
416 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
421 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
422 UseInitArray = UseInitArray_;
426 StaticCtorSection = getContext().getELFSection(
427 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
428 StaticDtorSection = getContext().getELFSection(
429 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
432 //===----------------------------------------------------------------------===//
434 //===----------------------------------------------------------------------===//
436 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
437 : TargetLoweringObjectFile() {
438 SupportIndirectSymViaGOTPCRel = true;
441 /// emitModuleFlags - Perform code emission for module flags.
442 void TargetLoweringObjectFileMachO::
443 emitModuleFlags(MCStreamer &Streamer,
444 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
445 Mangler &Mang, const TargetMachine &TM) const {
446 unsigned VersionVal = 0;
447 unsigned ImageInfoFlags = 0;
448 MDNode *LinkerOptions = nullptr;
449 StringRef SectionVal;
451 for (ArrayRef<Module::ModuleFlagEntry>::iterator
452 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
453 const Module::ModuleFlagEntry &MFE = *i;
455 // Ignore flags with 'Require' behavior.
456 if (MFE.Behavior == Module::Require)
459 StringRef Key = MFE.Key->getString();
460 Metadata *Val = MFE.Val;
462 if (Key == "Objective-C Image Info Version") {
463 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
464 } else if (Key == "Objective-C Garbage Collection" ||
465 Key == "Objective-C GC Only" ||
466 Key == "Objective-C Is Simulated" ||
467 Key == "Objective-C Image Swift Version") {
468 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
469 } else if (Key == "Objective-C Image Info Section") {
470 SectionVal = cast<MDString>(Val)->getString();
471 } else if (Key == "Linker Options") {
472 LinkerOptions = cast<MDNode>(Val);
476 // Emit the linker options if present.
478 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
479 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
480 SmallVector<std::string, 4> StrOptions;
482 // Convert to strings.
483 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
484 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
485 StrOptions.push_back(MDOption->getString());
488 Streamer.EmitLinkerOptions(StrOptions);
492 // The section is mandatory. If we don't have it, then we don't have GC info.
493 if (SectionVal.empty()) return;
495 StringRef Segment, Section;
496 unsigned TAA = 0, StubSize = 0;
498 std::string ErrorCode =
499 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
500 TAA, TAAParsed, StubSize);
501 if (!ErrorCode.empty())
502 // If invalid, report the error with report_fatal_error.
503 report_fatal_error("Invalid section specifier '" + Section + "': " +
507 MCSectionMachO *S = getContext().getMachOSection(
508 Segment, Section, TAA, StubSize, SectionKind::getDataNoRel());
509 Streamer.SwitchSection(S);
510 Streamer.EmitLabel(getContext().
511 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
512 Streamer.EmitIntValue(VersionVal, 4);
513 Streamer.EmitIntValue(ImageInfoFlags, 4);
514 Streamer.AddBlankLine();
517 static void checkMachOComdat(const GlobalValue *GV) {
518 const Comdat *C = GV->getComdat();
522 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
523 "' cannot be lowered.");
526 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
527 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
528 const TargetMachine &TM) const {
529 // Parse the section specifier and create it if valid.
530 StringRef Segment, Section;
531 unsigned TAA = 0, StubSize = 0;
534 checkMachOComdat(GV);
536 std::string ErrorCode =
537 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
538 TAA, TAAParsed, StubSize);
539 if (!ErrorCode.empty()) {
540 // If invalid, report the error with report_fatal_error.
541 report_fatal_error("Global variable '" + GV->getName() +
542 "' has an invalid section specifier '" +
543 GV->getSection() + "': " + ErrorCode + ".");
548 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
550 // If TAA wasn't set by ParseSectionSpecifier() above,
551 // use the value returned by getMachOSection() as a default.
553 TAA = S->getTypeAndAttributes();
555 // Okay, now that we got the section, verify that the TAA & StubSize agree.
556 // If the user declared multiple globals with different section flags, we need
557 // to reject it here.
558 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
559 // If invalid, report the error with report_fatal_error.
560 report_fatal_error("Global variable '" + GV->getName() +
561 "' section type or attributes does not match previous"
562 " section specifier");
568 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
569 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
570 const TargetMachine &TM) const {
571 checkMachOComdat(GV);
573 // Handle thread local data.
574 if (Kind.isThreadBSS()) return TLSBSSSection;
575 if (Kind.isThreadData()) return TLSDataSection;
578 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
580 // If this is weak/linkonce, put this in a coalescable section, either in text
581 // or data depending on if it is writable.
582 if (GV->isWeakForLinker()) {
583 if (Kind.isReadOnly())
584 return ConstTextCoalSection;
585 return DataCoalSection;
588 // FIXME: Alignment check should be handled by section classifier.
589 if (Kind.isMergeable1ByteCString() &&
590 GV->getParent()->getDataLayout().getPreferredAlignment(
591 cast<GlobalVariable>(GV)) < 32)
592 return CStringSection;
594 // Do not put 16-bit arrays in the UString section if they have an
595 // externally visible label, this runs into issues with certain linker
597 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
598 GV->getParent()->getDataLayout().getPreferredAlignment(
599 cast<GlobalVariable>(GV)) < 32)
600 return UStringSection;
602 // With MachO only variables whose corresponding symbol starts with 'l' or
603 // 'L' can be merged, so we only try merging GVs with private linkage.
604 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
605 if (Kind.isMergeableConst4())
606 return FourByteConstantSection;
607 if (Kind.isMergeableConst8())
608 return EightByteConstantSection;
609 if (Kind.isMergeableConst16())
610 return SixteenByteConstantSection;
613 // Otherwise, if it is readonly, but not something we can specially optimize,
614 // just drop it in .const.
615 if (Kind.isReadOnly())
616 return ReadOnlySection;
618 // If this is marked const, put it into a const section. But if the dynamic
619 // linker needs to write to it, put it in the data segment.
620 if (Kind.isReadOnlyWithRel())
621 return ConstDataSection;
623 // Put zero initialized globals with strong external linkage in the
624 // DATA, __common section with the .zerofill directive.
625 if (Kind.isBSSExtern())
626 return DataCommonSection;
628 // Put zero initialized globals with local linkage in __DATA,__bss directive
629 // with the .zerofill directive (aka .lcomm).
630 if (Kind.isBSSLocal())
631 return DataBSSSection;
633 // Otherwise, just drop the variable in the normal data section.
637 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
638 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
639 // If this constant requires a relocation, we have to put it in the data
640 // segment, not in the text segment.
641 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
642 return ConstDataSection;
644 if (Kind.isMergeableConst4())
645 return FourByteConstantSection;
646 if (Kind.isMergeableConst8())
647 return EightByteConstantSection;
648 if (Kind.isMergeableConst16())
649 return SixteenByteConstantSection;
650 return ReadOnlySection; // .const
653 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
654 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
655 const TargetMachine &TM, MachineModuleInfo *MMI,
656 MCStreamer &Streamer) const {
657 // The mach-o version of this method defaults to returning a stub reference.
659 if (Encoding & DW_EH_PE_indirect) {
660 MachineModuleInfoMachO &MachOMMI =
661 MMI->getObjFileInfo<MachineModuleInfoMachO>();
664 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
666 // Add information about the stub reference to MachOMMI so that the stub
667 // gets emitted by the asmprinter.
668 MachineModuleInfoImpl::StubValueTy &StubSym =
669 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
670 MachOMMI.getGVStubEntry(SSym);
671 if (!StubSym.getPointer()) {
672 MCSymbol *Sym = TM.getSymbol(GV, Mang);
673 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
676 return TargetLoweringObjectFile::
677 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
678 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
681 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
685 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
686 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
687 MachineModuleInfo *MMI) const {
688 // The mach-o version of this method defaults to returning a stub reference.
689 MachineModuleInfoMachO &MachOMMI =
690 MMI->getObjFileInfo<MachineModuleInfoMachO>();
692 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
694 // Add information about the stub reference to MachOMMI so that the stub
695 // gets emitted by the asmprinter.
696 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
697 if (!StubSym.getPointer()) {
698 MCSymbol *Sym = TM.getSymbol(GV, Mang);
699 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
705 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
706 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
707 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
708 // Although MachO 32-bit targets do not explictly have a GOTPCREL relocation
709 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
710 // through a non_lazy_ptr stub instead. One advantage is that it allows the
711 // computation of deltas to final external symbols. Example:
717 // .long _extgotequiv-_delta
719 // is transformed to:
722 // .long L_extfoo$non_lazy_ptr-(_delta+0)
724 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
725 // L_extfoo$non_lazy_ptr:
726 // .indirect_symbol _extfoo
729 MachineModuleInfoMachO &MachOMMI =
730 MMI->getObjFileInfo<MachineModuleInfoMachO>();
731 MCContext &Ctx = getContext();
733 // The offset must consider the original displacement from the base symbol
734 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
735 Offset = -MV.getConstant();
736 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
738 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
739 // non_lazy_ptr stubs.
740 SmallString<128> Name;
741 StringRef Suffix = "$non_lazy_ptr";
742 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
743 Name += Sym->getName();
745 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
747 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
748 if (!StubSym.getPointer())
749 StubSym = MachineModuleInfoImpl::
750 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
752 const MCExpr *BSymExpr =
753 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
755 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
758 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
761 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
762 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
765 //===----------------------------------------------------------------------===//
767 //===----------------------------------------------------------------------===//
770 getCOFFSectionFlags(SectionKind K) {
775 COFF::IMAGE_SCN_MEM_DISCARDABLE;
778 COFF::IMAGE_SCN_MEM_EXECUTE |
779 COFF::IMAGE_SCN_MEM_READ |
780 COFF::IMAGE_SCN_CNT_CODE;
783 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
784 COFF::IMAGE_SCN_MEM_READ |
785 COFF::IMAGE_SCN_MEM_WRITE;
786 else if (K.isThreadLocal())
788 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
789 COFF::IMAGE_SCN_MEM_READ |
790 COFF::IMAGE_SCN_MEM_WRITE;
791 else if (K.isReadOnly() || K.isReadOnlyWithRel())
793 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
794 COFF::IMAGE_SCN_MEM_READ;
795 else if (K.isWriteable())
797 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
798 COFF::IMAGE_SCN_MEM_READ |
799 COFF::IMAGE_SCN_MEM_WRITE;
804 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
805 const Comdat *C = GV->getComdat();
806 assert(C && "expected GV to have a Comdat!");
808 StringRef ComdatGVName = C->getName();
809 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
811 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
812 "' does not exist.");
814 if (ComdatGV->getComdat() != C)
815 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
816 "' is not a key for its COMDAT.");
821 static int getSelectionForCOFF(const GlobalValue *GV) {
822 if (const Comdat *C = GV->getComdat()) {
823 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
824 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
825 ComdatKey = GA->getBaseObject();
826 if (ComdatKey == GV) {
827 switch (C->getSelectionKind()) {
829 return COFF::IMAGE_COMDAT_SELECT_ANY;
830 case Comdat::ExactMatch:
831 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
832 case Comdat::Largest:
833 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
834 case Comdat::NoDuplicates:
835 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
836 case Comdat::SameSize:
837 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
840 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
846 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
847 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
848 const TargetMachine &TM) const {
850 unsigned Characteristics = getCOFFSectionFlags(Kind);
851 StringRef Name = GV->getSection();
852 StringRef COMDATSymName = "";
853 if (GV->hasComdat()) {
854 Selection = getSelectionForCOFF(GV);
855 const GlobalValue *ComdatGV;
856 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
857 ComdatGV = getComdatGVForCOFF(GV);
861 if (!ComdatGV->hasPrivateLinkage()) {
862 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
863 COMDATSymName = Sym->getName();
864 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
869 return getContext().getCOFFSection(Name,
876 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
881 if (Kind.isThreadLocal())
883 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
888 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
889 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
890 const TargetMachine &TM) const {
891 // If we have -ffunction-sections then we should emit the global value to a
892 // uniqued section specifically for it.
893 bool EmitUniquedSection;
895 EmitUniquedSection = TM.getFunctionSections();
897 EmitUniquedSection = TM.getDataSections();
899 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
900 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
901 unsigned Characteristics = getCOFFSectionFlags(Kind);
903 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
904 int Selection = getSelectionForCOFF(GV);
906 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
907 const GlobalValue *ComdatGV;
909 ComdatGV = getComdatGVForCOFF(GV);
913 if (!ComdatGV->hasPrivateLinkage()) {
914 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
915 StringRef COMDATSymName = Sym->getName();
916 return getContext().getCOFFSection(Name, Characteristics, Kind,
917 COMDATSymName, Selection);
919 SmallString<256> TmpData;
920 getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true, Mang, TM);
921 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
929 if (Kind.isThreadLocal())
930 return TLSDataSection;
932 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
933 return ReadOnlySection;
935 // Note: we claim that common symbols are put in BSSSection, but they are
936 // really emitted with the magic .comm directive, which creates a symbol table
937 // entry but not a section.
938 if (Kind.isBSS() || Kind.isCommon())
944 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
945 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
946 bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
947 if (GV->hasPrivateLinkage() &&
948 ((isa<Function>(GV) && TM.getFunctionSections()) ||
949 (isa<GlobalVariable>(GV) && TM.getDataSections())))
950 CannotUsePrivateLabel = true;
952 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
955 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
956 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
957 // If the function can be removed, produce a unique section so that
958 // the table doesn't prevent the removal.
959 const Comdat *C = F.getComdat();
960 bool EmitUniqueSection = TM.getFunctionSections() || C;
961 if (!EmitUniqueSection)
962 return ReadOnlySection;
964 // FIXME: we should produce a symbol for F instead.
965 if (F.hasPrivateLinkage())
966 return ReadOnlySection;
968 MCSymbol *Sym = TM.getSymbol(&F, Mang);
969 StringRef COMDATSymName = Sym->getName();
971 SectionKind Kind = SectionKind::getReadOnly();
972 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
973 unsigned Characteristics = getCOFFSectionFlags(Kind);
974 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
976 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
977 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
980 void TargetLoweringObjectFileCOFF::
981 emitModuleFlags(MCStreamer &Streamer,
982 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
983 Mangler &Mang, const TargetMachine &TM) const {
984 MDNode *LinkerOptions = nullptr;
986 // Look for the "Linker Options" flag, since it's the only one we support.
987 for (ArrayRef<Module::ModuleFlagEntry>::iterator
988 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
989 const Module::ModuleFlagEntry &MFE = *i;
990 StringRef Key = MFE.Key->getString();
991 Metadata *Val = MFE.Val;
992 if (Key == "Linker Options") {
993 LinkerOptions = cast<MDNode>(Val);
1000 // Emit the linker options to the linker .drectve section. According to the
1001 // spec, this section is a space-separated string containing flags for linker.
1002 MCSection *Sec = getDrectveSection();
1003 Streamer.SwitchSection(Sec);
1004 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1005 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1006 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1007 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
1008 // Lead with a space for consistency with our dllexport implementation.
1009 std::string Directive(" ");
1010 Directive.append(MDOption->getString());
1011 Streamer.EmitBytes(Directive);
1016 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1017 unsigned Priority, const MCSymbol *KeySym) const {
1018 return getContext().getAssociativeCOFFSection(
1019 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
1022 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1023 unsigned Priority, const MCSymbol *KeySym) const {
1024 return getContext().getAssociativeCOFFSection(
1025 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
1028 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1029 raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
1030 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1033 const Triple &TT = getTargetTriple();
1035 if (TT.isKnownWindowsMSVCEnvironment())
1040 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1042 raw_string_ostream FlagOS(Flag);
1043 Mang.getNameWithPrefix(FlagOS, GV, false);
1045 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
1046 OS << Flag.substr(1);
1050 Mang.getNameWithPrefix(OS, GV, false);
1053 if (!GV->getValueType()->isFunctionTy()) {
1054 if (TT.isKnownWindowsMSVCEnvironment())