LLVM 20.0.0git
TargetLoweringObjectFileImpl.cpp
Go to the documentation of this file.
1//===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements classes used to handle lowerings specific to common
10// object file formats.
11//
12//===----------------------------------------------------------------------===//
13
18#include "llvm/ADT/StringRef.h"
29#include "llvm/IR/Comdat.h"
30#include "llvm/IR/Constants.h"
31#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/Function.h"
36#include "llvm/IR/GlobalAlias.h"
38#include "llvm/IR/GlobalValue.h"
40#include "llvm/IR/Mangler.h"
41#include "llvm/IR/Metadata.h"
42#include "llvm/IR/Module.h"
43#include "llvm/IR/PseudoProbe.h"
44#include "llvm/IR/Type.h"
45#include "llvm/MC/MCAsmInfo.h"
47#include "llvm/MC/MCContext.h"
48#include "llvm/MC/MCExpr.h"
55#include "llvm/MC/MCStreamer.h"
56#include "llvm/MC/MCSymbol.h"
57#include "llvm/MC/MCSymbolELF.h"
58#include "llvm/MC/MCValue.h"
59#include "llvm/MC/SectionKind.h"
61#include "llvm/Support/Base64.h"
65#include "llvm/Support/Format.h"
69#include <cassert>
70#include <string>
71
72using namespace llvm;
73using namespace dwarf;
74
76 "jumptable-in-function-section", cl::Hidden, cl::init(false),
77 cl::desc("Putting Jump Table in function section"));
78
79static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
80 StringRef &Section) {
82 M.getModuleFlagsMetadata(ModuleFlags);
83
84 for (const auto &MFE: ModuleFlags) {
85 // Ignore flags with 'Require' behaviour.
86 if (MFE.Behavior == Module::Require)
87 continue;
88
89 StringRef Key = MFE.Key->getString();
90 if (Key == "Objective-C Image Info Version") {
91 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
92 } else if (Key == "Objective-C Garbage Collection" ||
93 Key == "Objective-C GC Only" ||
94 Key == "Objective-C Is Simulated" ||
95 Key == "Objective-C Class Properties" ||
96 Key == "Objective-C Image Swift Version") {
97 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
98 } else if (Key == "Objective-C Image Info Section") {
99 Section = cast<MDString>(MFE.Val)->getString();
100 }
101 // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
102 // "Objective-C Garbage Collection".
103 else if (Key == "Swift ABI Version") {
104 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
105 } else if (Key == "Swift Major Version") {
106 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
107 } else if (Key == "Swift Minor Version") {
108 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
109 }
110 }
111}
112
113//===----------------------------------------------------------------------===//
114// ELF
115//===----------------------------------------------------------------------===//
116
119}
120
122 const TargetMachine &TgtM) {
124
125 CodeModel::Model CM = TgtM.getCodeModel();
127
128 switch (TgtM.getTargetTriple().getArch()) {
129 case Triple::arm:
130 case Triple::armeb:
131 case Triple::thumb:
132 case Triple::thumbeb:
134 break;
135 // Fallthrough if not using EHABI
136 [[fallthrough]];
137 case Triple::ppc:
138 case Triple::ppcle:
139 case Triple::x86:
152 break;
153 case Triple::x86_64:
154 if (isPositionIndependent()) {
156 ((CM == CodeModel::Small || CM == CodeModel::Medium)
159 (CM == CodeModel::Small
162 ((CM == CodeModel::Small || CM == CodeModel::Medium)
164 } else {
166 (CM == CodeModel::Small || CM == CodeModel::Medium)
172 }
173 break;
174 case Triple::hexagon:
178 if (isPositionIndependent()) {
182 }
183 break;
184 case Triple::aarch64:
187 // The small model guarantees static code/data size < 4GB, but not where it
188 // will be in memory. Most of these could end up >2GB away so even a signed
189 // pc-relative 32-bit address is insufficient, theoretically.
190 //
191 // Use DW_EH_PE_indirect even for -fno-pic to avoid copy relocations.
198 break;
199 case Triple::lanai:
203 break;
204 case Triple::mips:
205 case Triple::mipsel:
206 case Triple::mips64:
207 case Triple::mips64el:
208 // MIPS uses indirect pointer to refer personality functions and types, so
209 // that the eh_frame section can be read-only. DW.ref.personality will be
210 // generated for relocation.
212 // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
213 // identify N64 from just a triple.
216
217 // FreeBSD must be explicit about the data size and using pcrel since it's
218 // assembler/linker won't do the automatic conversion that the Linux tools
219 // do.
223 }
224 break;
225 case Triple::ppc64:
226 case Triple::ppc64le:
232 break;
233 case Triple::sparcel:
234 case Triple::sparc:
235 if (isPositionIndependent()) {
241 } else {
245 }
247 break;
248 case Triple::riscv32:
249 case Triple::riscv64:
256 break;
257 case Triple::sparcv9:
259 if (isPositionIndependent()) {
264 } else {
267 }
268 break;
269 case Triple::systemz:
270 // All currently-defined code models guarantee that 4-byte PC-relative
271 // values will be in range.
272 if (isPositionIndependent()) {
278 } else {
282 }
283 break;
291 break;
292 default:
293 break;
294 }
295}
296
299 collectUsedGlobalVariables(M, Vec, false);
300 for (GlobalValue *GV : Vec)
301 if (auto *GO = dyn_cast<GlobalObject>(GV))
302 Used.insert(GO);
303}
304
306 Module &M) const {
307 auto &C = getContext();
308
309 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
310 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
312
313 Streamer.switchSection(S);
314
315 for (const auto *Operand : LinkerOptions->operands()) {
316 if (cast<MDNode>(Operand)->getNumOperands() != 2)
317 report_fatal_error("invalid llvm.linker.options");
318 for (const auto &Option : cast<MDNode>(Operand)->operands()) {
319 Streamer.emitBytes(cast<MDString>(Option)->getString());
320 Streamer.emitInt8(0);
321 }
322 }
323 }
324
325 if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
326 auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
328
329 Streamer.switchSection(S);
330
331 for (const auto *Operand : DependentLibraries->operands()) {
332 Streamer.emitBytes(
333 cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
334 Streamer.emitInt8(0);
335 }
336 }
337
338 if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
339 // Emit a descriptor for every function including functions that have an
340 // available external linkage. We may not want this for imported functions
341 // that has code in another thinLTO module but we don't have a good way to
342 // tell them apart from inline functions defined in header files. Therefore
343 // we put each descriptor in a separate comdat section and rely on the
344 // linker to deduplicate.
345 for (const auto *Operand : FuncInfo->operands()) {
346 const auto *MD = cast<MDNode>(Operand);
347 auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
348 auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
349 auto *Name = cast<MDString>(MD->getOperand(2));
350 auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
351 TM->getFunctionSections() ? Name->getString() : StringRef());
352
353 Streamer.switchSection(S);
354 Streamer.emitInt64(GUID->getZExtValue());
355 Streamer.emitInt64(Hash->getZExtValue());
356 Streamer.emitULEB128IntValue(Name->getString().size());
357 Streamer.emitBytes(Name->getString());
358 }
359 }
360
361 if (NamedMDNode *LLVMStats = M.getNamedMetadata("llvm.stats")) {
362 // Emit the metadata for llvm statistics into .llvm_stats section, which is
363 // formatted as a list of key/value pair, the value is base64 encoded.
364 auto *S = C.getObjectFileInfo()->getLLVMStatsSection();
365 Streamer.switchSection(S);
366 for (const auto *Operand : LLVMStats->operands()) {
367 const auto *MD = cast<MDNode>(Operand);
368 assert(MD->getNumOperands() % 2 == 0 &&
369 ("Operand num should be even for a list of key/value pair"));
370 for (size_t I = 0; I < MD->getNumOperands(); I += 2) {
371 // Encode the key string size.
372 auto *Key = cast<MDString>(MD->getOperand(I));
373 Streamer.emitULEB128IntValue(Key->getString().size());
374 Streamer.emitBytes(Key->getString());
375 // Encode the value into a Base64 string.
376 std::string Value = encodeBase64(
377 Twine(mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1))
378 ->getZExtValue())
379 .str());
380 Streamer.emitULEB128IntValue(Value.size());
381 Streamer.emitBytes(Value);
382 }
383 }
384 }
385
386 unsigned Version = 0;
387 unsigned Flags = 0;
388 StringRef Section;
389
390 GetObjCImageInfo(M, Version, Flags, Section);
391 if (!Section.empty()) {
392 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
393 Streamer.switchSection(S);
394 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
395 Streamer.emitInt32(Version);
396 Streamer.emitInt32(Flags);
397 Streamer.addBlankLine();
398 }
399
400 emitCGProfileMetadata(Streamer, M);
401}
402
404 const GlobalValue *GV, const TargetMachine &TM,
405 MachineModuleInfo *MMI) const {
406 unsigned Encoding = getPersonalityEncoding();
407 if ((Encoding & 0x80) == DW_EH_PE_indirect)
408 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
409 TM.getSymbol(GV)->getName());
410 if ((Encoding & 0x70) == DW_EH_PE_absptr)
411 return TM.getSymbol(GV);
412 report_fatal_error("We do not support this DWARF encoding yet!");
413}
414
416 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym,
417 const MachineModuleInfo *MMI) const {
418 SmallString<64> NameData("DW.ref.");
419 NameData += Sym->getName();
420 MCSymbolELF *Label =
421 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
422 Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
423 Streamer.emitSymbolAttribute(Label, MCSA_Weak);
424 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
425 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
426 ELF::SHT_PROGBITS, Flags, 0);
427 unsigned Size = DL.getPointerSize();
428 Streamer.switchSection(Sec);
429 Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0));
432 Streamer.emitELFSize(Label, E);
433 Streamer.emitLabel(Label);
434
435 emitPersonalityValueImpl(Streamer, DL, Sym, MMI);
436}
437
439 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym,
440 const MachineModuleInfo *MMI) const {
441 Streamer.emitSymbolValue(Sym, DL.getPointerSize());
442}
443
445 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
446 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
447 if (Encoding & DW_EH_PE_indirect) {
449
450 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
451
452 // Add information about the stub reference to ELFMMI so that the stub
453 // gets emitted by the asmprinter.
455 if (!StubSym.getPointer()) {
456 MCSymbol *Sym = TM.getSymbol(GV);
458 }
459
462 Encoding & ~DW_EH_PE_indirect, Streamer);
463 }
464
466 MMI, Streamer);
467}
468
470 // N.B.: The defaults used in here are not the same ones used in MC.
471 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
472 // both gas and MC will produce a section with no flags. Given
473 // section(".eh_frame") gcc will produce:
474 //
475 // .section .eh_frame,"a",@progbits
476
477 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
478 /*AddSegmentInfo=*/false) ||
480 /*AddSegmentInfo=*/false) ||
482 /*AddSegmentInfo=*/false) ||
484 /*AddSegmentInfo=*/false) ||
485 Name == ".llvmbc" || Name == ".llvmcmd")
487
488 if (!Name.starts_with(".")) return K;
489
490 // Default implementation based on some magic section names.
491 if (Name == ".bss" || Name.starts_with(".bss.") ||
492 Name.starts_with(".gnu.linkonce.b.") ||
493 Name.starts_with(".llvm.linkonce.b.") || Name == ".sbss" ||
494 Name.starts_with(".sbss.") || Name.starts_with(".gnu.linkonce.sb.") ||
495 Name.starts_with(".llvm.linkonce.sb."))
496 return SectionKind::getBSS();
497
498 if (Name == ".tdata" || Name.starts_with(".tdata.") ||
499 Name.starts_with(".gnu.linkonce.td.") ||
500 Name.starts_with(".llvm.linkonce.td."))
502
503 if (Name == ".tbss" || Name.starts_with(".tbss.") ||
504 Name.starts_with(".gnu.linkonce.tb.") ||
505 Name.starts_with(".llvm.linkonce.tb."))
507
508 return K;
509}
510
512 return SectionName.consume_front(Prefix) &&
513 (SectionName.empty() || SectionName[0] == '.');
514}
515
517 // Use SHT_NOTE for section whose name starts with ".note" to allow
518 // emitting ELF notes from C variable declaration.
519 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
520 if (Name.starts_with(".note"))
521 return ELF::SHT_NOTE;
522
523 if (hasPrefix(Name, ".init_array"))
524 return ELF::SHT_INIT_ARRAY;
525
526 if (hasPrefix(Name, ".fini_array"))
527 return ELF::SHT_FINI_ARRAY;
528
529 if (hasPrefix(Name, ".preinit_array"))
531
532 if (hasPrefix(Name, ".llvm.offloading"))
534 if (Name == ".llvm.lto")
535 return ELF::SHT_LLVM_LTO;
536
537 if (K.isBSS() || K.isThreadBSS())
538 return ELF::SHT_NOBITS;
539
540 return ELF::SHT_PROGBITS;
541}
542
543static unsigned getELFSectionFlags(SectionKind K) {
544 unsigned Flags = 0;
545
546 if (!K.isMetadata() && !K.isExclude())
547 Flags |= ELF::SHF_ALLOC;
548
549 if (K.isExclude())
550 Flags |= ELF::SHF_EXCLUDE;
551
552 if (K.isText())
553 Flags |= ELF::SHF_EXECINSTR;
554
555 if (K.isExecuteOnly())
556 Flags |= ELF::SHF_ARM_PURECODE;
557
558 if (K.isWriteable())
559 Flags |= ELF::SHF_WRITE;
560
561 if (K.isThreadLocal())
562 Flags |= ELF::SHF_TLS;
563
564 if (K.isMergeableCString() || K.isMergeableConst())
565 Flags |= ELF::SHF_MERGE;
566
567 if (K.isMergeableCString())
568 Flags |= ELF::SHF_STRINGS;
569
570 return Flags;
571}
572
573static const Comdat *getELFComdat(const GlobalValue *GV) {
574 const Comdat *C = GV->getComdat();
575 if (!C)
576 return nullptr;
577
578 if (C->getSelectionKind() != Comdat::Any &&
579 C->getSelectionKind() != Comdat::NoDeduplicate)
580 report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
581 "SelectionKind::NoDeduplicate, '" +
582 C->getName() + "' cannot be lowered.");
583
584 return C;
585}
586
588 const TargetMachine &TM) {
589 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
590 if (!MD)
591 return nullptr;
592
593 auto *VM = cast<ValueAsMetadata>(MD->getOperand(0).get());
594 auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
595 return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
596}
597
598static unsigned getEntrySizeForKind(SectionKind Kind) {
599 if (Kind.isMergeable1ByteCString())
600 return 1;
601 else if (Kind.isMergeable2ByteCString())
602 return 2;
603 else if (Kind.isMergeable4ByteCString())
604 return 4;
605 else if (Kind.isMergeableConst4())
606 return 4;
607 else if (Kind.isMergeableConst8())
608 return 8;
609 else if (Kind.isMergeableConst16())
610 return 16;
611 else if (Kind.isMergeableConst32())
612 return 32;
613 else {
614 // We shouldn't have mergeable C strings or mergeable constants that we
615 // didn't handle above.
616 assert(!Kind.isMergeableCString() && "unknown string width");
617 assert(!Kind.isMergeableConst() && "unknown data width");
618 return 0;
619 }
620}
621
622/// Return the section prefix name used by options FunctionsSections and
623/// DataSections.
625 if (Kind.isText())
626 return IsLarge ? ".ltext" : ".text";
627 if (Kind.isReadOnly())
628 return IsLarge ? ".lrodata" : ".rodata";
629 if (Kind.isBSS())
630 return IsLarge ? ".lbss" : ".bss";
631 if (Kind.isThreadData())
632 return ".tdata";
633 if (Kind.isThreadBSS())
634 return ".tbss";
635 if (Kind.isData())
636 return IsLarge ? ".ldata" : ".data";
637 if (Kind.isReadOnlyWithRel())
638 return IsLarge ? ".ldata.rel.ro" : ".data.rel.ro";
639 llvm_unreachable("Unknown section kind");
640}
641
642static SmallString<128>
644 Mangler &Mang, const TargetMachine &TM,
645 unsigned EntrySize, bool UniqueSectionName) {
647 getSectionPrefixForGlobal(Kind, TM.isLargeGlobalValue(GO));
648 if (Kind.isMergeableCString()) {
649 // We also need alignment here.
650 // FIXME: this is getting the alignment of the character, not the
651 // alignment of the global!
652 Align Alignment = GO->getDataLayout().getPreferredAlign(
653 cast<GlobalVariable>(GO));
654
655 Name += ".str";
656 Name += utostr(EntrySize);
657 Name += ".";
658 Name += utostr(Alignment.value());
659 } else if (Kind.isMergeableConst()) {
660 Name += ".cst";
661 Name += utostr(EntrySize);
662 }
663
664 bool HasPrefix = false;
665 if (const auto *F = dyn_cast<Function>(GO)) {
666 if (std::optional<StringRef> Prefix = F->getSectionPrefix()) {
667 raw_svector_ostream(Name) << '.' << *Prefix;
668 HasPrefix = true;
669 }
670 }
671
672 if (UniqueSectionName) {
673 Name.push_back('.');
674 TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
675 } else if (HasPrefix)
676 // For distinguishing between .text.${text-section-prefix}. (with trailing
677 // dot) and .text.${function-name}
678 Name.push_back('.');
679 return Name;
680}
681
682namespace {
683class LoweringDiagnosticInfo : public DiagnosticInfo {
684 const Twine &Msg;
685
686public:
687 LoweringDiagnosticInfo(const Twine &DiagMsg,
688 DiagnosticSeverity Severity = DS_Error)
689 : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
690 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
691};
692}
693
694/// Calculate an appropriate unique ID for a section, and update Flags,
695/// EntrySize and NextUniqueID where appropriate.
696static unsigned
698 SectionKind Kind, const TargetMachine &TM,
699 MCContext &Ctx, Mangler &Mang, unsigned &Flags,
700 unsigned &EntrySize, unsigned &NextUniqueID,
701 const bool Retain, const bool ForceUnique) {
702 // Increment uniqueID if we are forced to emit a unique section.
703 // This works perfectly fine with section attribute or pragma section as the
704 // sections with the same name are grouped together by the assembler.
705 if (ForceUnique)
706 return NextUniqueID++;
707
708 // A section can have at most one associated section. Put each global with
709 // MD_associated in a unique section.
710 const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
711 if (Associated) {
712 Flags |= ELF::SHF_LINK_ORDER;
713 return NextUniqueID++;
714 }
715
716 if (Retain) {
717 if (TM.getTargetTriple().isOSSolaris())
719 else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
720 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36))
721 Flags |= ELF::SHF_GNU_RETAIN;
722 return NextUniqueID++;
723 }
724
725 // If two symbols with differing sizes end up in the same mergeable section
726 // that section can be assigned an incorrect entry size. To avoid this we
727 // usually put symbols of the same size into distinct mergeable sections with
728 // the same name. Doing so relies on the ",unique ," assembly feature. This
729 // feature is not avalible until bintuils version 2.35
730 // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
731 const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
732 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
733 if (!SupportsUnique) {
734 Flags &= ~ELF::SHF_MERGE;
735 EntrySize = 0;
737 }
738
739 const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
740 const bool SeenSectionNameBefore =
742 // If this is the first ocurrence of this section name, treat it as the
743 // generic section
744 if (!SymbolMergeable && !SeenSectionNameBefore) {
745 if (TM.getSeparateNamedSections())
746 return NextUniqueID++;
747 else
749 }
750
751 // Symbols must be placed into sections with compatible entry sizes. Generate
752 // unique sections for symbols that have not been assigned to compatible
753 // sections.
754 const auto PreviousID =
755 Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
756 if (PreviousID && (!TM.getSeparateNamedSections() ||
757 *PreviousID == MCContext::GenericSectionID))
758 return *PreviousID;
759
760 // If the user has specified the same section name as would be created
761 // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
762 // to unique the section as the entry size for this symbol will be
763 // compatible with implicitly created sections.
764 SmallString<128> ImplicitSectionNameStem =
765 getELFSectionNameForGlobal(GO, Kind, Mang, TM, EntrySize, false);
766 if (SymbolMergeable &&
768 SectionName.starts_with(ImplicitSectionNameStem))
770
771 // We have seen this section name before, but with different flags or entity
772 // size. Create a new unique ID.
773 return NextUniqueID++;
774}
775
776static std::tuple<StringRef, bool, unsigned>
778 StringRef Group = "";
779 bool IsComdat = false;
780 unsigned Flags = 0;
781 if (const Comdat *C = getELFComdat(GO)) {
782 Flags |= ELF::SHF_GROUP;
783 Group = C->getName();
784 IsComdat = C->getSelectionKind() == Comdat::Any;
785 }
786 if (TM.isLargeGlobalValue(GO))
787 Flags |= ELF::SHF_X86_64_LARGE;
788 return {Group, IsComdat, Flags};
789}
790
792 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM,
793 MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID,
794 bool Retain, bool ForceUnique) {
796
797 // Check if '#pragma clang section' name is applicable.
798 // Note that pragma directive overrides -ffunction-section, -fdata-section
799 // and so section name is exactly as user specified and not uniqued.
800 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
801 if (GV && GV->hasImplicitSection()) {
802 auto Attrs = GV->getAttributes();
803 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
804 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
805 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
806 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
807 } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
808 SectionName = Attrs.getAttribute("relro-section").getValueAsString();
809 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
810 SectionName = Attrs.getAttribute("data-section").getValueAsString();
811 }
812 }
813
814 // Infer section flags from the section name if we can.
816
817 unsigned Flags = getELFSectionFlags(Kind);
818 auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM);
819 Flags |= ExtraFlags;
820
821 unsigned EntrySize = getEntrySizeForKind(Kind);
822 const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
823 GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
824 Retain, ForceUnique);
825
826 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
827 MCSectionELF *Section = Ctx.getELFSection(
828 SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
829 Group, IsComdat, UniqueID, LinkedToSym);
830 // Make sure that we did not get some other section with incompatible sh_link.
831 // This should not be possible due to UniqueID code above.
832 assert(Section->getLinkedToSymbol() == LinkedToSym &&
833 "Associated symbol mismatch between sections");
834
835 if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
836 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
837 // If we are using GNU as before 2.35, then this symbol might have
838 // been placed in an incompatible mergeable section. Emit an error if this
839 // is the case to avoid creating broken output.
840 if ((Section->getFlags() & ELF::SHF_MERGE) &&
841 (Section->getEntrySize() != getEntrySizeForKind(Kind)))
842 GO->getContext().diagnose(LoweringDiagnosticInfo(
843 "Symbol '" + GO->getName() + "' from module '" +
844 (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
845 "' required a section with entry-size=" +
846 Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
847 SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
848 ": Explicit assignment by pragma or attribute of an incompatible "
849 "symbol to this section?"));
850 }
851
852 return Section;
853}
854
856 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
858 NextUniqueID, Used.count(GO),
859 /* ForceUnique = */false);
860}
861
863 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
864 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
865 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
866
867 auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM);
868 Flags |= ExtraFlags;
869
870 // Get the section entry size based on the kind.
871 unsigned EntrySize = getEntrySizeForKind(Kind);
872
873 bool UniqueSectionName = false;
874 unsigned UniqueID = MCContext::GenericSectionID;
875 if (EmitUniqueSection) {
876 if (TM.getUniqueSectionNames()) {
877 UniqueSectionName = true;
878 } else {
879 UniqueID = *NextUniqueID;
880 (*NextUniqueID)++;
881 }
882 }
884 GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
885
886 // Use 0 as the unique ID for execute-only text.
887 if (Kind.isExecuteOnly())
888 UniqueID = 0;
889 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
890 EntrySize, Group, IsComdat, UniqueID,
891 AssociatedSymbol);
892}
893
895 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
896 const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
897 unsigned Flags, unsigned *NextUniqueID) {
898 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
899 if (LinkedToSym) {
900 EmitUniqueSection = true;
901 Flags |= ELF::SHF_LINK_ORDER;
902 }
903 if (Retain) {
904 if (TM.getTargetTriple().isOSSolaris()) {
905 EmitUniqueSection = true;
907 } else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
908 Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) {
909 EmitUniqueSection = true;
910 Flags |= ELF::SHF_GNU_RETAIN;
911 }
912 }
913
915 Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
916 NextUniqueID, LinkedToSym);
917 assert(Section->getLinkedToSymbol() == LinkedToSym);
918 return Section;
919}
920
922 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
923 unsigned Flags = getELFSectionFlags(Kind);
924
925 // If we have -ffunction-section or -fdata-section then we should emit the
926 // global value to a uniqued section specifically for it.
927 bool EmitUniqueSection = false;
928 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
929 if (Kind.isText())
930 EmitUniqueSection = TM.getFunctionSections();
931 else
932 EmitUniqueSection = TM.getDataSections();
933 }
934 EmitUniqueSection |= GO->hasComdat();
935 return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
936 Used.count(GO), EmitUniqueSection, Flags,
937 &NextUniqueID);
938}
939
941 const Function &F, const TargetMachine &TM) const {
943 unsigned Flags = getELFSectionFlags(Kind);
944 // If the function's section names is pre-determined via pragma or a
945 // section attribute, call selectExplicitSectionGlobal.
946 if (F.hasSection())
948 &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
949 Used.count(&F), /* ForceUnique = */true);
950 else
952 getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
953 /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
954}
955
957 const Function &F, const TargetMachine &TM) const {
958 // If the function can be removed, produce a unique section so that
959 // the table doesn't prevent the removal.
960 const Comdat *C = F.getComdat();
961 bool EmitUniqueSection = TM.getFunctionSections() || C;
962 if (!EmitUniqueSection)
963 return ReadOnlySection;
964
966 getMangler(), TM, EmitUniqueSection,
967 ELF::SHF_ALLOC, &NextUniqueID,
968 /* AssociatedSymbol */ nullptr);
969}
970
972 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
973 // If neither COMDAT nor function sections, use the monolithic LSDA section.
974 // Re-use this path if LSDASection is null as in the Arm EHABI.
975 if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
976 return LSDASection;
977
978 const auto *LSDA = cast<MCSectionELF>(LSDASection);
979 unsigned Flags = LSDA->getFlags();
980 const MCSymbolELF *LinkedToSym = nullptr;
981 StringRef Group;
982 bool IsComdat = false;
983 if (const Comdat *C = getELFComdat(&F)) {
984 Flags |= ELF::SHF_GROUP;
985 Group = C->getName();
986 IsComdat = C->getSelectionKind() == Comdat::Any;
987 }
988 // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
989 // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
990 if (TM.getFunctionSections() &&
991 (getContext().getAsmInfo()->useIntegratedAssembler() &&
992 getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
993 Flags |= ELF::SHF_LINK_ORDER;
994 LinkedToSym = cast<MCSymbolELF>(&FnSym);
995 }
996
997 // Append the function name as the suffix like GCC, assuming
998 // -funique-section-names applies to .gcc_except_table sections.
999 return getContext().getELFSection(
1000 (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
1001 : LSDA->getName()),
1002 LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
1003 LinkedToSym);
1004}
1005
1007 bool UsesLabelDifference, const Function &F) const {
1008 // We can always create relative relocations, so use another section
1009 // that can be marked non-executable.
1010 return false;
1011}
1012
1013/// Given a mergeable constant with the specified size and relocation
1014/// information, return a section that it should be placed in.
1016 const DataLayout &DL, SectionKind Kind, const Constant *C,
1017 Align &Alignment) const {
1018 if (Kind.isMergeableConst4() && MergeableConst4Section)
1020 if (Kind.isMergeableConst8() && MergeableConst8Section)
1022 if (Kind.isMergeableConst16() && MergeableConst16Section)
1024 if (Kind.isMergeableConst32() && MergeableConst32Section)
1026 if (Kind.isReadOnly())
1027 return ReadOnlySection;
1028
1029 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
1030 return DataRelROSection;
1031}
1032
1033/// Returns a unique section for the given machine basic block.
1035 const Function &F, const MachineBasicBlock &MBB,
1036 const TargetMachine &TM) const {
1037 assert(MBB.isBeginSection() && "Basic block does not start a section!");
1038 unsigned UniqueID = MCContext::GenericSectionID;
1039
1040 // For cold sections use the .text.split. prefix along with the parent
1041 // function name. All cold blocks for the same function go to the same
1042 // section. Similarly all exception blocks are grouped by symbol name
1043 // under the .text.eh prefix. For regular sections, we either use a unique
1044 // name, or a unique ID for the section.
1046 StringRef FunctionSectionName = MBB.getParent()->getSection()->getName();
1047 if (FunctionSectionName == ".text" ||
1048 FunctionSectionName.starts_with(".text.")) {
1049 // Function is in a regular .text section.
1050 StringRef FunctionName = MBB.getParent()->getName();
1053 Name += FunctionName;
1055 Name += ".text.eh.";
1056 Name += FunctionName;
1057 } else {
1058 Name += FunctionSectionName;
1060 if (!Name.ends_with("."))
1061 Name += ".";
1062 Name += MBB.getSymbol()->getName();
1063 } else {
1064 UniqueID = NextUniqueID++;
1065 }
1066 }
1067 } else {
1068 // If the original function has a custom non-dot-text section, then emit
1069 // all basic block sections into that section too, each with a unique id.
1070 Name = FunctionSectionName;
1071 UniqueID = NextUniqueID++;
1072 }
1073
1074 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
1075 std::string GroupName;
1076 if (F.hasComdat()) {
1077 Flags |= ELF::SHF_GROUP;
1078 GroupName = F.getComdat()->getName().str();
1079 }
1081 0 /* Entry Size */, GroupName,
1082 F.hasComdat(), UniqueID, nullptr);
1083}
1084
1085static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
1086 bool IsCtor, unsigned Priority,
1087 const MCSymbol *KeySym) {
1088 std::string Name;
1089 unsigned Type;
1090 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1091 StringRef Comdat = KeySym ? KeySym->getName() : "";
1092
1093 if (KeySym)
1094 Flags |= ELF::SHF_GROUP;
1095
1096 if (UseInitArray) {
1097 if (IsCtor) {
1099 Name = ".init_array";
1100 } else {
1102 Name = ".fini_array";
1103 }
1104 if (Priority != 65535) {
1105 Name += '.';
1106 Name += utostr(Priority);
1107 }
1108 } else {
1109 // The default scheme is .ctor / .dtor, so we have to invert the priority
1110 // numbering.
1111 if (IsCtor)
1112 Name = ".ctors";
1113 else
1114 Name = ".dtors";
1115 if (Priority != 65535)
1116 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1118 }
1119
1120 return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
1121}
1122
1124 unsigned Priority, const MCSymbol *KeySym) const {
1125 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
1126 KeySym);
1127}
1128
1130 unsigned Priority, const MCSymbol *KeySym) const {
1131 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
1132 KeySym);
1133}
1134
1136 const GlobalValue *LHS, const GlobalValue *RHS,
1137 const TargetMachine &TM) const {
1138 // We may only use a PLT-relative relocation to refer to unnamed_addr
1139 // functions.
1140 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1141 return nullptr;
1142
1143 // Basic correctness checks.
1144 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1145 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1146 RHS->isThreadLocal())
1147 return nullptr;
1148
1151 getContext()),
1153}
1154
1156 const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
1158
1159 const auto *GV = Equiv->getGlobalValue();
1160
1161 // A PLT entry is not needed for dso_local globals.
1162 if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
1164
1166 getContext());
1167}
1168
1170 // Use ".GCC.command.line" since this feature is to support clang's
1171 // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1172 // same name.
1173 return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1175}
1176
1177void
1179 UseInitArray = UseInitArray_;
1180 MCContext &Ctx = getContext();
1181 if (!UseInitArray) {
1184
1187 return;
1188 }
1189
1194}
1195
1196//===----------------------------------------------------------------------===//
1197// MachO
1198//===----------------------------------------------------------------------===//
1199
1202}
1203
1205 const TargetMachine &TM) {
1208 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1210 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1212 } else {
1213 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1216 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1219 }
1220
1226}
1227
1229 unsigned Priority, const MCSymbol *KeySym) const {
1230 return StaticDtorSection;
1231 // In userspace, we lower global destructors via atexit(), but kernel/kext
1232 // environments do not provide this function so we still need to support the
1233 // legacy way here.
1234 // See the -disable-atexit-based-global-dtor-lowering CodeGen flag for more
1235 // context.
1236}
1237
1239 Module &M) const {
1240 // Emit the linker options if present.
1241 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1242 for (const auto *Option : LinkerOptions->operands()) {
1243 SmallVector<std::string, 4> StrOptions;
1244 for (const auto &Piece : cast<MDNode>(Option)->operands())
1245 StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
1246 Streamer.emitLinkerOptions(StrOptions);
1247 }
1248 }
1249
1250 unsigned VersionVal = 0;
1251 unsigned ImageInfoFlags = 0;
1252 StringRef SectionVal;
1253
1254 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
1255 emitCGProfileMetadata(Streamer, M);
1256
1257 // The section is mandatory. If we don't have it, then we don't have GC info.
1258 if (SectionVal.empty())
1259 return;
1260
1261 StringRef Segment, Section;
1262 unsigned TAA = 0, StubSize = 0;
1263 bool TAAParsed;
1265 SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
1266 // If invalid, report the error with report_fatal_error.
1267 report_fatal_error("Invalid section specifier '" + Section +
1268 "': " + toString(std::move(E)) + ".");
1269 }
1270
1271 // Get the section.
1273 Segment, Section, TAA, StubSize, SectionKind::getData());
1274 Streamer.switchSection(S);
1275 Streamer.emitLabel(getContext().
1276 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
1277 Streamer.emitInt32(VersionVal);
1278 Streamer.emitInt32(ImageInfoFlags);
1279 Streamer.addBlankLine();
1280}
1281
1282static void checkMachOComdat(const GlobalValue *GV) {
1283 const Comdat *C = GV->getComdat();
1284 if (!C)
1285 return;
1286
1287 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1288 "' cannot be lowered.");
1289}
1290
1292 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1293
1295
1296 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
1297 if (GV && GV->hasImplicitSection()) {
1298 auto Attrs = GV->getAttributes();
1299 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
1300 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
1301 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
1302 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
1303 } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
1304 SectionName = Attrs.getAttribute("relro-section").getValueAsString();
1305 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
1306 SectionName = Attrs.getAttribute("data-section").getValueAsString();
1307 }
1308 }
1309
1310 // Parse the section specifier and create it if valid.
1311 StringRef Segment, Section;
1312 unsigned TAA = 0, StubSize = 0;
1313 bool TAAParsed;
1314
1315 checkMachOComdat(GO);
1316
1318 SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
1319 // If invalid, report the error with report_fatal_error.
1320 report_fatal_error("Global variable '" + GO->getName() +
1321 "' has an invalid section specifier '" +
1322 GO->getSection() + "': " + toString(std::move(E)) + ".");
1323 }
1324
1325 // Get the section.
1326 MCSectionMachO *S =
1327 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1328
1329 // If TAA wasn't set by ParseSectionSpecifier() above,
1330 // use the value returned by getMachOSection() as a default.
1331 if (!TAAParsed)
1332 TAA = S->getTypeAndAttributes();
1333
1334 // Okay, now that we got the section, verify that the TAA & StubSize agree.
1335 // If the user declared multiple globals with different section flags, we need
1336 // to reject it here.
1337 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1338 // If invalid, report the error with report_fatal_error.
1339 report_fatal_error("Global variable '" + GO->getName() +
1340 "' section type or attributes does not match previous"
1341 " section specifier");
1342 }
1343
1344 return S;
1345}
1346
1348 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1349 checkMachOComdat(GO);
1350
1351 // Handle thread local data.
1352 if (Kind.isThreadBSS()) return TLSBSSSection;
1353 if (Kind.isThreadData()) return TLSDataSection;
1354
1355 if (Kind.isText())
1357
1358 // If this is weak/linkonce, put this in a coalescable section, either in text
1359 // or data depending on if it is writable.
1360 if (GO->isWeakForLinker()) {
1361 if (Kind.isReadOnly())
1362 return ConstTextCoalSection;
1363 if (Kind.isReadOnlyWithRel())
1364 return ConstDataCoalSection;
1365 return DataCoalSection;
1366 }
1367
1368 // FIXME: Alignment check should be handled by section classifier.
1369 if (Kind.isMergeable1ByteCString() &&
1371 cast<GlobalVariable>(GO)) < Align(32))
1372 return CStringSection;
1373
1374 // Do not put 16-bit arrays in the UString section if they have an
1375 // externally visible label, this runs into issues with certain linker
1376 // versions.
1377 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
1379 cast<GlobalVariable>(GO)) < Align(32))
1380 return UStringSection;
1381
1382 // With MachO only variables whose corresponding symbol starts with 'l' or
1383 // 'L' can be merged, so we only try merging GVs with private linkage.
1384 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1385 if (Kind.isMergeableConst4())
1387 if (Kind.isMergeableConst8())
1389 if (Kind.isMergeableConst16())
1391 }
1392
1393 // Otherwise, if it is readonly, but not something we can specially optimize,
1394 // just drop it in .const.
1395 if (Kind.isReadOnly())
1396 return ReadOnlySection;
1397
1398 // If this is marked const, put it into a const section. But if the dynamic
1399 // linker needs to write to it, put it in the data segment.
1400 if (Kind.isReadOnlyWithRel())
1401 return ConstDataSection;
1402
1403 // Put zero initialized globals with strong external linkage in the
1404 // DATA, __common section with the .zerofill directive.
1405 if (Kind.isBSSExtern())
1406 return DataCommonSection;
1407
1408 // Put zero initialized globals with local linkage in __DATA,__bss directive
1409 // with the .zerofill directive (aka .lcomm).
1410 if (Kind.isBSSLocal())
1411 return DataBSSSection;
1412
1413 // Otherwise, just drop the variable in the normal data section.
1414 return DataSection;
1415}
1416
1418 const DataLayout &DL, SectionKind Kind, const Constant *C,
1419 Align &Alignment) const {
1420 // If this constant requires a relocation, we have to put it in the data
1421 // segment, not in the text segment.
1422 if (Kind.isData() || Kind.isReadOnlyWithRel())
1423 return ConstDataSection;
1424
1425 if (Kind.isMergeableConst4())
1427 if (Kind.isMergeableConst8())
1429 if (Kind.isMergeableConst16())
1431 return ReadOnlySection; // .const
1432}
1433
1435 return getContext().getMachOSection("__TEXT", "__command_line", 0,
1437}
1438
1440 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1441 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1442 // The mach-o version of this method defaults to returning a stub reference.
1443
1444 if (Encoding & DW_EH_PE_indirect) {
1445 MachineModuleInfoMachO &MachOMMI =
1447
1448 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1449
1450 // Add information about the stub reference to MachOMMI so that the stub
1451 // gets emitted by the asmprinter.
1452 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1453 if (!StubSym.getPointer()) {
1454 MCSymbol *Sym = TM.getSymbol(GV);
1456 }
1457
1460 Encoding & ~DW_EH_PE_indirect, Streamer);
1461 }
1462
1464 MMI, Streamer);
1465}
1466
1468 const GlobalValue *GV, const TargetMachine &TM,
1469 MachineModuleInfo *MMI) const {
1470 // The mach-o version of this method defaults to returning a stub reference.
1471 MachineModuleInfoMachO &MachOMMI =
1473
1474 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1475
1476 // Add information about the stub reference to MachOMMI so that the stub
1477 // gets emitted by the asmprinter.
1478 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1479 if (!StubSym.getPointer()) {
1480 MCSymbol *Sym = TM.getSymbol(GV);
1482 }
1483
1484 return SSym;
1485}
1486
1488 const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
1489 int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1490 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1491 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1492 // through a non_lazy_ptr stub instead. One advantage is that it allows the
1493 // computation of deltas to final external symbols. Example:
1494 //
1495 // _extgotequiv:
1496 // .long _extfoo
1497 //
1498 // _delta:
1499 // .long _extgotequiv-_delta
1500 //
1501 // is transformed to:
1502 //
1503 // _delta:
1504 // .long L_extfoo$non_lazy_ptr-(_delta+0)
1505 //
1506 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
1507 // L_extfoo$non_lazy_ptr:
1508 // .indirect_symbol _extfoo
1509 // .long 0
1510 //
1511 // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1512 // may point to both local (same translation unit) and global (other
1513 // translation units) symbols. Example:
1514 //
1515 // .section __DATA,__pointers,non_lazy_symbol_pointers
1516 // L1:
1517 // .indirect_symbol _myGlobal
1518 // .long 0
1519 // L2:
1520 // .indirect_symbol _myLocal
1521 // .long _myLocal
1522 //
1523 // If the symbol is local, instead of the symbol's index, the assembler
1524 // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1525 // Then the linker will notice the constant in the table and will look at the
1526 // content of the symbol.
1527 MachineModuleInfoMachO &MachOMMI =
1529 MCContext &Ctx = getContext();
1530
1531 // The offset must consider the original displacement from the base symbol
1532 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1533 Offset = -MV.getConstant();
1534 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1535
1536 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1537 // non_lazy_ptr stubs.
1539 StringRef Suffix = "$non_lazy_ptr";
1541 Name += Sym->getName();
1542 Name += Suffix;
1543 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1544
1545 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1546
1547 if (!StubSym.getPointer())
1548 StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1549 !GV->hasLocalLinkage());
1550
1551 const MCExpr *BSymExpr =
1553 const MCExpr *LHS =
1555
1556 if (!Offset)
1557 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1558
1559 const MCExpr *RHS =
1561 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1562}
1563
1564static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1565 const MCSection &Section) {
1567 return true;
1568
1569 // FIXME: we should be able to use private labels for sections that can't be
1570 // dead-stripped (there's no issue with blocking atomization there), but `ld
1571 // -r` sometimes drops the no_dead_strip attribute from sections so for safety
1572 // we don't allow it.
1573 return false;
1574}
1575
1577 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1578 const TargetMachine &TM) const {
1579 bool CannotUsePrivateLabel = true;
1580 if (auto *GO = GV->getAliaseeObject()) {
1582 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1583 CannotUsePrivateLabel =
1584 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1585 }
1586 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1587}
1588
1589//===----------------------------------------------------------------------===//
1590// COFF
1591//===----------------------------------------------------------------------===//
1592
1593static unsigned
1595 unsigned Flags = 0;
1596 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1597
1598 if (K.isMetadata())
1599 Flags |=
1601 else if (K.isExclude())
1602 Flags |=
1604 else if (K.isText())
1605 Flags |=
1610 else if (K.isBSS())
1611 Flags |=
1615 else if (K.isThreadLocal())
1616 Flags |=
1620 else if (K.isReadOnly() || K.isReadOnlyWithRel())
1621 Flags |=
1624 else if (K.isWriteable())
1625 Flags |=
1629
1630 return Flags;
1631}
1632
1634 const Comdat *C = GV->getComdat();
1635 assert(C && "expected GV to have a Comdat!");
1636
1637 StringRef ComdatGVName = C->getName();
1638 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1639 if (!ComdatGV)
1640 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1641 "' does not exist.");
1642
1643 if (ComdatGV->getComdat() != C)
1644 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1645 "' is not a key for its COMDAT.");
1646
1647 return ComdatGV;
1648}
1649
1650static int getSelectionForCOFF(const GlobalValue *GV) {
1651 if (const Comdat *C = GV->getComdat()) {
1652 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1653 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1654 ComdatKey = GA->getAliaseeObject();
1655 if (ComdatKey == GV) {
1656 switch (C->getSelectionKind()) {
1657 case Comdat::Any:
1659 case Comdat::ExactMatch:
1661 case Comdat::Largest:
1665 case Comdat::SameSize:
1667 }
1668 } else {
1670 }
1671 }
1672 return 0;
1673}
1674
1676 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1677 StringRef Name = GO->getSection();
1678 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::COFF,
1679 /*AddSegmentInfo=*/false) ||
1681 /*AddSegmentInfo=*/false) ||
1682 Name == getInstrProfSectionName(IPSK_covdata, Triple::COFF,
1683 /*AddSegmentInfo=*/false) ||
1684 Name == getInstrProfSectionName(IPSK_covname, Triple::COFF,
1685 /*AddSegmentInfo=*/false))
1686 Kind = SectionKind::getMetadata();
1687 int Selection = 0;
1688 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1689 StringRef COMDATSymName = "";
1690 if (GO->hasComdat()) {
1692 const GlobalValue *ComdatGV;
1694 ComdatGV = getComdatGVForCOFF(GO);
1695 else
1696 ComdatGV = GO;
1697
1698 if (!ComdatGV->hasPrivateLinkage()) {
1699 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1700 COMDATSymName = Sym->getName();
1702 } else {
1703 Selection = 0;
1704 }
1705 }
1706
1707 return getContext().getCOFFSection(Name, Characteristics, COMDATSymName,
1708 Selection);
1709}
1710
1712 if (Kind.isText())
1713 return ".text";
1714 if (Kind.isBSS())
1715 return ".bss";
1716 if (Kind.isThreadLocal())
1717 return ".tls$";
1718 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1719 return ".rdata";
1720 return ".data";
1721}
1722
1724 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1725 // If we have -ffunction-sections then we should emit the global value to a
1726 // uniqued section specifically for it.
1727 bool EmitUniquedSection;
1728 if (Kind.isText())
1729 EmitUniquedSection = TM.getFunctionSections();
1730 else
1731 EmitUniquedSection = TM.getDataSections();
1732
1733 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1735
1736 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1737
1740 if (!Selection)
1742 const GlobalValue *ComdatGV;
1743 if (GO->hasComdat())
1744 ComdatGV = getComdatGVForCOFF(GO);
1745 else
1746 ComdatGV = GO;
1747
1748 unsigned UniqueID = MCContext::GenericSectionID;
1749 if (EmitUniquedSection)
1750 UniqueID = NextUniqueID++;
1751
1752 if (!ComdatGV->hasPrivateLinkage()) {
1753 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1754 StringRef COMDATSymName = Sym->getName();
1755
1756 if (const auto *F = dyn_cast<Function>(GO))
1757 if (std::optional<StringRef> Prefix = F->getSectionPrefix())
1758 raw_svector_ostream(Name) << '$' << *Prefix;
1759
1760 // Append "$symbol" to the section name *before* IR-level mangling is
1761 // applied when targetting mingw. This is what GCC does, and the ld.bfd
1762 // COFF linker will not properly handle comdats otherwise.
1763 if (getContext().getTargetTriple().isWindowsGNUEnvironment())
1764 raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1765
1766 return getContext().getCOFFSection(Name, Characteristics, COMDATSymName,
1767 Selection, UniqueID);
1768 } else {
1769 SmallString<256> TmpData;
1770 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1771 return getContext().getCOFFSection(Name, Characteristics, TmpData,
1772 Selection, UniqueID);
1773 }
1774 }
1775
1776 if (Kind.isText())
1777 return TextSection;
1778
1779 if (Kind.isThreadLocal())
1780 return TLSDataSection;
1781
1782 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1783 return ReadOnlySection;
1784
1785 // Note: we claim that common symbols are put in BSSSection, but they are
1786 // really emitted with the magic .comm directive, which creates a symbol table
1787 // entry but not a section.
1788 if (Kind.isBSS() || Kind.isCommon())
1789 return BSSSection;
1790
1791 return DataSection;
1792}
1793
1795 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1796 const TargetMachine &TM) const {
1797 bool CannotUsePrivateLabel = false;
1798 if (GV->hasPrivateLinkage() &&
1799 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1800 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1801 CannotUsePrivateLabel = true;
1802
1803 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1804}
1805
1807 const Function &F, const TargetMachine &TM) const {
1808 // If the function can be removed, produce a unique section so that
1809 // the table doesn't prevent the removal.
1810 const Comdat *C = F.getComdat();
1811 bool EmitUniqueSection = TM.getFunctionSections() || C;
1812 if (!EmitUniqueSection)
1813 return ReadOnlySection;
1814
1815 // FIXME: we should produce a symbol for F instead.
1816 if (F.hasPrivateLinkage())
1817 return ReadOnlySection;
1818
1819 MCSymbol *Sym = TM.getSymbol(&F);
1820 StringRef COMDATSymName = Sym->getName();
1821
1824 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1826 unsigned UniqueID = NextUniqueID++;
1827
1828 return getContext().getCOFFSection(SecName, Characteristics, COMDATSymName,
1830 UniqueID);
1831}
1832
1834 bool UsesLabelDifference, const Function &F) const {
1835 if (TM->getTargetTriple().getArch() == Triple::x86_64) {
1837 // We can always create relative relocations, so use another section
1838 // that can be marked non-executable.
1839 return false;
1840 }
1841 }
1843 UsesLabelDifference, F);
1844}
1845
1847 Module &M) const {
1848 emitLinkerDirectives(Streamer, M);
1849
1850 unsigned Version = 0;
1851 unsigned Flags = 0;
1852 StringRef Section;
1853
1854 GetObjCImageInfo(M, Version, Flags, Section);
1855 if (!Section.empty()) {
1856 auto &C = getContext();
1857 auto *S = C.getCOFFSection(Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1859 Streamer.switchSection(S);
1860 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1861 Streamer.emitInt32(Version);
1862 Streamer.emitInt32(Flags);
1863 Streamer.addBlankLine();
1864 }
1865
1866 emitCGProfileMetadata(Streamer, M);
1867}
1868
1869void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
1870 MCStreamer &Streamer, Module &M) const {
1871 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1872 // Emit the linker options to the linker .drectve section. According to the
1873 // spec, this section is a space-separated string containing flags for
1874 // linker.
1876 Streamer.switchSection(Sec);
1877 for (const auto *Option : LinkerOptions->operands()) {
1878 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1879 // Lead with a space for consistency with our dllexport implementation.
1880 std::string Directive(" ");
1881 Directive.append(std::string(cast<MDString>(Piece)->getString()));
1882 Streamer.emitBytes(Directive);
1883 }
1884 }
1885 }
1886
1887 // Emit /EXPORT: flags for each exported global as necessary.
1888 std::string Flags;
1889 for (const GlobalValue &GV : M.global_values()) {
1890 raw_string_ostream OS(Flags);
1891 emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
1892 getMangler());
1893 OS.flush();
1894 if (!Flags.empty()) {
1895 Streamer.switchSection(getDrectveSection());
1896 Streamer.emitBytes(Flags);
1897 }
1898 Flags.clear();
1899 }
1900
1901 // Emit /INCLUDE: flags for each used global as necessary.
1902 if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1903 assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
1904 assert(isa<ArrayType>(LU->getValueType()) &&
1905 "expected llvm.used to be an array type");
1906 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1907 for (const Value *Op : A->operands()) {
1908 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1909 // Global symbols with internal or private linkage are not visible to
1910 // the linker, and thus would cause an error when the linker tried to
1911 // preserve the symbol due to the `/include:` directive.
1912 if (GV->hasLocalLinkage())
1913 continue;
1914
1915 raw_string_ostream OS(Flags);
1916 emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
1917 getMangler());
1918 OS.flush();
1919
1920 if (!Flags.empty()) {
1921 Streamer.switchSection(getDrectveSection());
1922 Streamer.emitBytes(Flags);
1923 }
1924 Flags.clear();
1925 }
1926 }
1927 }
1928}
1929
1931 const TargetMachine &TM) {
1933 this->TM = &TM;
1934 const Triple &T = TM.getTargetTriple();
1935 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1942 } else {
1949 }
1950}
1951
1953 const Triple &T, bool IsCtor,
1954 unsigned Priority,
1955 const MCSymbol *KeySym,
1957 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1958 // If the priority is the default, use .CRT$XCU, possibly associative.
1959 if (Priority == 65535)
1960 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1961
1962 // Otherwise, we need to compute a new section name. Low priorities should
1963 // run earlier. The linker will sort sections ASCII-betically, and we need a
1964 // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1965 // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1966 // low priorities need to sort before 'L', since the CRT uses that
1967 // internally, so we use ".CRT$XCA00001" for them. We have a contract with
1968 // the frontend that "init_seg(compiler)" corresponds to priority 200 and
1969 // "init_seg(lib)" corresponds to priority 400, and those respectively use
1970 // 'C' and 'L' without the priority suffix. Priorities between 200 and 400
1971 // use 'C' with the priority as a suffix.
1973 char LastLetter = 'T';
1974 bool AddPrioritySuffix = Priority != 200 && Priority != 400;
1975 if (Priority < 200)
1976 LastLetter = 'A';
1977 else if (Priority < 400)
1978 LastLetter = 'C';
1979 else if (Priority == 400)
1980 LastLetter = 'L';
1982 OS << ".CRT$X" << (IsCtor ? "C" : "T") << LastLetter;
1983 if (AddPrioritySuffix)
1984 OS << format("%05u", Priority);
1985 MCSectionCOFF *Sec = Ctx.getCOFFSection(
1987 return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1988 }
1989
1990 std::string Name = IsCtor ? ".ctors" : ".dtors";
1991 if (Priority != 65535)
1992 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1993
1994 return Ctx.getAssociativeCOFFSection(
1998 KeySym, 0);
1999}
2000
2002 unsigned Priority, const MCSymbol *KeySym) const {
2004 getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
2005 cast<MCSectionCOFF>(StaticCtorSection));
2006}
2007
2009 unsigned Priority, const MCSymbol *KeySym) const {
2011 getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
2012 cast<MCSectionCOFF>(StaticDtorSection));
2013}
2014
2016 const GlobalValue *LHS, const GlobalValue *RHS,
2017 const TargetMachine &TM) const {
2018 const Triple &T = TM.getTargetTriple();
2019 if (T.isOSCygMing())
2020 return nullptr;
2021
2022 // Our symbols should exist in address space zero, cowardly no-op if
2023 // otherwise.
2024 if (LHS->getType()->getPointerAddressSpace() != 0 ||
2026 return nullptr;
2027
2028 // Both ptrtoint instructions must wrap global objects:
2029 // - Only global variables are eligible for image relative relocations.
2030 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
2031 // We expect __ImageBase to be a global variable without a section, externally
2032 // defined.
2033 //
2034 // It should look something like this: @__ImageBase = external constant i8
2035 if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
2036 LHS->isThreadLocal() || RHS->isThreadLocal() ||
2037 RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
2038 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
2039 return nullptr;
2040
2041 return MCSymbolRefExpr::create(TM.getSymbol(LHS),
2043 getContext());
2044}
2045
2046static std::string APIntToHexString(const APInt &AI) {
2047 unsigned Width = (AI.getBitWidth() / 8) * 2;
2048 std::string HexString = toString(AI, 16, /*Signed=*/false);
2049 llvm::transform(HexString, HexString.begin(), tolower);
2050 unsigned Size = HexString.size();
2051 assert(Width >= Size && "hex string is too large!");
2052 HexString.insert(HexString.begin(), Width - Size, '0');
2053
2054 return HexString;
2055}
2056
2057static std::string scalarConstantToHexString(const Constant *C) {
2058 Type *Ty = C->getType();
2059 if (isa<UndefValue>(C)) {
2061 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
2062 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
2063 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
2064 return APIntToHexString(CI->getValue());
2065 } else {
2066 unsigned NumElements;
2067 if (auto *VTy = dyn_cast<VectorType>(Ty))
2068 NumElements = cast<FixedVectorType>(VTy)->getNumElements();
2069 else
2070 NumElements = Ty->getArrayNumElements();
2071 std::string HexString;
2072 for (int I = NumElements - 1, E = -1; I != E; --I)
2073 HexString += scalarConstantToHexString(C->getAggregateElement(I));
2074 return HexString;
2075 }
2076}
2077
2079 const DataLayout &DL, SectionKind Kind, const Constant *C,
2080 Align &Alignment) const {
2081 if (Kind.isMergeableConst() && C &&
2082 getContext().getAsmInfo()->hasCOFFComdatConstants()) {
2083 // This creates comdat sections with the given symbol name, but unless
2084 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
2085 // will be created with a null storage class, which makes GNU binutils
2086 // error out.
2090 std::string COMDATSymName;
2091 if (Kind.isMergeableConst4()) {
2092 if (Alignment <= 4) {
2093 COMDATSymName = "__real@" + scalarConstantToHexString(C);
2094 Alignment = Align(4);
2095 }
2096 } else if (Kind.isMergeableConst8()) {
2097 if (Alignment <= 8) {
2098 COMDATSymName = "__real@" + scalarConstantToHexString(C);
2099 Alignment = Align(8);
2100 }
2101 } else if (Kind.isMergeableConst16()) {
2102 // FIXME: These may not be appropriate for non-x86 architectures.
2103 if (Alignment <= 16) {
2104 COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
2105 Alignment = Align(16);
2106 }
2107 } else if (Kind.isMergeableConst32()) {
2108 if (Alignment <= 32) {
2109 COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
2110 Alignment = Align(32);
2111 }
2112 }
2113
2114 if (!COMDATSymName.empty())
2115 return getContext().getCOFFSection(".rdata", Characteristics,
2116 COMDATSymName,
2118 }
2119
2121 Alignment);
2122}
2123
2124//===----------------------------------------------------------------------===//
2125// Wasm
2126//===----------------------------------------------------------------------===//
2127
2128static const Comdat *getWasmComdat(const GlobalValue *GV) {
2129 const Comdat *C = GV->getComdat();
2130 if (!C)
2131 return nullptr;
2132
2133 if (C->getSelectionKind() != Comdat::Any)
2134 report_fatal_error("WebAssembly COMDATs only support "
2135 "SelectionKind::Any, '" + C->getName() + "' cannot be "
2136 "lowered.");
2137
2138 return C;
2139}
2140
2141static unsigned getWasmSectionFlags(SectionKind K, bool Retain) {
2142 unsigned Flags = 0;
2143
2144 if (K.isThreadLocal())
2145 Flags |= wasm::WASM_SEG_FLAG_TLS;
2146
2147 if (K.isMergeableCString())
2149
2150 if (Retain)
2152
2153 // TODO(sbc): Add suport for K.isMergeableConst()
2154
2155 return Flags;
2156}
2157
2160 collectUsedGlobalVariables(M, Vec, false);
2161 for (GlobalValue *GV : Vec)
2162 if (auto *GO = dyn_cast<GlobalObject>(GV))
2163 Used.insert(GO);
2164}
2165
2167 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2168 // We don't support explict section names for functions in the wasm object
2169 // format. Each function has to be in its own unique section.
2170 if (isa<Function>(GO)) {
2171 return SelectSectionForGlobal(GO, Kind, TM);
2172 }
2173
2174 StringRef Name = GO->getSection();
2175
2176 // Certain data sections we treat as named custom sections rather than
2177 // segments within the data section.
2178 // This could be avoided if all data segements (the wasm sense) were
2179 // represented as their own sections (in the llvm sense).
2180 // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
2181 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::Wasm,
2182 /*AddSegmentInfo=*/false) ||
2184 /*AddSegmentInfo=*/false) ||
2185 Name == ".llvmbc" || Name == ".llvmcmd")
2186 Kind = SectionKind::getMetadata();
2187
2188 StringRef Group = "";
2189 if (const Comdat *C = getWasmComdat(GO)) {
2190 Group = C->getName();
2191 }
2192
2193 unsigned Flags = getWasmSectionFlags(Kind, Used.count(GO));
2195 Name, Kind, Flags, Group, MCContext::GenericSectionID);
2196
2197 return Section;
2198}
2199
2200static MCSectionWasm *
2202 SectionKind Kind, Mangler &Mang,
2203 const TargetMachine &TM, bool EmitUniqueSection,
2204 unsigned *NextUniqueID, bool Retain) {
2205 StringRef Group = "";
2206 if (const Comdat *C = getWasmComdat(GO)) {
2207 Group = C->getName();
2208 }
2209
2210 bool UniqueSectionNames = TM.getUniqueSectionNames();
2211 SmallString<128> Name = getSectionPrefixForGlobal(Kind, /*IsLarge=*/false);
2212
2213 if (const auto *F = dyn_cast<Function>(GO)) {
2214 const auto &OptionalPrefix = F->getSectionPrefix();
2215 if (OptionalPrefix)
2216 raw_svector_ostream(Name) << '.' << *OptionalPrefix;
2217 }
2218
2219 if (EmitUniqueSection && UniqueSectionNames) {
2220 Name.push_back('.');
2221 TM.getNameWithPrefix(Name, GO, Mang, true);
2222 }
2223 unsigned UniqueID = MCContext::GenericSectionID;
2224 if (EmitUniqueSection && !UniqueSectionNames) {
2225 UniqueID = *NextUniqueID;
2226 (*NextUniqueID)++;
2227 }
2228
2229 unsigned Flags = getWasmSectionFlags(Kind, Retain);
2230 return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
2231}
2232
2234 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2235
2236 if (Kind.isCommon())
2237 report_fatal_error("mergable sections not supported yet on wasm");
2238
2239 // If we have -ffunction-section or -fdata-section then we should emit the
2240 // global value to a uniqued section specifically for it.
2241 bool EmitUniqueSection = false;
2242 if (Kind.isText())
2243 EmitUniqueSection = TM.getFunctionSections();
2244 else
2245 EmitUniqueSection = TM.getDataSections();
2246 EmitUniqueSection |= GO->hasComdat();
2247 bool Retain = Used.count(GO);
2248 EmitUniqueSection |= Retain;
2249
2250 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2251 EmitUniqueSection, &NextUniqueID, Retain);
2252}
2253
2255 bool UsesLabelDifference, const Function &F) const {
2256 // We can always create relative relocations, so use another section
2257 // that can be marked non-executable.
2258 return false;
2259}
2260
2262 const GlobalValue *LHS, const GlobalValue *RHS,
2263 const TargetMachine &TM) const {
2264 // We may only use a PLT-relative relocation to refer to unnamed_addr
2265 // functions.
2266 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
2267 return nullptr;
2268
2269 // Basic correctness checks.
2270 if (LHS->getType()->getPointerAddressSpace() != 0 ||
2271 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
2272 RHS->isThreadLocal())
2273 return nullptr;
2274
2277 getContext()),
2279}
2280
2284
2285 // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2286 // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2288}
2289
2291 unsigned Priority, const MCSymbol *KeySym) const {
2292 return Priority == UINT16_MAX ?
2294 getContext().getWasmSection(".init_array." + utostr(Priority),
2296}
2297
2299 unsigned Priority, const MCSymbol *KeySym) const {
2300 report_fatal_error("@llvm.global_dtors should have been lowered already");
2301}
2302
2303//===----------------------------------------------------------------------===//
2304// XCOFF
2305//===----------------------------------------------------------------------===//
2307 const MachineFunction *MF) {
2308 if (!MF->getLandingPads().empty())
2309 return true;
2310
2311 const Function &F = MF->getFunction();
2312 if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2313 return false;
2314
2315 const GlobalValue *Per =
2316 dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
2317 assert(Per && "Personality routine is not a GlobalValue type.");
2319 return false;
2320
2321 return true;
2322}
2323
2325 const MachineFunction *MF) {
2326 const Function &F = MF->getFunction();
2327 if (!F.hasStackProtectorFnAttr())
2328 return false;
2329 // FIXME: check presence of canary word
2330 // There are cases that the stack protectors are not really inserted even if
2331 // the attributes are on.
2332 return true;
2333}
2334
2335MCSymbol *
2337 MCSymbol *EHInfoSym = MF->getContext().getOrCreateSymbol(
2338 "__ehinfo." + Twine(MF->getFunctionNumber()));
2339 cast<MCSymbolXCOFF>(EHInfoSym)->setEHInfo();
2340 return EHInfoSym;
2341}
2342
2343MCSymbol *
2345 const TargetMachine &TM) const {
2346 // We always use a qualname symbol for a GV that represents
2347 // a declaration, a function descriptor, or a common symbol.
2348 // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2349 // also return a qualname so that a label symbol could be avoided.
2350 // It is inherently ambiguous when the GO represents the address of a
2351 // function, as the GO could either represent a function descriptor or a
2352 // function entry point. We choose to always return a function descriptor
2353 // here.
2354 if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2355 if (GO->isDeclarationForLinker())
2356 return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
2357 ->getQualNameSymbol();
2358
2359 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
2360 if (GVar->hasAttribute("toc-data"))
2361 return cast<MCSectionXCOFF>(
2363 ->getQualNameSymbol();
2364
2365 SectionKind GOKind = getKindForGlobal(GO, TM);
2366 if (GOKind.isText())
2367 return cast<MCSectionXCOFF>(
2368 getSectionForFunctionDescriptor(cast<Function>(GO), TM))
2369 ->getQualNameSymbol();
2370 if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
2371 GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
2372 return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
2373 ->getQualNameSymbol();
2374 }
2375
2376 // For all other cases, fall back to getSymbol to return the unqualified name.
2377 return nullptr;
2378}
2379
2381 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2382 if (!GO->hasSection())
2383 report_fatal_error("#pragma clang section is not yet supported");
2384
2386
2387 // Handle the XCOFF::TD case first, then deal with the rest.
2388 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2389 if (GVar->hasAttribute("toc-data"))
2390 return getContext().getXCOFFSection(
2391 SectionName, Kind,
2393 /* MultiSymbolsAllowed*/ true);
2394
2395 XCOFF::StorageMappingClass MappingClass;
2396 if (Kind.isText())
2397 MappingClass = XCOFF::XMC_PR;
2398 else if (Kind.isData() || Kind.isBSS())
2399 MappingClass = XCOFF::XMC_RW;
2400 else if (Kind.isReadOnlyWithRel())
2401 MappingClass =
2403 else if (Kind.isReadOnly())
2404 MappingClass = XCOFF::XMC_RO;
2405 else
2406 report_fatal_error("XCOFF other section types not yet implemented.");
2407
2408 return getContext().getXCOFFSection(
2409 SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
2410 /* MultiSymbolsAllowed*/ true);
2411}
2412
2414 const GlobalObject *GO, const TargetMachine &TM) const {
2416 "Tried to get ER section for a defined global.");
2417
2420
2421 // AIX TLS local-dynamic does not need the external reference for the
2422 // "_$TLSML" symbol.
2424 GO->hasName() && GO->getName() == "_$TLSML") {
2425 return getContext().getXCOFFSection(
2428 }
2429
2431 isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA;
2432 if (GO->isThreadLocal())
2433 SMC = XCOFF::XMC_UL;
2434
2435 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2436 if (GVar->hasAttribute("toc-data"))
2437 SMC = XCOFF::XMC_TD;
2438
2439 // Externals go into a csect of type ER.
2440 return getContext().getXCOFFSection(
2443}
2444
2446 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2447 // Handle the XCOFF::TD case first, then deal with the rest.
2448 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2449 if (GVar->hasAttribute("toc-data")) {
2452 XCOFF::SymbolType symType =
2454 return getContext().getXCOFFSection(
2455 Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, symType),
2456 /* MultiSymbolsAllowed*/ true);
2457 }
2458
2459 // Common symbols go into a csect with matching name which will get mapped
2460 // into the .bss section.
2461 // Zero-initialized local TLS symbols go into a csect with matching name which
2462 // will get mapped into the .tbss section.
2463 if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
2466 XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
2467 : Kind.isCommon() ? XCOFF::XMC_RW
2468 : XCOFF::XMC_UL;
2469 return getContext().getXCOFFSection(
2471 }
2472
2473 if (Kind.isText()) {
2474 if (TM.getFunctionSections()) {
2475 return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
2476 ->getRepresentedCsect();
2477 }
2478 return TextSection;
2479 }
2480
2481 if (TM.Options.XCOFFReadOnlyPointers && Kind.isReadOnlyWithRel()) {
2482 if (!TM.getDataSections())
2484 "ReadOnlyPointers is supported only if data sections is turned on");
2485
2488 return getContext().getXCOFFSection(
2491 }
2492
2493 // For BSS kind, zero initialized data must be emitted to the .data section
2494 // because external linkage control sections that get mapped to the .bss
2495 // section will be linked as tentative defintions, which is only appropriate
2496 // for SectionKind::Common.
2497 if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2498 if (TM.getDataSections()) {
2501 return getContext().getXCOFFSection(
2504 }
2505 return DataSection;
2506 }
2507
2508 if (Kind.isReadOnly()) {
2509 if (TM.getDataSections()) {
2512 return getContext().getXCOFFSection(
2515 }
2516 return ReadOnlySection;
2517 }
2518
2519 // External/weak TLS data and initialized local TLS data are not eligible
2520 // to be put into common csect. If data sections are enabled, thread
2521 // data are emitted into separate sections. Otherwise, thread data
2522 // are emitted into the .tdata section.
2523 if (Kind.isThreadLocal()) {
2524 if (TM.getDataSections()) {
2527 return getContext().getXCOFFSection(
2529 }
2530 return TLSDataSection;
2531 }
2532
2533 report_fatal_error("XCOFF other section types not yet implemented.");
2534}
2535
2537 const Function &F, const TargetMachine &TM) const {
2538 assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2539
2540 if (!TM.getFunctionSections())
2541 return ReadOnlySection;
2542
2543 // If the function can be removed, produce a unique section so that
2544 // the table doesn't prevent the removal.
2545 SmallString<128> NameStr(".rodata.jmp..");
2546 getNameWithPrefix(NameStr, &F, TM);
2547 return getContext().getXCOFFSection(
2548 NameStr, SectionKind::getReadOnly(),
2550}
2551
2553 bool UsesLabelDifference, const Function &F) const {
2554 return false;
2555}
2556
2557/// Given a mergeable constant with the specified size and relocation
2558/// information, return a section that it should be placed in.
2560 const DataLayout &DL, SectionKind Kind, const Constant *C,
2561 Align &Alignment) const {
2562 // TODO: Enable emiting constant pool to unique sections when we support it.
2563 if (Alignment > Align(16))
2564 report_fatal_error("Alignments greater than 16 not yet supported.");
2565
2566 if (Alignment == Align(8)) {
2567 assert(ReadOnly8Section && "Section should always be initialized.");
2568 return ReadOnly8Section;
2569 }
2570
2571 if (Alignment == Align(16)) {
2572 assert(ReadOnly16Section && "Section should always be initialized.");
2573 return ReadOnly16Section;
2574 }
2575
2576 return ReadOnlySection;
2577}
2578
2580 const TargetMachine &TgtM) {
2587 LSDAEncoding = 0;
2589
2590 // AIX debug for thread local location is not ready. And for integrated as
2591 // mode, the relocatable address for the thread local variable will cause
2592 // linker error. So disable the location attribute generation for thread local
2593 // variables for now.
2594 // FIXME: when TLS debug on AIX is ready, remove this setting.
2596}
2597
2599 unsigned Priority, const MCSymbol *KeySym) const {
2600 report_fatal_error("no static constructor section on AIX");
2601}
2602
2604 unsigned Priority, const MCSymbol *KeySym) const {
2605 report_fatal_error("no static destructor section on AIX");
2606}
2607
2609 const GlobalValue *LHS, const GlobalValue *RHS,
2610 const TargetMachine &TM) const {
2611 /* Not implemented yet, but don't crash, return nullptr. */
2612 return nullptr;
2613}
2614
2617 assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2618
2619 switch (GV->getLinkage()) {
2622 return XCOFF::C_HIDEXT;
2626 return XCOFF::C_EXT;
2632 return XCOFF::C_WEAKEXT;
2635 "There is no mapping that implements AppendingLinkage for XCOFF.");
2636 }
2637 llvm_unreachable("Unknown linkage type!");
2638}
2639
2641 const GlobalValue *Func, const TargetMachine &TM) const {
2642 assert((isa<Function>(Func) ||
2643 (isa<GlobalAlias>(Func) &&
2644 isa_and_nonnull<Function>(
2645 cast<GlobalAlias>(Func)->getAliaseeObject()))) &&
2646 "Func must be a function or an alias which has a function as base "
2647 "object.");
2648
2649 SmallString<128> NameStr;
2650 NameStr.push_back('.');
2651 getNameWithPrefix(NameStr, Func, TM);
2652
2653 // When -function-sections is enabled and explicit section is not specified,
2654 // it's not necessary to emit function entry point label any more. We will use
2655 // function entry point csect instead. And for function delcarations, the
2656 // undefined symbols gets treated as csect with XTY_ER property.
2657 if (((TM.getFunctionSections() && !Func->hasSection()) ||
2658 Func->isDeclarationForLinker()) &&
2659 isa<Function>(Func)) {
2660 return getContext()
2662 NameStr, SectionKind::getText(),
2663 XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclarationForLinker()
2665 : XCOFF::XTY_SD))
2667 }
2668
2669 return getContext().getOrCreateSymbol(NameStr);
2670}
2671
2673 const Function *F, const TargetMachine &TM) const {
2674 SmallString<128> NameStr;
2675 getNameWithPrefix(NameStr, F, TM);
2676 return getContext().getXCOFFSection(
2677 NameStr, SectionKind::getData(),
2679}
2680
2682 const MCSymbol *Sym, const TargetMachine &TM) const {
2683 const XCOFF::StorageMappingClass SMC = [](const MCSymbol *Sym,
2684 const TargetMachine &TM) {
2685 const MCSymbolXCOFF *XSym = cast<MCSymbolXCOFF>(Sym);
2686
2687 // The "_$TLSML" symbol for TLS local-dynamic mode requires XMC_TC,
2688 // otherwise the AIX assembler will complain.
2689 if (XSym->getSymbolTableName() == "_$TLSML")
2690 return XCOFF::XMC_TC;
2691
2692 // Use large code model toc entries for ehinfo symbols as they are
2693 // never referenced directly. The runtime loads their TOC entry
2694 // addresses from the trace-back table.
2695 if (XSym->isEHInfo())
2696 return XCOFF::XMC_TE;
2697
2698 // If the symbol does not have a code model specified use the module value.
2699 if (!XSym->hasPerSymbolCodeModel())
2701 : XCOFF::XMC_TC;
2702
2705 : XCOFF::XMC_TC;
2706 }(Sym, TM);
2707
2708 return getContext().getXCOFFSection(
2709 cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(),
2711}
2712
2714 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2715 auto *LSDA = cast<MCSectionXCOFF>(LSDASection);
2716 if (TM.getFunctionSections()) {
2717 // If option -ffunction-sections is on, append the function name to the
2718 // name of the LSDA csect so that each function has its own LSDA csect.
2719 // This helps the linker to garbage-collect EH info of unused functions.
2720 SmallString<128> NameStr = LSDA->getName();
2721 raw_svector_ostream(NameStr) << '.' << F.getName();
2722 LSDA = getContext().getXCOFFSection(NameStr, LSDA->getKind(),
2723 LSDA->getCsectProp());
2724 }
2725 return LSDA;
2726}
2727//===----------------------------------------------------------------------===//
2728// GOFF
2729//===----------------------------------------------------------------------===//
2731
2733 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2734 return SelectSectionForGlobal(GO, Kind, TM);
2735}
2736
2738 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2739 std::string Name = ".gcc_exception_table." + F.getName().str();
2740 return getContext().getGOFFSection(Name, SectionKind::getData(), nullptr, 0);
2741}
2742
2744 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2745 auto *Symbol = TM.getSymbol(GO);
2746 if (Kind.isBSS())
2747 return getContext().getGOFFSection(Symbol->getName(), SectionKind::getBSS(),
2748 nullptr, 0);
2749
2751}
amdgpu AMDGPU DAG DAG Pattern Instruction Selection
static bool isThumb(const MCSubtargetInfo &STI)
MachineBasicBlock & MBB
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
COFFYAML::WeakExternalCharacteristics Characteristics
Definition: COFFYAML.cpp:350
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file contains constants used for implementing Dwarf debug support.
std::string Name
uint64_t Size
Symbol * Sym
Definition: ELF_riscv.cpp:479
Module.h This file contains the declarations for the Module class.
This file declares the MCSectionGOFF class, which contains all of the necessary machine code sections...
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, const MCSection &Section)
static MCSection * selectExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM, MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID, bool Retain, bool ForceUnique)
static int getSelectionForCOFF(const GlobalValue *GV)
static MCSectionCOFF * getCOFFStaticStructorSection(MCContext &Ctx, const Triple &T, bool IsCtor, unsigned Priority, const MCSymbol *KeySym, MCSectionCOFF *Default)
static unsigned getEntrySizeForKind(SectionKind Kind)
static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, StringRef &Section)
static const GlobalValue * getComdatGVForCOFF(const GlobalValue *GV)
static unsigned getCOFFSectionFlags(SectionKind K, const TargetMachine &TM)
static unsigned getELFSectionType(StringRef Name, SectionKind K)
static bool hasPrefix(StringRef SectionName, StringRef Prefix)
static MCSectionWasm * selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID, bool Retain)
static const MCSymbolELF * getLinkedToSymbol(const GlobalObject *GO, const TargetMachine &TM)
static unsigned calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName, SectionKind Kind, const TargetMachine &TM, MCContext &Ctx, Mangler &Mang, unsigned &Flags, unsigned &EntrySize, unsigned &NextUniqueID, const bool Retain, const bool ForceUnique)
Calculate an appropriate unique ID for a section, and update Flags, EntrySize and NextUniqueID where ...
static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K)
static const Comdat * getWasmComdat(const GlobalValue *GV)
static MCSectionELF * getStaticStructorSection(MCContext &Ctx, bool UseInitArray, bool IsCtor, unsigned Priority, const MCSymbol *KeySym)
static unsigned getWasmSectionFlags(SectionKind K, bool Retain)
static void checkMachOComdat(const GlobalValue *GV)
static std::string APIntToHexString(const APInt &AI)
static cl::opt< bool > JumpTableInFunctionSection("jumptable-in-function-section", cl::Hidden, cl::init(false), cl::desc("Putting Jump Table in function section"))
static StringRef getSectionPrefixForGlobal(SectionKind Kind, bool IsLarge)
Return the section prefix name used by options FunctionsSections and DataSections.
static MCSectionELF * selectELFSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol)
static SmallString< 128 > getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, unsigned EntrySize, bool UniqueSectionName)
static std::string scalarConstantToHexString(const Constant *C)
static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind)
static const Comdat * getELFComdat(const GlobalValue *GV)
static std::tuple< StringRef, bool, unsigned > getGlobalObjectInfo(const GlobalObject *GO, const TargetMachine &TM)
static unsigned getELFSectionFlags(SectionKind K)
Value * RHS
Value * LHS
Class for arbitrary precision integers.
Definition: APInt.h:78
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1468
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition: APInt.h:200
@ Largest
The linker will choose the largest COMDAT.
Definition: Comdat.h:38
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition: Comdat.h:40
@ Any
The linker may choose any COMDAT.
Definition: Comdat.h:36
@ NoDeduplicate
No deduplication is performed.
Definition: Comdat.h:39
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition: Comdat.h:37
This is an important base class in LLVM.
Definition: Constant.h:42
Wrapper for a function that represents a value that functionally represents the original function.
Definition: Constants.h:941
GlobalValue * getGlobalValue() const
Definition: Constants.h:962
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
Align getPreferredAlign(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
Definition: DataLayout.cpp:988
StringRef getPrivateGlobalPrefix() const
Definition: DataLayout.h:285
This is the base abstract class for diagnostic reporting in the backend.
Interface for custom diagnostic printing.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:117
bool hasComdat() const
Definition: GlobalObject.h:127
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:109
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Value.h:565
bool hasExternalLinkage() const
Definition: GlobalValue.h:511
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
Definition: GlobalValue.h:263
LinkageTypes getLinkage() const
Definition: GlobalValue.h:546
bool hasLocalLinkage() const
Definition: GlobalValue.h:528
bool hasPrivateLinkage() const
Definition: GlobalValue.h:527
const Comdat * getComdat() const
Definition: Globals.cpp:199
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
bool isDeclarationForLinker() const
Definition: GlobalValue.h:618
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
const GlobalObject * getAliaseeObject() const
Definition: Globals.cpp:400
const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition: Globals.cpp:130
bool hasCommonLinkage() const
Definition: GlobalValue.h:532
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:458
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:60
@ CommonLinkage
Tentative definitions.
Definition: GlobalValue.h:62
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition: GlobalValue.h:54
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:57
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:56
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition: GlobalValue.h:58
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition: GlobalValue.h:53
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition: GlobalValue.h:55
AttributeSet getAttributes() const
Return the attribute set for this global.
bool hasImplicitSection() const
Check if section name is present.
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
static bool isSectionAtomizableBySymbols(const MCSection &Section)
True if the section is atomized using the symbols in it.
This class is intended to be used as a base class for asm properties and features specific to the tar...
Definition: MCAsmInfo.h:56
bool useIntegratedAssembler() const
Return true if assembly (inline or otherwise) should be parsed.
Definition: MCAsmInfo.h:802
bool binutilsIsAtLeast(int Major, int Minor) const
Definition: MCAsmInfo.h:809
ExceptionHandling getExceptionHandlingType() const
Definition: MCAsmInfo.h:740
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:537
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition: MCExpr.h:622
static const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition: MCExpr.cpp:222
Context object for machine code objects.
Definition: MCContext.h:83
const MCObjectFileInfo * getObjectFileInfo() const
Definition: MCContext.h:416
MCSectionMachO * getMachOSection(StringRef Segment, StringRef Section, unsigned TypeAndAttributes, unsigned Reserved2, SectionKind K, const char *BeginSymName=nullptr)
Return the MCSection for the specified mach-o section.
Definition: MCContext.cpp:488
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K, unsigned Flags=0)
Definition: MCContext.h:628
MCSectionELF * getELFNamedSection(const Twine &Prefix, const Twine &Suffix, unsigned Type, unsigned Flags, unsigned EntrySize=0)
Get a section with the provided group identifier.
Definition: MCContext.cpp:551
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition: MCContext.h:551
MCSectionXCOFF * getXCOFFSection(StringRef Section, SectionKind K, std::optional< XCOFF::CsectProperties > CsectProp=std::nullopt, bool MultiSymbolsAllowed=false, std::optional< XCOFF::DwarfSectionSubtypeFlags > DwarfSubtypeFlags=std::nullopt)
Definition: MCContext.cpp:805
MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, StringRef COMDATSymName, int Selection, unsigned UniqueID=GenericSectionID)
Definition: MCContext.cpp:692
MCSectionGOFF * getGOFFSection(StringRef Section, SectionKind Kind, MCSection *Parent, uint32_t Subsection=0)
Definition: MCContext.cpp:674
bool isELFGenericMergeableSection(StringRef Name)
Definition: MCContext.cpp:661
std::optional< unsigned > getELFUniqueIDForEntsize(StringRef SectionName, unsigned Flags, unsigned EntrySize)
Return the unique ID of the section with the given name, flags and entry size, if it exists.
Definition: MCContext.cpp:667
const MCAsmInfo * getAsmInfo() const
Definition: MCContext.h:412
MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
Definition: MCContext.cpp:212
bool isELFImplicitMergeableSectionNamePrefix(StringRef Name)
Definition: MCContext.cpp:656
MCSectionCOFF * getAssociativeCOFFSection(MCSectionCOFF *Sec, const MCSymbol *KeySym, unsigned UniqueID=GenericSectionID)
Gets or creates a section equivalent to Sec that is associated with the section containing KeySym.
Definition: MCContext.cpp:733
@ GenericSectionID
Pass this value as the UniqueID during section creation to get the generic section with the given nam...
Definition: MCContext.h:534
Base class for the full range of assembler expressions which are needed for parsing.
Definition: MCExpr.h:34
MCSection * TLSBSSSection
Section directive for Thread Local uninitialized data.
MCSection * MergeableConst16Section
MCSection * MergeableConst4Section
MCSection * TextSection
Section directive for standard text.
MCSection * ConstDataCoalSection
MCSection * ConstTextCoalSection
MCSection * TLSDataSection
Section directive for Thread Local data. ELF, MachO, COFF, and Wasm.
MCSection * MergeableConst8Section
MCSection * LSDASection
If exception handling is supported by the target, this is the section the Language Specific Data Area...
MCSection * FourByteConstantSection
MCSection * getDrectveSection() const
bool isPositionIndependent() const
MCSection * MergeableConst32Section
MCSection * SixteenByteConstantSection
MCSection * ReadOnlySection
Section that is readonly and can contain arbitrary initialized data.
MCSection * BSSSection
Section that is default initialized to zero.
MCSection * EightByteConstantSection
MCSection * getTextSection() const
MCContext & getContext() const
MCSection * DataSection
Section directive for standard data.
This represents a section on Windows.
Definition: MCSectionCOFF.h:27
This represents a section on linux, lots of unix variants and some bare metal systems.
Definition: MCSectionELF.h:27
This represents a section on a Mach-O system (used by Mac OS X).
static Error ParseSectionSpecifier(StringRef Spec, StringRef &Segment, StringRef &Section, unsigned &TAA, bool &TAAParsed, unsigned &StubSize)
Parse the section specifier indicated by "Spec".
unsigned getTypeAndAttributes() const
unsigned getStubSize() const
This represents a section on wasm.
Definition: MCSectionWasm.h:26
MCSymbolXCOFF * getQualNameSymbol() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition: MCSection.h:36
static constexpr unsigned NonUniqueID
Definition: MCSection.h:40
StringRef getName() const
Definition: MCSection.h:130
Streaming machine code generation interface.
Definition: MCStreamer.h:213
virtual void addBlankLine()
Emit a blank line to a .s file to pretty it up.
Definition: MCStreamer.h:387
virtual bool emitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute)=0
Add the given Attribute to Symbol.
virtual void emitELFSize(MCSymbol *Symbol, const MCExpr *Value)
Emit an ELF .size directive.
void emitSymbolValue(const MCSymbol *Sym, unsigned Size, bool IsSectionRelative=false)
Special case of EmitValue that avoids the client having to pass in a MCExpr for MCSymbols.
Definition: MCStreamer.cpp:183
virtual void emitLabel(MCSymbol *Symbol, SMLoc Loc=SMLoc())
Emit a label for Symbol into the current section.
Definition: MCStreamer.cpp:420
virtual void emitValueToAlignment(Align Alignment, int64_t Value=0, unsigned ValueSize=1, unsigned MaxBytesToEmit=0)
Emit some number of copies of Value until the byte alignment ByteAlignment is reached.
unsigned emitULEB128IntValue(uint64_t Value, unsigned PadTo=0)
Special case of EmitULEB128Value that avoids the client having to pass in a MCExpr for constant integ...
Definition: MCStreamer.cpp:161
virtual void emitLinkerOptions(ArrayRef< std::string > Kind)
Emit the given list Options of strings as linker options into the output.
Definition: MCStreamer.h:467
void emitInt64(uint64_t Value)
Definition: MCStreamer.h:722
virtual void switchSection(MCSection *Section, uint32_t Subsec=0)
Set the current section where code is being emitted to Section.
void emitInt32(uint64_t Value)
Definition: MCStreamer.h:721
void emitInt8(uint64_t Value)
Definition: MCStreamer.h:719
virtual void emitBytes(StringRef Data)
Emit the bytes in Data into the output.
const MCSymbol & getSymbol() const
Definition: MCExpr.h:411
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:398
StringRef getSymbolTableName() const
Definition: MCSymbolXCOFF.h:68
bool hasPerSymbolCodeModel() const
Definition: MCSymbolXCOFF.h:78
CodeModel getPerSymbolCodeModel() const
Definition: MCSymbolXCOFF.h:80
bool isEHInfo() const
Definition: MCSymbolXCOFF.h:74
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
This represents an "assembler immediate".
Definition: MCValue.h:36
int64_t getConstant() const
Definition: MCValue.h:43
const MCSymbolRefExpr * getSymB() const
Definition: MCValue.h:45
Metadata node.
Definition: Metadata.h:1069
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1430
Metadata * get() const
Definition: Metadata.h:920
MCSymbol * getSymbol() const
Return the MCSymbol for this basic block.
MBBSectionID getSectionID() const
Returns the section ID of this basic block.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
bool isBeginSection() const
Returns true if this block begins any section.
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current function.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MCContext & getContext() const
Function & getFunction()
Return the LLVM function that this machine code represents.
const std::vector< LandingPadInfo > & getLandingPads() const
Return a reference to the landing pad info for the current function.
MCSection * getSection() const
Returns the Section this function belongs to.
MachineModuleInfoELF - This is a MachineModuleInfoImpl implementation for ELF targets.
StubValueTy & getGVStubEntry(MCSymbol *Sym)
PointerIntPair< MCSymbol *, 1, bool > StubValueTy
MachineModuleInfoMachO - This is a MachineModuleInfoImpl implementation for MachO targets.
StubValueTy & getGVStubEntry(MCSymbol *Sym)
This class contains meta information specific to a module.
const Module * getModule() const
Ty & getObjFileInfo()
Keep track of various per-module pieces of information for backends that would like to do so.
void getNameWithPrefix(raw_ostream &OS, const GlobalValue *GV, bool CannotUsePrivateLabel) const
Print the appropriate prefix and the specified global variable's name.
Definition: Mangler.cpp:121
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
@ Require
Adds a requirement that another module flag be present and have a specified value after linking is pe...
Definition: Module.h:131
const std::string & getSourceFileName() const
Get the module's original source file name.
Definition: Module.h:279
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition: Module.cpp:170
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:294
A tuple of MDNodes.
Definition: Metadata.h:1731
PointerIntPair - This class implements a pair of a pointer and small integer.
PointerTy getPointer() const
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:22
static SectionKind getThreadData()
Definition: SectionKind.h:207
static SectionKind getMetadata()
Definition: SectionKind.h:188
bool isThreadBSSLocal() const
Definition: SectionKind.h:163
static SectionKind getText()
Definition: SectionKind.h:190
bool isBSSLocal() const
Definition: SectionKind.h:170
static SectionKind getData()
Definition: SectionKind.h:213
bool isText() const
Definition: SectionKind.h:127
static SectionKind getBSS()
Definition: SectionKind.h:209
static SectionKind getThreadBSS()
Definition: SectionKind.h:206
static SectionKind getReadOnly()
Definition: SectionKind.h:192
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:265
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:147
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const override
Given a mergeable constant with the specified size and relocation information, return a section that ...
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override
Emit Obj-C garbage collection and linker options.
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const override
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
MCSection * getUniqueSectionForFunction(const Function &F, const TargetMachine &TM) const override
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const override
Given a constant with the SectionKind, return a section that it should be placed in.
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override
Emit Obj-C garbage collection and linker options.
MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const override
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym, const MachineModuleInfo *MMI) const override
const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
Return an MCExpr to use for a reference to the specified type info global variable from exception han...
void getModuleMetadata(Module &M) override
Get the module-level metadata that the platform cares about.
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
const MCExpr * lowerDSOLocalEquivalent(const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const override
MCSection * getSectionForCommandLines() const override
If supported, return the section to use for the llvm.commandline metadata.
MCSection * getSectionForLSDA(const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const override
virtual void emitPersonalityValueImpl(MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym, const MachineModuleInfo *MMI) const
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
MCSection * getSectionForMachineBasicBlock(const Function &F, const MachineBasicBlock &MBB, const TargetMachine &TM) const override
Returns a unique section for the given machine basic block.
MCSymbolRefExpr::VariantKind PLTRelativeVariantKind
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * getSectionForLSDA(const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const override
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const override
Given a constant with the SectionKind, return a section that it should be placed in.
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const override
MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, const TargetMachine &TM, MachineModuleInfo *MMI) const override
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
const MCExpr * getIndirectSymViaGOTPCRel(const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
Get MachO PC relative GOT entry relocation.
void emitModuleMetadata(MCStreamer &Streamer, Module &M) const override
Emit the module flags that specify the garbage collection information.
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
MCSection * getSectionForCommandLines() const override
If supported, return the section to use for the llvm.commandline metadata.
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const override
The mach-o version of this method defaults to returning a stub reference.
void getModuleMetadata(Module &M) override
Get the module-level metadata that the platform cares about.
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
static bool ShouldSetSSPCanaryBitInTB(const MachineFunction *MF)
void Initialize(MCContext &Ctx, const TargetMachine &TM) override
This method must be called before any actual lowering is done.
MCSection * getSectionForTOCEntry(const MCSymbol *Sym, const TargetMachine &TM) const override
On targets that support TOC entries, return a section for the entry given the symbol it refers to.
MCSection * getSectionForExternalReference(const GlobalObject *GO, const TargetMachine &TM) const override
For external functions, this will always return a function descriptor csect.
MCSymbol * getFunctionEntryPointSymbol(const GlobalValue *Func, const TargetMachine &TM) const override
If supported, return the function entry point symbol.
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, const TargetMachine &TM) const override
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
static MCSymbol * getEHInfoTableSymbol(const MachineFunction *MF)
MCSection * getExplicitSectionGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
Targets should implement this method to assign a section to globals with an explicit section specfied...
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
static XCOFF::StorageClass getStorageClassForGlobal(const GlobalValue *GV)
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const override
Given a constant with the SectionKind, return a section that it should be placed in.
MCSymbol * getTargetSymbol(const GlobalValue *GV, const TargetMachine &TM) const override
For functions, this will always return a function descriptor symbol.
MCSection * getSectionForFunctionDescriptor(const Function *F, const TargetMachine &TM) const override
On targets that use separate function descriptor symbols, return a section for the descriptor given i...
static bool ShouldEmitEHBlock(const MachineFunction *MF)
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getSectionForLSDA(const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const override
For functions, this will return the LSDA section.
void emitCGProfileMetadata(MCStreamer &Streamer, Module &M) const
Emit Call Graph Profile metadata.
virtual void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const
MCSection * StaticDtorSection
This section contains the static destructor pointer list.
unsigned PersonalityEncoding
PersonalityEncoding, LSDAEncoding, TTypeEncoding - Some encoding values for EH.
static SectionKind getKindForGlobal(const GlobalObject *GO, const TargetMachine &TM)
Classify the specified global variable into a set of target independent categories embodied in Sectio...
virtual bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const
bool supportDSOLocalEquivalentLowering() const
Target supports a native lowering of a dso_local_equivalent constant without needing to replace it wi...
virtual void Initialize(MCContext &ctx, const TargetMachine &TM)
This method must be called before any actual lowering is done.
MCSection * StaticCtorSection
This section contains the static constructor pointer list.
virtual MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment) const
Given a constant with the SectionKind, return a section that it should be placed in.
MCSymbol * getSymbolWithGlobalValueBase(const GlobalValue *GV, StringRef Suffix, const TargetMachine &TM) const
Return the MCSymbol for a private symbol with global value name as its base, with the specified suffi...
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, MachineModuleInfo *MMI, MCStreamer &Streamer) const
Return an MCExpr to use for a reference to the specified global variable from exception handling info...
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
MCSection * SectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const
This method computes the appropriate section to emit the specified global variable or function defini...
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
const Triple & getTargetTriple() const
bool getUniqueBasicBlockSectionNames() const
Return true if unique basic block section names must be generated.
bool getUniqueSectionNames() const
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
TargetOptions Options
MCSymbol * getSymbol(const GlobalValue *GV) const
bool getDataSections() const
Return true if data objects should be emitted into their own section, corresponds to -fdata-sections.
CodeModel::Model getCodeModel() const
Returns the code model.
bool getFunctionSections() const
Return true if functions should be emitted into their own section, corresponding to -ffunction-sectio...
const MCAsmInfo * getMCAsmInfo() const
Return target specific asm information.
unsigned XCOFFReadOnlyPointers
When set to true, const objects with relocatable address values are put into the RO data section.
unsigned UseInitArray
UseInitArray - Use .init_array instead of .ctors for static constructors.
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
@ loongarch32
Definition: Triple.h:61
@ aarch64_be
Definition: Triple.h:52
@ loongarch64
Definition: Triple.h:62
@ mips64el
Definition: Triple.h:67
@ aarch64_32
Definition: Triple.h:53
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:383
EnvironmentType getEnvironment() const
Get the parsed environment type of this triple.
Definition: Triple.h:400
bool isOSFreeBSD() const
Definition: Triple.h:594
bool isArch32Bit() const
Test whether the architecture is 32-bit.
Definition: Triple.cpp:1685
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
std::string str() const
Return the twine contents as a std::string.
Definition: Twine.cpp:17
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
uint64_t getArrayNumElements() const
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
This file contains the declaration of the Comdat class, which represents a single COMDAT in LLVM.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
SectionCharacteristics
Definition: COFF.h:297
@ IMAGE_SCN_LNK_REMOVE
Definition: COFF.h:307
@ IMAGE_SCN_CNT_CODE
Definition: COFF.h:302
@ IMAGE_SCN_MEM_READ
Definition: COFF.h:335
@ IMAGE_SCN_MEM_EXECUTE
Definition: COFF.h:334
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition: COFF.h:304
@ IMAGE_SCN_MEM_DISCARDABLE
Definition: COFF.h:330
@ IMAGE_SCN_MEM_16BIT
Definition: COFF.h:311
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition: COFF.h:303
@ IMAGE_SCN_LNK_COMDAT
Definition: COFF.h:308
@ IMAGE_SCN_MEM_WRITE
Definition: COFF.h:336
@ IMAGE_COMDAT_SELECT_NODUPLICATES
Definition: COFF.h:454
@ IMAGE_COMDAT_SELECT_LARGEST
Definition: COFF.h:459
@ IMAGE_COMDAT_SELECT_SAME_SIZE
Definition: COFF.h:456
@ IMAGE_COMDAT_SELECT_ASSOCIATIVE
Definition: COFF.h:458
@ IMAGE_COMDAT_SELECT_EXACT_MATCH
Definition: COFF.h:457
@ IMAGE_COMDAT_SELECT_ANY
Definition: COFF.h:455
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
@ SHT_LLVM_DEPENDENT_LIBRARIES
Definition: ELF.h:1121
@ SHT_PROGBITS
Definition: ELF.h:1090
@ SHT_LLVM_LINKER_OPTIONS
Definition: ELF.h:1118
@ SHT_NOBITS
Definition: ELF.h:1097
@ SHT_LLVM_OFFLOADING
Definition: ELF.h:1131
@ SHT_LLVM_LTO
Definition: ELF.h:1132
@ SHT_PREINIT_ARRAY
Definition: ELF.h:1103
@ SHT_INIT_ARRAY
Definition: ELF.h:1101
@ SHT_NOTE
Definition: ELF.h:1096
@ SHT_FINI_ARRAY
Definition: ELF.h:1102
@ SHF_MERGE
Definition: ELF.h:1194
@ SHF_STRINGS
Definition: ELF.h:1197
@ SHF_EXCLUDE
Definition: ELF.h:1222
@ SHF_ALLOC
Definition: ELF.h:1188
@ SHF_LINK_ORDER
Definition: ELF.h:1203
@ SHF_GROUP
Definition: ELF.h:1210
@ SHF_SUNW_NODISCARD
Definition: ELF.h:1229
@ SHF_X86_64_LARGE
Definition: ELF.h:1251
@ SHF_GNU_RETAIN
Definition: ELF.h:1219
@ SHF_WRITE
Definition: ELF.h:1185
@ SHF_TLS
Definition: ELF.h:1213
@ SHF_ARM_PURECODE
Definition: ELF.h:1283
@ SHF_EXECINSTR
Definition: ELF.h:1191
@ S_MOD_TERM_FUNC_POINTERS
S_MOD_TERM_FUNC_POINTERS - Section with only function pointers for termination.
Definition: MachO.h:150
@ S_MOD_INIT_FUNC_POINTERS
S_MOD_INIT_FUNC_POINTERS - Section with only function pointers for initialization.
Definition: MachO.h:147
StorageClass
Definition: XCOFF.h:170
@ C_WEAKEXT
Definition: XCOFF.h:199
@ C_HIDEXT
Definition: XCOFF.h:206
StorageMappingClass
Storage Mapping Class definitions.
Definition: XCOFF.h:103
@ XMC_TE
Symbol mapped at the end of TOC.
Definition: XCOFF.h:128
@ XMC_DS
Descriptor csect.
Definition: XCOFF.h:121
@ XMC_RW
Read Write Data.
Definition: XCOFF.h:117
@ XMC_TL
Initialized thread-local variable.
Definition: XCOFF.h:126
@ XMC_RO
Read Only Constant.
Definition: XCOFF.h:106
@ XMC_UA
Unclassified - Treated as Read Write.
Definition: XCOFF.h:122
@ XMC_TD
Scalar data item in the TOC.
Definition: XCOFF.h:120
@ XMC_UL
Uninitialized thread-local variable.
Definition: XCOFF.h:127
@ XMC_PR
Program Code.
Definition: XCOFF.h:105
@ XMC_BS
BSS class (uninitialized static internal)
Definition: XCOFF.h:123
@ XMC_TC
General TOC item.
Definition: XCOFF.h:119
@ XTY_CM
Common csect definition. For uninitialized storage.
Definition: XCOFF.h:245
@ XTY_SD
Csect definition for initialized storage.
Definition: XCOFF.h:242
@ XTY_ER
External reference.
Definition: XCOFF.h:241
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ DW_EH_PE_datarel
Definition: Dwarf.h:860
@ DW_EH_PE_pcrel
Definition: Dwarf.h:858
@ DW_EH_PE_sdata4
Definition: Dwarf.h:855
@ DW_EH_PE_sdata8
Definition: Dwarf.h:856
@ DW_EH_PE_absptr
Definition: Dwarf.h:847
@ DW_EH_PE_udata4
Definition: Dwarf.h:851
@ DW_EH_PE_udata8
Definition: Dwarf.h:852
@ DW_EH_PE_indirect
Definition: Dwarf.h:863
@ WASM_SEG_FLAG_RETAIN
Definition: Wasm.h:227
@ WASM_SEG_FLAG_TLS
Definition: Wasm.h:226
@ WASM_SEG_FLAG_STRINGS
Definition: Wasm.h:225
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:480
std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
Definition: InstrProf.cpp:236
@ DK_Lowering
bool isNoOpWithoutInvoke(EHPersonality Pers)
Return true if this personality may be safely removed if there are no invoke instructions remaining i...
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition: STLExtras.h:1952
std::string encodeBase64(InputBytes const &Bytes)
Definition: Base64.h:23
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
void emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &T, Mangler &M)
Definition: Mangler.cpp:280
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:125
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
@ DS_Error
void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition: Mangler.cpp:214
const char * toString(DWARFSectionKind Kind)
cl::opt< std::string > BBSectionsColdTextPrefix
@ Default
The result values are uniform if and only if all operands are uniform.
@ MCSA_Weak
.weak
Definition: MCDirectives.h:45
@ MCSA_ELF_TypeObject
.type _foo, STT_OBJECT # aka @object
Definition: MCDirectives.h:25
@ MCSA_Hidden
.hidden (ELF)
Definition: MCDirectives.h:33
GlobalVariable * collectUsedGlobalVariables(const Module &M, SmallVectorImpl< GlobalValue * > &Vec, bool CompilerUsed)
Given "llvm.used" or "llvm.compiler.used" as a global name, collect the initializer elements of that ...
Definition: Module.cpp:865
constexpr const char * PseudoProbeDescMetadataName
Definition: PseudoProbe.h:25
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
uint64_t value() const
This is a hole in the type system and should not be abused.
Definition: Alignment.h:85
static const MBBSectionID ExceptionSectionID
static const MBBSectionID ColdSectionID