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 // FIXME: There is nothing in ELF preventing an SHF_MERGE from being
185 // in a comdat. We just avoid it for now because we don't print
186 // those .sections correctly.
187 if (!InCOMDAT && (K.isMergeableCString() || K.isMergeableConst()))
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, GV->hasComdat());
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 /*EntrySize=*/0, Group);
227 /// Return the section prefix name used by options FunctionsSections and
229 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
232 if (Kind.isReadOnly())
236 if (Kind.isThreadData())
238 if (Kind.isThreadBSS())
240 if (Kind.isDataNoRel())
242 if (Kind.isDataRelLocal())
243 return ".data.rel.local.";
244 if (Kind.isDataRel())
246 if (Kind.isReadOnlyWithRelLocal())
247 return ".data.rel.ro.local.";
248 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
249 return ".data.rel.ro.";
252 const MCSection *TargetLoweringObjectFileELF::
253 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
254 Mangler &Mang, const TargetMachine &TM) const {
255 unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
257 // If we have -ffunction-section or -fdata-section then we should emit the
258 // global value to a uniqued section specifically for it.
259 bool EmitUniquedSection = false;
260 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
262 EmitUniquedSection = TM.getFunctionSections();
264 EmitUniquedSection = TM.getDataSections();
267 if (EmitUniquedSection || GV->hasComdat()) {
268 StringRef Prefix = getSectionPrefixForGlobal(Kind);
270 SmallString<128> Name(Prefix);
271 TM.getNameWithPrefix(Name, GV, Mang, true);
273 StringRef Group = "";
274 if (const Comdat *C = getELFComdat(GV)) {
275 Flags |= ELF::SHF_GROUP;
276 Group = C->getName();
279 return getContext().getELFSection(
280 Name.str(), getELFSectionType(Name.str(), Kind), Flags, 0, Group);
283 if (Kind.isText()) return TextSection;
285 if (Kind.isMergeableCString()) {
287 // We also need alignment here.
288 // FIXME: this is getting the alignment of the character, not the
289 // alignment of the global!
291 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
293 unsigned EntrySize = 1;
294 if (Kind.isMergeable2ByteCString())
296 else if (Kind.isMergeable4ByteCString())
299 assert(Kind.isMergeable1ByteCString() && "unknown string width");
301 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
302 std::string Name = SizeSpec + utostr(Align);
303 return getContext().getELFSection(
304 Name, ELF::SHT_PROGBITS,
305 ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize, "");
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 const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
338 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
339 // If the function can be removed, produce a unique section so that
340 // the table doesn't prevent the removal.
341 const Comdat *C = F.getComdat();
342 bool EmitUniqueSection = TM.getFunctionSections() || C;
343 if (!EmitUniqueSection)
344 return ReadOnlySection;
346 SmallString<128> Name(".rodata.");
347 TM.getNameWithPrefix(Name, &F, Mang, true);
349 unsigned Flags = ELF::SHF_ALLOC;
350 StringRef Group = "";
352 Flags |= ELF::SHF_GROUP;
353 Group = C->getName();
356 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags, 0, Group);
359 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
360 bool UsesLabelDifference, const Function &F) const {
361 // We can always create relative relocations, so use another section
362 // that can be marked non-executable.
366 /// getSectionForConstant - Given a mergeable constant with the
367 /// specified size and relocation information, return a section that it
368 /// should be placed in.
370 TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
371 const Constant *C) const {
372 if (Kind.isMergeableConst4() && MergeableConst4Section)
373 return MergeableConst4Section;
374 if (Kind.isMergeableConst8() && MergeableConst8Section)
375 return MergeableConst8Section;
376 if (Kind.isMergeableConst16() && MergeableConst16Section)
377 return MergeableConst16Section;
378 if (Kind.isReadOnly())
379 return ReadOnlySection;
381 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
382 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
383 return DataRelROSection;
386 static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
390 const MCSymbol *KeySym) {
393 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
394 StringRef COMDAT = KeySym ? KeySym->getName() : "";
397 Flags |= ELF::SHF_GROUP;
401 Type = ELF::SHT_INIT_ARRAY;
402 Name = ".init_array";
404 Type = ELF::SHT_FINI_ARRAY;
405 Name = ".fini_array";
407 if (Priority != 65535) {
409 Name += utostr(Priority);
412 // The default scheme is .ctor / .dtor, so we have to invert the priority
418 if (Priority != 65535) {
420 Name += utostr(65535 - Priority);
422 Type = ELF::SHT_PROGBITS;
425 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
428 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
429 unsigned Priority, const MCSymbol *KeySym) const {
430 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
434 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
435 unsigned Priority, const MCSymbol *KeySym) const {
436 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
441 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
442 UseInitArray = UseInitArray_;
446 StaticCtorSection = getContext().getELFSection(
447 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
448 StaticDtorSection = getContext().getELFSection(
449 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
452 //===----------------------------------------------------------------------===//
454 //===----------------------------------------------------------------------===//
456 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
457 /// option string. Returns StringRef() if the option does not specify a library.
458 StringRef TargetLoweringObjectFileMachO::
459 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
460 const char *LibCmd = "-l";
461 if (LinkerOption.startswith(LibCmd))
462 return LinkerOption.substr(strlen(LibCmd));
466 /// emitModuleFlags - Perform code emission for module flags.
467 void TargetLoweringObjectFileMachO::
468 emitModuleFlags(MCStreamer &Streamer,
469 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
470 Mangler &Mang, const TargetMachine &TM) const {
471 unsigned VersionVal = 0;
472 unsigned ImageInfoFlags = 0;
473 MDNode *LinkerOptions = nullptr;
474 StringRef SectionVal;
476 for (ArrayRef<Module::ModuleFlagEntry>::iterator
477 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
478 const Module::ModuleFlagEntry &MFE = *i;
480 // Ignore flags with 'Require' behavior.
481 if (MFE.Behavior == Module::Require)
484 StringRef Key = MFE.Key->getString();
485 Metadata *Val = MFE.Val;
487 if (Key == "Objective-C Image Info Version") {
488 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
489 } else if (Key == "Objective-C Garbage Collection" ||
490 Key == "Objective-C GC Only" ||
491 Key == "Objective-C Is Simulated" ||
492 Key == "Objective-C Image Swift Version") {
493 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
494 } else if (Key == "Objective-C Image Info Section") {
495 SectionVal = cast<MDString>(Val)->getString();
496 } else if (Key == "Linker Options") {
497 LinkerOptions = cast<MDNode>(Val);
501 // Emit the linker options if present.
503 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
504 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
505 SmallVector<std::string, 4> StrOptions;
507 // Convert to strings.
508 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
509 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
510 StrOptions.push_back(MDOption->getString());
513 Streamer.EmitLinkerOptions(StrOptions);
517 // The section is mandatory. If we don't have it, then we don't have GC info.
518 if (SectionVal.empty()) return;
520 StringRef Segment, Section;
521 unsigned TAA = 0, StubSize = 0;
523 std::string ErrorCode =
524 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
525 TAA, TAAParsed, StubSize);
526 if (!ErrorCode.empty())
527 // If invalid, report the error with report_fatal_error.
528 report_fatal_error("Invalid section specifier '" + Section + "': " +
532 const MCSectionMachO *S =
533 getContext().getMachOSection(Segment, Section, TAA, StubSize,
534 SectionKind::getDataNoRel());
535 Streamer.SwitchSection(S);
536 Streamer.EmitLabel(getContext().
537 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
538 Streamer.EmitIntValue(VersionVal, 4);
539 Streamer.EmitIntValue(ImageInfoFlags, 4);
540 Streamer.AddBlankLine();
543 static void checkMachOComdat(const GlobalValue *GV) {
544 const Comdat *C = GV->getComdat();
548 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
549 "' cannot be lowered.");
552 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
553 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
554 const TargetMachine &TM) const {
555 // Parse the section specifier and create it if valid.
556 StringRef Segment, Section;
557 unsigned TAA = 0, StubSize = 0;
560 checkMachOComdat(GV);
562 std::string ErrorCode =
563 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
564 TAA, TAAParsed, StubSize);
565 if (!ErrorCode.empty()) {
566 // If invalid, report the error with report_fatal_error.
567 report_fatal_error("Global variable '" + GV->getName() +
568 "' has an invalid section specifier '" +
569 GV->getSection() + "': " + ErrorCode + ".");
573 const MCSectionMachO *S =
574 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
576 // If TAA wasn't set by ParseSectionSpecifier() above,
577 // use the value returned by getMachOSection() as a default.
579 TAA = S->getTypeAndAttributes();
581 // Okay, now that we got the section, verify that the TAA & StubSize agree.
582 // If the user declared multiple globals with different section flags, we need
583 // to reject it here.
584 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
585 // If invalid, report the error with report_fatal_error.
586 report_fatal_error("Global variable '" + GV->getName() +
587 "' section type or attributes does not match previous"
588 " section specifier");
594 const MCSection *TargetLoweringObjectFileMachO::
595 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
596 Mangler &Mang, const TargetMachine &TM) const {
597 checkMachOComdat(GV);
599 // Handle thread local data.
600 if (Kind.isThreadBSS()) return TLSBSSSection;
601 if (Kind.isThreadData()) return TLSDataSection;
604 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
606 // If this is weak/linkonce, put this in a coalescable section, either in text
607 // or data depending on if it is writable.
608 if (GV->isWeakForLinker()) {
609 if (Kind.isReadOnly())
610 return ConstTextCoalSection;
611 return DataCoalSection;
614 // FIXME: Alignment check should be handled by section classifier.
615 if (Kind.isMergeable1ByteCString() &&
616 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
617 return CStringSection;
619 // Do not put 16-bit arrays in the UString section if they have an
620 // externally visible label, this runs into issues with certain linker
622 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
623 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
624 return UStringSection;
626 // With MachO only variables whose corresponding symbol starts with 'l' or
627 // 'L' can be merged, so we only try merging GVs with private linkage.
628 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
629 if (Kind.isMergeableConst4())
630 return FourByteConstantSection;
631 if (Kind.isMergeableConst8())
632 return EightByteConstantSection;
633 if (Kind.isMergeableConst16())
634 return SixteenByteConstantSection;
637 // Otherwise, if it is readonly, but not something we can specially optimize,
638 // just drop it in .const.
639 if (Kind.isReadOnly())
640 return ReadOnlySection;
642 // If this is marked const, put it into a const section. But if the dynamic
643 // linker needs to write to it, put it in the data segment.
644 if (Kind.isReadOnlyWithRel())
645 return ConstDataSection;
647 // Put zero initialized globals with strong external linkage in the
648 // DATA, __common section with the .zerofill directive.
649 if (Kind.isBSSExtern())
650 return DataCommonSection;
652 // Put zero initialized globals with local linkage in __DATA,__bss directive
653 // with the .zerofill directive (aka .lcomm).
654 if (Kind.isBSSLocal())
655 return DataBSSSection;
657 // Otherwise, just drop the variable in the normal data section.
662 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
663 const Constant *C) const {
664 // If this constant requires a relocation, we have to put it in the data
665 // segment, not in the text segment.
666 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
667 return ConstDataSection;
669 if (Kind.isMergeableConst4())
670 return FourByteConstantSection;
671 if (Kind.isMergeableConst8())
672 return EightByteConstantSection;
673 if (Kind.isMergeableConst16())
674 return SixteenByteConstantSection;
675 return ReadOnlySection; // .const
678 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
679 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
680 const TargetMachine &TM, MachineModuleInfo *MMI,
681 MCStreamer &Streamer) const {
682 // The mach-o version of this method defaults to returning a stub reference.
684 if (Encoding & DW_EH_PE_indirect) {
685 MachineModuleInfoMachO &MachOMMI =
686 MMI->getObjFileInfo<MachineModuleInfoMachO>();
689 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
691 // Add information about the stub reference to MachOMMI so that the stub
692 // gets emitted by the asmprinter.
693 MachineModuleInfoImpl::StubValueTy &StubSym =
694 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
695 MachOMMI.getGVStubEntry(SSym);
696 if (!StubSym.getPointer()) {
697 MCSymbol *Sym = TM.getSymbol(GV, Mang);
698 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
701 return TargetLoweringObjectFile::
702 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
703 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
706 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
710 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
711 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
712 MachineModuleInfo *MMI) const {
713 // The mach-o version of this method defaults to returning a stub reference.
714 MachineModuleInfoMachO &MachOMMI =
715 MMI->getObjFileInfo<MachineModuleInfoMachO>();
717 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
719 // Add information about the stub reference to MachOMMI so that the stub
720 // gets emitted by the asmprinter.
721 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
722 if (!StubSym.getPointer()) {
723 MCSymbol *Sym = TM.getSymbol(GV, Mang);
724 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
730 //===----------------------------------------------------------------------===//
732 //===----------------------------------------------------------------------===//
735 getCOFFSectionFlags(SectionKind K) {
740 COFF::IMAGE_SCN_MEM_DISCARDABLE;
743 COFF::IMAGE_SCN_MEM_EXECUTE |
744 COFF::IMAGE_SCN_MEM_READ |
745 COFF::IMAGE_SCN_CNT_CODE;
748 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
749 COFF::IMAGE_SCN_MEM_READ |
750 COFF::IMAGE_SCN_MEM_WRITE;
751 else if (K.isThreadLocal())
753 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
754 COFF::IMAGE_SCN_MEM_READ |
755 COFF::IMAGE_SCN_MEM_WRITE;
756 else if (K.isReadOnly() || K.isReadOnlyWithRel())
758 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
759 COFF::IMAGE_SCN_MEM_READ;
760 else if (K.isWriteable())
762 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
763 COFF::IMAGE_SCN_MEM_READ |
764 COFF::IMAGE_SCN_MEM_WRITE;
769 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
770 const Comdat *C = GV->getComdat();
771 assert(C && "expected GV to have a Comdat!");
773 StringRef ComdatGVName = C->getName();
774 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
776 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
777 "' does not exist.");
779 if (ComdatGV->getComdat() != C)
780 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
781 "' is not a key for its COMDAT.");
786 static int getSelectionForCOFF(const GlobalValue *GV) {
787 if (const Comdat *C = GV->getComdat()) {
788 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
789 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
790 ComdatKey = GA->getBaseObject();
791 if (ComdatKey == GV) {
792 switch (C->getSelectionKind()) {
794 return COFF::IMAGE_COMDAT_SELECT_ANY;
795 case Comdat::ExactMatch:
796 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
797 case Comdat::Largest:
798 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
799 case Comdat::NoDuplicates:
800 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
801 case Comdat::SameSize:
802 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
805 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
807 } else if (GV->isWeakForLinker()) {
808 return COFF::IMAGE_COMDAT_SELECT_ANY;
813 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
814 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
815 const TargetMachine &TM) const {
817 unsigned Characteristics = getCOFFSectionFlags(Kind);
818 StringRef Name = GV->getSection();
819 StringRef COMDATSymName = "";
820 if (GV->hasComdat()) {
821 Selection = getSelectionForCOFF(GV);
822 const GlobalValue *ComdatGV;
823 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
824 ComdatGV = getComdatGVForCOFF(GV);
828 if (!ComdatGV->hasPrivateLinkage()) {
829 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
830 COMDATSymName = Sym->getName();
831 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
836 return getContext().getCOFFSection(Name,
843 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
848 if (Kind.isThreadLocal())
850 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
856 const MCSection *TargetLoweringObjectFileCOFF::
857 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
858 Mangler &Mang, const TargetMachine &TM) const {
859 // If we have -ffunction-sections then we should emit the global value to a
860 // uniqued section specifically for it.
861 bool EmitUniquedSection;
863 EmitUniquedSection = TM.getFunctionSections();
865 EmitUniquedSection = TM.getDataSections();
867 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
868 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
869 unsigned Characteristics = getCOFFSectionFlags(Kind);
871 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
872 int Selection = getSelectionForCOFF(GV);
874 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
875 const GlobalValue *ComdatGV;
877 ComdatGV = getComdatGVForCOFF(GV);
881 if (!ComdatGV->hasPrivateLinkage()) {
882 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
883 StringRef COMDATSymName = Sym->getName();
884 return getContext().getCOFFSection(Name, Characteristics, Kind,
885 COMDATSymName, Selection);
892 if (Kind.isThreadLocal())
893 return TLSDataSection;
895 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
896 return ReadOnlySection;
898 // Note: we claim that common symbols are put in BSSSection, but they are
899 // really emitted with the magic .comm directive, which creates a symbol table
900 // entry but not a section.
901 if (Kind.isBSS() || Kind.isCommon())
907 StringRef TargetLoweringObjectFileCOFF::
908 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
909 const char *LibCmd = "/DEFAULTLIB:";
910 if (LinkerOption.startswith(LibCmd))
911 return LinkerOption.substr(strlen(LibCmd));
915 void TargetLoweringObjectFileCOFF::
916 emitModuleFlags(MCStreamer &Streamer,
917 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
918 Mangler &Mang, const TargetMachine &TM) const {
919 MDNode *LinkerOptions = nullptr;
921 // Look for the "Linker Options" flag, since it's the only one we support.
922 for (ArrayRef<Module::ModuleFlagEntry>::iterator
923 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
924 const Module::ModuleFlagEntry &MFE = *i;
925 StringRef Key = MFE.Key->getString();
926 Metadata *Val = MFE.Val;
927 if (Key == "Linker Options") {
928 LinkerOptions = cast<MDNode>(Val);
935 // Emit the linker options to the linker .drectve section. According to the
936 // spec, this section is a space-separated string containing flags for linker.
937 const MCSection *Sec = getDrectveSection();
938 Streamer.SwitchSection(Sec);
939 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
940 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
941 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
942 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
943 StringRef Op = MDOption->getString();
944 // Lead with a space for consistency with our dllexport implementation.
945 std::string Escaped(" ");
946 if (!Op.startswith("\"") && (Op.find(" ") != StringRef::npos)) {
947 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
948 // how to escape quotes, but it probably uses this algorithm:
949 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
950 // FIXME: Reuse escaping code from Support/Windows/Program.inc
951 Escaped.push_back('\"');
953 Escaped.push_back('\"');
957 Streamer.EmitBytes(Escaped);
962 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
963 unsigned Priority, const MCSymbol *KeySym) const {
964 return getContext().getAssociativeCOFFSection(
965 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
968 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
969 unsigned Priority, const MCSymbol *KeySym) const {
970 return getContext().getAssociativeCOFFSection(
971 cast<MCSectionCOFF>(StaticDtorSection), KeySym);