1 //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements classes used to handle lowerings specific to common
11 // object file formats.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
20 #include "llvm/IR/Constants.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Function.h"
24 #include "llvm/IR/GlobalVariable.h"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCSectionCOFF.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/ELF.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetMachine.h"
40 #include "llvm/Target/TargetSubtargetInfo.h"
42 using namespace dwarf;
44 //===----------------------------------------------------------------------===//
46 //===----------------------------------------------------------------------===//
48 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
49 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
50 MachineModuleInfo *MMI) const {
51 unsigned Encoding = getPersonalityEncoding();
52 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
53 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
54 TM.getSymbol(GV, Mang)->getName());
55 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
56 return TM.getSymbol(GV, Mang);
57 report_fatal_error("We do not support this DWARF encoding yet!");
60 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
61 const TargetMachine &TM,
62 const MCSymbol *Sym) const {
63 SmallString<64> NameData("DW.ref.");
64 NameData += Sym->getName();
65 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
66 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
67 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
68 StringRef Prefix = ".data.";
69 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
70 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
71 const MCSection *Sec = getContext().getELFSection(NameData,
74 SectionKind::getDataRel(),
76 unsigned Size = TM.getSubtargetImpl()->getDataLayout()->getPointerSize();
77 Streamer.SwitchSection(Sec);
78 Streamer.EmitValueToAlignment(
79 TM.getSubtargetImpl()->getDataLayout()->getPointerABIAlignment());
80 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
81 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
82 Streamer.EmitELFSize(Label, E);
83 Streamer.EmitLabel(Label);
85 Streamer.EmitSymbolValue(Sym, Size);
88 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
89 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
90 const TargetMachine &TM, MachineModuleInfo *MMI,
91 MCStreamer &Streamer) const {
93 if (Encoding & dwarf::DW_EH_PE_indirect) {
94 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
96 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
98 // Add information about the stub reference to ELFMMI so that the stub
99 // gets emitted by the asmprinter.
100 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
101 if (!StubSym.getPointer()) {
102 MCSymbol *Sym = TM.getSymbol(GV, Mang);
103 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
106 return TargetLoweringObjectFile::
107 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
108 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
111 return TargetLoweringObjectFile::
112 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
116 getELFKindForNamedSection(StringRef Name, SectionKind K) {
117 // N.B.: The defaults used in here are no the same ones used in MC.
118 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
119 // both gas and MC will produce a section with no flags. Given
120 // section(".eh_frame") gcc will produce:
122 // .section .eh_frame,"a",@progbits
123 if (Name.empty() || Name[0] != '.') return K;
125 // Some lame default implementation based on some magic section names.
126 if (Name == ".bss" ||
127 Name.startswith(".bss.") ||
128 Name.startswith(".gnu.linkonce.b.") ||
129 Name.startswith(".llvm.linkonce.b.") ||
131 Name.startswith(".sbss.") ||
132 Name.startswith(".gnu.linkonce.sb.") ||
133 Name.startswith(".llvm.linkonce.sb."))
134 return SectionKind::getBSS();
136 if (Name == ".tdata" ||
137 Name.startswith(".tdata.") ||
138 Name.startswith(".gnu.linkonce.td.") ||
139 Name.startswith(".llvm.linkonce.td."))
140 return SectionKind::getThreadData();
142 if (Name == ".tbss" ||
143 Name.startswith(".tbss.") ||
144 Name.startswith(".gnu.linkonce.tb.") ||
145 Name.startswith(".llvm.linkonce.tb."))
146 return SectionKind::getThreadBSS();
152 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
154 if (Name == ".init_array")
155 return ELF::SHT_INIT_ARRAY;
157 if (Name == ".fini_array")
158 return ELF::SHT_FINI_ARRAY;
160 if (Name == ".preinit_array")
161 return ELF::SHT_PREINIT_ARRAY;
163 if (K.isBSS() || K.isThreadBSS())
164 return ELF::SHT_NOBITS;
166 return ELF::SHT_PROGBITS;
171 getELFSectionFlags(SectionKind K) {
175 Flags |= ELF::SHF_ALLOC;
178 Flags |= ELF::SHF_EXECINSTR;
181 Flags |= ELF::SHF_WRITE;
183 if (K.isThreadLocal())
184 Flags |= ELF::SHF_TLS;
186 // K.isMergeableConst() is left out to honour PR4650
187 if (K.isMergeableCString() || K.isMergeableConst4() ||
188 K.isMergeableConst8() || K.isMergeableConst16())
189 Flags |= ELF::SHF_MERGE;
191 if (K.isMergeableCString())
192 Flags |= ELF::SHF_STRINGS;
197 static const Comdat *getELFComdat(const GlobalValue *GV) {
198 const Comdat *C = GV->getComdat();
202 if (C->getSelectionKind() != Comdat::Any)
203 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
204 C->getName() + "' cannot be lowered.");
209 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
210 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
211 const TargetMachine &TM) const {
212 StringRef SectionName = GV->getSection();
214 // Infer section flags from the section name if we can.
215 Kind = getELFKindForNamedSection(SectionName, Kind);
217 StringRef Group = "";
218 unsigned Flags = getELFSectionFlags(Kind);
219 if (const Comdat *C = getELFComdat(GV)) {
220 Group = C->getName();
221 Flags |= ELF::SHF_GROUP;
223 return getContext().getELFSection(SectionName,
224 getELFSectionType(SectionName, Kind), Flags,
225 Kind, /*EntrySize=*/0, Group);
228 /// getSectionPrefixForGlobal - Return the section prefix name used by options
229 /// FunctionsSections and DataSections.
230 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
231 if (Kind.isText()) return ".text.";
232 if (Kind.isReadOnly()) return ".rodata.";
233 if (Kind.isBSS()) return ".bss.";
235 if (Kind.isThreadData()) return ".tdata.";
236 if (Kind.isThreadBSS()) return ".tbss.";
238 if (Kind.isDataNoRel()) return ".data.";
239 if (Kind.isDataRelLocal()) return ".data.rel.local.";
240 if (Kind.isDataRel()) return ".data.rel.";
241 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
243 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
244 return ".data.rel.ro.";
247 const MCSection *TargetLoweringObjectFileELF::
248 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
249 Mangler &Mang, const TargetMachine &TM) const {
250 // If we have -ffunction-section or -fdata-section then we should emit the
251 // global value to a uniqued section specifically for it.
252 bool EmitUniquedSection;
254 EmitUniquedSection = TM.getFunctionSections();
256 EmitUniquedSection = TM.getDataSections();
258 // If this global is linkonce/weak and the target handles this by emitting it
259 // into a 'uniqued' section name, create and return the section now.
260 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
261 StringRef Prefix = getSectionPrefixForGlobal(Kind);
263 SmallString<128> Name(Prefix);
264 TM.getNameWithPrefix(Name, GV, Mang, true);
266 StringRef Group = "";
267 unsigned Flags = getELFSectionFlags(Kind);
268 if (const Comdat *C = getELFComdat(GV)) {
269 Flags |= ELF::SHF_GROUP;
270 Group = C->getName();
273 return getContext().getELFSection(Name.str(),
274 getELFSectionType(Name.str(), Kind),
275 Flags, Kind, 0, Group);
278 if (Kind.isText()) return TextSection;
280 if (Kind.isMergeable1ByteCString() ||
281 Kind.isMergeable2ByteCString() ||
282 Kind.isMergeable4ByteCString()) {
284 // We also need alignment here.
285 // FIXME: this is getting the alignment of the character, not the
286 // alignment of the global!
288 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
289 cast<GlobalVariable>(GV));
291 const char *SizeSpec = ".rodata.str1.";
292 if (Kind.isMergeable2ByteCString())
293 SizeSpec = ".rodata.str2.";
294 else if (Kind.isMergeable4ByteCString())
295 SizeSpec = ".rodata.str4.";
297 assert(Kind.isMergeable1ByteCString() && "unknown string width");
300 std::string Name = SizeSpec + utostr(Align);
301 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
308 if (Kind.isMergeableConst()) {
309 if (Kind.isMergeableConst4() && MergeableConst4Section)
310 return MergeableConst4Section;
311 if (Kind.isMergeableConst8() && MergeableConst8Section)
312 return MergeableConst8Section;
313 if (Kind.isMergeableConst16() && MergeableConst16Section)
314 return MergeableConst16Section;
315 return ReadOnlySection; // .const
318 if (Kind.isReadOnly()) return ReadOnlySection;
320 if (Kind.isThreadData()) return TLSDataSection;
321 if (Kind.isThreadBSS()) return TLSBSSSection;
323 // Note: we claim that common symbols are put in BSSSection, but they are
324 // really emitted with the magic .comm directive, which creates a symbol table
325 // entry but not a section.
326 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
328 if (Kind.isDataNoRel()) return DataSection;
329 if (Kind.isDataRelLocal()) return DataRelLocalSection;
330 if (Kind.isDataRel()) return DataRelSection;
331 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
333 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
334 return DataRelROSection;
337 /// getSectionForConstant - Given a mergeable constant with the
338 /// specified size and relocation information, return a section that it
339 /// should be placed in.
341 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
342 const Constant *C) const {
343 if (Kind.isMergeableConst4() && MergeableConst4Section)
344 return MergeableConst4Section;
345 if (Kind.isMergeableConst8() && MergeableConst8Section)
346 return MergeableConst8Section;
347 if (Kind.isMergeableConst16() && MergeableConst16Section)
348 return MergeableConst16Section;
349 if (Kind.isReadOnly())
350 return ReadOnlySection;
352 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
353 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
354 return DataRelROSection;
357 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
361 const MCSymbol *KeySym) {
364 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
365 SectionKind Kind = SectionKind::getDataRel();
366 StringRef COMDAT = KeySym ? KeySym->getName() : "";
369 Flags |= ELF::SHF_GROUP;
373 Type = ELF::SHT_INIT_ARRAY;
374 Name = ".init_array";
376 Type = ELF::SHT_FINI_ARRAY;
377 Name = ".fini_array";
379 if (Priority != 65535) {
381 Name += utostr(Priority);
384 // The default scheme is .ctor / .dtor, so we have to invert the priority
390 if (Priority != 65535) {
392 Name += utostr(65535 - Priority);
394 Type = ELF::SHT_PROGBITS;
397 return Ctx.getELFSection(Name, Type, Flags, Kind, 0, COMDAT);
400 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
401 unsigned Priority, const MCSymbol *KeySym) const {
402 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
406 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
407 unsigned Priority, const MCSymbol *KeySym) const {
408 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
413 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
414 UseInitArray = UseInitArray_;
419 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
422 SectionKind::getDataRel());
424 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
427 SectionKind::getDataRel());
430 //===----------------------------------------------------------------------===//
432 //===----------------------------------------------------------------------===//
434 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
435 /// option string. Returns StringRef() if the option does not specify a library.
436 StringRef TargetLoweringObjectFileMachO::
437 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
438 const char *LibCmd = "-l";
439 if (LinkerOption.startswith(LibCmd))
440 return LinkerOption.substr(strlen(LibCmd));
444 /// emitModuleFlags - Perform code emission for module flags.
445 void TargetLoweringObjectFileMachO::
446 emitModuleFlags(MCStreamer &Streamer,
447 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
448 Mangler &Mang, const TargetMachine &TM) const {
449 unsigned VersionVal = 0;
450 unsigned ImageInfoFlags = 0;
451 MDNode *LinkerOptions = nullptr;
452 StringRef SectionVal;
454 for (ArrayRef<Module::ModuleFlagEntry>::iterator
455 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
456 const Module::ModuleFlagEntry &MFE = *i;
458 // Ignore flags with 'Require' behavior.
459 if (MFE.Behavior == Module::Require)
462 StringRef Key = MFE.Key->getString();
463 Metadata *Val = MFE.Val;
465 if (Key == "Objective-C Image Info Version") {
466 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
467 } else if (Key == "Objective-C Garbage Collection" ||
468 Key == "Objective-C GC Only" ||
469 Key == "Objective-C Is Simulated" ||
470 Key == "Objective-C Image Swift Version") {
471 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
472 } else if (Key == "Objective-C Image Info Section") {
473 SectionVal = cast<MDString>(Val)->getString();
474 } else if (Key == "Linker Options") {
475 LinkerOptions = cast<MDNode>(Val);
479 // Emit the linker options if present.
481 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
482 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
483 SmallVector<std::string, 4> StrOptions;
485 // Convert to strings.
486 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
487 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
488 StrOptions.push_back(MDOption->getString());
491 Streamer.EmitLinkerOptions(StrOptions);
495 // The section is mandatory. If we don't have it, then we don't have GC info.
496 if (SectionVal.empty()) return;
498 StringRef Segment, Section;
499 unsigned TAA = 0, StubSize = 0;
501 std::string ErrorCode =
502 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
503 TAA, TAAParsed, StubSize);
504 if (!ErrorCode.empty())
505 // If invalid, report the error with report_fatal_error.
506 report_fatal_error("Invalid section specifier '" + Section + "': " +
510 const MCSectionMachO *S =
511 getContext().getMachOSection(Segment, Section, TAA, StubSize,
512 SectionKind::getDataNoRel());
513 Streamer.SwitchSection(S);
514 Streamer.EmitLabel(getContext().
515 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
516 Streamer.EmitIntValue(VersionVal, 4);
517 Streamer.EmitIntValue(ImageInfoFlags, 4);
518 Streamer.AddBlankLine();
521 static void checkMachOComdat(const GlobalValue *GV) {
522 const Comdat *C = GV->getComdat();
526 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
527 "' cannot be lowered.");
530 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
531 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
532 const TargetMachine &TM) const {
533 // Parse the section specifier and create it if valid.
534 StringRef Segment, Section;
535 unsigned TAA = 0, StubSize = 0;
538 checkMachOComdat(GV);
540 std::string ErrorCode =
541 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
542 TAA, TAAParsed, StubSize);
543 if (!ErrorCode.empty()) {
544 // If invalid, report the error with report_fatal_error.
545 report_fatal_error("Global variable '" + GV->getName() +
546 "' has an invalid section specifier '" +
547 GV->getSection() + "': " + ErrorCode + ".");
551 const MCSectionMachO *S =
552 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
554 // If TAA wasn't set by ParseSectionSpecifier() above,
555 // use the value returned by getMachOSection() as a default.
557 TAA = S->getTypeAndAttributes();
559 // Okay, now that we got the section, verify that the TAA & StubSize agree.
560 // If the user declared multiple globals with different section flags, we need
561 // to reject it here.
562 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
563 // If invalid, report the error with report_fatal_error.
564 report_fatal_error("Global variable '" + GV->getName() +
565 "' section type or attributes does not match previous"
566 " section specifier");
572 const MCSection *TargetLoweringObjectFileMachO::
573 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
574 Mangler &Mang, const TargetMachine &TM) const {
575 checkMachOComdat(GV);
577 // Handle thread local data.
578 if (Kind.isThreadBSS()) return TLSBSSSection;
579 if (Kind.isThreadData()) return TLSDataSection;
582 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
584 // If this is weak/linkonce, put this in a coalescable section, either in text
585 // or data depending on if it is writable.
586 if (GV->isWeakForLinker()) {
587 if (Kind.isReadOnly())
588 return ConstTextCoalSection;
589 return DataCoalSection;
592 // FIXME: Alignment check should be handled by section classifier.
593 if (Kind.isMergeable1ByteCString() &&
594 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
595 cast<GlobalVariable>(GV)) < 32)
596 return CStringSection;
598 // Do not put 16-bit arrays in the UString section if they have an
599 // externally visible label, this runs into issues with certain linker
601 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
602 TM.getSubtargetImpl()->getDataLayout()->getPreferredAlignment(
603 cast<GlobalVariable>(GV)) < 32)
604 return UStringSection;
606 // With MachO only variables whose corresponding symbol starts with 'l' or
607 // 'L' can be merged, so we only try merging GVs with private linkage.
608 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
609 if (Kind.isMergeableConst4())
610 return FourByteConstantSection;
611 if (Kind.isMergeableConst8())
612 return EightByteConstantSection;
613 if (Kind.isMergeableConst16())
614 return SixteenByteConstantSection;
617 // Otherwise, if it is readonly, but not something we can specially optimize,
618 // just drop it in .const.
619 if (Kind.isReadOnly())
620 return ReadOnlySection;
622 // If this is marked const, put it into a const section. But if the dynamic
623 // linker needs to write to it, put it in the data segment.
624 if (Kind.isReadOnlyWithRel())
625 return ConstDataSection;
627 // Put zero initialized globals with strong external linkage in the
628 // DATA, __common section with the .zerofill directive.
629 if (Kind.isBSSExtern())
630 return DataCommonSection;
632 // Put zero initialized globals with local linkage in __DATA,__bss directive
633 // with the .zerofill directive (aka .lcomm).
634 if (Kind.isBSSLocal())
635 return DataBSSSection;
637 // Otherwise, just drop the variable in the normal data section.
642 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
643 const Constant *C) const {
644 // If this constant requires a relocation, we have to put it in the data
645 // segment, not in the text segment.
646 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
647 return ConstDataSection;
649 if (Kind.isMergeableConst4())
650 return FourByteConstantSection;
651 if (Kind.isMergeableConst8())
652 return EightByteConstantSection;
653 if (Kind.isMergeableConst16())
654 return SixteenByteConstantSection;
655 return ReadOnlySection; // .const
658 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
659 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
660 const TargetMachine &TM, MachineModuleInfo *MMI,
661 MCStreamer &Streamer) const {
662 // The mach-o version of this method defaults to returning a stub reference.
664 if (Encoding & DW_EH_PE_indirect) {
665 MachineModuleInfoMachO &MachOMMI =
666 MMI->getObjFileInfo<MachineModuleInfoMachO>();
669 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
671 // Add information about the stub reference to MachOMMI so that the stub
672 // gets emitted by the asmprinter.
673 MachineModuleInfoImpl::StubValueTy &StubSym =
674 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
675 MachOMMI.getGVStubEntry(SSym);
676 if (!StubSym.getPointer()) {
677 MCSymbol *Sym = TM.getSymbol(GV, Mang);
678 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
681 return TargetLoweringObjectFile::
682 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
683 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
686 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
690 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
691 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
692 MachineModuleInfo *MMI) const {
693 // The mach-o version of this method defaults to returning a stub reference.
694 MachineModuleInfoMachO &MachOMMI =
695 MMI->getObjFileInfo<MachineModuleInfoMachO>();
697 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
699 // Add information about the stub reference to MachOMMI so that the stub
700 // gets emitted by the asmprinter.
701 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
702 if (!StubSym.getPointer()) {
703 MCSymbol *Sym = TM.getSymbol(GV, Mang);
704 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
710 //===----------------------------------------------------------------------===//
712 //===----------------------------------------------------------------------===//
715 getCOFFSectionFlags(SectionKind K) {
720 COFF::IMAGE_SCN_MEM_DISCARDABLE;
723 COFF::IMAGE_SCN_MEM_EXECUTE |
724 COFF::IMAGE_SCN_MEM_READ |
725 COFF::IMAGE_SCN_CNT_CODE;
728 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
729 COFF::IMAGE_SCN_MEM_READ |
730 COFF::IMAGE_SCN_MEM_WRITE;
731 else if (K.isThreadLocal())
733 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
734 COFF::IMAGE_SCN_MEM_READ |
735 COFF::IMAGE_SCN_MEM_WRITE;
736 else if (K.isReadOnly() || K.isReadOnlyWithRel())
738 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
739 COFF::IMAGE_SCN_MEM_READ;
740 else if (K.isWriteable())
742 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
743 COFF::IMAGE_SCN_MEM_READ |
744 COFF::IMAGE_SCN_MEM_WRITE;
749 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
750 const Comdat *C = GV->getComdat();
751 assert(C && "expected GV to have a Comdat!");
753 StringRef ComdatGVName = C->getName();
754 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
756 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
757 "' does not exist.");
759 if (ComdatGV->getComdat() != C)
760 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
761 "' is not a key for its COMDAT.");
766 static int getSelectionForCOFF(const GlobalValue *GV) {
767 if (const Comdat *C = GV->getComdat()) {
768 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
769 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
770 ComdatKey = GA->getBaseObject();
771 if (ComdatKey == GV) {
772 switch (C->getSelectionKind()) {
774 return COFF::IMAGE_COMDAT_SELECT_ANY;
775 case Comdat::ExactMatch:
776 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
777 case Comdat::Largest:
778 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
779 case Comdat::NoDuplicates:
780 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
781 case Comdat::SameSize:
782 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
785 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
787 } else if (GV->isWeakForLinker()) {
788 return COFF::IMAGE_COMDAT_SELECT_ANY;
793 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
794 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
795 const TargetMachine &TM) const {
797 unsigned Characteristics = getCOFFSectionFlags(Kind);
798 StringRef Name = GV->getSection();
799 StringRef COMDATSymName = "";
800 if (GV->hasComdat()) {
801 Selection = getSelectionForCOFF(GV);
802 const GlobalValue *ComdatGV;
803 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
804 ComdatGV = getComdatGVForCOFF(GV);
808 if (!ComdatGV->hasPrivateLinkage()) {
809 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
810 COMDATSymName = Sym->getName();
811 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
816 return getContext().getCOFFSection(Name,
823 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
828 if (Kind.isThreadLocal())
830 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
836 const MCSection *TargetLoweringObjectFileCOFF::
837 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
838 Mangler &Mang, const TargetMachine &TM) const {
839 // If we have -ffunction-sections then we should emit the global value to a
840 // uniqued section specifically for it.
841 bool EmitUniquedSection;
843 EmitUniquedSection = TM.getFunctionSections();
845 EmitUniquedSection = TM.getDataSections();
847 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
848 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
849 unsigned Characteristics = getCOFFSectionFlags(Kind);
851 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
852 int Selection = getSelectionForCOFF(GV);
854 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
855 const GlobalValue *ComdatGV;
857 ComdatGV = getComdatGVForCOFF(GV);
861 if (!ComdatGV->hasPrivateLinkage()) {
862 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
863 StringRef COMDATSymName = Sym->getName();
864 return getContext().getCOFFSection(Name, Characteristics, Kind,
865 COMDATSymName, Selection);
872 if (Kind.isThreadLocal())
873 return TLSDataSection;
875 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
876 return ReadOnlySection;
878 // Note: we claim that common symbols are put in BSSSection, but they are
879 // really emitted with the magic .comm directive, which creates a symbol table
880 // entry but not a section.
881 if (Kind.isBSS() || Kind.isCommon())
887 StringRef TargetLoweringObjectFileCOFF::
888 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
889 const char *LibCmd = "/DEFAULTLIB:";
890 if (LinkerOption.startswith(LibCmd))
891 return LinkerOption.substr(strlen(LibCmd));
895 void TargetLoweringObjectFileCOFF::
896 emitModuleFlags(MCStreamer &Streamer,
897 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
898 Mangler &Mang, const TargetMachine &TM) const {
899 MDNode *LinkerOptions = nullptr;
901 // Look for the "Linker Options" flag, since it's the only one we support.
902 for (ArrayRef<Module::ModuleFlagEntry>::iterator
903 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
904 const Module::ModuleFlagEntry &MFE = *i;
905 StringRef Key = MFE.Key->getString();
906 Metadata *Val = MFE.Val;
907 if (Key == "Linker Options") {
908 LinkerOptions = cast<MDNode>(Val);
915 // Emit the linker options to the linker .drectve section. According to the
916 // spec, this section is a space-separated string containing flags for linker.
917 const MCSection *Sec = getDrectveSection();
918 Streamer.SwitchSection(Sec);
919 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
920 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
921 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
922 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
923 StringRef Op = MDOption->getString();
924 // Lead with a space for consistency with our dllexport implementation.
925 std::string Escaped(" ");
926 if (!Op.startswith("\"") && (Op.find(" ") != StringRef::npos)) {
927 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
928 // how to escape quotes, but it probably uses this algorithm:
929 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
930 // FIXME: Reuse escaping code from Support/Windows/Program.inc
931 Escaped.push_back('\"');
933 Escaped.push_back('\"');
937 Streamer.EmitBytes(Escaped);
942 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
943 unsigned Priority, const MCSymbol *KeySym) const {
944 return getContext().getAssociativeCOFFSection(
945 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
948 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
949 unsigned Priority, const MCSymbol *KeySym) const {
950 return getContext().getAssociativeCOFFSection(
951 cast<MCSectionCOFF>(StaticDtorSection), KeySym);