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/SmallVector.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/BinaryFormat/COFF.h"
22 #include "llvm/BinaryFormat/Dwarf.h"
23 #include "llvm/BinaryFormat/ELF.h"
24 #include "llvm/BinaryFormat/MachO.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
27 #include "llvm/IR/Comdat.h"
28 #include "llvm/IR/Constants.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GlobalAlias.h"
33 #include "llvm/IR/GlobalObject.h"
34 #include "llvm/IR/GlobalValue.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/IR/Mangler.h"
37 #include "llvm/IR/Metadata.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/IR/Type.h"
40 #include "llvm/MC/MCAsmInfo.h"
41 #include "llvm/MC/MCContext.h"
42 #include "llvm/MC/MCExpr.h"
43 #include "llvm/MC/MCSectionCOFF.h"
44 #include "llvm/MC/MCSectionELF.h"
45 #include "llvm/MC/MCSectionMachO.h"
46 #include "llvm/MC/MCSectionWasm.h"
47 #include "llvm/MC/MCStreamer.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/MC/MCSymbolELF.h"
50 #include "llvm/MC/MCValue.h"
51 #include "llvm/MC/SectionKind.h"
52 #include "llvm/ProfileData/InstrProf.h"
53 #include "llvm/Support/Casting.h"
54 #include "llvm/Support/CodeGen.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Target/TargetMachine.h"
62 using namespace dwarf;
64 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
66 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
67 M.getModuleFlagsMetadata(ModuleFlags);
69 for (const auto &MFE: ModuleFlags) {
70 // Ignore flags with 'Require' behaviour.
71 if (MFE.Behavior == Module::Require)
74 StringRef Key = MFE.Key->getString();
75 if (Key == "Objective-C Image Info Version") {
76 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
77 } else if (Key == "Objective-C Garbage Collection" ||
78 Key == "Objective-C GC Only" ||
79 Key == "Objective-C Is Simulated" ||
80 Key == "Objective-C Class Properties" ||
81 Key == "Objective-C Image Swift Version") {
82 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
83 } else if (Key == "Objective-C Image Info Section") {
84 Section = cast<MDString>(MFE.Val)->getString();
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 void TargetLoweringObjectFileELF::emitModuleMetadata(
94 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
99 GetObjCImageInfo(M, Version, Flags, Section);
103 auto &C = getContext();
104 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
105 Streamer.SwitchSection(S);
106 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
107 Streamer.EmitIntValue(Version, 4);
108 Streamer.EmitIntValue(Flags, 4);
109 Streamer.AddBlankLine();
112 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
113 const GlobalValue *GV, const TargetMachine &TM,
114 MachineModuleInfo *MMI) const {
115 unsigned Encoding = getPersonalityEncoding();
116 if ((Encoding & 0x80) == DW_EH_PE_indirect)
117 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
118 TM.getSymbol(GV)->getName());
119 if ((Encoding & 0x70) == DW_EH_PE_absptr)
120 return TM.getSymbol(GV);
121 report_fatal_error("We do not support this DWARF encoding yet!");
124 void TargetLoweringObjectFileELF::emitPersonalityValue(
125 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
126 SmallString<64> NameData("DW.ref.");
127 NameData += Sym->getName();
129 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
130 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
131 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
132 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
133 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
134 ELF::SHT_PROGBITS, Flags, 0);
135 unsigned Size = DL.getPointerSize();
136 Streamer.SwitchSection(Sec);
137 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
138 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
139 const MCExpr *E = MCConstantExpr::create(Size, getContext());
140 Streamer.emitELFSize(Label, E);
141 Streamer.EmitLabel(Label);
143 Streamer.EmitSymbolValue(Sym, Size);
146 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
147 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
148 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
149 if (Encoding & DW_EH_PE_indirect) {
150 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
152 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
154 // Add information about the stub reference to ELFMMI so that the stub
155 // gets emitted by the asmprinter.
156 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
157 if (!StubSym.getPointer()) {
158 MCSymbol *Sym = TM.getSymbol(GV);
159 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
162 return TargetLoweringObjectFile::
163 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
164 Encoding & ~DW_EH_PE_indirect, Streamer);
167 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
172 getELFKindForNamedSection(StringRef Name, SectionKind K) {
173 // N.B.: The defaults used in here are no the same ones used in MC.
174 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
175 // both gas and MC will produce a section with no flags. Given
176 // section(".eh_frame") gcc will produce:
178 // .section .eh_frame,"a",@progbits
180 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
181 /*AddSegmentInfo=*/false))
182 return SectionKind::getMetadata();
184 if (Name.empty() || Name[0] != '.') return K;
186 // Some lame default implementation based on some magic section names.
187 if (Name == ".bss" ||
188 Name.startswith(".bss.") ||
189 Name.startswith(".gnu.linkonce.b.") ||
190 Name.startswith(".llvm.linkonce.b.") ||
192 Name.startswith(".sbss.") ||
193 Name.startswith(".gnu.linkonce.sb.") ||
194 Name.startswith(".llvm.linkonce.sb."))
195 return SectionKind::getBSS();
197 if (Name == ".tdata" ||
198 Name.startswith(".tdata.") ||
199 Name.startswith(".gnu.linkonce.td.") ||
200 Name.startswith(".llvm.linkonce.td."))
201 return SectionKind::getThreadData();
203 if (Name == ".tbss" ||
204 Name.startswith(".tbss.") ||
205 Name.startswith(".gnu.linkonce.tb.") ||
206 Name.startswith(".llvm.linkonce.tb."))
207 return SectionKind::getThreadBSS();
212 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
213 // Use SHT_NOTE for section whose name starts with ".note" to allow
214 // emitting ELF notes from C variable declaration.
215 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
216 if (Name.startswith(".note"))
217 return ELF::SHT_NOTE;
219 if (Name == ".init_array")
220 return ELF::SHT_INIT_ARRAY;
222 if (Name == ".fini_array")
223 return ELF::SHT_FINI_ARRAY;
225 if (Name == ".preinit_array")
226 return ELF::SHT_PREINIT_ARRAY;
228 if (K.isBSS() || K.isThreadBSS())
229 return ELF::SHT_NOBITS;
231 return ELF::SHT_PROGBITS;
234 static unsigned getELFSectionFlags(SectionKind K) {
238 Flags |= ELF::SHF_ALLOC;
241 Flags |= ELF::SHF_EXECINSTR;
243 if (K.isExecuteOnly())
244 Flags |= ELF::SHF_ARM_PURECODE;
247 Flags |= ELF::SHF_WRITE;
249 if (K.isThreadLocal())
250 Flags |= ELF::SHF_TLS;
252 if (K.isMergeableCString() || K.isMergeableConst())
253 Flags |= ELF::SHF_MERGE;
255 if (K.isMergeableCString())
256 Flags |= ELF::SHF_STRINGS;
261 static const Comdat *getELFComdat(const GlobalValue *GV) {
262 const Comdat *C = GV->getComdat();
266 if (C->getSelectionKind() != Comdat::Any)
267 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
268 C->getName() + "' cannot be lowered.");
273 static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
274 const TargetMachine &TM) {
275 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
279 const MDOperand &Op = MD->getOperand(0);
283 auto *VM = dyn_cast<ValueAsMetadata>(Op);
285 report_fatal_error("MD_associated operand is not ValueAsMetadata");
287 GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
288 return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
291 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
292 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
293 StringRef SectionName = GO->getSection();
295 // Check if '#pragma clang section' name is applicable.
296 // Note that pragma directive overrides -ffunction-section, -fdata-section
297 // and so section name is exactly as user specified and not uniqued.
298 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
299 if (GV && GV->hasImplicitSection()) {
300 auto Attrs = GV->getAttributes();
301 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
302 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
303 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
304 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
305 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
306 SectionName = Attrs.getAttribute("data-section").getValueAsString();
309 const Function *F = dyn_cast<Function>(GO);
310 if (F && F->hasFnAttribute("implicit-section-name")) {
311 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
314 // Infer section flags from the section name if we can.
315 Kind = getELFKindForNamedSection(SectionName, Kind);
317 StringRef Group = "";
318 unsigned Flags = getELFSectionFlags(Kind);
319 if (const Comdat *C = getELFComdat(GO)) {
320 Group = C->getName();
321 Flags |= ELF::SHF_GROUP;
324 // A section can have at most one associated section. Put each global with
325 // MD_associated in a unique section.
326 unsigned UniqueID = MCContext::GenericSectionID;
327 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
328 if (AssociatedSymbol) {
329 UniqueID = NextUniqueID++;
330 Flags |= ELF::SHF_LINK_ORDER;
333 MCSectionELF *Section = getContext().getELFSection(
334 SectionName, getELFSectionType(SectionName, Kind), Flags,
335 /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
336 // Make sure that we did not get some other section with incompatible sh_link.
337 // This should not be possible due to UniqueID code above.
338 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
342 /// Return the section prefix name used by options FunctionsSections and
344 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
347 if (Kind.isReadOnly())
351 if (Kind.isThreadData())
353 if (Kind.isThreadBSS())
357 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
358 return ".data.rel.ro";
361 static MCSectionELF *selectELFSectionForGlobal(
362 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
363 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
364 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
365 unsigned EntrySize = 0;
366 if (Kind.isMergeableCString()) {
367 if (Kind.isMergeable2ByteCString()) {
369 } else if (Kind.isMergeable4ByteCString()) {
373 assert(Kind.isMergeable1ByteCString() && "unknown string width");
375 } else if (Kind.isMergeableConst()) {
376 if (Kind.isMergeableConst4()) {
378 } else if (Kind.isMergeableConst8()) {
380 } else if (Kind.isMergeableConst16()) {
383 assert(Kind.isMergeableConst32() && "unknown data width");
388 StringRef Group = "";
389 if (const Comdat *C = getELFComdat(GO)) {
390 Flags |= ELF::SHF_GROUP;
391 Group = C->getName();
394 bool UniqueSectionNames = TM.getUniqueSectionNames();
395 SmallString<128> Name;
396 if (Kind.isMergeableCString()) {
397 // We also need alignment here.
398 // FIXME: this is getting the alignment of the character, not the
399 // alignment of the global!
400 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
401 cast<GlobalVariable>(GO));
403 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
404 Name = SizeSpec + utostr(Align);
405 } else if (Kind.isMergeableConst()) {
406 Name = ".rodata.cst";
407 Name += utostr(EntrySize);
409 Name = getSectionPrefixForGlobal(Kind);
412 if (const auto *F = dyn_cast<Function>(GO)) {
413 const auto &OptionalPrefix = F->getSectionPrefix();
415 Name += *OptionalPrefix;
418 if (EmitUniqueSection && UniqueSectionNames) {
420 TM.getNameWithPrefix(Name, GO, Mang, true);
422 unsigned UniqueID = MCContext::GenericSectionID;
423 if (EmitUniqueSection && !UniqueSectionNames) {
424 UniqueID = *NextUniqueID;
427 // Use 0 as the unique ID for execute-only text
428 if (Kind.isExecuteOnly())
430 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
431 EntrySize, Group, UniqueID, AssociatedSymbol);
434 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
435 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
436 unsigned Flags = getELFSectionFlags(Kind);
438 // If we have -ffunction-section or -fdata-section then we should emit the
439 // global value to a uniqued section specifically for it.
440 bool EmitUniqueSection = false;
441 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
443 EmitUniqueSection = TM.getFunctionSections();
445 EmitUniqueSection = TM.getDataSections();
447 EmitUniqueSection |= GO->hasComdat();
449 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
450 if (AssociatedSymbol) {
451 EmitUniqueSection = true;
452 Flags |= ELF::SHF_LINK_ORDER;
455 MCSectionELF *Section = selectELFSectionForGlobal(
456 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
457 &NextUniqueID, AssociatedSymbol);
458 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
462 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
463 const Function &F, const TargetMachine &TM) const {
464 // If the function can be removed, produce a unique section so that
465 // the table doesn't prevent the removal.
466 const Comdat *C = F.getComdat();
467 bool EmitUniqueSection = TM.getFunctionSections() || C;
468 if (!EmitUniqueSection)
469 return ReadOnlySection;
471 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
472 getMangler(), TM, EmitUniqueSection,
473 ELF::SHF_ALLOC, &NextUniqueID,
474 /* AssociatedSymbol */ nullptr);
477 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
478 bool UsesLabelDifference, const Function &F) const {
479 // We can always create relative relocations, so use another section
480 // that can be marked non-executable.
484 /// Given a mergeable constant with the specified size and relocation
485 /// information, return a section that it should be placed in.
486 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
487 const DataLayout &DL, SectionKind Kind, const Constant *C,
488 unsigned &Align) const {
489 if (Kind.isMergeableConst4() && MergeableConst4Section)
490 return MergeableConst4Section;
491 if (Kind.isMergeableConst8() && MergeableConst8Section)
492 return MergeableConst8Section;
493 if (Kind.isMergeableConst16() && MergeableConst16Section)
494 return MergeableConst16Section;
495 if (Kind.isMergeableConst32() && MergeableConst32Section)
496 return MergeableConst32Section;
497 if (Kind.isReadOnly())
498 return ReadOnlySection;
500 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
501 return DataRelROSection;
504 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
505 bool IsCtor, unsigned Priority,
506 const MCSymbol *KeySym) {
509 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
510 StringRef COMDAT = KeySym ? KeySym->getName() : "";
513 Flags |= ELF::SHF_GROUP;
517 Type = ELF::SHT_INIT_ARRAY;
518 Name = ".init_array";
520 Type = ELF::SHT_FINI_ARRAY;
521 Name = ".fini_array";
523 if (Priority != 65535) {
525 Name += utostr(Priority);
528 // The default scheme is .ctor / .dtor, so we have to invert the priority
534 if (Priority != 65535) {
536 Name += utostr(65535 - Priority);
538 Type = ELF::SHT_PROGBITS;
541 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
544 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
545 unsigned Priority, const MCSymbol *KeySym) const {
546 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
550 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
551 unsigned Priority, const MCSymbol *KeySym) const {
552 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
556 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
557 const GlobalValue *LHS, const GlobalValue *RHS,
558 const TargetMachine &TM) const {
559 // We may only use a PLT-relative relocation to refer to unnamed_addr
561 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
564 // Basic sanity checks.
565 if (LHS->getType()->getPointerAddressSpace() != 0 ||
566 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
567 RHS->isThreadLocal())
570 return MCBinaryExpr::createSub(
571 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
573 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
577 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
578 UseInitArray = UseInitArray_;
579 MCContext &Ctx = getContext();
581 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
582 ELF::SHF_ALLOC | ELF::SHF_WRITE);
584 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
585 ELF::SHF_ALLOC | ELF::SHF_WRITE);
589 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
590 ELF::SHF_WRITE | ELF::SHF_ALLOC);
591 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
592 ELF::SHF_WRITE | ELF::SHF_ALLOC);
595 //===----------------------------------------------------------------------===//
597 //===----------------------------------------------------------------------===//
599 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
600 : TargetLoweringObjectFile() {
601 SupportIndirectSymViaGOTPCRel = true;
604 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
605 const TargetMachine &TM) {
606 TargetLoweringObjectFile::Initialize(Ctx, TM);
607 if (TM.getRelocationModel() == Reloc::Static) {
608 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
609 SectionKind::getData());
610 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
611 SectionKind::getData());
613 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
614 MachO::S_MOD_INIT_FUNC_POINTERS,
615 SectionKind::getData());
616 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
617 MachO::S_MOD_TERM_FUNC_POINTERS,
618 SectionKind::getData());
622 void TargetLoweringObjectFileMachO::emitModuleMetadata(
623 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
624 // Emit the linker options if present.
625 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
626 for (const auto &Option : LinkerOptions->operands()) {
627 SmallVector<std::string, 4> StrOptions;
628 for (const auto &Piece : cast<MDNode>(Option)->operands())
629 StrOptions.push_back(cast<MDString>(Piece)->getString());
630 Streamer.EmitLinkerOptions(StrOptions);
634 unsigned VersionVal = 0;
635 unsigned ImageInfoFlags = 0;
636 StringRef SectionVal;
638 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
640 // The section is mandatory. If we don't have it, then we don't have GC info.
641 if (SectionVal.empty())
644 StringRef Segment, Section;
645 unsigned TAA = 0, StubSize = 0;
647 std::string ErrorCode =
648 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
649 TAA, TAAParsed, StubSize);
650 if (!ErrorCode.empty())
651 // If invalid, report the error with report_fatal_error.
652 report_fatal_error("Invalid section specifier '" + Section + "': " +
656 MCSectionMachO *S = getContext().getMachOSection(
657 Segment, Section, TAA, StubSize, SectionKind::getData());
658 Streamer.SwitchSection(S);
659 Streamer.EmitLabel(getContext().
660 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
661 Streamer.EmitIntValue(VersionVal, 4);
662 Streamer.EmitIntValue(ImageInfoFlags, 4);
663 Streamer.AddBlankLine();
666 static void checkMachOComdat(const GlobalValue *GV) {
667 const Comdat *C = GV->getComdat();
671 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
672 "' cannot be lowered.");
675 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
676 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
677 // Parse the section specifier and create it if valid.
678 StringRef Segment, Section;
679 unsigned TAA = 0, StubSize = 0;
682 checkMachOComdat(GO);
684 std::string ErrorCode =
685 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
686 TAA, TAAParsed, StubSize);
687 if (!ErrorCode.empty()) {
688 // If invalid, report the error with report_fatal_error.
689 report_fatal_error("Global variable '" + GO->getName() +
690 "' has an invalid section specifier '" +
691 GO->getSection() + "': " + ErrorCode + ".");
696 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
698 // If TAA wasn't set by ParseSectionSpecifier() above,
699 // use the value returned by getMachOSection() as a default.
701 TAA = S->getTypeAndAttributes();
703 // Okay, now that we got the section, verify that the TAA & StubSize agree.
704 // If the user declared multiple globals with different section flags, we need
705 // to reject it here.
706 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
707 // If invalid, report the error with report_fatal_error.
708 report_fatal_error("Global variable '" + GO->getName() +
709 "' section type or attributes does not match previous"
710 " section specifier");
716 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
717 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
718 checkMachOComdat(GO);
720 // Handle thread local data.
721 if (Kind.isThreadBSS()) return TLSBSSSection;
722 if (Kind.isThreadData()) return TLSDataSection;
725 return GO->isWeakForLinker() ? TextCoalSection : TextSection;
727 // If this is weak/linkonce, put this in a coalescable section, either in text
728 // or data depending on if it is writable.
729 if (GO->isWeakForLinker()) {
730 if (Kind.isReadOnly())
731 return ConstTextCoalSection;
732 return DataCoalSection;
735 // FIXME: Alignment check should be handled by section classifier.
736 if (Kind.isMergeable1ByteCString() &&
737 GO->getParent()->getDataLayout().getPreferredAlignment(
738 cast<GlobalVariable>(GO)) < 32)
739 return CStringSection;
741 // Do not put 16-bit arrays in the UString section if they have an
742 // externally visible label, this runs into issues with certain linker
744 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
745 GO->getParent()->getDataLayout().getPreferredAlignment(
746 cast<GlobalVariable>(GO)) < 32)
747 return UStringSection;
749 // With MachO only variables whose corresponding symbol starts with 'l' or
750 // 'L' can be merged, so we only try merging GVs with private linkage.
751 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
752 if (Kind.isMergeableConst4())
753 return FourByteConstantSection;
754 if (Kind.isMergeableConst8())
755 return EightByteConstantSection;
756 if (Kind.isMergeableConst16())
757 return SixteenByteConstantSection;
760 // Otherwise, if it is readonly, but not something we can specially optimize,
761 // just drop it in .const.
762 if (Kind.isReadOnly())
763 return ReadOnlySection;
765 // If this is marked const, put it into a const section. But if the dynamic
766 // linker needs to write to it, put it in the data segment.
767 if (Kind.isReadOnlyWithRel())
768 return ConstDataSection;
770 // Put zero initialized globals with strong external linkage in the
771 // DATA, __common section with the .zerofill directive.
772 if (Kind.isBSSExtern())
773 return DataCommonSection;
775 // Put zero initialized globals with local linkage in __DATA,__bss directive
776 // with the .zerofill directive (aka .lcomm).
777 if (Kind.isBSSLocal())
778 return DataBSSSection;
780 // Otherwise, just drop the variable in the normal data section.
784 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
785 const DataLayout &DL, SectionKind Kind, const Constant *C,
786 unsigned &Align) const {
787 // If this constant requires a relocation, we have to put it in the data
788 // segment, not in the text segment.
789 if (Kind.isData() || Kind.isReadOnlyWithRel())
790 return ConstDataSection;
792 if (Kind.isMergeableConst4())
793 return FourByteConstantSection;
794 if (Kind.isMergeableConst8())
795 return EightByteConstantSection;
796 if (Kind.isMergeableConst16())
797 return SixteenByteConstantSection;
798 return ReadOnlySection; // .const
801 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
802 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
803 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
804 // The mach-o version of this method defaults to returning a stub reference.
806 if (Encoding & DW_EH_PE_indirect) {
807 MachineModuleInfoMachO &MachOMMI =
808 MMI->getObjFileInfo<MachineModuleInfoMachO>();
810 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
812 // Add information about the stub reference to MachOMMI so that the stub
813 // gets emitted by the asmprinter.
814 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
815 if (!StubSym.getPointer()) {
816 MCSymbol *Sym = TM.getSymbol(GV);
817 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
820 return TargetLoweringObjectFile::
821 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
822 Encoding & ~DW_EH_PE_indirect, Streamer);
825 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
829 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
830 const GlobalValue *GV, const TargetMachine &TM,
831 MachineModuleInfo *MMI) const {
832 // The mach-o version of this method defaults to returning a stub reference.
833 MachineModuleInfoMachO &MachOMMI =
834 MMI->getObjFileInfo<MachineModuleInfoMachO>();
836 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
838 // Add information about the stub reference to MachOMMI so that the stub
839 // gets emitted by the asmprinter.
840 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
841 if (!StubSym.getPointer()) {
842 MCSymbol *Sym = TM.getSymbol(GV);
843 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
849 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
850 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
851 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
852 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
853 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
854 // through a non_lazy_ptr stub instead. One advantage is that it allows the
855 // computation of deltas to final external symbols. Example:
861 // .long _extgotequiv-_delta
863 // is transformed to:
866 // .long L_extfoo$non_lazy_ptr-(_delta+0)
868 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
869 // L_extfoo$non_lazy_ptr:
870 // .indirect_symbol _extfoo
873 MachineModuleInfoMachO &MachOMMI =
874 MMI->getObjFileInfo<MachineModuleInfoMachO>();
875 MCContext &Ctx = getContext();
877 // The offset must consider the original displacement from the base symbol
878 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
879 Offset = -MV.getConstant();
880 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
882 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
883 // non_lazy_ptr stubs.
884 SmallString<128> Name;
885 StringRef Suffix = "$non_lazy_ptr";
886 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
887 Name += Sym->getName();
889 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
891 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
892 if (!StubSym.getPointer())
893 StubSym = MachineModuleInfoImpl::
894 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
896 const MCExpr *BSymExpr =
897 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
899 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
902 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
905 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
906 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
909 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
910 const MCSection &Section) {
911 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
914 // If it is not dead stripped, it is safe to use private labels.
915 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
916 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
922 void TargetLoweringObjectFileMachO::getNameWithPrefix(
923 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
924 const TargetMachine &TM) const {
925 bool CannotUsePrivateLabel = true;
926 if (auto *GO = GV->getBaseObject()) {
927 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
928 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
929 CannotUsePrivateLabel =
930 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
932 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
935 //===----------------------------------------------------------------------===//
937 //===----------------------------------------------------------------------===//
940 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
942 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
946 COFF::IMAGE_SCN_MEM_DISCARDABLE;
949 COFF::IMAGE_SCN_MEM_EXECUTE |
950 COFF::IMAGE_SCN_MEM_READ |
951 COFF::IMAGE_SCN_CNT_CODE |
952 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
955 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
956 COFF::IMAGE_SCN_MEM_READ |
957 COFF::IMAGE_SCN_MEM_WRITE;
958 else if (K.isThreadLocal())
960 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
961 COFF::IMAGE_SCN_MEM_READ |
962 COFF::IMAGE_SCN_MEM_WRITE;
963 else if (K.isReadOnly() || K.isReadOnlyWithRel())
965 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
966 COFF::IMAGE_SCN_MEM_READ;
967 else if (K.isWriteable())
969 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
970 COFF::IMAGE_SCN_MEM_READ |
971 COFF::IMAGE_SCN_MEM_WRITE;
976 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
977 const Comdat *C = GV->getComdat();
978 assert(C && "expected GV to have a Comdat!");
980 StringRef ComdatGVName = C->getName();
981 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
983 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
984 "' does not exist.");
986 if (ComdatGV->getComdat() != C)
987 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
988 "' is not a key for its COMDAT.");
993 static int getSelectionForCOFF(const GlobalValue *GV) {
994 if (const Comdat *C = GV->getComdat()) {
995 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
996 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
997 ComdatKey = GA->getBaseObject();
998 if (ComdatKey == GV) {
999 switch (C->getSelectionKind()) {
1001 return COFF::IMAGE_COMDAT_SELECT_ANY;
1002 case Comdat::ExactMatch:
1003 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1004 case Comdat::Largest:
1005 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1006 case Comdat::NoDuplicates:
1007 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1008 case Comdat::SameSize:
1009 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1012 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1018 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1019 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1021 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1022 StringRef Name = GO->getSection();
1023 StringRef COMDATSymName = "";
1024 if (GO->hasComdat()) {
1025 Selection = getSelectionForCOFF(GO);
1026 const GlobalValue *ComdatGV;
1027 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1028 ComdatGV = getComdatGVForCOFF(GO);
1032 if (!ComdatGV->hasPrivateLinkage()) {
1033 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1034 COMDATSymName = Sym->getName();
1035 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1041 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1045 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1050 if (Kind.isThreadLocal())
1052 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1057 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1058 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1059 // If we have -ffunction-sections then we should emit the global value to a
1060 // uniqued section specifically for it.
1061 bool EmitUniquedSection;
1063 EmitUniquedSection = TM.getFunctionSections();
1065 EmitUniquedSection = TM.getDataSections();
1067 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1068 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1069 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1071 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1072 int Selection = getSelectionForCOFF(GO);
1074 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1075 const GlobalValue *ComdatGV;
1076 if (GO->hasComdat())
1077 ComdatGV = getComdatGVForCOFF(GO);
1081 unsigned UniqueID = MCContext::GenericSectionID;
1082 if (EmitUniquedSection)
1083 UniqueID = NextUniqueID++;
1085 if (!ComdatGV->hasPrivateLinkage()) {
1086 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1087 StringRef COMDATSymName = Sym->getName();
1088 return getContext().getCOFFSection(Name, Characteristics, Kind,
1089 COMDATSymName, Selection, UniqueID);
1091 SmallString<256> TmpData;
1092 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1093 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1094 Selection, UniqueID);
1101 if (Kind.isThreadLocal())
1102 return TLSDataSection;
1104 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1105 return ReadOnlySection;
1107 // Note: we claim that common symbols are put in BSSSection, but they are
1108 // really emitted with the magic .comm directive, which creates a symbol table
1109 // entry but not a section.
1110 if (Kind.isBSS() || Kind.isCommon())
1116 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1117 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1118 const TargetMachine &TM) const {
1119 bool CannotUsePrivateLabel = false;
1120 if (GV->hasPrivateLinkage() &&
1121 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1122 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1123 CannotUsePrivateLabel = true;
1125 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1128 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1129 const Function &F, const TargetMachine &TM) const {
1130 // If the function can be removed, produce a unique section so that
1131 // the table doesn't prevent the removal.
1132 const Comdat *C = F.getComdat();
1133 bool EmitUniqueSection = TM.getFunctionSections() || C;
1134 if (!EmitUniqueSection)
1135 return ReadOnlySection;
1137 // FIXME: we should produce a symbol for F instead.
1138 if (F.hasPrivateLinkage())
1139 return ReadOnlySection;
1141 MCSymbol *Sym = TM.getSymbol(&F);
1142 StringRef COMDATSymName = Sym->getName();
1144 SectionKind Kind = SectionKind::getReadOnly();
1145 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
1146 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1147 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1148 unsigned UniqueID = NextUniqueID++;
1150 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1151 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1154 void TargetLoweringObjectFileCOFF::emitModuleMetadata(
1155 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
1156 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1157 // Emit the linker options to the linker .drectve section. According to the
1158 // spec, this section is a space-separated string containing flags for
1160 MCSection *Sec = getDrectveSection();
1161 Streamer.SwitchSection(Sec);
1162 for (const auto &Option : LinkerOptions->operands()) {
1163 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1164 // Lead with a space for consistency with our dllexport implementation.
1165 std::string Directive(" ");
1166 Directive.append(cast<MDString>(Piece)->getString());
1167 Streamer.EmitBytes(Directive);
1172 unsigned Version = 0;
1176 GetObjCImageInfo(M, Version, Flags, Section);
1177 if (Section.empty())
1180 auto &C = getContext();
1181 auto *S = C.getCOFFSection(
1182 Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1183 SectionKind::getReadOnly());
1184 Streamer.SwitchSection(S);
1185 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1186 Streamer.EmitIntValue(Version, 4);
1187 Streamer.EmitIntValue(Flags, 4);
1188 Streamer.AddBlankLine();
1191 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1192 const TargetMachine &TM) {
1193 TargetLoweringObjectFile::Initialize(Ctx, TM);
1194 const Triple &T = TM.getTargetTriple();
1195 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1197 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1198 COFF::IMAGE_SCN_MEM_READ,
1199 SectionKind::getReadOnly());
1201 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1202 COFF::IMAGE_SCN_MEM_READ,
1203 SectionKind::getReadOnly());
1205 StaticCtorSection = Ctx.getCOFFSection(
1206 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1207 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1208 SectionKind::getData());
1209 StaticDtorSection = Ctx.getCOFFSection(
1210 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1211 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1212 SectionKind::getData());
1216 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1217 unsigned Priority, const MCSymbol *KeySym) const {
1218 return getContext().getAssociativeCOFFSection(
1219 cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
1222 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1223 unsigned Priority, const MCSymbol *KeySym) const {
1224 return getContext().getAssociativeCOFFSection(
1225 cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
1228 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1229 raw_ostream &OS, const GlobalValue *GV) const {
1230 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
1233 //===----------------------------------------------------------------------===//
1235 //===----------------------------------------------------------------------===//
1237 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1238 const Comdat *C = GV->getComdat();
1242 if (C->getSelectionKind() != Comdat::Any)
1243 report_fatal_error("Wasm COMDATs only support SelectionKind::Any, '" +
1244 C->getName() + "' cannot be lowered.");
1249 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1250 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1251 llvm_unreachable("getExplicitSectionGlobal not yet implemented");
1255 static MCSectionWasm *
1256 selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO,
1257 SectionKind Kind, Mangler &Mang,
1258 const TargetMachine &TM, bool EmitUniqueSection,
1259 unsigned Flags, unsigned *NextUniqueID) {
1260 StringRef Group = "";
1261 if (getWasmComdat(GO))
1262 llvm_unreachable("comdat not yet supported for wasm");
1264 bool UniqueSectionNames = TM.getUniqueSectionNames();
1265 SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1267 if (const auto *F = dyn_cast<Function>(GO)) {
1268 const auto &OptionalPrefix = F->getSectionPrefix();
1270 Name += *OptionalPrefix;
1273 if (EmitUniqueSection && UniqueSectionNames) {
1274 Name.push_back('.');
1275 TM.getNameWithPrefix(Name, GO, Mang, true);
1277 unsigned UniqueID = MCContext::GenericSectionID;
1278 if (EmitUniqueSection && !UniqueSectionNames) {
1279 UniqueID = *NextUniqueID;
1282 return Ctx.getWasmSection(Name, /*Type=*/0, Flags,
1286 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1287 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1289 if (Kind.isCommon())
1290 report_fatal_error("mergable sections not supported yet on wasm");
1292 // If we have -ffunction-section or -fdata-section then we should emit the
1293 // global value to a uniqued section specifically for it.
1294 bool EmitUniqueSection = false;
1296 EmitUniqueSection = TM.getFunctionSections();
1298 EmitUniqueSection = TM.getDataSections();
1299 EmitUniqueSection |= GO->hasComdat();
1301 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1302 EmitUniqueSection, /*Flags=*/0,
1306 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1307 bool UsesLabelDifference, const Function &F) const {
1308 // We can always create relative relocations, so use another section
1309 // that can be marked non-executable.
1313 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1314 const GlobalValue *LHS, const GlobalValue *RHS,
1315 const TargetMachine &TM) const {
1316 // We may only use a PLT-relative relocation to refer to unnamed_addr
1318 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1321 // Basic sanity checks.
1322 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1323 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1324 RHS->isThreadLocal())
1327 return MCBinaryExpr::createSub(
1328 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1330 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1334 TargetLoweringObjectFileWasm::InitializeWasm() {
1335 // TODO: Initialize StaticCtorSection and StaticDtorSection.