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,
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;
169 getELFSectionFlags(SectionKind K, bool InCOMDAT) {
173 Flags |= ELF::SHF_ALLOC;
176 Flags |= ELF::SHF_EXECINSTR;
179 Flags |= ELF::SHF_WRITE;
181 if (K.isThreadLocal())
182 Flags |= ELF::SHF_TLS;
184 if (!InCOMDAT && (K.isMergeableCString() || K.isMergeableConst()))
185 Flags |= ELF::SHF_MERGE;
187 if (K.isMergeableCString())
188 Flags |= ELF::SHF_STRINGS;
193 static const Comdat *getELFComdat(const GlobalValue *GV) {
194 const Comdat *C = GV->getComdat();
198 if (C->getSelectionKind() != Comdat::Any)
199 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
200 C->getName() + "' cannot be lowered.");
205 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
206 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
207 const TargetMachine &TM) const {
208 StringRef SectionName = GV->getSection();
210 // Infer section flags from the section name if we can.
211 Kind = getELFKindForNamedSection(SectionName, Kind);
213 StringRef Group = "";
214 unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
215 if (const Comdat *C = getELFComdat(GV)) {
216 Group = C->getName();
217 Flags |= ELF::SHF_GROUP;
219 return getContext().getELFSection(SectionName,
220 getELFSectionType(SectionName, Kind), Flags,
221 /*EntrySize=*/0, Group);
224 /// getSectionPrefixForGlobal - Return the section prefix name used by options
225 /// FunctionsSections and DataSections.
226 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
227 if (Kind.isText()) return ".text.";
228 if (Kind.isReadOnly()) return ".rodata.";
229 if (Kind.isBSS()) return ".bss.";
231 if (Kind.isThreadData()) return ".tdata.";
232 if (Kind.isThreadBSS()) return ".tbss.";
234 if (Kind.isDataNoRel()) return ".data.";
235 if (Kind.isDataRelLocal()) return ".data.rel.local.";
236 if (Kind.isDataRel()) return ".data.rel.";
237 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
239 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
240 return ".data.rel.ro.";
243 const MCSection *TargetLoweringObjectFileELF::
244 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
245 Mangler &Mang, const TargetMachine &TM) const {
246 unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
248 // If we have -ffunction-section or -fdata-section then we should emit the
249 // global value to a uniqued section specifically for it.
250 bool EmitUniquedSection = false;
251 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
253 EmitUniquedSection = TM.getFunctionSections();
255 EmitUniquedSection = TM.getDataSections();
258 if (EmitUniquedSection || GV->hasComdat()) {
259 StringRef Prefix = getSectionPrefixForGlobal(Kind);
261 SmallString<128> Name(Prefix);
262 TM.getNameWithPrefix(Name, GV, Mang, true);
264 StringRef Group = "";
265 if (const Comdat *C = getELFComdat(GV)) {
266 Flags |= ELF::SHF_GROUP;
267 Group = C->getName();
270 return getContext().getELFSection(
271 Name.str(), getELFSectionType(Name.str(), Kind), Flags, 0, Group);
274 if (Kind.isText()) return TextSection;
276 if (Kind.isMergeableCString()) {
278 // We also need alignment here.
279 // FIXME: this is getting the alignment of the character, not the
280 // alignment of the global!
282 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
284 unsigned EntrySize = 1;
285 if (Kind.isMergeable2ByteCString())
287 else if (Kind.isMergeable4ByteCString())
290 assert(Kind.isMergeable1ByteCString() && "unknown string width");
292 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
293 std::string Name = SizeSpec + utostr(Align);
294 return getContext().getELFSection(
295 Name, ELF::SHT_PROGBITS,
296 ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize, "");
299 if (Kind.isMergeableConst()) {
300 if (Kind.isMergeableConst4() && MergeableConst4Section)
301 return MergeableConst4Section;
302 if (Kind.isMergeableConst8() && MergeableConst8Section)
303 return MergeableConst8Section;
304 if (Kind.isMergeableConst16() && MergeableConst16Section)
305 return MergeableConst16Section;
306 return ReadOnlySection; // .const
309 if (Kind.isReadOnly()) return ReadOnlySection;
311 if (Kind.isThreadData()) return TLSDataSection;
312 if (Kind.isThreadBSS()) return TLSBSSSection;
314 // Note: we claim that common symbols are put in BSSSection, but they are
315 // really emitted with the magic .comm directive, which creates a symbol table
316 // entry but not a section.
317 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
319 if (Kind.isDataNoRel()) return DataSection;
320 if (Kind.isDataRelLocal()) return DataRelLocalSection;
321 if (Kind.isDataRel()) return DataRelSection;
322 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
324 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
325 return DataRelROSection;
328 /// getSectionForConstant - Given a mergeable constant with the
329 /// specified size and relocation information, return a section that it
330 /// should be placed in.
332 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
333 const Constant *C) const {
334 if (Kind.isMergeableConst4() && MergeableConst4Section)
335 return MergeableConst4Section;
336 if (Kind.isMergeableConst8() && MergeableConst8Section)
337 return MergeableConst8Section;
338 if (Kind.isMergeableConst16() && MergeableConst16Section)
339 return MergeableConst16Section;
340 if (Kind.isReadOnly())
341 return ReadOnlySection;
343 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
344 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
345 return DataRelROSection;
348 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
352 const MCSymbol *KeySym) {
355 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
356 StringRef COMDAT = KeySym ? KeySym->getName() : "";
359 Flags |= ELF::SHF_GROUP;
363 Type = ELF::SHT_INIT_ARRAY;
364 Name = ".init_array";
366 Type = ELF::SHT_FINI_ARRAY;
367 Name = ".fini_array";
369 if (Priority != 65535) {
371 Name += utostr(Priority);
374 // The default scheme is .ctor / .dtor, so we have to invert the priority
380 if (Priority != 65535) {
382 Name += utostr(65535 - Priority);
384 Type = ELF::SHT_PROGBITS;
387 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
390 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
391 unsigned Priority, const MCSymbol *KeySym) const {
392 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
396 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
397 unsigned Priority, const MCSymbol *KeySym) const {
398 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
403 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
404 UseInitArray = UseInitArray_;
408 StaticCtorSection = getContext().getELFSection(
409 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
410 StaticDtorSection = getContext().getELFSection(
411 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
414 //===----------------------------------------------------------------------===//
416 //===----------------------------------------------------------------------===//
418 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
419 /// option string. Returns StringRef() if the option does not specify a library.
420 StringRef TargetLoweringObjectFileMachO::
421 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
422 const char *LibCmd = "-l";
423 if (LinkerOption.startswith(LibCmd))
424 return LinkerOption.substr(strlen(LibCmd));
428 /// emitModuleFlags - Perform code emission for module flags.
429 void TargetLoweringObjectFileMachO::
430 emitModuleFlags(MCStreamer &Streamer,
431 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
432 Mangler &Mang, const TargetMachine &TM) const {
433 unsigned VersionVal = 0;
434 unsigned ImageInfoFlags = 0;
435 MDNode *LinkerOptions = nullptr;
436 StringRef SectionVal;
438 for (ArrayRef<Module::ModuleFlagEntry>::iterator
439 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
440 const Module::ModuleFlagEntry &MFE = *i;
442 // Ignore flags with 'Require' behavior.
443 if (MFE.Behavior == Module::Require)
446 StringRef Key = MFE.Key->getString();
447 Metadata *Val = MFE.Val;
449 if (Key == "Objective-C Image Info Version") {
450 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
451 } else if (Key == "Objective-C Garbage Collection" ||
452 Key == "Objective-C GC Only" ||
453 Key == "Objective-C Is Simulated" ||
454 Key == "Objective-C Image Swift Version") {
455 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
456 } else if (Key == "Objective-C Image Info Section") {
457 SectionVal = cast<MDString>(Val)->getString();
458 } else if (Key == "Linker Options") {
459 LinkerOptions = cast<MDNode>(Val);
463 // Emit the linker options if present.
465 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
466 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
467 SmallVector<std::string, 4> StrOptions;
469 // Convert to strings.
470 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
471 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
472 StrOptions.push_back(MDOption->getString());
475 Streamer.EmitLinkerOptions(StrOptions);
479 // The section is mandatory. If we don't have it, then we don't have GC info.
480 if (SectionVal.empty()) return;
482 StringRef Segment, Section;
483 unsigned TAA = 0, StubSize = 0;
485 std::string ErrorCode =
486 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
487 TAA, TAAParsed, StubSize);
488 if (!ErrorCode.empty())
489 // If invalid, report the error with report_fatal_error.
490 report_fatal_error("Invalid section specifier '" + Section + "': " +
494 const MCSectionMachO *S =
495 getContext().getMachOSection(Segment, Section, TAA, StubSize,
496 SectionKind::getDataNoRel());
497 Streamer.SwitchSection(S);
498 Streamer.EmitLabel(getContext().
499 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
500 Streamer.EmitIntValue(VersionVal, 4);
501 Streamer.EmitIntValue(ImageInfoFlags, 4);
502 Streamer.AddBlankLine();
505 static void checkMachOComdat(const GlobalValue *GV) {
506 const Comdat *C = GV->getComdat();
510 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
511 "' cannot be lowered.");
514 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
515 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
516 const TargetMachine &TM) const {
517 // Parse the section specifier and create it if valid.
518 StringRef Segment, Section;
519 unsigned TAA = 0, StubSize = 0;
522 checkMachOComdat(GV);
524 std::string ErrorCode =
525 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
526 TAA, TAAParsed, StubSize);
527 if (!ErrorCode.empty()) {
528 // If invalid, report the error with report_fatal_error.
529 report_fatal_error("Global variable '" + GV->getName() +
530 "' has an invalid section specifier '" +
531 GV->getSection() + "': " + ErrorCode + ".");
535 const MCSectionMachO *S =
536 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
538 // If TAA wasn't set by ParseSectionSpecifier() above,
539 // use the value returned by getMachOSection() as a default.
541 TAA = S->getTypeAndAttributes();
543 // Okay, now that we got the section, verify that the TAA & StubSize agree.
544 // If the user declared multiple globals with different section flags, we need
545 // to reject it here.
546 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
547 // If invalid, report the error with report_fatal_error.
548 report_fatal_error("Global variable '" + GV->getName() +
549 "' section type or attributes does not match previous"
550 " section specifier");
556 const MCSection *TargetLoweringObjectFileMachO::
557 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
558 Mangler &Mang, const TargetMachine &TM) const {
559 checkMachOComdat(GV);
561 // Handle thread local data.
562 if (Kind.isThreadBSS()) return TLSBSSSection;
563 if (Kind.isThreadData()) return TLSDataSection;
566 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
568 // If this is weak/linkonce, put this in a coalescable section, either in text
569 // or data depending on if it is writable.
570 if (GV->isWeakForLinker()) {
571 if (Kind.isReadOnly())
572 return ConstTextCoalSection;
573 return DataCoalSection;
576 // FIXME: Alignment check should be handled by section classifier.
577 if (Kind.isMergeable1ByteCString() &&
578 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
579 return CStringSection;
581 // Do not put 16-bit arrays in the UString section if they have an
582 // externally visible label, this runs into issues with certain linker
584 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
585 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
586 return UStringSection;
588 // With MachO only variables whose corresponding symbol starts with 'l' or
589 // 'L' can be merged, so we only try merging GVs with private linkage.
590 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
591 if (Kind.isMergeableConst4())
592 return FourByteConstantSection;
593 if (Kind.isMergeableConst8())
594 return EightByteConstantSection;
595 if (Kind.isMergeableConst16())
596 return SixteenByteConstantSection;
599 // Otherwise, if it is readonly, but not something we can specially optimize,
600 // just drop it in .const.
601 if (Kind.isReadOnly())
602 return ReadOnlySection;
604 // If this is marked const, put it into a const section. But if the dynamic
605 // linker needs to write to it, put it in the data segment.
606 if (Kind.isReadOnlyWithRel())
607 return ConstDataSection;
609 // Put zero initialized globals with strong external linkage in the
610 // DATA, __common section with the .zerofill directive.
611 if (Kind.isBSSExtern())
612 return DataCommonSection;
614 // Put zero initialized globals with local linkage in __DATA,__bss directive
615 // with the .zerofill directive (aka .lcomm).
616 if (Kind.isBSSLocal())
617 return DataBSSSection;
619 // Otherwise, just drop the variable in the normal data section.
624 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
625 const Constant *C) const {
626 // If this constant requires a relocation, we have to put it in the data
627 // segment, not in the text segment.
628 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
629 return ConstDataSection;
631 if (Kind.isMergeableConst4())
632 return FourByteConstantSection;
633 if (Kind.isMergeableConst8())
634 return EightByteConstantSection;
635 if (Kind.isMergeableConst16())
636 return SixteenByteConstantSection;
637 return ReadOnlySection; // .const
640 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
641 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
642 const TargetMachine &TM, MachineModuleInfo *MMI,
643 MCStreamer &Streamer) const {
644 // The mach-o version of this method defaults to returning a stub reference.
646 if (Encoding & DW_EH_PE_indirect) {
647 MachineModuleInfoMachO &MachOMMI =
648 MMI->getObjFileInfo<MachineModuleInfoMachO>();
651 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
653 // Add information about the stub reference to MachOMMI so that the stub
654 // gets emitted by the asmprinter.
655 MachineModuleInfoImpl::StubValueTy &StubSym =
656 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
657 MachOMMI.getGVStubEntry(SSym);
658 if (!StubSym.getPointer()) {
659 MCSymbol *Sym = TM.getSymbol(GV, Mang);
660 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
663 return TargetLoweringObjectFile::
664 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
665 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
668 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
672 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
673 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
674 MachineModuleInfo *MMI) const {
675 // The mach-o version of this method defaults to returning a stub reference.
676 MachineModuleInfoMachO &MachOMMI =
677 MMI->getObjFileInfo<MachineModuleInfoMachO>();
679 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
681 // Add information about the stub reference to MachOMMI so that the stub
682 // gets emitted by the asmprinter.
683 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
684 if (!StubSym.getPointer()) {
685 MCSymbol *Sym = TM.getSymbol(GV, Mang);
686 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
692 //===----------------------------------------------------------------------===//
694 //===----------------------------------------------------------------------===//
697 getCOFFSectionFlags(SectionKind K) {
702 COFF::IMAGE_SCN_MEM_DISCARDABLE;
705 COFF::IMAGE_SCN_MEM_EXECUTE |
706 COFF::IMAGE_SCN_MEM_READ |
707 COFF::IMAGE_SCN_CNT_CODE;
710 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
711 COFF::IMAGE_SCN_MEM_READ |
712 COFF::IMAGE_SCN_MEM_WRITE;
713 else if (K.isThreadLocal())
715 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
716 COFF::IMAGE_SCN_MEM_READ |
717 COFF::IMAGE_SCN_MEM_WRITE;
718 else if (K.isReadOnly() || K.isReadOnlyWithRel())
720 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
721 COFF::IMAGE_SCN_MEM_READ;
722 else if (K.isWriteable())
724 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
725 COFF::IMAGE_SCN_MEM_READ |
726 COFF::IMAGE_SCN_MEM_WRITE;
731 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
732 const Comdat *C = GV->getComdat();
733 assert(C && "expected GV to have a Comdat!");
735 StringRef ComdatGVName = C->getName();
736 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
738 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
739 "' does not exist.");
741 if (ComdatGV->getComdat() != C)
742 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
743 "' is not a key for its COMDAT.");
748 static int getSelectionForCOFF(const GlobalValue *GV) {
749 if (const Comdat *C = GV->getComdat()) {
750 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
751 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
752 ComdatKey = GA->getBaseObject();
753 if (ComdatKey == GV) {
754 switch (C->getSelectionKind()) {
756 return COFF::IMAGE_COMDAT_SELECT_ANY;
757 case Comdat::ExactMatch:
758 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
759 case Comdat::Largest:
760 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
761 case Comdat::NoDuplicates:
762 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
763 case Comdat::SameSize:
764 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
767 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
769 } else if (GV->isWeakForLinker()) {
770 return COFF::IMAGE_COMDAT_SELECT_ANY;
775 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
776 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
777 const TargetMachine &TM) const {
779 unsigned Characteristics = getCOFFSectionFlags(Kind);
780 StringRef Name = GV->getSection();
781 StringRef COMDATSymName = "";
782 if (GV->hasComdat()) {
783 Selection = getSelectionForCOFF(GV);
784 const GlobalValue *ComdatGV;
785 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
786 ComdatGV = getComdatGVForCOFF(GV);
790 if (!ComdatGV->hasPrivateLinkage()) {
791 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
792 COMDATSymName = Sym->getName();
793 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
798 return getContext().getCOFFSection(Name,
805 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
810 if (Kind.isThreadLocal())
812 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
818 const MCSection *TargetLoweringObjectFileCOFF::
819 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
820 Mangler &Mang, const TargetMachine &TM) const {
821 // If we have -ffunction-sections then we should emit the global value to a
822 // uniqued section specifically for it.
823 bool EmitUniquedSection;
825 EmitUniquedSection = TM.getFunctionSections();
827 EmitUniquedSection = TM.getDataSections();
829 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
830 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
831 unsigned Characteristics = getCOFFSectionFlags(Kind);
833 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
834 int Selection = getSelectionForCOFF(GV);
836 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
837 const GlobalValue *ComdatGV;
839 ComdatGV = getComdatGVForCOFF(GV);
843 if (!ComdatGV->hasPrivateLinkage()) {
844 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
845 StringRef COMDATSymName = Sym->getName();
846 return getContext().getCOFFSection(Name, Characteristics, Kind,
847 COMDATSymName, Selection);
854 if (Kind.isThreadLocal())
855 return TLSDataSection;
857 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
858 return ReadOnlySection;
860 // Note: we claim that common symbols are put in BSSSection, but they are
861 // really emitted with the magic .comm directive, which creates a symbol table
862 // entry but not a section.
863 if (Kind.isBSS() || Kind.isCommon())
869 StringRef TargetLoweringObjectFileCOFF::
870 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
871 const char *LibCmd = "/DEFAULTLIB:";
872 if (LinkerOption.startswith(LibCmd))
873 return LinkerOption.substr(strlen(LibCmd));
877 void TargetLoweringObjectFileCOFF::
878 emitModuleFlags(MCStreamer &Streamer,
879 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
880 Mangler &Mang, const TargetMachine &TM) const {
881 MDNode *LinkerOptions = nullptr;
883 // Look for the "Linker Options" flag, since it's the only one we support.
884 for (ArrayRef<Module::ModuleFlagEntry>::iterator
885 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
886 const Module::ModuleFlagEntry &MFE = *i;
887 StringRef Key = MFE.Key->getString();
888 Metadata *Val = MFE.Val;
889 if (Key == "Linker Options") {
890 LinkerOptions = cast<MDNode>(Val);
897 // Emit the linker options to the linker .drectve section. According to the
898 // spec, this section is a space-separated string containing flags for linker.
899 const MCSection *Sec = getDrectveSection();
900 Streamer.SwitchSection(Sec);
901 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
902 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
903 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
904 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
905 StringRef Op = MDOption->getString();
906 // Lead with a space for consistency with our dllexport implementation.
907 std::string Escaped(" ");
908 if (!Op.startswith("\"") && (Op.find(" ") != StringRef::npos)) {
909 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
910 // how to escape quotes, but it probably uses this algorithm:
911 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
912 // FIXME: Reuse escaping code from Support/Windows/Program.inc
913 Escaped.push_back('\"');
915 Escaped.push_back('\"');
919 Streamer.EmitBytes(Escaped);
924 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
925 unsigned Priority, const MCSymbol *KeySym) const {
926 return getContext().getAssociativeCOFFSection(
927 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
930 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
931 unsigned Priority, const MCSymbol *KeySym) const {
932 return getContext().getAssociativeCOFFSection(
933 cast<MCSectionCOFF>(StaticDtorSection), KeySym);