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/Format.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/raw_ostream.h"
58 #include "llvm/Target/TargetMachine.h"
63 using namespace dwarf;
65 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
67 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
68 M.getModuleFlagsMetadata(ModuleFlags);
70 for (const auto &MFE: ModuleFlags) {
71 // Ignore flags with 'Require' behaviour.
72 if (MFE.Behavior == Module::Require)
75 StringRef Key = MFE.Key->getString();
76 if (Key == "Objective-C Image Info Version") {
77 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
78 } else if (Key == "Objective-C Garbage Collection" ||
79 Key == "Objective-C GC Only" ||
80 Key == "Objective-C Is Simulated" ||
81 Key == "Objective-C Class Properties" ||
82 Key == "Objective-C Image Swift Version") {
83 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
84 } else if (Key == "Objective-C Image Info Section") {
85 Section = cast<MDString>(MFE.Val)->getString();
90 //===----------------------------------------------------------------------===//
92 //===----------------------------------------------------------------------===//
94 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
95 const TargetMachine &TgtM) {
96 TargetLoweringObjectFile::Initialize(Ctx, TgtM);
100 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
102 auto &C = getContext();
104 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
105 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
108 Streamer.SwitchSection(S);
110 for (const auto &Operand : LinkerOptions->operands()) {
111 if (cast<MDNode>(Operand)->getNumOperands() != 2)
112 report_fatal_error("invalid llvm.linker.options");
113 for (const auto &Option : cast<MDNode>(Operand)->operands()) {
114 Streamer.EmitBytes(cast<MDString>(Option)->getString());
115 Streamer.EmitIntValue(0, 1);
120 unsigned Version = 0;
124 GetObjCImageInfo(M, Version, Flags, Section);
125 if (!Section.empty()) {
126 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
127 Streamer.SwitchSection(S);
128 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
129 Streamer.EmitIntValue(Version, 4);
130 Streamer.EmitIntValue(Flags, 4);
131 Streamer.AddBlankLine();
134 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
135 M.getModuleFlagsMetadata(ModuleFlags);
137 MDNode *CFGProfile = nullptr;
139 for (const auto &MFE : ModuleFlags) {
140 StringRef Key = MFE.Key->getString();
141 if (Key == "CG Profile") {
142 CFGProfile = cast<MDNode>(MFE.Val);
150 auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * {
153 auto V = cast<ValueAsMetadata>(MDO);
154 const Function *F = cast<Function>(V->getValue());
155 return TM->getSymbol(F);
158 for (const auto &Edge : CFGProfile->operands()) {
159 MDNode *E = cast<MDNode>(Edge);
160 const MCSymbol *From = GetSym(E->getOperand(0));
161 const MCSymbol *To = GetSym(E->getOperand(1));
162 // Skip null functions. This can happen if functions are dead stripped after
163 // the CGProfile pass has been run.
166 uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2))
170 Streamer.emitCGProfileEntry(
171 MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C),
172 MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count);
176 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
177 const GlobalValue *GV, const TargetMachine &TM,
178 MachineModuleInfo *MMI) const {
179 unsigned Encoding = getPersonalityEncoding();
180 if ((Encoding & 0x80) == DW_EH_PE_indirect)
181 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
182 TM.getSymbol(GV)->getName());
183 if ((Encoding & 0x70) == DW_EH_PE_absptr)
184 return TM.getSymbol(GV);
185 report_fatal_error("We do not support this DWARF encoding yet!");
188 void TargetLoweringObjectFileELF::emitPersonalityValue(
189 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
190 SmallString<64> NameData("DW.ref.");
191 NameData += Sym->getName();
193 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
194 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
195 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
196 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
197 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
198 ELF::SHT_PROGBITS, Flags, 0);
199 unsigned Size = DL.getPointerSize();
200 Streamer.SwitchSection(Sec);
201 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0));
202 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
203 const MCExpr *E = MCConstantExpr::create(Size, getContext());
204 Streamer.emitELFSize(Label, E);
205 Streamer.EmitLabel(Label);
207 Streamer.EmitSymbolValue(Sym, Size);
210 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
211 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
212 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
213 if (Encoding & DW_EH_PE_indirect) {
214 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
216 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
218 // Add information about the stub reference to ELFMMI so that the stub
219 // gets emitted by the asmprinter.
220 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
221 if (!StubSym.getPointer()) {
222 MCSymbol *Sym = TM.getSymbol(GV);
223 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
226 return TargetLoweringObjectFile::
227 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
228 Encoding & ~DW_EH_PE_indirect, Streamer);
231 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
235 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
236 // N.B.: The defaults used in here are not the same ones used in MC.
237 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
238 // both gas and MC will produce a section with no flags. Given
239 // section(".eh_frame") gcc will produce:
241 // .section .eh_frame,"a",@progbits
243 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
244 /*AddSegmentInfo=*/false))
245 return SectionKind::getMetadata();
247 if (Name.empty() || Name[0] != '.') return K;
249 // Default implementation based on some magic section names.
250 if (Name == ".bss" ||
251 Name.startswith(".bss.") ||
252 Name.startswith(".gnu.linkonce.b.") ||
253 Name.startswith(".llvm.linkonce.b.") ||
255 Name.startswith(".sbss.") ||
256 Name.startswith(".gnu.linkonce.sb.") ||
257 Name.startswith(".llvm.linkonce.sb."))
258 return SectionKind::getBSS();
260 if (Name == ".tdata" ||
261 Name.startswith(".tdata.") ||
262 Name.startswith(".gnu.linkonce.td.") ||
263 Name.startswith(".llvm.linkonce.td."))
264 return SectionKind::getThreadData();
266 if (Name == ".tbss" ||
267 Name.startswith(".tbss.") ||
268 Name.startswith(".gnu.linkonce.tb.") ||
269 Name.startswith(".llvm.linkonce.tb."))
270 return SectionKind::getThreadBSS();
275 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
276 // Use SHT_NOTE for section whose name starts with ".note" to allow
277 // emitting ELF notes from C variable declaration.
278 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
279 if (Name.startswith(".note"))
280 return ELF::SHT_NOTE;
282 if (Name == ".init_array")
283 return ELF::SHT_INIT_ARRAY;
285 if (Name == ".fini_array")
286 return ELF::SHT_FINI_ARRAY;
288 if (Name == ".preinit_array")
289 return ELF::SHT_PREINIT_ARRAY;
291 if (K.isBSS() || K.isThreadBSS())
292 return ELF::SHT_NOBITS;
294 return ELF::SHT_PROGBITS;
297 static unsigned getELFSectionFlags(SectionKind K) {
301 Flags |= ELF::SHF_ALLOC;
304 Flags |= ELF::SHF_EXECINSTR;
306 if (K.isExecuteOnly())
307 Flags |= ELF::SHF_ARM_PURECODE;
310 Flags |= ELF::SHF_WRITE;
312 if (K.isThreadLocal())
313 Flags |= ELF::SHF_TLS;
315 if (K.isMergeableCString() || K.isMergeableConst())
316 Flags |= ELF::SHF_MERGE;
318 if (K.isMergeableCString())
319 Flags |= ELF::SHF_STRINGS;
324 static const Comdat *getELFComdat(const GlobalValue *GV) {
325 const Comdat *C = GV->getComdat();
329 if (C->getSelectionKind() != Comdat::Any)
330 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
331 C->getName() + "' cannot be lowered.");
336 static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
337 const TargetMachine &TM) {
338 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
342 const MDOperand &Op = MD->getOperand(0);
346 auto *VM = dyn_cast<ValueAsMetadata>(Op);
348 report_fatal_error("MD_associated operand is not ValueAsMetadata");
350 GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
351 return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
354 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
355 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
356 StringRef SectionName = GO->getSection();
358 // Check if '#pragma clang section' name is applicable.
359 // Note that pragma directive overrides -ffunction-section, -fdata-section
360 // and so section name is exactly as user specified and not uniqued.
361 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
362 if (GV && GV->hasImplicitSection()) {
363 auto Attrs = GV->getAttributes();
364 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
365 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
366 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
367 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
368 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
369 SectionName = Attrs.getAttribute("data-section").getValueAsString();
372 const Function *F = dyn_cast<Function>(GO);
373 if (F && F->hasFnAttribute("implicit-section-name")) {
374 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
377 // Infer section flags from the section name if we can.
378 Kind = getELFKindForNamedSection(SectionName, Kind);
380 StringRef Group = "";
381 unsigned Flags = getELFSectionFlags(Kind);
382 if (const Comdat *C = getELFComdat(GO)) {
383 Group = C->getName();
384 Flags |= ELF::SHF_GROUP;
387 // A section can have at most one associated section. Put each global with
388 // MD_associated in a unique section.
389 unsigned UniqueID = MCContext::GenericSectionID;
390 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
391 if (AssociatedSymbol) {
392 UniqueID = NextUniqueID++;
393 Flags |= ELF::SHF_LINK_ORDER;
396 MCSectionELF *Section = getContext().getELFSection(
397 SectionName, getELFSectionType(SectionName, Kind), Flags,
398 /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
399 // Make sure that we did not get some other section with incompatible sh_link.
400 // This should not be possible due to UniqueID code above.
401 assert(Section->getAssociatedSymbol() == AssociatedSymbol &&
402 "Associated symbol mismatch between sections");
406 /// Return the section prefix name used by options FunctionsSections and
408 static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
411 if (Kind.isReadOnly())
415 if (Kind.isThreadData())
417 if (Kind.isThreadBSS())
421 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
422 return ".data.rel.ro";
425 static unsigned getEntrySizeForKind(SectionKind Kind) {
426 if (Kind.isMergeable1ByteCString())
428 else if (Kind.isMergeable2ByteCString())
430 else if (Kind.isMergeable4ByteCString())
432 else if (Kind.isMergeableConst4())
434 else if (Kind.isMergeableConst8())
436 else if (Kind.isMergeableConst16())
438 else if (Kind.isMergeableConst32())
441 // We shouldn't have mergeable C strings or mergeable constants that we
442 // didn't handle above.
443 assert(!Kind.isMergeableCString() && "unknown string width");
444 assert(!Kind.isMergeableConst() && "unknown data width");
449 static MCSectionELF *selectELFSectionForGlobal(
450 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
451 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
452 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
454 StringRef Group = "";
455 if (const Comdat *C = getELFComdat(GO)) {
456 Flags |= ELF::SHF_GROUP;
457 Group = C->getName();
460 // Get the section entry size based on the kind.
461 unsigned EntrySize = getEntrySizeForKind(Kind);
463 SmallString<128> Name;
464 if (Kind.isMergeableCString()) {
465 // We also need alignment here.
466 // FIXME: this is getting the alignment of the character, not the
467 // alignment of the global!
468 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
469 cast<GlobalVariable>(GO));
471 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
472 Name = SizeSpec + utostr(Align);
473 } else if (Kind.isMergeableConst()) {
474 Name = ".rodata.cst";
475 Name += utostr(EntrySize);
477 Name = getSectionPrefixForGlobal(Kind);
480 if (const auto *F = dyn_cast<Function>(GO)) {
481 const auto &OptionalPrefix = F->getSectionPrefix();
483 Name += *OptionalPrefix;
486 unsigned UniqueID = MCContext::GenericSectionID;
487 if (EmitUniqueSection) {
488 if (TM.getUniqueSectionNames()) {
490 TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/);
492 UniqueID = *NextUniqueID;
496 // Use 0 as the unique ID for execute-only text.
497 if (Kind.isExecuteOnly())
499 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
500 EntrySize, Group, UniqueID, AssociatedSymbol);
503 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
504 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
505 unsigned Flags = getELFSectionFlags(Kind);
507 // If we have -ffunction-section or -fdata-section then we should emit the
508 // global value to a uniqued section specifically for it.
509 bool EmitUniqueSection = false;
510 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
512 EmitUniqueSection = TM.getFunctionSections();
514 EmitUniqueSection = TM.getDataSections();
516 EmitUniqueSection |= GO->hasComdat();
518 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
519 if (AssociatedSymbol) {
520 EmitUniqueSection = true;
521 Flags |= ELF::SHF_LINK_ORDER;
524 MCSectionELF *Section = selectELFSectionForGlobal(
525 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
526 &NextUniqueID, AssociatedSymbol);
527 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
531 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
532 const Function &F, const TargetMachine &TM) const {
533 // If the function can be removed, produce a unique section so that
534 // the table doesn't prevent the removal.
535 const Comdat *C = F.getComdat();
536 bool EmitUniqueSection = TM.getFunctionSections() || C;
537 if (!EmitUniqueSection)
538 return ReadOnlySection;
540 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
541 getMangler(), TM, EmitUniqueSection,
542 ELF::SHF_ALLOC, &NextUniqueID,
543 /* AssociatedSymbol */ nullptr);
546 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
547 bool UsesLabelDifference, const Function &F) const {
548 // We can always create relative relocations, so use another section
549 // that can be marked non-executable.
553 /// Given a mergeable constant with the specified size and relocation
554 /// information, return a section that it should be placed in.
555 MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
556 const DataLayout &DL, SectionKind Kind, const Constant *C,
557 unsigned &Align) const {
558 if (Kind.isMergeableConst4() && MergeableConst4Section)
559 return MergeableConst4Section;
560 if (Kind.isMergeableConst8() && MergeableConst8Section)
561 return MergeableConst8Section;
562 if (Kind.isMergeableConst16() && MergeableConst16Section)
563 return MergeableConst16Section;
564 if (Kind.isMergeableConst32() && MergeableConst32Section)
565 return MergeableConst32Section;
566 if (Kind.isReadOnly())
567 return ReadOnlySection;
569 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
570 return DataRelROSection;
573 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
574 bool IsCtor, unsigned Priority,
575 const MCSymbol *KeySym) {
578 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
579 StringRef COMDAT = KeySym ? KeySym->getName() : "";
582 Flags |= ELF::SHF_GROUP;
586 Type = ELF::SHT_INIT_ARRAY;
587 Name = ".init_array";
589 Type = ELF::SHT_FINI_ARRAY;
590 Name = ".fini_array";
592 if (Priority != 65535) {
594 Name += utostr(Priority);
597 // The default scheme is .ctor / .dtor, so we have to invert the priority
603 if (Priority != 65535)
604 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
605 Type = ELF::SHT_PROGBITS;
608 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
611 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
612 unsigned Priority, const MCSymbol *KeySym) const {
613 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
617 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
618 unsigned Priority, const MCSymbol *KeySym) const {
619 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
623 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
624 const GlobalValue *LHS, const GlobalValue *RHS,
625 const TargetMachine &TM) const {
626 // We may only use a PLT-relative relocation to refer to unnamed_addr
628 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
631 // Basic sanity checks.
632 if (LHS->getType()->getPointerAddressSpace() != 0 ||
633 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
634 RHS->isThreadLocal())
637 return MCBinaryExpr::createSub(
638 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
640 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
644 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
645 UseInitArray = UseInitArray_;
646 MCContext &Ctx = getContext();
648 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
649 ELF::SHF_ALLOC | ELF::SHF_WRITE);
651 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
652 ELF::SHF_ALLOC | ELF::SHF_WRITE);
656 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
657 ELF::SHF_WRITE | ELF::SHF_ALLOC);
658 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
659 ELF::SHF_WRITE | ELF::SHF_ALLOC);
662 //===----------------------------------------------------------------------===//
664 //===----------------------------------------------------------------------===//
666 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
667 : TargetLoweringObjectFile() {
668 SupportIndirectSymViaGOTPCRel = true;
671 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
672 const TargetMachine &TM) {
673 TargetLoweringObjectFile::Initialize(Ctx, TM);
674 if (TM.getRelocationModel() == Reloc::Static) {
675 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
676 SectionKind::getData());
677 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
678 SectionKind::getData());
680 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
681 MachO::S_MOD_INIT_FUNC_POINTERS,
682 SectionKind::getData());
683 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
684 MachO::S_MOD_TERM_FUNC_POINTERS,
685 SectionKind::getData());
689 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
691 // Emit the linker options if present.
692 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
693 for (const auto &Option : LinkerOptions->operands()) {
694 SmallVector<std::string, 4> StrOptions;
695 for (const auto &Piece : cast<MDNode>(Option)->operands())
696 StrOptions.push_back(cast<MDString>(Piece)->getString());
697 Streamer.EmitLinkerOptions(StrOptions);
701 unsigned VersionVal = 0;
702 unsigned ImageInfoFlags = 0;
703 StringRef SectionVal;
705 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
707 // The section is mandatory. If we don't have it, then we don't have GC info.
708 if (SectionVal.empty())
711 StringRef Segment, Section;
712 unsigned TAA = 0, StubSize = 0;
714 std::string ErrorCode =
715 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
716 TAA, TAAParsed, StubSize);
717 if (!ErrorCode.empty())
718 // If invalid, report the error with report_fatal_error.
719 report_fatal_error("Invalid section specifier '" + Section + "': " +
723 MCSectionMachO *S = getContext().getMachOSection(
724 Segment, Section, TAA, StubSize, SectionKind::getData());
725 Streamer.SwitchSection(S);
726 Streamer.EmitLabel(getContext().
727 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
728 Streamer.EmitIntValue(VersionVal, 4);
729 Streamer.EmitIntValue(ImageInfoFlags, 4);
730 Streamer.AddBlankLine();
733 static void checkMachOComdat(const GlobalValue *GV) {
734 const Comdat *C = GV->getComdat();
738 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
739 "' cannot be lowered.");
742 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
743 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
744 // Parse the section specifier and create it if valid.
745 StringRef Segment, Section;
746 unsigned TAA = 0, StubSize = 0;
749 checkMachOComdat(GO);
751 std::string ErrorCode =
752 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
753 TAA, TAAParsed, StubSize);
754 if (!ErrorCode.empty()) {
755 // If invalid, report the error with report_fatal_error.
756 report_fatal_error("Global variable '" + GO->getName() +
757 "' has an invalid section specifier '" +
758 GO->getSection() + "': " + ErrorCode + ".");
763 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
765 // If TAA wasn't set by ParseSectionSpecifier() above,
766 // use the value returned by getMachOSection() as a default.
768 TAA = S->getTypeAndAttributes();
770 // Okay, now that we got the section, verify that the TAA & StubSize agree.
771 // If the user declared multiple globals with different section flags, we need
772 // to reject it here.
773 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
774 // If invalid, report the error with report_fatal_error.
775 report_fatal_error("Global variable '" + GO->getName() +
776 "' section type or attributes does not match previous"
777 " section specifier");
783 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
784 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
785 checkMachOComdat(GO);
787 // Handle thread local data.
788 if (Kind.isThreadBSS()) return TLSBSSSection;
789 if (Kind.isThreadData()) return TLSDataSection;
792 return GO->isWeakForLinker() ? TextCoalSection : TextSection;
794 // If this is weak/linkonce, put this in a coalescable section, either in text
795 // or data depending on if it is writable.
796 if (GO->isWeakForLinker()) {
797 if (Kind.isReadOnly())
798 return ConstTextCoalSection;
799 if (Kind.isReadOnlyWithRel())
800 return ConstDataCoalSection;
801 return DataCoalSection;
804 // FIXME: Alignment check should be handled by section classifier.
805 if (Kind.isMergeable1ByteCString() &&
806 GO->getParent()->getDataLayout().getPreferredAlignment(
807 cast<GlobalVariable>(GO)) < 32)
808 return CStringSection;
810 // Do not put 16-bit arrays in the UString section if they have an
811 // externally visible label, this runs into issues with certain linker
813 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
814 GO->getParent()->getDataLayout().getPreferredAlignment(
815 cast<GlobalVariable>(GO)) < 32)
816 return UStringSection;
818 // With MachO only variables whose corresponding symbol starts with 'l' or
819 // 'L' can be merged, so we only try merging GVs with private linkage.
820 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
821 if (Kind.isMergeableConst4())
822 return FourByteConstantSection;
823 if (Kind.isMergeableConst8())
824 return EightByteConstantSection;
825 if (Kind.isMergeableConst16())
826 return SixteenByteConstantSection;
829 // Otherwise, if it is readonly, but not something we can specially optimize,
830 // just drop it in .const.
831 if (Kind.isReadOnly())
832 return ReadOnlySection;
834 // If this is marked const, put it into a const section. But if the dynamic
835 // linker needs to write to it, put it in the data segment.
836 if (Kind.isReadOnlyWithRel())
837 return ConstDataSection;
839 // Put zero initialized globals with strong external linkage in the
840 // DATA, __common section with the .zerofill directive.
841 if (Kind.isBSSExtern())
842 return DataCommonSection;
844 // Put zero initialized globals with local linkage in __DATA,__bss directive
845 // with the .zerofill directive (aka .lcomm).
846 if (Kind.isBSSLocal())
847 return DataBSSSection;
849 // Otherwise, just drop the variable in the normal data section.
853 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
854 const DataLayout &DL, SectionKind Kind, const Constant *C,
855 unsigned &Align) const {
856 // If this constant requires a relocation, we have to put it in the data
857 // segment, not in the text segment.
858 if (Kind.isData() || Kind.isReadOnlyWithRel())
859 return ConstDataSection;
861 if (Kind.isMergeableConst4())
862 return FourByteConstantSection;
863 if (Kind.isMergeableConst8())
864 return EightByteConstantSection;
865 if (Kind.isMergeableConst16())
866 return SixteenByteConstantSection;
867 return ReadOnlySection; // .const
870 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
871 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
872 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
873 // The mach-o version of this method defaults to returning a stub reference.
875 if (Encoding & DW_EH_PE_indirect) {
876 MachineModuleInfoMachO &MachOMMI =
877 MMI->getObjFileInfo<MachineModuleInfoMachO>();
879 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
881 // Add information about the stub reference to MachOMMI so that the stub
882 // gets emitted by the asmprinter.
883 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
884 if (!StubSym.getPointer()) {
885 MCSymbol *Sym = TM.getSymbol(GV);
886 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
889 return TargetLoweringObjectFile::
890 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
891 Encoding & ~DW_EH_PE_indirect, Streamer);
894 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
898 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
899 const GlobalValue *GV, const TargetMachine &TM,
900 MachineModuleInfo *MMI) const {
901 // The mach-o version of this method defaults to returning a stub reference.
902 MachineModuleInfoMachO &MachOMMI =
903 MMI->getObjFileInfo<MachineModuleInfoMachO>();
905 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
907 // Add information about the stub reference to MachOMMI so that the stub
908 // gets emitted by the asmprinter.
909 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
910 if (!StubSym.getPointer()) {
911 MCSymbol *Sym = TM.getSymbol(GV);
912 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
918 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
919 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
920 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
921 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
922 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
923 // through a non_lazy_ptr stub instead. One advantage is that it allows the
924 // computation of deltas to final external symbols. Example:
930 // .long _extgotequiv-_delta
932 // is transformed to:
935 // .long L_extfoo$non_lazy_ptr-(_delta+0)
937 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
938 // L_extfoo$non_lazy_ptr:
939 // .indirect_symbol _extfoo
942 MachineModuleInfoMachO &MachOMMI =
943 MMI->getObjFileInfo<MachineModuleInfoMachO>();
944 MCContext &Ctx = getContext();
946 // The offset must consider the original displacement from the base symbol
947 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
948 Offset = -MV.getConstant();
949 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
951 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
952 // non_lazy_ptr stubs.
953 SmallString<128> Name;
954 StringRef Suffix = "$non_lazy_ptr";
955 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
956 Name += Sym->getName();
958 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
960 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
961 if (!StubSym.getPointer())
962 StubSym = MachineModuleInfoImpl::
963 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
965 const MCExpr *BSymExpr =
966 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
968 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
971 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
974 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
975 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
978 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
979 const MCSection &Section) {
980 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
983 // If it is not dead stripped, it is safe to use private labels.
984 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
985 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
991 void TargetLoweringObjectFileMachO::getNameWithPrefix(
992 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
993 const TargetMachine &TM) const {
994 bool CannotUsePrivateLabel = true;
995 if (auto *GO = GV->getBaseObject()) {
996 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
997 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
998 CannotUsePrivateLabel =
999 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1001 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1004 //===----------------------------------------------------------------------===//
1006 //===----------------------------------------------------------------------===//
1009 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1011 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1015 COFF::IMAGE_SCN_MEM_DISCARDABLE;
1016 else if (K.isText())
1018 COFF::IMAGE_SCN_MEM_EXECUTE |
1019 COFF::IMAGE_SCN_MEM_READ |
1020 COFF::IMAGE_SCN_CNT_CODE |
1021 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
1024 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1025 COFF::IMAGE_SCN_MEM_READ |
1026 COFF::IMAGE_SCN_MEM_WRITE;
1027 else if (K.isThreadLocal())
1029 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1030 COFF::IMAGE_SCN_MEM_READ |
1031 COFF::IMAGE_SCN_MEM_WRITE;
1032 else if (K.isReadOnly() || K.isReadOnlyWithRel())
1034 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1035 COFF::IMAGE_SCN_MEM_READ;
1036 else if (K.isWriteable())
1038 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1039 COFF::IMAGE_SCN_MEM_READ |
1040 COFF::IMAGE_SCN_MEM_WRITE;
1045 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1046 const Comdat *C = GV->getComdat();
1047 assert(C && "expected GV to have a Comdat!");
1049 StringRef ComdatGVName = C->getName();
1050 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1052 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1053 "' does not exist.");
1055 if (ComdatGV->getComdat() != C)
1056 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1057 "' is not a key for its COMDAT.");
1062 static int getSelectionForCOFF(const GlobalValue *GV) {
1063 if (const Comdat *C = GV->getComdat()) {
1064 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1065 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1066 ComdatKey = GA->getBaseObject();
1067 if (ComdatKey == GV) {
1068 switch (C->getSelectionKind()) {
1070 return COFF::IMAGE_COMDAT_SELECT_ANY;
1071 case Comdat::ExactMatch:
1072 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1073 case Comdat::Largest:
1074 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1075 case Comdat::NoDuplicates:
1076 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1077 case Comdat::SameSize:
1078 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1081 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1087 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1088 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1090 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1091 StringRef Name = GO->getSection();
1092 StringRef COMDATSymName = "";
1093 if (GO->hasComdat()) {
1094 Selection = getSelectionForCOFF(GO);
1095 const GlobalValue *ComdatGV;
1096 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1097 ComdatGV = getComdatGVForCOFF(GO);
1101 if (!ComdatGV->hasPrivateLinkage()) {
1102 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1103 COMDATSymName = Sym->getName();
1104 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1110 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1114 static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1119 if (Kind.isThreadLocal())
1121 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1126 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1127 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1128 // If we have -ffunction-sections then we should emit the global value to a
1129 // uniqued section specifically for it.
1130 bool EmitUniquedSection;
1132 EmitUniquedSection = TM.getFunctionSections();
1134 EmitUniquedSection = TM.getDataSections();
1136 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1137 SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1139 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1141 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1142 int Selection = getSelectionForCOFF(GO);
1144 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1145 const GlobalValue *ComdatGV;
1146 if (GO->hasComdat())
1147 ComdatGV = getComdatGVForCOFF(GO);
1151 unsigned UniqueID = MCContext::GenericSectionID;
1152 if (EmitUniquedSection)
1153 UniqueID = NextUniqueID++;
1155 if (!ComdatGV->hasPrivateLinkage()) {
1156 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1157 StringRef COMDATSymName = Sym->getName();
1159 // Append "$symbol" to the section name *before* IR-level mangling is
1160 // applied when targetting mingw. This is what GCC does, and the ld.bfd
1161 // COFF linker will not properly handle comdats otherwise.
1162 if (getTargetTriple().isWindowsGNUEnvironment())
1163 raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1165 return getContext().getCOFFSection(Name, Characteristics, Kind,
1166 COMDATSymName, Selection, UniqueID);
1168 SmallString<256> TmpData;
1169 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1170 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1171 Selection, UniqueID);
1178 if (Kind.isThreadLocal())
1179 return TLSDataSection;
1181 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1182 return ReadOnlySection;
1184 // Note: we claim that common symbols are put in BSSSection, but they are
1185 // really emitted with the magic .comm directive, which creates a symbol table
1186 // entry but not a section.
1187 if (Kind.isBSS() || Kind.isCommon())
1193 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1194 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1195 const TargetMachine &TM) const {
1196 bool CannotUsePrivateLabel = false;
1197 if (GV->hasPrivateLinkage() &&
1198 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1199 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1200 CannotUsePrivateLabel = true;
1202 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1205 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1206 const Function &F, const TargetMachine &TM) const {
1207 // If the function can be removed, produce a unique section so that
1208 // the table doesn't prevent the removal.
1209 const Comdat *C = F.getComdat();
1210 bool EmitUniqueSection = TM.getFunctionSections() || C;
1211 if (!EmitUniqueSection)
1212 return ReadOnlySection;
1214 // FIXME: we should produce a symbol for F instead.
1215 if (F.hasPrivateLinkage())
1216 return ReadOnlySection;
1218 MCSymbol *Sym = TM.getSymbol(&F);
1219 StringRef COMDATSymName = Sym->getName();
1221 SectionKind Kind = SectionKind::getReadOnly();
1222 StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
1223 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1224 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1225 unsigned UniqueID = NextUniqueID++;
1227 return getContext().getCOFFSection(
1228 SecName, Characteristics, Kind, COMDATSymName,
1229 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1232 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1234 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1235 // Emit the linker options to the linker .drectve section. According to the
1236 // spec, this section is a space-separated string containing flags for
1238 MCSection *Sec = getDrectveSection();
1239 Streamer.SwitchSection(Sec);
1240 for (const auto &Option : LinkerOptions->operands()) {
1241 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1242 // Lead with a space for consistency with our dllexport implementation.
1243 std::string Directive(" ");
1244 Directive.append(cast<MDString>(Piece)->getString());
1245 Streamer.EmitBytes(Directive);
1250 unsigned Version = 0;
1254 GetObjCImageInfo(M, Version, Flags, Section);
1255 if (Section.empty())
1258 auto &C = getContext();
1259 auto *S = C.getCOFFSection(
1260 Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1261 SectionKind::getReadOnly());
1262 Streamer.SwitchSection(S);
1263 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1264 Streamer.EmitIntValue(Version, 4);
1265 Streamer.EmitIntValue(Flags, 4);
1266 Streamer.AddBlankLine();
1269 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1270 const TargetMachine &TM) {
1271 TargetLoweringObjectFile::Initialize(Ctx, TM);
1272 const Triple &T = TM.getTargetTriple();
1273 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1275 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1276 COFF::IMAGE_SCN_MEM_READ,
1277 SectionKind::getReadOnly());
1279 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1280 COFF::IMAGE_SCN_MEM_READ,
1281 SectionKind::getReadOnly());
1283 StaticCtorSection = Ctx.getCOFFSection(
1284 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1285 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1286 SectionKind::getData());
1287 StaticDtorSection = Ctx.getCOFFSection(
1288 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1289 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1290 SectionKind::getData());
1294 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1295 const Triple &T, bool IsCtor,
1297 const MCSymbol *KeySym,
1298 MCSectionCOFF *Default) {
1299 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment())
1300 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1302 std::string Name = IsCtor ? ".ctors" : ".dtors";
1303 if (Priority != 65535)
1304 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1306 return Ctx.getAssociativeCOFFSection(
1307 Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1308 COFF::IMAGE_SCN_MEM_READ |
1309 COFF::IMAGE_SCN_MEM_WRITE,
1310 SectionKind::getData()),
1314 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1315 unsigned Priority, const MCSymbol *KeySym) const {
1316 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1318 cast<MCSectionCOFF>(StaticCtorSection));
1321 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1322 unsigned Priority, const MCSymbol *KeySym) const {
1323 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1325 cast<MCSectionCOFF>(StaticDtorSection));
1328 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1329 raw_ostream &OS, const GlobalValue *GV) const {
1330 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
1333 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
1334 raw_ostream &OS, const GlobalValue *GV) const {
1335 emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
1338 const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1339 const GlobalValue *LHS, const GlobalValue *RHS,
1340 const TargetMachine &TM) const {
1341 const Triple &T = TM.getTargetTriple();
1342 if (!T.isKnownWindowsMSVCEnvironment() &&
1343 !T.isWindowsItaniumEnvironment() &&
1344 !T.isWindowsCoreCLREnvironment())
1347 // Our symbols should exist in address space zero, cowardly no-op if
1349 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1350 RHS->getType()->getPointerAddressSpace() != 0)
1353 // Both ptrtoint instructions must wrap global objects:
1354 // - Only global variables are eligible for image relative relocations.
1355 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1356 // We expect __ImageBase to be a global variable without a section, externally
1359 // It should look something like this: @__ImageBase = external constant i8
1360 if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1361 LHS->isThreadLocal() || RHS->isThreadLocal() ||
1362 RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1363 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1366 return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1367 MCSymbolRefExpr::VK_COFF_IMGREL32,
1371 static std::string APIntToHexString(const APInt &AI) {
1372 unsigned Width = (AI.getBitWidth() / 8) * 2;
1373 std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true);
1374 unsigned Size = HexString.size();
1375 assert(Width >= Size && "hex string is too large!");
1376 HexString.insert(HexString.begin(), Width - Size, '0');
1381 static std::string scalarConstantToHexString(const Constant *C) {
1382 Type *Ty = C->getType();
1383 if (isa<UndefValue>(C)) {
1384 return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
1385 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1386 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1387 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1388 return APIntToHexString(CI->getValue());
1390 unsigned NumElements;
1391 if (isa<VectorType>(Ty))
1392 NumElements = Ty->getVectorNumElements();
1394 NumElements = Ty->getArrayNumElements();
1395 std::string HexString;
1396 for (int I = NumElements - 1, E = -1; I != E; --I)
1397 HexString += scalarConstantToHexString(C->getAggregateElement(I));
1402 MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
1403 const DataLayout &DL, SectionKind Kind, const Constant *C,
1404 unsigned &Align) const {
1405 if (Kind.isMergeableConst() && C &&
1406 getContext().getAsmInfo()->hasCOFFComdatConstants()) {
1407 // This creates comdat sections with the given symbol name, but unless
1408 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1409 // will be created with a null storage class, which makes GNU binutils
1411 const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1412 COFF::IMAGE_SCN_MEM_READ |
1413 COFF::IMAGE_SCN_LNK_COMDAT;
1414 std::string COMDATSymName;
1415 if (Kind.isMergeableConst4()) {
1417 COMDATSymName = "__real@" + scalarConstantToHexString(C);
1420 } else if (Kind.isMergeableConst8()) {
1422 COMDATSymName = "__real@" + scalarConstantToHexString(C);
1425 } else if (Kind.isMergeableConst16()) {
1426 // FIXME: These may not be appropriate for non-x86 architectures.
1428 COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
1431 } else if (Kind.isMergeableConst32()) {
1433 COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
1438 if (!COMDATSymName.empty())
1439 return getContext().getCOFFSection(".rdata", Characteristics, Kind,
1441 COFF::IMAGE_COMDAT_SELECT_ANY);
1444 return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align);
1448 //===----------------------------------------------------------------------===//
1450 //===----------------------------------------------------------------------===//
1452 static const Comdat *getWasmComdat(const GlobalValue *GV) {
1453 const Comdat *C = GV->getComdat();
1457 if (C->getSelectionKind() != Comdat::Any)
1458 report_fatal_error("WebAssembly COMDATs only support "
1459 "SelectionKind::Any, '" + C->getName() + "' cannot be "
1465 static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) {
1466 // If we're told we have function data, then use that.
1468 return SectionKind::getText();
1470 // Otherwise, ignore whatever section type the generic impl detected and use
1471 // a plain data section.
1472 return SectionKind::getData();
1475 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1476 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1477 // We don't support explict section names for functions in the wasm object
1478 // format. Each function has to be in its own unique section.
1479 if (isa<Function>(GO)) {
1480 return SelectSectionForGlobal(GO, Kind, TM);
1483 StringRef Name = GO->getSection();
1485 Kind = getWasmKindForNamedSection(Name, Kind);
1487 StringRef Group = "";
1488 if (const Comdat *C = getWasmComdat(GO)) {
1489 Group = C->getName();
1492 return getContext().getWasmSection(Name, Kind, Group,
1493 MCContext::GenericSectionID);
1496 static MCSectionWasm *selectWasmSectionForGlobal(
1497 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1498 const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
1499 StringRef Group = "";
1500 if (const Comdat *C = getWasmComdat(GO)) {
1501 Group = C->getName();
1504 bool UniqueSectionNames = TM.getUniqueSectionNames();
1505 SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1507 if (const auto *F = dyn_cast<Function>(GO)) {
1508 const auto &OptionalPrefix = F->getSectionPrefix();
1510 Name += *OptionalPrefix;
1513 if (EmitUniqueSection && UniqueSectionNames) {
1514 Name.push_back('.');
1515 TM.getNameWithPrefix(Name, GO, Mang, true);
1517 unsigned UniqueID = MCContext::GenericSectionID;
1518 if (EmitUniqueSection && !UniqueSectionNames) {
1519 UniqueID = *NextUniqueID;
1522 return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
1525 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1526 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1528 if (Kind.isCommon())
1529 report_fatal_error("mergable sections not supported yet on wasm");
1531 // If we have -ffunction-section or -fdata-section then we should emit the
1532 // global value to a uniqued section specifically for it.
1533 bool EmitUniqueSection = false;
1535 EmitUniqueSection = TM.getFunctionSections();
1537 EmitUniqueSection = TM.getDataSections();
1538 EmitUniqueSection |= GO->hasComdat();
1540 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1541 EmitUniqueSection, &NextUniqueID);
1544 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1545 bool UsesLabelDifference, const Function &F) const {
1546 // We can always create relative relocations, so use another section
1547 // that can be marked non-executable.
1551 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1552 const GlobalValue *LHS, const GlobalValue *RHS,
1553 const TargetMachine &TM) const {
1554 // We may only use a PLT-relative relocation to refer to unnamed_addr
1556 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1559 // Basic sanity checks.
1560 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1561 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1562 RHS->isThreadLocal())
1565 return MCBinaryExpr::createSub(
1566 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1568 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1571 void TargetLoweringObjectFileWasm::InitializeWasm() {
1573 getContext().getWasmSection(".init_array", SectionKind::getData());
1576 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
1577 unsigned Priority, const MCSymbol *KeySym) const {
1578 return Priority == UINT16_MAX ?
1580 getContext().getWasmSection(".init_array." + utostr(Priority),
1581 SectionKind::getData());
1584 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
1585 unsigned Priority, const MCSymbol *KeySym) const {
1586 llvm_unreachable("@llvm.global_dtors should have been lowered already");