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/MCAsmInfo.h"
28 #include "llvm/MC/MCContext.h"
29 #include "llvm/MC/MCExpr.h"
30 #include "llvm/MC/MCSectionCOFF.h"
31 #include "llvm/MC/MCSectionELF.h"
32 #include "llvm/MC/MCSectionMachO.h"
33 #include "llvm/MC/MCStreamer.h"
34 #include "llvm/MC/MCSymbolELF.h"
35 #include "llvm/MC/MCValue.h"
36 #include "llvm/ProfileData/InstrProf.h"
37 #include "llvm/Support/COFF.h"
38 #include "llvm/Support/Dwarf.h"
39 #include "llvm/Support/ELF.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Target/TargetLowering.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Target/TargetSubtargetInfo.h"
46 using namespace dwarf;
48 //===----------------------------------------------------------------------===//
50 //===----------------------------------------------------------------------===//
52 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
53 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
54 MachineModuleInfo *MMI) const {
55 unsigned Encoding = getPersonalityEncoding();
56 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
57 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
58 TM.getSymbol(GV, Mang)->getName());
59 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
60 return TM.getSymbol(GV, Mang);
61 report_fatal_error("We do not support this DWARF encoding yet!");
64 void TargetLoweringObjectFileELF::emitPersonalityValue(
65 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
66 SmallString<64> NameData("DW.ref.");
67 NameData += Sym->getName();
69 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
70 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
71 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
72 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
73 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
74 ELF::SHT_PROGBITS, Flags, 0);
75 unsigned Size = DL.getPointerSize();
76 Streamer.SwitchSection(Sec);
77 Streamer.EmitValueToAlignment(DL.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
122 if (Name == getInstrProfCoverageSectionName(false))
123 return SectionKind::getMetadata();
125 if (Name.empty() || Name[0] != '.') return K;
127 // Some lame default implementation based on some magic section names.
128 if (Name == ".bss" ||
129 Name.startswith(".bss.") ||
130 Name.startswith(".gnu.linkonce.b.") ||
131 Name.startswith(".llvm.linkonce.b.") ||
133 Name.startswith(".sbss.") ||
134 Name.startswith(".gnu.linkonce.sb.") ||
135 Name.startswith(".llvm.linkonce.sb."))
136 return SectionKind::getBSS();
138 if (Name == ".tdata" ||
139 Name.startswith(".tdata.") ||
140 Name.startswith(".gnu.linkonce.td.") ||
141 Name.startswith(".llvm.linkonce.td."))
142 return SectionKind::getThreadData();
144 if (Name == ".tbss" ||
145 Name.startswith(".tbss.") ||
146 Name.startswith(".gnu.linkonce.tb.") ||
147 Name.startswith(".llvm.linkonce.tb."))
148 return SectionKind::getThreadBSS();
154 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
156 if (Name == ".init_array")
157 return ELF::SHT_INIT_ARRAY;
159 if (Name == ".fini_array")
160 return ELF::SHT_FINI_ARRAY;
162 if (Name == ".preinit_array")
163 return ELF::SHT_PREINIT_ARRAY;
165 if (K.isBSS() || K.isThreadBSS())
166 return ELF::SHT_NOBITS;
168 return ELF::SHT_PROGBITS;
171 static unsigned 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 if (K.isMergeableCString() || K.isMergeableConst())
187 Flags |= ELF::SHF_MERGE;
189 if (K.isMergeableCString())
190 Flags |= ELF::SHF_STRINGS;
195 static const Comdat *getELFComdat(const GlobalValue *GV) {
196 const Comdat *C = GV->getComdat();
200 if (C->getSelectionKind() != Comdat::Any)
201 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
202 C->getName() + "' cannot be lowered.");
207 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
208 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
209 const TargetMachine &TM) const {
210 StringRef SectionName = GV->getSection();
212 // Infer section flags from the section name if we can.
213 Kind = getELFKindForNamedSection(SectionName, Kind);
215 StringRef Group = "";
216 unsigned Flags = getELFSectionFlags(Kind);
217 if (const Comdat *C = getELFComdat(GV)) {
218 Group = C->getName();
219 Flags |= ELF::SHF_GROUP;
221 return getContext().getELFSection(SectionName,
222 getELFSectionType(SectionName, Kind), Flags,
223 /*EntrySize=*/0, Group);
226 /// Return the section prefix name used by options FunctionsSections and
228 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
231 if (Kind.isReadOnly())
235 if (Kind.isThreadData())
237 if (Kind.isThreadBSS())
241 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
242 return ".data.rel.ro";
245 static MCSectionELF *
246 selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
247 SectionKind Kind, Mangler &Mang,
248 const TargetMachine &TM, bool EmitUniqueSection,
249 unsigned Flags, unsigned *NextUniqueID) {
250 unsigned EntrySize = 0;
251 if (Kind.isMergeableCString()) {
252 if (Kind.isMergeable2ByteCString()) {
254 } else if (Kind.isMergeable4ByteCString()) {
258 assert(Kind.isMergeable1ByteCString() && "unknown string width");
260 } else if (Kind.isMergeableConst()) {
261 if (Kind.isMergeableConst4()) {
263 } else if (Kind.isMergeableConst8()) {
265 } else if (Kind.isMergeableConst16()) {
268 assert(Kind.isMergeableConst32() && "unknown data width");
273 StringRef Group = "";
274 if (const Comdat *C = getELFComdat(GV)) {
275 Flags |= ELF::SHF_GROUP;
276 Group = C->getName();
279 bool UniqueSectionNames = TM.getUniqueSectionNames();
280 SmallString<128> Name;
281 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!
285 unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
286 cast<GlobalVariable>(GV));
288 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
289 Name = SizeSpec + utostr(Align);
290 } else if (Kind.isMergeableConst()) {
291 Name = ".rodata.cst";
292 Name += utostr(EntrySize);
294 Name = getSectionPrefixForGlobal(Kind);
296 // FIXME: Extend the section prefix to include hotness catagories such as .hot
297 // or .unlikely for functions.
299 if (EmitUniqueSection && UniqueSectionNames) {
301 TM.getNameWithPrefix(Name, GV, Mang, true);
303 unsigned UniqueID = MCContext::GenericSectionID;
304 if (EmitUniqueSection && !UniqueSectionNames) {
305 UniqueID = *NextUniqueID;
308 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
309 EntrySize, Group, UniqueID);
312 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
313 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
314 const TargetMachine &TM) const {
315 unsigned Flags = getELFSectionFlags(Kind);
317 // If we have -ffunction-section or -fdata-section then we should emit the
318 // global value to a uniqued section specifically for it.
319 bool EmitUniqueSection = false;
320 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
322 EmitUniqueSection = TM.getFunctionSections();
324 EmitUniqueSection = TM.getDataSections();
326 EmitUniqueSection |= GV->hasComdat();
328 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
329 EmitUniqueSection, Flags, &NextUniqueID);
332 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
333 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
334 // If the function can be removed, produce a unique section so that
335 // the table doesn't prevent the removal.
336 const Comdat *C = F.getComdat();
337 bool EmitUniqueSection = TM.getFunctionSections() || C;
338 if (!EmitUniqueSection)
339 return ReadOnlySection;
341 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
342 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
346 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
347 bool UsesLabelDifference, const Function &F) const {
348 // We can always create relative relocations, so use another section
349 // that can be marked non-executable.
353 /// Given a mergeable constant with the specified size and relocation
354 /// information, return a section that it should be placed in.
355 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
356 const DataLayout &DL, SectionKind Kind, const Constant *C,
357 unsigned &Align) const {
358 if (Kind.isMergeableConst4() && MergeableConst4Section)
359 return MergeableConst4Section;
360 if (Kind.isMergeableConst8() && MergeableConst8Section)
361 return MergeableConst8Section;
362 if (Kind.isMergeableConst16() && MergeableConst16Section)
363 return MergeableConst16Section;
364 if (Kind.isMergeableConst32() && MergeableConst32Section)
365 return MergeableConst32Section;
366 if (Kind.isReadOnly())
367 return ReadOnlySection;
369 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
370 return DataRelROSection;
373 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
374 bool IsCtor, unsigned Priority,
375 const MCSymbol *KeySym) {
378 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
379 StringRef COMDAT = KeySym ? KeySym->getName() : "";
382 Flags |= ELF::SHF_GROUP;
386 Type = ELF::SHT_INIT_ARRAY;
387 Name = ".init_array";
389 Type = ELF::SHT_FINI_ARRAY;
390 Name = ".fini_array";
392 if (Priority != 65535) {
394 Name += utostr(Priority);
397 // The default scheme is .ctor / .dtor, so we have to invert the priority
403 if (Priority != 65535) {
405 Name += utostr(65535 - Priority);
407 Type = ELF::SHT_PROGBITS;
410 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
413 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
414 unsigned Priority, const MCSymbol *KeySym) const {
415 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
419 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
420 unsigned Priority, const MCSymbol *KeySym) const {
421 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
425 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
426 const GlobalValue *LHS, const GlobalValue *RHS, Mangler &Mang,
427 const TargetMachine &TM) const {
428 // We may only use a PLT-relative relocation to refer to unnamed_addr
430 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
433 // Basic sanity checks.
434 if (LHS->getType()->getPointerAddressSpace() != 0 ||
435 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
436 RHS->isThreadLocal())
439 return MCBinaryExpr::createSub(
440 MCSymbolRefExpr::create(TM.getSymbol(LHS, Mang), PLTRelativeVariantKind,
442 MCSymbolRefExpr::create(TM.getSymbol(RHS, Mang), getContext()),
447 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
448 UseInitArray = UseInitArray_;
452 StaticCtorSection = getContext().getELFSection(
453 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
454 StaticDtorSection = getContext().getELFSection(
455 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
458 //===----------------------------------------------------------------------===//
460 //===----------------------------------------------------------------------===//
462 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
463 : TargetLoweringObjectFile() {
464 SupportIndirectSymViaGOTPCRel = true;
467 /// emitModuleFlags - Perform code emission for module flags.
468 void TargetLoweringObjectFileMachO::
469 emitModuleFlags(MCStreamer &Streamer,
470 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
471 Mangler &Mang, const TargetMachine &TM) const {
472 unsigned VersionVal = 0;
473 unsigned ImageInfoFlags = 0;
474 MDNode *LinkerOptions = nullptr;
475 StringRef SectionVal;
477 for (const auto &MFE : ModuleFlags) {
478 // Ignore flags with 'Require' behavior.
479 if (MFE.Behavior == Module::Require)
482 StringRef Key = MFE.Key->getString();
483 Metadata *Val = MFE.Val;
485 if (Key == "Objective-C Image Info Version") {
486 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
487 } else if (Key == "Objective-C Garbage Collection" ||
488 Key == "Objective-C GC Only" ||
489 Key == "Objective-C Is Simulated" ||
490 Key == "Objective-C Class Properties" ||
491 Key == "Objective-C Image Swift Version") {
492 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
493 } else if (Key == "Objective-C Image Info Section") {
494 SectionVal = cast<MDString>(Val)->getString();
495 } else if (Key == "Linker Options") {
496 LinkerOptions = cast<MDNode>(Val);
500 // Emit the linker options if present.
502 for (const auto &Option : LinkerOptions->operands()) {
503 SmallVector<std::string, 4> StrOptions;
504 for (const auto &Piece : cast<MDNode>(Option)->operands())
505 StrOptions.push_back(cast<MDString>(Piece)->getString());
506 Streamer.EmitLinkerOptions(StrOptions);
510 // The section is mandatory. If we don't have it, then we don't have GC info.
511 if (SectionVal.empty()) return;
513 StringRef Segment, Section;
514 unsigned TAA = 0, StubSize = 0;
516 std::string ErrorCode =
517 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
518 TAA, TAAParsed, StubSize);
519 if (!ErrorCode.empty())
520 // If invalid, report the error with report_fatal_error.
521 report_fatal_error("Invalid section specifier '" + Section + "': " +
525 MCSectionMachO *S = getContext().getMachOSection(
526 Segment, Section, TAA, StubSize, SectionKind::getData());
527 Streamer.SwitchSection(S);
528 Streamer.EmitLabel(getContext().
529 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
530 Streamer.EmitIntValue(VersionVal, 4);
531 Streamer.EmitIntValue(ImageInfoFlags, 4);
532 Streamer.AddBlankLine();
535 static void checkMachOComdat(const GlobalValue *GV) {
536 const Comdat *C = GV->getComdat();
540 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
541 "' cannot be lowered.");
544 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
545 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
546 const TargetMachine &TM) const {
547 // Parse the section specifier and create it if valid.
548 StringRef Segment, Section;
549 unsigned TAA = 0, StubSize = 0;
552 checkMachOComdat(GV);
554 std::string ErrorCode =
555 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
556 TAA, TAAParsed, StubSize);
557 if (!ErrorCode.empty()) {
558 // If invalid, report the error with report_fatal_error.
559 report_fatal_error("Global variable '" + GV->getName() +
560 "' has an invalid section specifier '" +
561 GV->getSection() + "': " + ErrorCode + ".");
566 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
568 // If TAA wasn't set by ParseSectionSpecifier() above,
569 // use the value returned by getMachOSection() as a default.
571 TAA = S->getTypeAndAttributes();
573 // Okay, now that we got the section, verify that the TAA & StubSize agree.
574 // If the user declared multiple globals with different section flags, we need
575 // to reject it here.
576 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
577 // If invalid, report the error with report_fatal_error.
578 report_fatal_error("Global variable '" + GV->getName() +
579 "' section type or attributes does not match previous"
580 " section specifier");
586 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
587 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
588 const TargetMachine &TM) const {
589 checkMachOComdat(GV);
591 // Handle thread local data.
592 if (Kind.isThreadBSS()) return TLSBSSSection;
593 if (Kind.isThreadData()) return TLSDataSection;
596 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
598 // If this is weak/linkonce, put this in a coalescable section, either in text
599 // or data depending on if it is writable.
600 if (GV->isWeakForLinker()) {
601 if (Kind.isReadOnly())
602 return ConstTextCoalSection;
603 return DataCoalSection;
606 // FIXME: Alignment check should be handled by section classifier.
607 if (Kind.isMergeable1ByteCString() &&
608 GV->getParent()->getDataLayout().getPreferredAlignment(
609 cast<GlobalVariable>(GV)) < 32)
610 return CStringSection;
612 // Do not put 16-bit arrays in the UString section if they have an
613 // externally visible label, this runs into issues with certain linker
615 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
616 GV->getParent()->getDataLayout().getPreferredAlignment(
617 cast<GlobalVariable>(GV)) < 32)
618 return UStringSection;
620 // With MachO only variables whose corresponding symbol starts with 'l' or
621 // 'L' can be merged, so we only try merging GVs with private linkage.
622 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
623 if (Kind.isMergeableConst4())
624 return FourByteConstantSection;
625 if (Kind.isMergeableConst8())
626 return EightByteConstantSection;
627 if (Kind.isMergeableConst16())
628 return SixteenByteConstantSection;
631 // Otherwise, if it is readonly, but not something we can specially optimize,
632 // just drop it in .const.
633 if (Kind.isReadOnly())
634 return ReadOnlySection;
636 // If this is marked const, put it into a const section. But if the dynamic
637 // linker needs to write to it, put it in the data segment.
638 if (Kind.isReadOnlyWithRel())
639 return ConstDataSection;
641 // Put zero initialized globals with strong external linkage in the
642 // DATA, __common section with the .zerofill directive.
643 if (Kind.isBSSExtern())
644 return DataCommonSection;
646 // Put zero initialized globals with local linkage in __DATA,__bss directive
647 // with the .zerofill directive (aka .lcomm).
648 if (Kind.isBSSLocal())
649 return DataBSSSection;
651 // Otherwise, just drop the variable in the normal data section.
655 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
656 const DataLayout &DL, SectionKind Kind, const Constant *C,
657 unsigned &Align) const {
658 // If this constant requires a relocation, we have to put it in the data
659 // segment, not in the text segment.
660 if (Kind.isData() || Kind.isReadOnlyWithRel())
661 return ConstDataSection;
663 if (Kind.isMergeableConst4())
664 return FourByteConstantSection;
665 if (Kind.isMergeableConst8())
666 return EightByteConstantSection;
667 if (Kind.isMergeableConst16())
668 return SixteenByteConstantSection;
669 return ReadOnlySection; // .const
672 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
673 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
674 const TargetMachine &TM, MachineModuleInfo *MMI,
675 MCStreamer &Streamer) const {
676 // The mach-o version of this method defaults to returning a stub reference.
678 if (Encoding & DW_EH_PE_indirect) {
679 MachineModuleInfoMachO &MachOMMI =
680 MMI->getObjFileInfo<MachineModuleInfoMachO>();
683 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
685 // Add information about the stub reference to MachOMMI so that the stub
686 // gets emitted by the asmprinter.
687 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
688 if (!StubSym.getPointer()) {
689 MCSymbol *Sym = TM.getSymbol(GV, Mang);
690 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
693 return TargetLoweringObjectFile::
694 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
695 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
698 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
702 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
703 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
704 MachineModuleInfo *MMI) const {
705 // The mach-o version of this method defaults to returning a stub reference.
706 MachineModuleInfoMachO &MachOMMI =
707 MMI->getObjFileInfo<MachineModuleInfoMachO>();
709 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
711 // Add information about the stub reference to MachOMMI so that the stub
712 // gets emitted by the asmprinter.
713 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
714 if (!StubSym.getPointer()) {
715 MCSymbol *Sym = TM.getSymbol(GV, Mang);
716 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
722 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
723 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
724 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
725 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
726 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
727 // through a non_lazy_ptr stub instead. One advantage is that it allows the
728 // computation of deltas to final external symbols. Example:
734 // .long _extgotequiv-_delta
736 // is transformed to:
739 // .long L_extfoo$non_lazy_ptr-(_delta+0)
741 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
742 // L_extfoo$non_lazy_ptr:
743 // .indirect_symbol _extfoo
746 MachineModuleInfoMachO &MachOMMI =
747 MMI->getObjFileInfo<MachineModuleInfoMachO>();
748 MCContext &Ctx = getContext();
750 // The offset must consider the original displacement from the base symbol
751 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
752 Offset = -MV.getConstant();
753 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
755 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
756 // non_lazy_ptr stubs.
757 SmallString<128> Name;
758 StringRef Suffix = "$non_lazy_ptr";
759 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
760 Name += Sym->getName();
762 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
764 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
765 if (!StubSym.getPointer())
766 StubSym = MachineModuleInfoImpl::
767 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
769 const MCExpr *BSymExpr =
770 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
772 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
775 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
778 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
779 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
782 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
783 const MCSection &Section) {
784 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
787 // If it is not dead stripped, it is safe to use private labels.
788 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
789 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
795 void TargetLoweringObjectFileMachO::getNameWithPrefix(
796 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
797 const TargetMachine &TM) const {
798 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
799 const MCSection *TheSection = SectionForGlobal(GV, GVKind, Mang, TM);
800 bool CannotUsePrivateLabel =
801 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
802 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
805 //===----------------------------------------------------------------------===//
807 //===----------------------------------------------------------------------===//
810 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
812 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
816 COFF::IMAGE_SCN_MEM_DISCARDABLE;
819 COFF::IMAGE_SCN_MEM_EXECUTE |
820 COFF::IMAGE_SCN_MEM_READ |
821 COFF::IMAGE_SCN_CNT_CODE |
822 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
825 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
826 COFF::IMAGE_SCN_MEM_READ |
827 COFF::IMAGE_SCN_MEM_WRITE;
828 else if (K.isThreadLocal())
830 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
831 COFF::IMAGE_SCN_MEM_READ |
832 COFF::IMAGE_SCN_MEM_WRITE;
833 else if (K.isReadOnly() || K.isReadOnlyWithRel())
835 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
836 COFF::IMAGE_SCN_MEM_READ;
837 else if (K.isWriteable())
839 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
840 COFF::IMAGE_SCN_MEM_READ |
841 COFF::IMAGE_SCN_MEM_WRITE;
846 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
847 const Comdat *C = GV->getComdat();
848 assert(C && "expected GV to have a Comdat!");
850 StringRef ComdatGVName = C->getName();
851 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
853 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
854 "' does not exist.");
856 if (ComdatGV->getComdat() != C)
857 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
858 "' is not a key for its COMDAT.");
863 static int getSelectionForCOFF(const GlobalValue *GV) {
864 if (const Comdat *C = GV->getComdat()) {
865 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
866 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
867 ComdatKey = GA->getBaseObject();
868 if (ComdatKey == GV) {
869 switch (C->getSelectionKind()) {
871 return COFF::IMAGE_COMDAT_SELECT_ANY;
872 case Comdat::ExactMatch:
873 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
874 case Comdat::Largest:
875 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
876 case Comdat::NoDuplicates:
877 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
878 case Comdat::SameSize:
879 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
882 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
888 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
889 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
890 const TargetMachine &TM) const {
892 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
893 StringRef Name = GV->getSection();
894 StringRef COMDATSymName = "";
895 if (GV->hasComdat()) {
896 Selection = getSelectionForCOFF(GV);
897 const GlobalValue *ComdatGV;
898 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
899 ComdatGV = getComdatGVForCOFF(GV);
903 if (!ComdatGV->hasPrivateLinkage()) {
904 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
905 COMDATSymName = Sym->getName();
906 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
912 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
916 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
921 if (Kind.isThreadLocal())
923 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
928 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
929 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
930 const TargetMachine &TM) const {
931 // If we have -ffunction-sections then we should emit the global value to a
932 // uniqued section specifically for it.
933 bool EmitUniquedSection;
935 EmitUniquedSection = TM.getFunctionSections();
937 EmitUniquedSection = TM.getDataSections();
939 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
940 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
941 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
943 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
944 int Selection = getSelectionForCOFF(GV);
946 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
947 const GlobalValue *ComdatGV;
949 ComdatGV = getComdatGVForCOFF(GV);
953 unsigned UniqueID = MCContext::GenericSectionID;
954 if (EmitUniquedSection)
955 UniqueID = NextUniqueID++;
957 if (!ComdatGV->hasPrivateLinkage()) {
958 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
959 StringRef COMDATSymName = Sym->getName();
960 return getContext().getCOFFSection(Name, Characteristics, Kind,
961 COMDATSymName, Selection, UniqueID);
963 SmallString<256> TmpData;
964 Mang.getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
965 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
966 Selection, UniqueID);
973 if (Kind.isThreadLocal())
974 return TLSDataSection;
976 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
977 return ReadOnlySection;
979 // Note: we claim that common symbols are put in BSSSection, but they are
980 // really emitted with the magic .comm directive, which creates a symbol table
981 // entry but not a section.
982 if (Kind.isBSS() || Kind.isCommon())
988 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
989 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
990 const TargetMachine &TM) const {
991 bool CannotUsePrivateLabel = false;
992 if (GV->hasPrivateLinkage() &&
993 ((isa<Function>(GV) && TM.getFunctionSections()) ||
994 (isa<GlobalVariable>(GV) && TM.getDataSections())))
995 CannotUsePrivateLabel = true;
997 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1000 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1001 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
1002 // If the function can be removed, produce a unique section so that
1003 // the table doesn't prevent the removal.
1004 const Comdat *C = F.getComdat();
1005 bool EmitUniqueSection = TM.getFunctionSections() || C;
1006 if (!EmitUniqueSection)
1007 return ReadOnlySection;
1009 // FIXME: we should produce a symbol for F instead.
1010 if (F.hasPrivateLinkage())
1011 return ReadOnlySection;
1013 MCSymbol *Sym = TM.getSymbol(&F, Mang);
1014 StringRef COMDATSymName = Sym->getName();
1016 SectionKind Kind = SectionKind::getReadOnly();
1017 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1018 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1019 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1020 unsigned UniqueID = NextUniqueID++;
1022 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1023 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1026 void TargetLoweringObjectFileCOFF::
1027 emitModuleFlags(MCStreamer &Streamer,
1028 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1029 Mangler &Mang, const TargetMachine &TM) const {
1030 MDNode *LinkerOptions = nullptr;
1032 for (const auto &MFE : ModuleFlags) {
1033 StringRef Key = MFE.Key->getString();
1034 if (Key == "Linker Options")
1035 LinkerOptions = cast<MDNode>(MFE.Val);
1038 if (LinkerOptions) {
1039 // Emit the linker options to the linker .drectve section. According to the
1040 // spec, this section is a space-separated string containing flags for
1042 MCSection *Sec = getDrectveSection();
1043 Streamer.SwitchSection(Sec);
1044 for (const auto &Option : LinkerOptions->operands()) {
1045 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1046 // Lead with a space for consistency with our dllexport implementation.
1047 std::string Directive(" ");
1048 Directive.append(cast<MDString>(Piece)->getString());
1049 Streamer.EmitBytes(Directive);
1055 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1056 unsigned Priority, const MCSymbol *KeySym) const {
1057 return getContext().getAssociativeCOFFSection(
1058 cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
1061 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1062 unsigned Priority, const MCSymbol *KeySym) const {
1063 return getContext().getAssociativeCOFFSection(
1064 cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
1067 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1068 raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
1069 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1072 const Triple &TT = getTargetTriple();
1074 if (TT.isKnownWindowsMSVCEnvironment())
1079 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1081 raw_string_ostream FlagOS(Flag);
1082 Mang.getNameWithPrefix(FlagOS, GV, false);
1084 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
1085 OS << Flag.substr(1);
1089 Mang.getNameWithPrefix(OS, GV, false);
1092 if (!GV->getValueType()->isFunctionTy()) {
1093 if (TT.isKnownWindowsMSVCEnvironment())