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.getDataLayout()->getPointerSize();
77 Streamer.SwitchSection(Sec);
78 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
79 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
80 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
81 Streamer.EmitELFSize(Label, E);
82 Streamer.EmitLabel(Label);
84 Streamer.EmitSymbolValue(Sym, Size);
87 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
88 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
89 const TargetMachine &TM, MachineModuleInfo *MMI,
90 MCStreamer &Streamer) const {
92 if (Encoding & dwarf::DW_EH_PE_indirect) {
93 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
95 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
97 // Add information about the stub reference to ELFMMI so that the stub
98 // gets emitted by the asmprinter.
99 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
100 if (!StubSym.getPointer()) {
101 MCSymbol *Sym = TM.getSymbol(GV, Mang);
102 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
105 return TargetLoweringObjectFile::
106 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
107 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
110 return TargetLoweringObjectFile::
111 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
115 getELFKindForNamedSection(StringRef Name, SectionKind K) {
116 // N.B.: The defaults used in here are no the same ones used in MC.
117 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
118 // both gas and MC will produce a section with no flags. Given
119 // section(".eh_frame") gcc will produce:
121 // .section .eh_frame,"a",@progbits
122 if (Name.empty() || Name[0] != '.') return K;
124 // Some lame default implementation based on some magic section names.
125 if (Name == ".bss" ||
126 Name.startswith(".bss.") ||
127 Name.startswith(".gnu.linkonce.b.") ||
128 Name.startswith(".llvm.linkonce.b.") ||
130 Name.startswith(".sbss.") ||
131 Name.startswith(".gnu.linkonce.sb.") ||
132 Name.startswith(".llvm.linkonce.sb."))
133 return SectionKind::getBSS();
135 if (Name == ".tdata" ||
136 Name.startswith(".tdata.") ||
137 Name.startswith(".gnu.linkonce.td.") ||
138 Name.startswith(".llvm.linkonce.td."))
139 return SectionKind::getThreadData();
141 if (Name == ".tbss" ||
142 Name.startswith(".tbss.") ||
143 Name.startswith(".gnu.linkonce.tb.") ||
144 Name.startswith(".llvm.linkonce.tb."))
145 return SectionKind::getThreadBSS();
151 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
153 if (Name == ".init_array")
154 return ELF::SHT_INIT_ARRAY;
156 if (Name == ".fini_array")
157 return ELF::SHT_FINI_ARRAY;
159 if (Name == ".preinit_array")
160 return ELF::SHT_PREINIT_ARRAY;
162 if (K.isBSS() || K.isThreadBSS())
163 return ELF::SHT_NOBITS;
165 return ELF::SHT_PROGBITS;
170 getELFSectionFlags(SectionKind K) {
174 Flags |= ELF::SHF_ALLOC;
177 Flags |= ELF::SHF_EXECINSTR;
180 Flags |= ELF::SHF_WRITE;
182 if (K.isThreadLocal())
183 Flags |= ELF::SHF_TLS;
185 // K.isMergeableConst() is left out to honour PR4650
186 if (K.isMergeableCString() || K.isMergeableConst4() ||
187 K.isMergeableConst8() || K.isMergeableConst16())
188 Flags |= ELF::SHF_MERGE;
190 if (K.isMergeableCString())
191 Flags |= ELF::SHF_STRINGS;
196 static const Comdat *getELFComdat(const GlobalValue *GV) {
197 const Comdat *C = GV->getComdat();
201 if (C->getSelectionKind() != Comdat::Any)
202 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
203 C->getName() + "' cannot be lowered.");
208 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
209 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
210 const TargetMachine &TM) const {
211 StringRef SectionName = GV->getSection();
213 // Infer section flags from the section name if we can.
214 Kind = getELFKindForNamedSection(SectionName, Kind);
216 StringRef Group = "";
217 unsigned Flags = getELFSectionFlags(Kind);
218 if (const Comdat *C = getELFComdat(GV)) {
219 Group = C->getName();
220 Flags |= ELF::SHF_GROUP;
222 return getContext().getELFSection(SectionName,
223 getELFSectionType(SectionName, Kind), Flags,
224 Kind, /*EntrySize=*/0, Group);
227 /// getSectionPrefixForGlobal - Return the section prefix name used by options
228 /// FunctionsSections and DataSections.
229 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
230 if (Kind.isText()) return ".text.";
231 if (Kind.isReadOnly()) return ".rodata.";
232 if (Kind.isBSS()) return ".bss.";
234 if (Kind.isThreadData()) return ".tdata.";
235 if (Kind.isThreadBSS()) return ".tbss.";
237 if (Kind.isDataNoRel()) return ".data.";
238 if (Kind.isDataRelLocal()) return ".data.rel.local.";
239 if (Kind.isDataRel()) return ".data.rel.";
240 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
242 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
243 return ".data.rel.ro.";
246 const MCSection *TargetLoweringObjectFileELF::
247 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
248 Mangler &Mang, const TargetMachine &TM) const {
249 unsigned Flags = getELFSectionFlags(Kind);
251 // If we have -ffunction-section or -fdata-section then we should emit the
252 // global value to a uniqued section specifically for it.
253 bool EmitUniquedSection = false;
254 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
256 EmitUniquedSection = TM.getFunctionSections();
258 EmitUniquedSection = TM.getDataSections();
261 if (EmitUniquedSection || GV->hasComdat()) {
262 StringRef Prefix = getSectionPrefixForGlobal(Kind);
264 SmallString<128> Name(Prefix);
265 TM.getNameWithPrefix(Name, GV, Mang, true);
267 StringRef Group = "";
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.isMergeableCString()) {
282 // We also need alignment here.
283 // FIXME: this is getting the alignment of the character, not the
284 // alignment of the global!
286 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
288 const char *SizeSpec = ".rodata.str1.";
289 if (Kind.isMergeable2ByteCString())
290 SizeSpec = ".rodata.str2.";
291 else if (Kind.isMergeable4ByteCString())
292 SizeSpec = ".rodata.str4.";
294 assert(Kind.isMergeable1ByteCString() && "unknown string width");
297 std::string Name = SizeSpec + utostr(Align);
298 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
305 if (Kind.isMergeableConst()) {
306 if (Kind.isMergeableConst4() && MergeableConst4Section)
307 return MergeableConst4Section;
308 if (Kind.isMergeableConst8() && MergeableConst8Section)
309 return MergeableConst8Section;
310 if (Kind.isMergeableConst16() && MergeableConst16Section)
311 return MergeableConst16Section;
312 return ReadOnlySection; // .const
315 if (Kind.isReadOnly()) return ReadOnlySection;
317 if (Kind.isThreadData()) return TLSDataSection;
318 if (Kind.isThreadBSS()) return TLSBSSSection;
320 // Note: we claim that common symbols are put in BSSSection, but they are
321 // really emitted with the magic .comm directive, which creates a symbol table
322 // entry but not a section.
323 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
325 if (Kind.isDataNoRel()) return DataSection;
326 if (Kind.isDataRelLocal()) return DataRelLocalSection;
327 if (Kind.isDataRel()) return DataRelSection;
328 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
330 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
331 return DataRelROSection;
334 /// getSectionForConstant - Given a mergeable constant with the
335 /// specified size and relocation information, return a section that it
336 /// should be placed in.
338 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
339 const Constant *C) const {
340 if (Kind.isMergeableConst4() && MergeableConst4Section)
341 return MergeableConst4Section;
342 if (Kind.isMergeableConst8() && MergeableConst8Section)
343 return MergeableConst8Section;
344 if (Kind.isMergeableConst16() && MergeableConst16Section)
345 return MergeableConst16Section;
346 if (Kind.isReadOnly())
347 return ReadOnlySection;
349 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
350 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
351 return DataRelROSection;
354 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
358 const MCSymbol *KeySym) {
361 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
362 SectionKind Kind = SectionKind::getDataRel();
363 StringRef COMDAT = KeySym ? KeySym->getName() : "";
366 Flags |= ELF::SHF_GROUP;
370 Type = ELF::SHT_INIT_ARRAY;
371 Name = ".init_array";
373 Type = ELF::SHT_FINI_ARRAY;
374 Name = ".fini_array";
376 if (Priority != 65535) {
378 Name += utostr(Priority);
381 // The default scheme is .ctor / .dtor, so we have to invert the priority
387 if (Priority != 65535) {
389 Name += utostr(65535 - Priority);
391 Type = ELF::SHT_PROGBITS;
394 return Ctx.getELFSection(Name, Type, Flags, Kind, 0, COMDAT);
397 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
398 unsigned Priority, const MCSymbol *KeySym) const {
399 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
403 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
404 unsigned Priority, const MCSymbol *KeySym) const {
405 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
410 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
411 UseInitArray = UseInitArray_;
416 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
419 SectionKind::getDataRel());
421 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
424 SectionKind::getDataRel());
427 //===----------------------------------------------------------------------===//
429 //===----------------------------------------------------------------------===//
431 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
432 /// option string. Returns StringRef() if the option does not specify a library.
433 StringRef TargetLoweringObjectFileMachO::
434 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
435 const char *LibCmd = "-l";
436 if (LinkerOption.startswith(LibCmd))
437 return LinkerOption.substr(strlen(LibCmd));
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 const MCSectionMachO *S =
508 getContext().getMachOSection(Segment, Section, TAA, StubSize,
509 SectionKind::getDataNoRel());
510 Streamer.SwitchSection(S);
511 Streamer.EmitLabel(getContext().
512 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
513 Streamer.EmitIntValue(VersionVal, 4);
514 Streamer.EmitIntValue(ImageInfoFlags, 4);
515 Streamer.AddBlankLine();
518 static void checkMachOComdat(const GlobalValue *GV) {
519 const Comdat *C = GV->getComdat();
523 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
524 "' cannot be lowered.");
527 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
528 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
529 const TargetMachine &TM) const {
530 // Parse the section specifier and create it if valid.
531 StringRef Segment, Section;
532 unsigned TAA = 0, StubSize = 0;
535 checkMachOComdat(GV);
537 std::string ErrorCode =
538 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
539 TAA, TAAParsed, StubSize);
540 if (!ErrorCode.empty()) {
541 // If invalid, report the error with report_fatal_error.
542 report_fatal_error("Global variable '" + GV->getName() +
543 "' has an invalid section specifier '" +
544 GV->getSection() + "': " + ErrorCode + ".");
548 const MCSectionMachO *S =
549 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
551 // If TAA wasn't set by ParseSectionSpecifier() above,
552 // use the value returned by getMachOSection() as a default.
554 TAA = S->getTypeAndAttributes();
556 // Okay, now that we got the section, verify that the TAA & StubSize agree.
557 // If the user declared multiple globals with different section flags, we need
558 // to reject it here.
559 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
560 // If invalid, report the error with report_fatal_error.
561 report_fatal_error("Global variable '" + GV->getName() +
562 "' section type or attributes does not match previous"
563 " section specifier");
569 const MCSection *TargetLoweringObjectFileMachO::
570 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
571 Mangler &Mang, const TargetMachine &TM) const {
572 checkMachOComdat(GV);
574 // Handle thread local data.
575 if (Kind.isThreadBSS()) return TLSBSSSection;
576 if (Kind.isThreadData()) return TLSDataSection;
579 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
581 // If this is weak/linkonce, put this in a coalescable section, either in text
582 // or data depending on if it is writable.
583 if (GV->isWeakForLinker()) {
584 if (Kind.isReadOnly())
585 return ConstTextCoalSection;
586 return DataCoalSection;
589 // FIXME: Alignment check should be handled by section classifier.
590 if (Kind.isMergeable1ByteCString() &&
591 TM.getDataLayout()->getPreferredAlignment(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 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
599 return UStringSection;
601 // With MachO only variables whose corresponding symbol starts with 'l' or
602 // 'L' can be merged, so we only try merging GVs with private linkage.
603 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
604 if (Kind.isMergeableConst4())
605 return FourByteConstantSection;
606 if (Kind.isMergeableConst8())
607 return EightByteConstantSection;
608 if (Kind.isMergeableConst16())
609 return SixteenByteConstantSection;
612 // Otherwise, if it is readonly, but not something we can specially optimize,
613 // just drop it in .const.
614 if (Kind.isReadOnly())
615 return ReadOnlySection;
617 // If this is marked const, put it into a const section. But if the dynamic
618 // linker needs to write to it, put it in the data segment.
619 if (Kind.isReadOnlyWithRel())
620 return ConstDataSection;
622 // Put zero initialized globals with strong external linkage in the
623 // DATA, __common section with the .zerofill directive.
624 if (Kind.isBSSExtern())
625 return DataCommonSection;
627 // Put zero initialized globals with local linkage in __DATA,__bss directive
628 // with the .zerofill directive (aka .lcomm).
629 if (Kind.isBSSLocal())
630 return DataBSSSection;
632 // Otherwise, just drop the variable in the normal data section.
637 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
638 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 //===----------------------------------------------------------------------===//
707 //===----------------------------------------------------------------------===//
710 getCOFFSectionFlags(SectionKind K) {
715 COFF::IMAGE_SCN_MEM_DISCARDABLE;
718 COFF::IMAGE_SCN_MEM_EXECUTE |
719 COFF::IMAGE_SCN_MEM_READ |
720 COFF::IMAGE_SCN_CNT_CODE;
723 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
724 COFF::IMAGE_SCN_MEM_READ |
725 COFF::IMAGE_SCN_MEM_WRITE;
726 else if (K.isThreadLocal())
728 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
729 COFF::IMAGE_SCN_MEM_READ |
730 COFF::IMAGE_SCN_MEM_WRITE;
731 else if (K.isReadOnly() || K.isReadOnlyWithRel())
733 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
734 COFF::IMAGE_SCN_MEM_READ;
735 else if (K.isWriteable())
737 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
738 COFF::IMAGE_SCN_MEM_READ |
739 COFF::IMAGE_SCN_MEM_WRITE;
744 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
745 const Comdat *C = GV->getComdat();
746 assert(C && "expected GV to have a Comdat!");
748 StringRef ComdatGVName = C->getName();
749 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
751 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
752 "' does not exist.");
754 if (ComdatGV->getComdat() != C)
755 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
756 "' is not a key for its COMDAT.");
761 static int getSelectionForCOFF(const GlobalValue *GV) {
762 if (const Comdat *C = GV->getComdat()) {
763 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
764 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
765 ComdatKey = GA->getBaseObject();
766 if (ComdatKey == GV) {
767 switch (C->getSelectionKind()) {
769 return COFF::IMAGE_COMDAT_SELECT_ANY;
770 case Comdat::ExactMatch:
771 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
772 case Comdat::Largest:
773 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
774 case Comdat::NoDuplicates:
775 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
776 case Comdat::SameSize:
777 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
780 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
782 } else if (GV->isWeakForLinker()) {
783 return COFF::IMAGE_COMDAT_SELECT_ANY;
788 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
789 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
790 const TargetMachine &TM) const {
792 unsigned Characteristics = getCOFFSectionFlags(Kind);
793 StringRef Name = GV->getSection();
794 StringRef COMDATSymName = "";
795 if (GV->hasComdat()) {
796 Selection = getSelectionForCOFF(GV);
797 const GlobalValue *ComdatGV;
798 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
799 ComdatGV = getComdatGVForCOFF(GV);
803 if (!ComdatGV->hasPrivateLinkage()) {
804 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
805 COMDATSymName = Sym->getName();
806 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
811 return getContext().getCOFFSection(Name,
818 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
823 if (Kind.isThreadLocal())
825 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
831 const MCSection *TargetLoweringObjectFileCOFF::
832 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
833 Mangler &Mang, const TargetMachine &TM) const {
834 // If we have -ffunction-sections then we should emit the global value to a
835 // uniqued section specifically for it.
836 bool EmitUniquedSection;
838 EmitUniquedSection = TM.getFunctionSections();
840 EmitUniquedSection = TM.getDataSections();
842 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
843 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
844 unsigned Characteristics = getCOFFSectionFlags(Kind);
846 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
847 int Selection = getSelectionForCOFF(GV);
849 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
850 const GlobalValue *ComdatGV;
852 ComdatGV = getComdatGVForCOFF(GV);
856 if (!ComdatGV->hasPrivateLinkage()) {
857 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
858 StringRef COMDATSymName = Sym->getName();
859 return getContext().getCOFFSection(Name, Characteristics, Kind,
860 COMDATSymName, Selection);
867 if (Kind.isThreadLocal())
868 return TLSDataSection;
870 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
871 return ReadOnlySection;
873 // Note: we claim that common symbols are put in BSSSection, but they are
874 // really emitted with the magic .comm directive, which creates a symbol table
875 // entry but not a section.
876 if (Kind.isBSS() || Kind.isCommon())
882 StringRef TargetLoweringObjectFileCOFF::
883 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
884 const char *LibCmd = "/DEFAULTLIB:";
885 if (LinkerOption.startswith(LibCmd))
886 return LinkerOption.substr(strlen(LibCmd));
890 void TargetLoweringObjectFileCOFF::
891 emitModuleFlags(MCStreamer &Streamer,
892 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
893 Mangler &Mang, const TargetMachine &TM) const {
894 MDNode *LinkerOptions = nullptr;
896 // Look for the "Linker Options" flag, since it's the only one we support.
897 for (ArrayRef<Module::ModuleFlagEntry>::iterator
898 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
899 const Module::ModuleFlagEntry &MFE = *i;
900 StringRef Key = MFE.Key->getString();
901 Metadata *Val = MFE.Val;
902 if (Key == "Linker Options") {
903 LinkerOptions = cast<MDNode>(Val);
910 // Emit the linker options to the linker .drectve section. According to the
911 // spec, this section is a space-separated string containing flags for linker.
912 const MCSection *Sec = getDrectveSection();
913 Streamer.SwitchSection(Sec);
914 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
915 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
916 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
917 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
918 StringRef Op = MDOption->getString();
919 // Lead with a space for consistency with our dllexport implementation.
920 std::string Escaped(" ");
921 if (!Op.startswith("\"") && (Op.find(" ") != StringRef::npos)) {
922 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
923 // how to escape quotes, but it probably uses this algorithm:
924 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
925 // FIXME: Reuse escaping code from Support/Windows/Program.inc
926 Escaped.push_back('\"');
928 Escaped.push_back('\"');
932 Streamer.EmitBytes(Escaped);
937 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
938 unsigned Priority, const MCSymbol *KeySym) const {
939 return getContext().getAssociativeCOFFSection(
940 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
943 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
944 unsigned Priority, const MCSymbol *KeySym) const {
945 return getContext().getAssociativeCOFFSection(
946 cast<MCSectionCOFF>(StaticDtorSection), KeySym);