LLVM 24.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"
32#include "llvm/IR/Comdat.h"
33#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
38#include "llvm/IR/Function.h"
39#include "llvm/IR/GlobalAlias.h"
41#include "llvm/IR/GlobalValue.h"
43#include "llvm/IR/Mangler.h"
44#include "llvm/IR/Metadata.h"
45#include "llvm/IR/Module.h"
46#include "llvm/IR/Type.h"
47#include "llvm/MC/MCAsmInfo.h"
49#include "llvm/MC/MCContext.h"
50#include "llvm/MC/MCExpr.h"
58#include "llvm/MC/MCStreamer.h"
59#include "llvm/MC/MCSymbol.h"
60#include "llvm/MC/MCSymbolELF.h"
62#include "llvm/MC/MCValue.h"
63#include "llvm/MC/SectionKind.h"
65#include "llvm/Support/Base64.h"
69#include "llvm/Support/Format.h"
70#include "llvm/Support/Path.h"
74#include <cassert>
75#include <string>
76
77using namespace llvm;
78using namespace dwarf;
79
81 "jumptable-in-function-section", cl::Hidden, cl::init(false),
82 cl::desc("Putting Jump Table in function section"));
83
84static void GetObjCImageInfo(const Module &M, unsigned &Version,
85 unsigned &Flags, StringRef &Section) {
87 M.getModuleFlagsMetadata(ModuleFlags);
88
89 for (const auto &MFE: ModuleFlags) {
90 // Ignore flags with 'Require' behaviour.
91 if (MFE.Behavior == Module::Require)
92 continue;
93
94 StringRef Key = MFE.Key->getString();
95 if (Key == "Objective-C Image Info Version") {
96 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
97 } else if (Key == "Objective-C Garbage Collection" ||
98 Key == "Objective-C GC Only" ||
99 Key == "Objective-C Is Simulated" ||
100 Key == "Objective-C Class Properties" ||
101 Key == "Objective-C Image Swift Version") {
102 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
103 } else if (Key == "Objective-C Image Info Section") {
104 Section = cast<MDString>(MFE.Val)->getString();
105 }
106 // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
107 // "Objective-C Garbage Collection".
108 else if (Key == "Swift ABI Version") {
109 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
110 } else if (Key == "Swift Major Version") {
111 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
112 } else if (Key == "Swift Minor Version") {
113 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
114 }
115 }
116}
117
118//===----------------------------------------------------------------------===//
119// ELF
120//===----------------------------------------------------------------------===//
121
123 const TargetMachine &TgtM,
124 const Module &M) {
126
127 const CodeModel::Model CM = TgtM.getCodeModel();
129
130 switch (TgtM.getTargetTriple().getArch()) {
131 case Triple::arm:
132 case Triple::armeb:
133 case Triple::thumb:
134 case Triple::thumbeb:
135 if (M.getExceptionModel() == ExceptionHandling::ARM)
136 break;
137 // Fallthrough if not using EHABI
138 [[fallthrough]];
139 case Triple::m68k:
140 case Triple::ppc:
141 case Triple::ppcle:
142 case Triple::x86:
155 break;
156 case Triple::x86_64: {
157 // The large EH encoding forces 64-bit-wide EH pointers regardless of the
158 // code model, so treat it like the Large code model when selecting
159 // encodings below.
160 const CodeModel::Model EHCM =
162 if (isPositionIndependent()) {
165 ((EHCM == CodeModel::Small || EHCM == CodeModel::Medium)
172 ((EHCM == CodeModel::Small || EHCM == CodeModel::Medium)
175 } else {
177 (EHCM == CodeModel::Small || EHCM == CodeModel::Medium)
184 }
185 break;
186 }
187 case Triple::hexagon:
191 if (isPositionIndependent()) {
195 }
196 break;
197 case Triple::aarch64:
200 // The small model guarantees static code/data size < 4GB, but not where it
201 // will be in memory. Most of these could end up >2GB away so even a signed
202 // pc-relative 32-bit address is insufficient, theoretically.
203 //
204 // Use DW_EH_PE_indirect even for -fno-pic to avoid copy relocations.
206 (TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32
211 break;
212 case Triple::lanai:
216 break;
217 case Triple::mips:
218 case Triple::mipsel:
219 case Triple::mips64:
220 case Triple::mips64el:
221 // MIPS uses indirect pointer to refer personality functions and types, so
222 // that the eh_frame section can be read-only. DW.ref.personality will be
223 // generated for relocation.
225 // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
226 // identify N64 from just a triple.
229
230 // FreeBSD must be explicit about the data size and using pcrel since it's
231 // assembler/linker won't do the automatic conversion that the Linux tools
232 // do.
236 }
237 break;
238 case Triple::ppc64:
239 case Triple::ppc64le:
245 break;
246 case Triple::sparcel:
247 case Triple::sparc:
248 if (isPositionIndependent()) {
254 } else {
258 }
260 break;
261 case Triple::riscv32:
262 case Triple::riscv64:
271 break;
272 case Triple::sparcv9:
274 if (isPositionIndependent()) {
279 } else {
282 }
283 break;
284 case Triple::systemz:
285 // All currently-defined code models guarantee that 4-byte PC-relative
286 // values will be in range.
287 if (isPositionIndependent()) {
293 } else {
297 }
298 break;
306 break;
307 default:
308 break;
309 }
310
312 collectUsedGlobalVariables(M, Vec, false);
313 for (GlobalValue *GV : Vec)
314 if (auto *GO = dyn_cast<GlobalObject>(GV))
315 Used.insert(GO);
316}
317
319 const Module &M) const {
320 auto &C = getContext();
321
323
324 if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
325 auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
327
328 Streamer.switchSection(S);
329
330 for (const auto *Operand : DependentLibraries->operands()) {
331 Streamer.emitBytes(
332 cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
333 Streamer.emitInt8(0);
334 }
335 }
336
338
339 if (NamedMDNode *LLVMStats = M.getNamedMetadata("llvm.stats")) {
340 // Emit the metadata for llvm statistics into .llvm_stats section, which is
341 // formatted as a list of key/value pair, the value is base64 encoded.
342 auto *S = C.getObjectFileInfo()->getLLVMStatsSection();
343 Streamer.switchSection(S);
344 for (const auto *Operand : LLVMStats->operands()) {
345 const auto *MD = cast<MDNode>(Operand);
346 assert(MD->getNumOperands() % 2 == 0 &&
347 ("Operand num should be even for a list of key/value pair"));
348 for (size_t I = 0; I < MD->getNumOperands(); I += 2) {
349 // Encode the key string size.
350 auto *Key = cast<MDString>(MD->getOperand(I));
351 Streamer.emitULEB128IntValue(Key->getString().size());
352 Streamer.emitBytes(Key->getString());
353 // Encode the value into a Base64 string.
354 std::string Value = encodeBase64(
355 Twine(mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1))
356 ->getZExtValue())
357 .str());
358 Streamer.emitULEB128IntValue(Value.size());
359 Streamer.emitBytes(Value);
360 }
361 }
362 }
363
364 unsigned Version = 0;
365 unsigned Flags = 0;
366 StringRef Section;
367
368 GetObjCImageInfo(M, Version, Flags, Section);
369 if (!Section.empty()) {
370 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
371 Streamer.switchSection(S);
372 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
373 Streamer.emitInt32(Version);
374 Streamer.emitInt32(Flags);
375 Streamer.addBlankLine();
376 }
377
379}
380
382 const Module &M) const {
383 auto &C = getContext();
384 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
385 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
387
388 Streamer.switchSection(S);
389
390 for (const auto *Operand : LinkerOptions->operands()) {
391 if (cast<MDNode>(Operand)->getNumOperands() != 2)
392 report_fatal_error("invalid llvm.linker.options");
393 for (const auto &Option : cast<MDNode>(Operand)->operands()) {
394 Streamer.emitBytes(cast<MDString>(Option)->getString());
395 Streamer.emitInt8(0);
396 }
397 }
398 }
399}
400
402 const GlobalValue *GV, const TargetMachine &TM,
403 MachineModuleInfo *MMI) const {
404 unsigned Encoding = getPersonalityEncoding();
405 if ((Encoding & 0x80) == DW_EH_PE_indirect)
406 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
407 TM.getSymbol(GV)->getName());
408 if ((Encoding & 0x70) == DW_EH_PE_absptr)
409 return TM.getSymbol(GV);
410 report_fatal_error("We do not support this DWARF encoding yet!");
411}
412
414 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym,
415 const MachineModuleInfo *MMI) const {
416 SmallString<64> NameData("DW.ref.");
417 NameData += Sym->getName();
418 auto *Label =
419 static_cast<MCSymbolELF *>(getContext().getOrCreateSymbol(NameData));
420 Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
421 Streamer.emitSymbolAttribute(Label, MCSA_Weak);
422 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
423 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
424 ELF::SHT_PROGBITS, Flags, 0);
425 unsigned Size = DL.getPointerSize();
426 Streamer.switchSection(Sec);
427 Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0));
428 Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
430 Streamer.emitELFSize(Label, E);
431 Streamer.emitLabel(Label);
432
434}
435
437 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym,
438 const MachineModuleInfo *MMI) const {
439 Streamer.emitSymbolValue(Sym, DL.getPointerSize());
440}
441
443 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
445 if (Encoding & DW_EH_PE_indirect) {
447
448 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
449
450 // Add information about the stub reference to ELFMMI so that the stub
451 // gets emitted by the asmprinter.
453 if (!StubSym.getPointer()) {
454 MCSymbol *Sym = TM.getSymbol(GV);
456 }
457
460 Encoding & ~DW_EH_PE_indirect, Streamer);
461 }
462
464 MMI, Streamer);
465}
466
468 // N.B.: The defaults used in here are not the same ones used in MC.
469 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
470 // both gas and MC will produce a section with no flags. Given
471 // section(".eh_frame") gcc will produce:
472 //
473 // .section .eh_frame,"a",@progbits
474
475 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
476 /*AddSegmentInfo=*/false) ||
477 Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
478 /*AddSegmentInfo=*/false) ||
479 Name == getInstrProfSectionName(IPSK_covdata, Triple::ELF,
480 /*AddSegmentInfo=*/false) ||
481 Name == getInstrProfSectionName(IPSK_covname, Triple::ELF,
482 /*AddSegmentInfo=*/false) ||
483 Name == ".llvmbc" || Name == ".llvmcmd")
485
486 if (!Name.starts_with(".")) return K;
487
488 // Default implementation based on some magic section names.
489 if (Name == ".bss" || Name.starts_with(".bss.") ||
490 Name.starts_with(".gnu.linkonce.b.") ||
491 Name.starts_with(".llvm.linkonce.b.") || Name == ".sbss" ||
492 Name.starts_with(".sbss.") || Name.starts_with(".gnu.linkonce.sb.") ||
493 Name.starts_with(".llvm.linkonce.sb."))
494 return SectionKind::getBSS();
495
496 if (Name == ".tdata" || Name.starts_with(".tdata.") ||
497 Name.starts_with(".gnu.linkonce.td.") ||
498 Name.starts_with(".llvm.linkonce.td."))
500
501 if (Name == ".tbss" || Name.starts_with(".tbss.") ||
502 Name.starts_with(".gnu.linkonce.tb.") ||
503 Name.starts_with(".llvm.linkonce.tb."))
505
506 return K;
507}
508
510 return SectionName.consume_front(Prefix) &&
511 (SectionName.empty() || SectionName[0] == '.');
512}
513
514static unsigned getELFSectionType(StringRef Name, SectionKind K) {
515 // Use SHT_NOTE for section whose name starts with ".note" to allow
516 // emitting ELF notes from C variable declaration.
517 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
518 if (Name.starts_with(".note"))
519 return ELF::SHT_NOTE;
520
521 if (hasPrefix(Name, ".init_array"))
522 return ELF::SHT_INIT_ARRAY;
523
524 if (hasPrefix(Name, ".fini_array"))
525 return ELF::SHT_FINI_ARRAY;
526
527 if (hasPrefix(Name, ".preinit_array"))
529
530 if (hasPrefix(Name, ".llvm.offloading"))
532 if (Name == ".llvm.lto")
533 return ELF::SHT_LLVM_LTO;
534
535 if (K.isBSS() || K.isThreadBSS())
536 return ELF::SHT_NOBITS;
537
538 return ELF::SHT_PROGBITS;
539}
540
541static unsigned getELFSectionFlags(SectionKind K, const Triple &T) {
542 unsigned Flags = 0;
543
544 if (!K.isMetadata() && !K.isExclude())
545 Flags |= ELF::SHF_ALLOC;
546
547 if (K.isExclude())
548 Flags |= ELF::SHF_EXCLUDE;
549
550 if (K.isText())
551 Flags |= ELF::SHF_EXECINSTR;
552
553 if (K.isExecuteOnly()) {
554 if (T.isAArch64())
556 else if (T.isARM() || T.isThumb())
557 Flags |= ELF::SHF_ARM_PURECODE;
558 }
559
560 if (K.isWriteable())
561 Flags |= ELF::SHF_WRITE;
562
563 if (K.isThreadLocal())
564 Flags |= ELF::SHF_TLS;
565
566 if (K.isMergeableCString() || K.isMergeableConst())
567 Flags |= ELF::SHF_MERGE;
568
569 if (K.isMergeableCString())
570 Flags |= ELF::SHF_STRINGS;
571
572 return Flags;
573}
574
575MCSection *
577 SectionKind Kind) const {
578 unsigned Type = getELFSectionType(Name, Kind);
579 unsigned Flags = getELFSectionFlags(Kind, getContext().getTargetTriple());
580 return getContext().getELFSection(Name, Type, Flags);
581}
582
583static const Comdat *getELFComdat(const GlobalValue *GV) {
584 const Comdat *C = GV->getComdat();
585 if (!C)
586 return nullptr;
587
588 if (C->getSelectionKind() != Comdat::Any &&
589 C->getSelectionKind() != Comdat::NoDeduplicate)
590 report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
591 "SelectionKind::NoDeduplicate, '" +
592 C->getName() + "' cannot be lowered.");
593
594 return C;
595}
596
598 const TargetMachine &TM) {
599 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
600 if (!MD)
601 return nullptr;
602
603 auto *VM = cast<ValueAsMetadata>(MD->getOperand(0).get());
604 auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
605 return OtherGV ? static_cast<const MCSymbolELF *>(TM.getSymbol(OtherGV))
606 : nullptr;
607}
608
609static unsigned getEntrySizeForKind(SectionKind Kind) {
610 if (Kind.isMergeable1ByteCString())
611 return 1;
612 else if (Kind.isMergeable2ByteCString())
613 return 2;
614 else if (Kind.isMergeable4ByteCString())
615 return 4;
616 else if (Kind.isMergeableConst4())
617 return 4;
618 else if (Kind.isMergeableConst8())
619 return 8;
620 else if (Kind.isMergeableConst16())
621 return 16;
622 else if (Kind.isMergeableConst32())
623 return 32;
624 else {
625 // We shouldn't have mergeable C strings or mergeable constants that we
626 // didn't handle above.
627 assert(!Kind.isMergeableCString() && "unknown string width");
628 assert(!Kind.isMergeableConst() && "unknown data width");
629 return 0;
630 }
631}
632
633/// Return the section prefix name used by options FunctionsSections and
634/// DataSections.
636 if (Kind.isText())
637 return IsLarge ? ".ltext" : ".text";
638 if (Kind.isReadOnly())
639 return IsLarge ? ".lrodata" : ".rodata";
640 if (Kind.isBSS())
641 return IsLarge ? ".lbss" : ".bss";
642 if (Kind.isThreadData())
643 return ".tdata";
644 if (Kind.isThreadBSS())
645 return ".tbss";
646 if (Kind.isData())
647 return IsLarge ? ".ldata" : ".data";
648 if (Kind.isReadOnlyWithRel())
649 return IsLarge ? ".ldata.rel.ro" : ".data.rel.ro";
650 llvm_unreachable("Unknown section kind");
651}
652
653static SmallString<128>
655 Mangler &Mang, const TargetMachine &TM,
656 bool UniqueSectionName,
657 const MachineJumpTableEntry *JTE) {
658 SmallString<128> Name =
660 unsigned EntrySize = getEntrySizeForKind(Kind);
661 if (Kind.isMergeableCString()) {
662 // We also need alignment here.
663 // FIXME: this is getting the alignment of the character, not the
664 // alignment of the global!
665 Align Alignment = GO->getDataLayout().getPreferredAlign(
667
668 Name += ".str";
669 Name += utostr(EntrySize);
670 Name += ".";
671 Name += utostr(Alignment.value());
672 } else if (Kind.isMergeableConst()) {
673 Name += ".cst";
674 Name += utostr(EntrySize);
675 }
676
677 bool HasPrefix = false;
678 SmallString<32> SectionPrefix;
679 if (const auto *F = dyn_cast<Function>(GO)) {
680 // Jump table hotness takes precedence over its enclosing function's hotness
681 // if it's known. The function's section prefix is used if jump table entry
682 // hotness is unknown.
683 if (JTE && JTE->Hotness != MachineFunctionDataHotness::Unknown) {
684 switch (JTE->Hotness) {
686 raw_svector_ostream(SectionPrefix) << ".unlikely";
687 break;
690 GO->getContext()))
691 raw_svector_ostream(SectionPrefix) << ".hot";
692 break;
693 }
694 default:
695 llvm_unreachable("Unknown jump table hotness");
696 break;
697 }
698 } else if (std::optional<StringRef> Prefix = F->getSectionPrefix())
699 raw_svector_ostream(SectionPrefix) << "." << *Prefix;
700 } else if (const auto *GV = dyn_cast<GlobalVariable>(GO)) {
701 if (std::optional<StringRef> Prefix = GV->getSectionPrefix()) {
702 raw_svector_ostream(SectionPrefix) << "." << *Prefix;
703 }
704 }
705
706 if (!SectionPrefix.empty()) {
707 bool AddSectionPrefix = true;
708 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel() || Kind.isData() ||
709 Kind.isBSS()) {
710 AddSectionPrefix =
712 (!SectionPrefix.starts_with(".hot") ||
714 GO->getContext()));
715 }
716
717 if (AddSectionPrefix) {
718 Name += SectionPrefix;
719 HasPrefix = true;
720 }
721 }
722
723 if (UniqueSectionName) {
724 Name.push_back('.');
725 TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
726 } else if (HasPrefix)
727 // For distinguishing between .text.${text-section-prefix}. (with trailing
728 // dot) and .text.${function-name}
729 Name.push_back('.');
730 return Name;
731}
732
733namespace {
734class LoweringDiagnosticInfo : public DiagnosticInfo {
735 const Twine &Msg;
736
737public:
738 LoweringDiagnosticInfo(const Twine &DiagMsg LLVM_LIFETIME_BOUND,
739 DiagnosticSeverity Severity = DS_Error)
740 : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
741 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
742};
743}
744
745/// Calculate an appropriate unique ID for a section, and update Flags,
746/// EntrySize and NextUniqueID where appropriate.
747static unsigned
749 SectionKind Kind, const TargetMachine &TM,
750 MCContext &Ctx, Mangler &Mang, unsigned &Flags,
751 unsigned &EntrySize, unsigned &NextUniqueID,
752 const bool Retain, const bool ForceUnique) {
753 // Increment uniqueID if we are forced to emit a unique section.
754 // This works perfectly fine with section attribute or pragma section as the
755 // sections with the same name are grouped together by the assembler.
756 if (ForceUnique)
757 return NextUniqueID++;
758
759 // A section can have at most one associated section. Put each global with
760 // MD_associated in a unique section.
761 const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
762 if (Associated) {
763 Flags |= ELF::SHF_LINK_ORDER;
764 return NextUniqueID++;
765 }
766
767 if (Retain) {
768 if (TM.getTargetTriple().isOSSolaris())
770 else if (Ctx.getAsmInfo().useIntegratedAssembler() ||
771 Ctx.getAsmInfo().binutilsIsAtLeast(2, 36))
772 Flags |= ELF::SHF_GNU_RETAIN;
773 return NextUniqueID++;
774 }
775
776 // If two symbols with differing sizes end up in the same mergeable section
777 // that section can be assigned an incorrect entry size. To avoid this we
778 // usually put symbols of the same size into distinct mergeable sections with
779 // the same name. Doing so relies on the ",unique ," assembly feature. This
780 // feature is not available until binutils version 2.35
781 // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
782 const bool SupportsUnique = Ctx.getAsmInfo().useIntegratedAssembler() ||
783 Ctx.getAsmInfo().binutilsIsAtLeast(2, 35);
784 if (!SupportsUnique) {
785 Flags &= ~ELF::SHF_MERGE;
786 EntrySize = 0;
788 }
789
790 const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
791 const bool SeenSectionNameBefore =
792 Ctx.isELFGenericMergeableSection(SectionName);
793 // If this is the first occurrence of this section name, treat it as the
794 // generic section
795 if (!SymbolMergeable && !SeenSectionNameBefore) {
797 return NextUniqueID++;
798 else
800 }
801
802 // Symbols must be placed into sections with compatible entry sizes. Generate
803 // unique sections for symbols that have not been assigned to compatible
804 // sections.
805 const auto PreviousID =
806 Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
807 if (PreviousID &&
808 (!TM.getSeparateNamedSections() || *PreviousID == MCSection::NonUniqueID))
809 return *PreviousID;
810
811 // If the user has specified the same section name as would be created
812 // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
813 // to unique the section as the entry size for this symbol will be
814 // compatible with implicitly created sections.
815 SmallString<128> ImplicitSectionNameStem =
816 getELFSectionNameForGlobal(GO, Kind, Mang, TM, false, /*MJTE=*/nullptr);
817 if (SymbolMergeable &&
818 Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) &&
819 SectionName.starts_with(ImplicitSectionNameStem))
821
822 // We have seen this section name before, but with different flags or entity
823 // size. Create a new unique ID.
824 return NextUniqueID++;
825}
826
827static std::tuple<StringRef, bool, unsigned, unsigned, unsigned>
830 StringRef Group = "";
831 bool IsComdat = false;
832 unsigned Flags = 0;
833 if (const Comdat *C = getELFComdat(GO)) {
834 Flags |= ELF::SHF_GROUP;
835 Group = C->getName();
836 IsComdat = C->getSelectionKind() == Comdat::Any;
837 }
838 if (TM.isLargeGlobalValue(GO))
839 Flags |= ELF::SHF_X86_64_LARGE;
840
841 unsigned Type, EntrySize;
842 if (MDNode *MD = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
843 Type = cast<ConstantAsMetadata>(MD->getOperand(0))
844 ->getValue()
845 ->getUniqueInteger()
846 .getZExtValue();
847 EntrySize = cast<ConstantAsMetadata>(MD->getOperand(1))
848 ->getValue()
849 ->getUniqueInteger()
850 .getZExtValue();
851 } else {
853 EntrySize = getEntrySizeForKind(Kind);
854 }
855
856 return {Group, IsComdat, Flags, Type, EntrySize};
857}
858
860 SectionKind Kind,
861 const TargetMachine &TM,
862 MCContext &Ctx, Mangler &Mang,
863 unsigned &NextUniqueID,
864 bool Retain, bool ForceUnique) {
867
868 // Infer section flags from the section name if we can.
870
871 unsigned Flags = getELFSectionFlags(Kind, GO->getParent()->getTargetTriple());
872 auto [Group, IsComdat, ExtraFlags, Type, EntrySize] =
873 getGlobalObjectInfo(GO, TM, SectionName, Kind);
874 Flags |= ExtraFlags;
875
877 GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
878 Retain, ForceUnique);
879
880 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
881 MCSectionELF *Section =
882 Ctx.getELFSection(SectionName, Type, Flags, EntrySize, Group, IsComdat,
883 UniqueID, LinkedToSym);
884 // Make sure that we did not get some other section with incompatible sh_link.
885 // This should not be possible due to UniqueID code above.
886 assert(Section->getLinkedToSymbol() == LinkedToSym &&
887 "Associated symbol mismatch between sections");
888
889 if (!(Ctx.getAsmInfo().useIntegratedAssembler() ||
890 Ctx.getAsmInfo().binutilsIsAtLeast(2, 35))) {
891 // If we are using GNU as before 2.35, then this symbol might have
892 // been placed in an incompatible mergeable section. Emit an error if this
893 // is the case to avoid creating broken output.
894 if ((Section->getFlags() & ELF::SHF_MERGE) &&
895 (Section->getEntrySize() != getEntrySizeForKind(Kind)))
896 GO->getContext().diagnose(LoweringDiagnosticInfo(
897 "Symbol '" + GO->getName() + "' from module '" +
898 (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
899 "' required a section with entry-size=" +
900 Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
901 SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
902 ": Explicit assignment by pragma or attribute of an incompatible "
903 "symbol to this section?"));
904 }
905
906 return Section;
907}
908
910 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
912 NextUniqueID, Used.count(GO),
913 /* ForceUnique = */false);
914}
915
917 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
918 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
919 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol,
920 const MachineJumpTableEntry *MJTE = nullptr) {
921 bool UniqueSectionName = false;
923 if (EmitUniqueSection) {
924 if (TM.getUniqueSectionNames()) {
925 UniqueSectionName = true;
926 } else {
927 UniqueID = *NextUniqueID;
928 (*NextUniqueID)++;
929 }
930 }
931 SmallString<128> Name =
932 getELFSectionNameForGlobal(GO, Kind, Mang, TM, UniqueSectionName, MJTE);
933
934 auto [Group, IsComdat, ExtraFlags, Type, EntrySize] =
935 getGlobalObjectInfo(GO, TM, Name, Kind);
936 Flags |= ExtraFlags;
937
938 // Use 0 as the unique ID for execute-only text.
939 if (Kind.isExecuteOnly())
940 UniqueID = 0;
941 return Ctx.getELFSection(Name, Type, Flags, EntrySize, Group, IsComdat,
942 UniqueID, AssociatedSymbol);
943}
944
946 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
947 const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
948 unsigned Flags, unsigned *NextUniqueID) {
949 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
950 if (LinkedToSym) {
951 EmitUniqueSection = true;
952 Flags |= ELF::SHF_LINK_ORDER;
953 }
954 if (Retain) {
955 if (TM.getTargetTriple().isOSSolaris()) {
956 EmitUniqueSection = true;
958 } else if (Ctx.getAsmInfo().useIntegratedAssembler() ||
959 Ctx.getAsmInfo().binutilsIsAtLeast(2, 36)) {
960 EmitUniqueSection = true;
961 Flags |= ELF::SHF_GNU_RETAIN;
962 }
963 }
964 if (GO->hasMetadata(LLVMContext::MD_elf_section_properties))
965 EmitUniqueSection = true;
966
968 Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
969 NextUniqueID, LinkedToSym);
970 assert(Section->getLinkedToSymbol() == LinkedToSym);
971 return Section;
972}
973
975 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
976 unsigned Flags = getELFSectionFlags(Kind, GO->getParent()->getTargetTriple());
977
978 // If we have -ffunction-section or -fdata-section then we should emit the
979 // global value to a uniqued section specifically for it.
980 bool EmitUniqueSection = false;
981 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
982 if (Kind.isText())
983 EmitUniqueSection = TM.getFunctionSections();
984 else
985 EmitUniqueSection = TM.getDataSections();
986 }
987 EmitUniqueSection |= GO->hasComdat();
988 return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
989 Used.count(GO), EmitUniqueSection, Flags,
990 &NextUniqueID);
991}
992
994 const Function &F, const TargetMachine &TM) const {
996 unsigned Flags = getELFSectionFlags(Kind, F.getParent()->getTargetTriple());
997 // If the function's section names is pre-determined via pragma or a
998 // section attribute, call selectExplicitSectionGlobal.
999 if (F.hasSection())
1001 &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
1002 Used.count(&F), /* ForceUnique = */true);
1003
1005 getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
1006 /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
1007}
1008
1010 const Function &F, const TargetMachine &TM) const {
1011 return getSectionForJumpTable(F, TM, /*JTE=*/nullptr);
1012}
1013
1015 const Function &F, const TargetMachine &TM,
1016 const MachineJumpTableEntry *JTE) const {
1017 // If the function can be removed, produce a unique section so that
1018 // the table doesn't prevent the removal.
1019 const Comdat *C = F.getComdat();
1020 bool EmitUniqueSection = TM.getFunctionSections() || C;
1021 if (!EmitUniqueSection && !TM.getEnableStaticDataPartitioning())
1022 return ReadOnlySection;
1023
1025 getMangler(), TM, EmitUniqueSection,
1026 ELF::SHF_ALLOC, &NextUniqueID,
1027 /* AssociatedSymbol */ nullptr, JTE);
1028}
1029
1031 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
1032 // If neither COMDAT nor function sections, use the monolithic LSDA section.
1033 // Re-use this path if LSDASection is null as in the Arm EHABI.
1034 if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
1035 return LSDASection;
1036
1037 const auto *LSDA = static_cast<const MCSectionELF *>(LSDASection);
1038 unsigned Flags = LSDA->getFlags();
1039 const MCSymbolELF *LinkedToSym = nullptr;
1040 StringRef Group;
1041 bool IsComdat = false;
1042 if (const Comdat *C = getELFComdat(&F)) {
1043 Flags |= ELF::SHF_GROUP;
1044 Group = C->getName();
1045 IsComdat = C->getSelectionKind() == Comdat::Any;
1046 }
1047 // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
1048 // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
1049 if (TM.getFunctionSections() &&
1050 (getContext().getAsmInfo().useIntegratedAssembler() &&
1051 getContext().getAsmInfo().binutilsIsAtLeast(2, 36))) {
1052 Flags |= ELF::SHF_LINK_ORDER;
1053 LinkedToSym = static_cast<const MCSymbolELF *>(&FnSym);
1054 }
1055
1056 // Append the function name as the suffix like GCC, assuming
1057 // -funique-section-names applies to .gcc_except_table sections.
1058 return getContext().getELFSection(
1059 (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
1060 : LSDA->getName()),
1061 LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
1062 LinkedToSym);
1063}
1064
1066 bool UsesLabelDifference, const Function &F) const {
1067 // We can always create relative relocations, so use another section
1068 // that can be marked non-executable.
1069 return false;
1070}
1071
1072/// Given a mergeable constant with the specified size and relocation
1073/// information, return a section that it should be placed in.
1075 SectionKind Kind,
1076 const Constant *C) const {
1077 if (!TM)
1078 return false;
1079 if (TM->getCodeModel() == CodeModel::Large)
1080 return TM->getTargetTriple().getArch() == Triple::x86_64;
1081 if (Kind.isMergeableCString() && C) {
1082 assert(C->getType()->isSized());
1083 return TM->isLargeDataSize(DL.getTypeAllocSize(C->getType()));
1084 }
1085 // Globals generated by the compiler, e.g. constant pool entries, are always
1086 // small under the x86-64 medium code model.
1087 return false;
1088}
1089
1091 const DataLayout &DL, SectionKind Kind, const Constant *C,
1092 StringRef SectionSuffix) const {
1093 auto &Context = getContext();
1094 unsigned MergeableCstFlags = ELF::SHF_ALLOC;
1095 if (Kind.isMergeableConst() || Kind.isMergeableCString())
1096 MergeableCstFlags |= ELF::SHF_MERGE;
1097 bool IsLarge = isLargeConstant(DL, Kind, C);
1098 if (IsLarge)
1099 MergeableCstFlags |= ELF::SHF_X86_64_LARGE;
1100
1101 StringRef CstPrefix = IsLarge ? ".lrodata" : ".rodata";
1102 SmallString<32> SectionSuffixStr;
1103 if (!SectionSuffix.empty()) {
1104 SectionSuffixStr.push_back('.');
1105 SectionSuffixStr += SectionSuffix;
1106 SectionSuffixStr.push_back('.');
1107 }
1108
1109 if (Kind.isMergeableConst4())
1110 return Context.getELFSection(CstPrefix + ".cst4" + SectionSuffixStr,
1111 ELF::SHT_PROGBITS, MergeableCstFlags, 4);
1112 if (Kind.isMergeableConst8())
1113 return Context.getELFSection(CstPrefix + ".cst8" + SectionSuffixStr,
1114 ELF::SHT_PROGBITS, MergeableCstFlags, 8);
1115 if (Kind.isMergeableConst16())
1116 return Context.getELFSection(CstPrefix + ".cst16" + SectionSuffixStr,
1117 ELF::SHT_PROGBITS, MergeableCstFlags, 16);
1118 if (Kind.isMergeableConst32())
1119 return Context.getELFSection(CstPrefix + ".cst32" + SectionSuffixStr,
1120 ELF::SHT_PROGBITS, MergeableCstFlags, 32);
1121 if (Kind.isReadOnly())
1122 return Context.getELFSection(
1123 CstPrefix + SectionSuffixStr, ELF::SHT_PROGBITS,
1124 ELF::SHF_ALLOC | (IsLarge ? ELF::SHF_X86_64_LARGE : 0));
1125
1126 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
1127 return Context.getELFSection(".data.rel.ro" + SectionSuffixStr,
1130}
1131
1133 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
1134 const Function *F) const {
1135 return getSectionForConstantImpl(DL, Kind, C, "");
1136}
1137
1139 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
1140 const Function *F, StringRef SectionSuffix) const {
1141 if (SectionSuffix.empty())
1142 return getSectionForConstant(DL, Kind, C, Alignment, F);
1143
1144 return getSectionForConstantImpl(DL, Kind, C, SectionSuffix);
1145}
1146
1147/// Returns a unique section for the given machine basic block.
1149 const Function &F, const MachineBasicBlock &MBB,
1150 const TargetMachine &TM) const {
1151 assert(MBB.isBeginSection() && "Basic block does not start a section!");
1153
1154 // For cold sections use the .text.split. prefix along with the parent
1155 // function name. All cold blocks for the same function go to the same
1156 // section. Similarly all exception blocks are grouped by symbol name
1157 // under the .text.eh prefix. For regular sections, we either use a unique
1158 // name, or a unique ID for the section.
1159 SmallString<128> Name;
1160 StringRef FunctionSectionName = MBB.getParent()->getSection()->getName();
1161 if (FunctionSectionName == ".text" ||
1162 FunctionSectionName.starts_with(".text.")) {
1163 // Function is in a regular .text section.
1164 StringRef FunctionName = MBB.getParent()->getName();
1165 if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
1167 Name += FunctionName;
1168 } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
1169 Name += ".text.eh.";
1170 Name += FunctionName;
1171 } else {
1172 Name += FunctionSectionName;
1173 if (TM.getUniqueBasicBlockSectionNames()) {
1174 if (!Name.ends_with("."))
1175 Name += ".";
1176 Name += MBB.getSymbol()->getName();
1177 } else {
1178 UniqueID = NextUniqueID++;
1179 }
1180 }
1181 } else {
1182 // If the original function has a custom non-dot-text section, then emit
1183 // all basic block sections into that section too, each with a unique id.
1184 Name = FunctionSectionName;
1185 UniqueID = NextUniqueID++;
1186 }
1187
1188 unsigned Flags =
1189 static_cast<const MCSectionELF *>(MBB.getParent()->getSection())
1190 ->getFlags();
1191 std::string GroupName;
1192 if (F.hasComdat()) {
1193 Flags |= ELF::SHF_GROUP;
1194 GroupName = F.getComdat()->getName().str();
1195 }
1196 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
1197 0 /* Entry Size */, GroupName,
1198 F.hasComdat(), UniqueID, nullptr);
1199}
1200
1201static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
1202 bool IsCtor, unsigned Priority,
1203 const MCSymbol *KeySym) {
1204 std::string Name;
1205 unsigned Type;
1206 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1207 StringRef Comdat = KeySym ? KeySym->getName() : "";
1208
1209 if (KeySym)
1210 Flags |= ELF::SHF_GROUP;
1211
1212 if (UseInitArray) {
1213 if (IsCtor) {
1215 Name = ".init_array";
1216 } else {
1218 Name = ".fini_array";
1219 }
1220 if (Priority != 65535) {
1221 Name += '.';
1222 Name += utostr(Priority);
1223 }
1224 } else {
1225 // The default scheme is .ctor / .dtor, so we have to invert the priority
1226 // numbering.
1227 if (IsCtor)
1228 Name = ".ctors";
1229 else
1230 Name = ".dtors";
1231 if (Priority != 65535)
1232 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1234 }
1235
1236 return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
1237}
1238
1240 unsigned Priority, const MCSymbol *KeySym) const {
1241 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
1242 KeySym);
1243}
1244
1246 unsigned Priority, const MCSymbol *KeySym) const {
1247 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
1248 KeySym);
1249}
1250
1252 const MCSymbol *LHS, const MCSymbol *RHS, int64_t Addend,
1253 std::optional<int64_t> PCRelativeOffset) const {
1254 auto &Ctx = getContext();
1255 const MCExpr *Res;
1256 // Return a relocatable expression with the PLT specifier, %plt(GV) or
1257 // %plt(GV-RHS).
1258 if (PCRelativeOffset && PLTPCRelativeSpecifier) {
1259 Res = MCSymbolRefExpr::create(LHS, Ctx);
1260 // The current location is RHS plus *PCRelativeOffset. Compensate for it.
1261 Addend += *PCRelativeOffset;
1262 if (Addend)
1263 Res = MCBinaryExpr::createAdd(Res, MCConstantExpr::create(Addend, Ctx),
1264 Ctx);
1266 }
1267
1269 return nullptr;
1272 MCSymbolRefExpr::create(RHS, Ctx), Ctx);
1273 if (Addend)
1274 Res =
1275 MCBinaryExpr::createAdd(Res, MCConstantExpr::create(Addend, Ctx), Ctx);
1276 return Res;
1277}
1278
1279// Reference the PLT entry of a function, optionally with a subtrahend (`RHS`).
1281 const MCSymbol *LHS, const MCSymbol *RHS, int64_t Addend,
1282 std::optional<int64_t> PCRelativeOffset, const TargetMachine &TM) const {
1283 if (RHS)
1284 return lowerSymbolDifference(LHS, RHS, Addend, PCRelativeOffset);
1285
1286 // Only the legacy MCSymbolRefExpr::VariantKind approach is implemented.
1287 // Reference LHS@plt or LHS@plt - RHS.
1290 return nullptr;
1291}
1292
1294 // Use ".GCC.command.line" since this feature is to support clang's
1295 // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1296 // same name.
1297 return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1299}
1300
1301void
1303 UseInitArray = UseInitArray_;
1304 MCContext &Ctx = getContext();
1305 if (!UseInitArray) {
1306 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
1308
1309 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
1311 return;
1312 }
1313
1314 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
1316 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
1318}
1319
1320//===----------------------------------------------------------------------===//
1321// MachO
1322//===----------------------------------------------------------------------===//
1323
1327
1329 const TargetMachine &TM,
1330 const Module &M) {
1332 if (TM.getRelocationModel() == Reloc::Static) {
1333 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1335 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1337 } else {
1338 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1341 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1344 }
1345
1351}
1352
1354 unsigned Priority, const MCSymbol *KeySym) const {
1355 return StaticDtorSection;
1356 // In userspace, we lower global destructors via atexit(), but kernel/kext
1357 // environments do not provide this function so we still need to support the
1358 // legacy way here.
1359 // See the -disable-atexit-based-global-dtor-lowering CodeGen flag for more
1360 // context.
1361}
1362
1364 const Module &M) const {
1365 // Emit the linker options if present.
1367
1369
1370 unsigned VersionVal = 0;
1371 unsigned ImageInfoFlags = 0;
1372 StringRef SectionVal;
1373
1374 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
1376
1377 // The section is mandatory. If we don't have it, then we don't have GC info.
1378 if (SectionVal.empty())
1379 return;
1380
1381 StringRef Segment, Section;
1382 unsigned TAA = 0, StubSize = 0;
1383 bool TAAParsed;
1385 SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
1386 // If invalid, report the error with report_fatal_error.
1387 report_fatal_error("Invalid section specifier '" + Section +
1388 "': " + toString(std::move(E)) + ".");
1389 }
1390
1391 // Get the section.
1393 Segment, Section, TAA, StubSize, SectionKind::getData());
1394 Streamer.switchSection(S);
1395 Streamer.emitLabel(getContext().
1396 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
1397 Streamer.emitInt32(VersionVal);
1398 Streamer.emitInt32(ImageInfoFlags);
1399 Streamer.addBlankLine();
1400}
1401
1402MCSection *
1404 SectionKind Kind) const {
1405 auto [Segment, SecName] = Name.split(',');
1406 return getContext().getMachOSection(Segment, SecName, 0, Kind);
1407}
1408
1410 MCStreamer &Streamer, const Module &M) const {
1411 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1412 for (const auto *Option : LinkerOptions->operands()) {
1413 SmallVector<std::string, 4> StrOptions;
1414 for (const auto &Piece : cast<MDNode>(Option)->operands())
1415 StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
1416 Streamer.emitLinkerOptions(StrOptions);
1417 }
1418 }
1419}
1420
1421static void checkMachOComdat(const GlobalValue *GV) {
1422 const Comdat *C = GV->getComdat();
1423 if (!C)
1424 return;
1425
1426 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1427 "' cannot be lowered.");
1428}
1429
1431 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1432
1435
1436 // Parse the section specifier and create it if valid.
1437 StringRef Segment, Section;
1438 unsigned TAA = 0, StubSize = 0;
1439 bool TAAParsed;
1440
1441 checkMachOComdat(GO);
1442
1444 SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
1445 // If invalid, report the error with report_fatal_error.
1446 report_fatal_error("Global variable '" + GO->getName() +
1447 "' has an invalid section specifier '" +
1448 GO->getSection() + "': " + toString(std::move(E)) + ".");
1449 }
1450
1451 // Get the section.
1452 MCSectionMachO *S =
1453 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1454
1455 // If TAA wasn't set by ParseSectionSpecifier() above,
1456 // use the value returned by getMachOSection() as a default.
1457 if (!TAAParsed)
1458 TAA = S->getTypeAndAttributes();
1459
1460 // Okay, now that we got the section, verify that the TAA & StubSize agree.
1461 // If the user declared multiple globals with different section flags, we need
1462 // to reject it here.
1463 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1464 // If invalid, report the error with report_fatal_error.
1465 report_fatal_error("Global variable '" + GO->getName() +
1466 "' section type or attributes does not match previous"
1467 " section specifier");
1468 }
1469
1470 return S;
1471}
1472
1474 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1475 checkMachOComdat(GO);
1476
1477 // Handle thread local data.
1478 if (Kind.isThreadBSS()) return TLSBSSSection;
1479 if (Kind.isThreadData()) return TLSDataSection;
1480
1481 if (Kind.isText())
1483
1484 // If this is weak/linkonce, put this in a coalescable section, either in text
1485 // or data depending on if it is writable.
1486 if (GO->isWeakForLinker()) {
1487 if (Kind.isReadOnly())
1488 return ConstTextCoalSection;
1489 if (Kind.isReadOnlyWithRel())
1490 return ConstDataCoalSection;
1491 return DataCoalSection;
1492 }
1493
1494 // FIXME: Alignment check should be handled by section classifier.
1495 if (Kind.isMergeable1ByteCString() &&
1497 cast<GlobalVariable>(GO)) < Align(32))
1498 return CStringSection;
1499
1500 // Do not put 16-bit arrays in the UString section if they have an
1501 // externally visible label, this runs into issues with certain linker
1502 // versions.
1503 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
1505 cast<GlobalVariable>(GO)) < Align(32))
1506 return UStringSection;
1507
1508 // With MachO only variables whose corresponding symbol starts with 'l' or
1509 // 'L' can be merged, so we only try merging GVs with private linkage.
1510 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1511 if (Kind.isMergeableConst4())
1513 if (Kind.isMergeableConst8())
1515 if (Kind.isMergeableConst16())
1517 }
1518
1519 // Otherwise, if it is readonly, but not something we can specially optimize,
1520 // just drop it in .const.
1521 if (Kind.isReadOnly())
1522 return ReadOnlySection;
1523
1524 // If this is marked const, put it into a const section. But if the dynamic
1525 // linker needs to write to it, put it in the data segment.
1526 if (Kind.isReadOnlyWithRel())
1527 return ConstDataSection;
1528
1529 // Put zero initialized globals with strong external linkage in the
1530 // DATA, __common section with the .zerofill directive.
1531 if (Kind.isBSSExtern())
1532 return DataCommonSection;
1533
1534 // Put zero initialized globals with local linkage in __DATA,__bss directive
1535 // with the .zerofill directive (aka .lcomm).
1536 if (Kind.isBSSLocal())
1537 return DataBSSSection;
1538
1539 // Otherwise, just drop the variable in the normal data section.
1540 return DataSection;
1541}
1542
1544 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
1545 const Function *F) const {
1546 // If this constant requires a relocation, we have to put it in the data
1547 // segment, not in the text segment.
1548 if (Kind.isData() || Kind.isReadOnlyWithRel())
1549 return ConstDataSection;
1550
1551 if (Kind.isMergeableConst4())
1553 if (Kind.isMergeableConst8())
1555 if (Kind.isMergeableConst16())
1557 return ReadOnlySection; // .const
1558}
1559
1564
1566 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1567 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1568 // The mach-o version of this method defaults to returning a stub reference.
1569
1570 if (Encoding & DW_EH_PE_indirect) {
1571 MachineModuleInfoMachO &MachOMMI =
1573
1574 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1575
1576 // Add information about the stub reference to MachOMMI so that the stub
1577 // gets emitted by the asmprinter.
1578 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1579 if (!StubSym.getPointer()) {
1580 MCSymbol *Sym = TM.getSymbol(GV);
1582 }
1583
1586 Encoding & ~DW_EH_PE_indirect, Streamer);
1587 }
1588
1590 MMI, Streamer);
1591}
1592
1594 const GlobalValue *GV, const TargetMachine &TM,
1595 MachineModuleInfo *MMI) const {
1596 // The mach-o version of this method defaults to returning a stub reference.
1597 MachineModuleInfoMachO &MachOMMI =
1599
1600 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1601
1602 // Add information about the stub reference to MachOMMI so that the stub
1603 // gets emitted by the asmprinter.
1604 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1605 if (!StubSym.getPointer()) {
1606 MCSymbol *Sym = TM.getSymbol(GV);
1608 }
1609
1610 return SSym;
1611}
1612
1614 const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
1615 int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1616 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1617 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1618 // through a non_lazy_ptr stub instead. One advantage is that it allows the
1619 // computation of deltas to final external symbols. Example:
1620 //
1621 // _extgotequiv:
1622 // .long _extfoo
1623 //
1624 // _delta:
1625 // .long _extgotequiv-_delta
1626 //
1627 // is transformed to:
1628 //
1629 // _delta:
1630 // .long L_extfoo$non_lazy_ptr-(_delta+0)
1631 //
1632 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
1633 // L_extfoo$non_lazy_ptr:
1634 // .indirect_symbol _extfoo
1635 // .long 0
1636 //
1637 // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1638 // may point to both local (same translation unit) and global (other
1639 // translation units) symbols. Example:
1640 //
1641 // .section __DATA,__pointers,non_lazy_symbol_pointers
1642 // L1:
1643 // .indirect_symbol _myGlobal
1644 // .long 0
1645 // L2:
1646 // .indirect_symbol _myLocal
1647 // .long _myLocal
1648 //
1649 // If the symbol is local, instead of the symbol's index, the assembler
1650 // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1651 // Then the linker will notice the constant in the table and will look at the
1652 // content of the symbol.
1653 MachineModuleInfoMachO &MachOMMI =
1655 MCContext &Ctx = getContext();
1656
1657 // The offset must consider the original displacement from the base symbol
1658 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1659 Offset = -MV.getConstant();
1660 const MCSymbol *BaseSym = MV.getSubSym();
1661
1662 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1663 // non_lazy_ptr stubs.
1664 SmallString<128> Name;
1665 StringRef Suffix = "$non_lazy_ptr";
1667 Name += Sym->getName();
1668 Name += Suffix;
1669 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1670
1671 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1672
1673 if (!StubSym.getPointer())
1674 StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1675 !GV->hasLocalLinkage());
1676
1677 const MCExpr *BSymExpr = MCSymbolRefExpr::create(BaseSym, Ctx);
1678 const MCExpr *LHS = MCSymbolRefExpr::create(Stub, Ctx);
1679
1680 if (!Offset)
1681 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1682
1683 const MCExpr *RHS =
1685 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1686}
1687
1688static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1689 const MCSection &Section) {
1691 return true;
1692
1693 // FIXME: we should be able to use private labels for sections that can't be
1694 // dead-stripped (there's no issue with blocking atomization there), but `ld
1695 // -r` sometimes drops the no_dead_strip attribute from sections so for safety
1696 // we don't allow it.
1697 return false;
1698}
1699
1701 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1702 const TargetMachine &TM) const {
1703 bool CannotUsePrivateLabel = true;
1704 if (auto *GO = GV->getAliaseeObject()) {
1706 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1707 CannotUsePrivateLabel = !canUsePrivateLabel(TM.getMCAsmInfo(), *TheSection);
1708 }
1709 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1710}
1711
1712//===----------------------------------------------------------------------===//
1713// COFF
1714//===----------------------------------------------------------------------===//
1715
1716static unsigned
1718 unsigned Flags = 0;
1720
1721 if (K.isMetadata())
1722 Flags |=
1724 else if (K.isExclude())
1725 Flags |=
1727 else if (K.isText())
1728 Flags |=
1733 else if (K.isBSS())
1734 Flags |=
1738 else if (K.isThreadLocal())
1739 Flags |=
1743 else if (K.isReadOnly() || K.isReadOnlyWithRel())
1744 Flags |=
1747 else if (K.isWriteable())
1748 Flags |=
1752
1753 return Flags;
1754}
1755
1757 const Comdat *C = GV->getComdat();
1758 assert(C && "expected GV to have a Comdat!");
1759
1760 StringRef ComdatGVName = C->getName();
1761 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1762 if (!ComdatGV)
1763 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1764 "' does not exist.");
1765
1766 if (ComdatGV->getComdat() != C)
1767 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1768 "' is not a key for its COMDAT.");
1769
1770 return ComdatGV;
1771}
1772
1773static int getSelectionForCOFF(const GlobalValue *GV) {
1774 if (const Comdat *C = GV->getComdat()) {
1775 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1776 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1777 ComdatKey = GA->getAliaseeObject();
1778 if (ComdatKey == GV) {
1779 switch (C->getSelectionKind()) {
1780 case Comdat::Any:
1782 case Comdat::ExactMatch:
1784 case Comdat::Largest:
1788 case Comdat::SameSize:
1790 }
1791 } else {
1793 }
1794 }
1795 return 0;
1796}
1797
1799 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1801 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::COFF,
1802 /*AddSegmentInfo=*/false) ||
1803 Name == getInstrProfSectionName(IPSK_covfun, Triple::COFF,
1804 /*AddSegmentInfo=*/false) ||
1805 Name == getInstrProfSectionName(IPSK_covdata, Triple::COFF,
1806 /*AddSegmentInfo=*/false) ||
1807 Name == getInstrProfSectionName(IPSK_covname, Triple::COFF,
1808 /*AddSegmentInfo=*/false) ||
1809 Name == ".llvmbc" || Name == ".llvmcmd")
1810 Kind = SectionKind::getMetadata();
1811 int Selection = 0;
1812 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1813 StringRef COMDATSymName = "";
1814 if (GO->hasComdat()) {
1816 const GlobalValue *ComdatGV;
1818 ComdatGV = getComdatGVForCOFF(GO);
1819 else
1820 ComdatGV = GO;
1821
1822 if (!ComdatGV->hasPrivateLinkage()) {
1823 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1824 COMDATSymName = Sym->getName();
1825 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1826 } else {
1827 Selection = 0;
1828 }
1829 }
1830
1831 return getContext().getCOFFSection(Name, Characteristics, COMDATSymName,
1832 Selection);
1833}
1834
1836 if (Kind.isText())
1837 return ".text";
1838 if (Kind.isBSS())
1839 return ".bss";
1840 if (Kind.isThreadLocal())
1841 return ".tls$";
1842 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1843 return ".rdata";
1844 return ".data";
1845}
1846
1848 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1849 // If we have -ffunction-sections then we should emit the global value to a
1850 // uniqued section specifically for it.
1851 bool EmitUniquedSection;
1852 if (Kind.isText())
1853 EmitUniquedSection = TM.getFunctionSections();
1854 else
1855 EmitUniquedSection = TM.getDataSections();
1856
1857 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1859
1860 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1861
1862 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1864 if (!Selection)
1866 const GlobalValue *ComdatGV;
1867 if (GO->hasComdat())
1868 ComdatGV = getComdatGVForCOFF(GO);
1869 else
1870 ComdatGV = GO;
1871
1873 if (EmitUniquedSection)
1874 UniqueID = NextUniqueID++;
1875
1876 if (!ComdatGV->hasPrivateLinkage()) {
1877 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1878 StringRef COMDATSymName = Sym->getName();
1879
1880 if (const auto *F = dyn_cast<Function>(GO))
1881 if (std::optional<StringRef> Prefix = F->getSectionPrefix())
1882 raw_svector_ostream(Name) << '$' << *Prefix;
1883
1884 // Append "$symbol" to the section name *before* IR-level mangling is
1885 // applied when targetting mingw. This is what GCC does, and the ld.bfd
1886 // COFF linker will not properly handle comdats otherwise.
1887 if (getContext().getTargetTriple().isOSCygMing())
1888 raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1889
1890 return getContext().getCOFFSection(Name, Characteristics, COMDATSymName,
1892 } else {
1893 SmallString<256> TmpData;
1894 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1895 return getContext().getCOFFSection(Name, Characteristics, TmpData,
1897 }
1898 }
1899
1900 if (Kind.isText())
1901 return TextSection;
1902
1903 if (Kind.isThreadLocal())
1904 return TLSDataSection;
1905
1906 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1907 return ReadOnlySection;
1908
1909 // Note: we claim that common symbols are put in BSSSection, but they are
1910 // really emitted with the magic .comm directive, which creates a symbol table
1911 // entry but not a section.
1912 if (Kind.isBSS() || Kind.isCommon())
1913 return BSSSection;
1914
1915 return DataSection;
1916}
1917
1919 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1920 const TargetMachine &TM) const {
1921 bool CannotUsePrivateLabel = false;
1922 if (GV->hasPrivateLinkage() &&
1923 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1924 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1925 CannotUsePrivateLabel = true;
1926
1927 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1928}
1929
1931 const Function &F, const TargetMachine &TM) const {
1932 // If the function can be removed, produce a unique section so that
1933 // the table doesn't prevent the removal.
1934 const Comdat *C = F.getComdat();
1935 bool EmitUniqueSection = TM.getFunctionSections() || C;
1936 if (!EmitUniqueSection)
1937 return ReadOnlySection;
1938
1939 // FIXME: we should produce a symbol for F instead.
1940 if (F.hasPrivateLinkage())
1941 return ReadOnlySection;
1942
1943 MCSymbol *Sym = TM.getSymbol(&F);
1944 StringRef COMDATSymName = Sym->getName();
1945
1948 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1949 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1950 unsigned UniqueID = NextUniqueID++;
1951
1952 return getContext().getCOFFSection(SecName, Characteristics, COMDATSymName,
1954 UniqueID);
1955}
1956
1958 bool UsesLabelDifference, const Function &F) const {
1959 if (TM->getTargetTriple().getArch() == Triple::x86_64) {
1961 // We can always create relative relocations, so use another section
1962 // that can be marked non-executable.
1963 return false;
1964 }
1965 }
1967 UsesLabelDifference, F);
1968}
1969
1971 const Module &M) const {
1973
1974 unsigned Version = 0;
1975 unsigned Flags = 0;
1976 StringRef Section;
1977
1978 GetObjCImageInfo(M, Version, Flags, Section);
1979 if (!Section.empty()) {
1980 auto &C = getContext();
1981 auto *S = C.getCOFFSection(Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1983 Streamer.switchSection(S);
1984 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1985 Streamer.emitInt32(Version);
1986 Streamer.emitInt32(Flags);
1987 Streamer.addBlankLine();
1988 }
1989
1992 if (MCSymbol *Sym =
1993 static_cast<MCSectionCOFF *>(Streamer.getCurrentSectionOnly())
1994 ->getCOMDATSymbol())
1995 if (Sym->isUndefined()) {
1996 // COMDAT symbol must be external to perform deduplication.
1997 Streamer.emitSymbolAttribute(Sym, MCSA_Global);
1998 Streamer.emitLabel(Sym);
1999 }
2000 });
2001}
2002
2003MCSection *
2008
2010 const Module &M) const {
2011 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
2012 // Emit the linker options to the linker .drectve section. According to the
2013 // spec, this section is a space-separated string containing flags for
2014 // linker.
2016 Streamer.switchSection(Sec);
2017 for (const auto *Option : LinkerOptions->operands()) {
2018 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
2019 // Lead with a space for consistency with our dllexport implementation.
2020 std::string Directive(" ");
2021 Directive.append(std::string(cast<MDString>(Piece)->getString()));
2022 Streamer.emitBytes(Directive);
2023 }
2024 }
2025 }
2026
2027 // Emit /EXPORT: flags for each exported global as necessary.
2028 std::string Flags;
2029 for (const GlobalValue &GV : M.global_values()) {
2030 raw_string_ostream OS(Flags);
2031 emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
2032 getMangler());
2033 if (!Flags.empty()) {
2034 Streamer.switchSection(getDrectveSection());
2035 Streamer.emitBytes(Flags);
2036 }
2037 Flags.clear();
2038 }
2039
2040 // Emit /INCLUDE: flags for each used global as necessary.
2041 if (const auto *LU = M.getNamedGlobal("llvm.used")) {
2042 assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
2043 assert(isa<ArrayType>(LU->getValueType()) &&
2044 "expected llvm.used to be an array type");
2045 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
2046 for (const Value *Op : A->operands()) {
2047 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
2048 // Global symbols with internal or private linkage are not visible to
2049 // the linker, and thus would cause an error when the linker tried to
2050 // preserve the symbol due to the `/include:` directive.
2051 if (GV->hasLocalLinkage())
2052 continue;
2053
2054 raw_string_ostream OS(Flags);
2055 emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
2056 getMangler());
2057
2058 if (!Flags.empty()) {
2059 Streamer.switchSection(getDrectveSection());
2060 Streamer.emitBytes(Flags);
2061 }
2062 Flags.clear();
2063 }
2064 }
2065 }
2066}
2067
2069 const TargetMachine &TM,
2070 const Module &M) {
2072 const Triple &T = TM.getTargetTriple();
2073 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
2075 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
2078 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
2080 } else {
2081 StaticCtorSection = Ctx.getCOFFSection(
2084 StaticDtorSection = Ctx.getCOFFSection(
2087 }
2088}
2089
2091 const Triple &T, bool IsCtor,
2092 unsigned Priority,
2093 const MCSymbol *KeySym,
2095 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
2096 // If the priority is the default, use .CRT$XCU, possibly associative.
2097 if (Priority == 65535)
2098 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
2099
2100 // Otherwise, we need to compute a new section name. Low priorities should
2101 // run earlier. The linker will sort sections ASCII-betically, and we need a
2102 // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
2103 // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
2104 // low priorities need to sort before 'L', since the CRT uses that
2105 // internally, so we use ".CRT$XCA00001" for them. We have a contract with
2106 // the frontend that "init_seg(compiler)" corresponds to priority 200 and
2107 // "init_seg(lib)" corresponds to priority 400, and those respectively use
2108 // 'C' and 'L' without the priority suffix. Priorities between 200 and 400
2109 // use 'C' with the priority as a suffix.
2110 SmallString<24> Name;
2111 char LastLetter = 'T';
2112 bool AddPrioritySuffix = Priority != 200 && Priority != 400;
2113 if (Priority < 200)
2114 LastLetter = 'A';
2115 else if (Priority < 400)
2116 LastLetter = 'C';
2117 else if (Priority == 400)
2118 LastLetter = 'L';
2119 raw_svector_ostream OS(Name);
2120 OS << ".CRT$X" << (IsCtor ? "C" : "T") << LastLetter;
2121 if (AddPrioritySuffix)
2122 OS << format("%05u", Priority);
2123 MCSectionCOFF *Sec = Ctx.getCOFFSection(
2125 return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
2126 }
2127
2128 std::string Name = IsCtor ? ".ctors" : ".dtors";
2129 if (Priority != 65535)
2130 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
2131
2132 return Ctx.getAssociativeCOFFSection(
2133 Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
2136 KeySym, 0);
2137}
2138
2140 unsigned Priority, const MCSymbol *KeySym) const {
2142 getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
2143 static_cast<MCSectionCOFF *>(StaticCtorSection));
2144}
2145
2147 unsigned Priority, const MCSymbol *KeySym) const {
2149 getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
2150 static_cast<MCSectionCOFF *>(StaticDtorSection));
2151}
2152
2154 const GlobalValue *LHS, const GlobalValue *RHS, int64_t Addend,
2155 std::optional<int64_t> PCRelativeOffset, const TargetMachine &TM) const {
2156 // Our symbols should exist in address space zero, cowardly no-op if
2157 // otherwise.
2158 if (LHS->getType()->getPointerAddressSpace() != 0 ||
2159 RHS->getType()->getPointerAddressSpace() != 0)
2160 return nullptr;
2161
2162 const auto *GA = dyn_cast<GlobalAlias>(LHS);
2163 const GlobalObject *GO = GA ? dyn_cast_or_null<GlobalObject>(GA->getAliasee())
2165
2166 // Both ptrtoint instructions must wrap global objects:
2167 // - Only global variables that are dso_local are eligible for image relative
2168 // relocations.
2169 // - FIXME: Referring to a dllimport function produces an image-relative
2170 // relocation against the local import thunk rather than the canonical
2171 // function pointer, which lacks program-wide pointer identity. This is
2172 // sufficient for use cases like MSVC exception handling metadata (where the
2173 // function is only invoked), but is not theoretically sound in general.
2174 // We probably need something like dso_local_equivalent to explicitly
2175 // request a callable local entry point.
2176 // - The subtrahend refers to the special symbol __ImageBase, a
2177 // GlobalVariable. We expect __ImageBase to be a global variable without a
2178 // section, externally defined.
2179 //
2180 // It should look something like this: @__ImageBase = external constant i8
2181 if (!GO || (isa<GlobalVariable>(GO) && !TM.shouldAssumeDSOLocal(LHS)) ||
2182 GO->isThreadLocal() || !isa<GlobalVariable>(RHS) ||
2183 RHS->isThreadLocal() || RHS->getName() != "__ImageBase" ||
2184 !RHS->hasExternalLinkage() ||
2185 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
2186 return nullptr;
2187
2188 const MCExpr *Res = MCSymbolRefExpr::create(
2190 if (Addend != 0)
2192 Res, MCConstantExpr::create(Addend, getContext()), getContext());
2193 return Res;
2194}
2195
2196static std::string APIntToHexString(const APInt &AI) {
2197 unsigned Width = (AI.getBitWidth() / 8) * 2;
2198 std::string HexString = toString(AI, 16, /*Signed=*/false);
2199 llvm::transform(HexString, HexString.begin(), tolower);
2200 unsigned Size = HexString.size();
2201 assert(Width >= Size && "hex string is too large!");
2202 HexString.insert(HexString.begin(), Width - Size, '0');
2203
2204 return HexString;
2205}
2206
2207static std::string scalarConstantToHexString(const Constant *C) {
2208 Type *Ty = C->getType();
2209 if (isa<UndefValue>(C)) {
2210 return APIntToHexString(APInt::getZero(Ty->getPrimitiveSizeInBits()));
2211 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
2212 if (CFP->getType()->isFloatingPointTy())
2213 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
2214
2215 std::string HexString;
2216 unsigned NumElements =
2217 cast<FixedVectorType>(CFP->getType())->getNumElements();
2218 for (unsigned I = 0; I < NumElements; ++I)
2219 HexString += APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
2220 return HexString;
2221 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
2222 if (CI->getType()->isIntegerTy())
2223 return APIntToHexString(CI->getValue());
2224
2225 std::string HexString;
2226 unsigned NumElements =
2227 cast<FixedVectorType>(CI->getType())->getNumElements();
2228 for (unsigned I = 0; I < NumElements; ++I)
2229 HexString += APIntToHexString(CI->getValue());
2230 return HexString;
2231 } else {
2232 unsigned NumElements;
2233 if (auto *VTy = dyn_cast<VectorType>(Ty))
2234 NumElements = cast<FixedVectorType>(VTy)->getNumElements();
2235 else
2236 NumElements = Ty->getArrayNumElements();
2237 std::string HexString;
2238 for (int I = NumElements - 1, E = -1; I != E; --I)
2239 HexString += scalarConstantToHexString(C->getAggregateElement(I));
2240 return HexString;
2241 }
2242}
2243
2245 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
2246 const Function *F) const {
2247 if (Kind.isMergeableConst() && C &&
2248 getContext().getAsmInfo().hasCOFFComdatConstants()) {
2249 // This creates comdat sections with the given symbol name, but unless
2250 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
2251 // will be created with a null storage class, which makes GNU binutils
2252 // error out.
2253 const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
2256 std::string COMDATSymName;
2257 if (Kind.isMergeableConst4()) {
2258 if (Alignment <= 4) {
2259 COMDATSymName = "__real@" + scalarConstantToHexString(C);
2260 Alignment = Align(4);
2261 }
2262 } else if (Kind.isMergeableConst8()) {
2263 if (Alignment <= 8) {
2264 COMDATSymName = "__real@" + scalarConstantToHexString(C);
2265 Alignment = Align(8);
2266 }
2267 } else if (Kind.isMergeableConst16()) {
2268 // FIXME: These may not be appropriate for non-x86 architectures.
2269 if (Alignment <= 16) {
2270 COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
2271 Alignment = Align(16);
2272 }
2273 } else if (Kind.isMergeableConst32()) {
2274 if (Alignment <= 32) {
2275 COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
2276 Alignment = Align(32);
2277 }
2278 }
2279
2280 if (!COMDATSymName.empty())
2281 return getContext().getCOFFSection(".rdata", Characteristics,
2282 COMDATSymName,
2284 }
2285
2286 return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Alignment,
2287 F);
2288}
2289
2290//===----------------------------------------------------------------------===//
2291// Wasm
2292//===----------------------------------------------------------------------===//
2293
2294static const Comdat *getWasmComdat(const GlobalValue *GV) {
2295 const Comdat *C = GV->getComdat();
2296 if (!C)
2297 return nullptr;
2298
2299 if (C->getSelectionKind() != Comdat::Any)
2300 report_fatal_error("WebAssembly COMDATs only support "
2301 "SelectionKind::Any, '" + C->getName() + "' cannot be "
2302 "lowered.");
2303
2304 return C;
2305}
2306
2307static unsigned getWasmSectionFlags(SectionKind K, bool Retain) {
2308 unsigned Flags = 0;
2309
2310 if (K.isThreadLocal())
2311 Flags |= wasm::WASM_SEG_FLAG_TLS;
2312
2313 if (K.isMergeableCString())
2315
2316 if (Retain)
2318
2319 // TODO(sbc): Add suport for K.isMergeableConst()
2320
2321 return Flags;
2322}
2323
2325 const TargetMachine &TM,
2326 const Module &M) {
2328
2330 collectUsedGlobalVariables(M, Vec, false);
2331 for (GlobalValue *GV : Vec)
2332 if (auto *GO = dyn_cast<GlobalObject>(GV))
2333 Used.insert(GO);
2334}
2335
2336MCSection *
2338 SectionKind Kind) const {
2339 if (Kind.isMetadata())
2340 return getContext().getWasmSection(".custom_section." + Name, Kind);
2341 return getContext().getWasmSection(Name, Kind);
2342}
2343
2345 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2346 // We don't support explict section names for functions in the wasm object
2347 // format. Each function has to be in its own unique section.
2348 if (isa<Function>(GO)) {
2349 return SelectSectionForGlobal(GO, Kind, TM);
2350 }
2351
2352 StringRef Name = GO->getSection();
2353
2354 // Certain data sections we treat as named custom sections rather than
2355 // segments within the data section.
2356 // This could be avoided if all data segements (the wasm sense) were
2357 // represented as their own sections (in the llvm sense).
2358 // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
2359 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::Wasm,
2360 /*AddSegmentInfo=*/false) ||
2361 Name == getInstrProfSectionName(IPSK_covfun, Triple::Wasm,
2362 /*AddSegmentInfo=*/false) ||
2363 Name == ".llvmbc" || Name == ".llvmcmd")
2364 Kind = SectionKind::getMetadata();
2365
2366 StringRef Group = "";
2367 if (const Comdat *C = getWasmComdat(GO)) {
2368 Group = C->getName();
2369 }
2370
2371 unsigned Flags = getWasmSectionFlags(Kind, Used.count(GO));
2372 MCSectionWasm *Section = getContext().getWasmSection(Name, Kind, Flags, Group,
2374
2375 return Section;
2376}
2377
2378static MCSectionWasm *
2380 SectionKind Kind, Mangler &Mang,
2381 const TargetMachine &TM, bool EmitUniqueSection,
2382 unsigned *NextUniqueID, bool Retain) {
2383 StringRef Group = "";
2384 if (const Comdat *C = getWasmComdat(GO)) {
2385 Group = C->getName();
2386 }
2387
2388 bool UniqueSectionNames = TM.getUniqueSectionNames();
2389 SmallString<128> Name = getSectionPrefixForGlobal(Kind, /*IsLarge=*/false);
2390
2391 if (const auto *F = dyn_cast<Function>(GO)) {
2392 const auto &OptionalPrefix = F->getSectionPrefix();
2393 if (OptionalPrefix)
2394 raw_svector_ostream(Name) << '.' << *OptionalPrefix;
2395 }
2396
2397 if (EmitUniqueSection && UniqueSectionNames) {
2398 Name.push_back('.');
2399 TM.getNameWithPrefix(Name, GO, Mang, true);
2400 }
2402 if (EmitUniqueSection && !UniqueSectionNames) {
2403 UniqueID = *NextUniqueID;
2404 (*NextUniqueID)++;
2405 }
2406
2407 unsigned Flags = getWasmSectionFlags(Kind, Retain);
2408 return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
2409}
2410
2412 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2413
2414 if (Kind.isCommon())
2415 report_fatal_error("mergable sections not supported yet on wasm");
2416
2417 // If we have -ffunction-section or -fdata-section then we should emit the
2418 // global value to a uniqued section specifically for it.
2419 bool EmitUniqueSection = false;
2420 if (Kind.isText())
2421 EmitUniqueSection = TM.getFunctionSections();
2422 else
2423 EmitUniqueSection = TM.getDataSections();
2424 EmitUniqueSection |= GO->hasComdat();
2425 bool Retain = Used.count(GO);
2426 EmitUniqueSection |= Retain;
2427
2428 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2429 EmitUniqueSection, &NextUniqueID, Retain);
2430}
2431
2433 bool UsesLabelDifference, const Function &F) const {
2434 // We can always create relative relocations, so use another section
2435 // that can be marked non-executable.
2436 return false;
2437}
2438
2442
2443 // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2444 // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2446}
2447
2449 unsigned Priority, const MCSymbol *KeySym) const {
2450 return Priority == UINT16_MAX ?
2452 getContext().getWasmSection(".init_array." + utostr(Priority),
2454}
2455
2457 unsigned Priority, const MCSymbol *KeySym) const {
2458 report_fatal_error("@llvm.global_dtors should have been lowered already");
2459}
2460
2461//===----------------------------------------------------------------------===//
2462// XCOFF
2463//===----------------------------------------------------------------------===//
2465 const MachineFunction *MF) {
2466 if (!MF->getLandingPads().empty())
2467 return true;
2468
2469 const Function &F = MF->getFunction();
2470 if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2471 return false;
2472
2473 const GlobalValue *Per =
2474 dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
2475 assert(Per && "Personality routine is not a GlobalValue type.");
2477 return false;
2478
2479 return true;
2480}
2481
2483 const MachineFunction *MF) {
2484 const Function &F = MF->getFunction();
2485 if (!F.hasStackProtectorFnAttr())
2486 return false;
2487 // FIXME: check presence of canary word
2488 // There are cases that the stack protectors are not really inserted even if
2489 // the attributes are on.
2490 return true;
2491}
2492
2493MCSymbol *
2495 auto *EHInfoSym =
2496 static_cast<MCSymbolXCOFF *>(MF->getContext().getOrCreateSymbol(
2497 "__ehinfo." + Twine(MF->getFunctionNumber())));
2498 EHInfoSym->setEHInfo();
2499 return EHInfoSym;
2500}
2501
2502MCSymbol *
2504 const TargetMachine &TM) const {
2505 // We always use a qualname symbol for a GV that represents
2506 // a declaration, a function descriptor, or a common symbol. An IFunc is
2507 // lowered as a special trampoline function which has an entry point and a
2508 // descriptor.
2509 // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2510 // also return a qualname so that a label symbol could be avoided.
2511 // It is inherently ambiguous when the GO represents the address of a
2512 // function, as the GO could either represent a function descriptor or a
2513 // function entry point. We choose to always return a function descriptor
2514 // here.
2515 if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2516 if (GO->isDeclarationForLinker())
2517 return static_cast<const MCSectionXCOFF *>(
2519 ->getQualNameSymbol();
2520
2521 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
2522 if (GVar->hasAttribute("toc-data"))
2523 return static_cast<const MCSectionXCOFF *>(
2525 ->getQualNameSymbol();
2526
2527 if (isa<GlobalIFunc>(GO))
2528 return static_cast<const MCSectionXCOFF *>(
2530 ->getQualNameSymbol();
2531
2532 SectionKind GOKind = getKindForGlobal(GO, TM);
2533 if (GOKind.isText())
2534 return static_cast<const MCSectionXCOFF *>(
2536 ->getQualNameSymbol();
2537 if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
2538 GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
2539 return static_cast<const MCSectionXCOFF *>(
2540 SectionForGlobal(GO, GOKind, TM))
2541 ->getQualNameSymbol();
2542 }
2543
2544 // For all other cases, fall back to getSymbol to return the unqualified name.
2545 return nullptr;
2546}
2547
2549 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2550 if (!GO->hasSection())
2551 report_fatal_error("#pragma clang section is not yet supported");
2552
2554
2555 // Handle the XCOFF::TD case first, then deal with the rest.
2556 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2557 if (GVar->hasAttribute("toc-data"))
2558 return getContext().getXCOFFSection(
2559 SectionName, Kind,
2561 /* MultiSymbolsAllowed*/ true);
2562
2563 XCOFF::StorageMappingClass MappingClass;
2564 if (Kind.isText())
2565 MappingClass = XCOFF::XMC_PR;
2566 else if (Kind.isData() || Kind.isBSS())
2567 MappingClass = XCOFF::XMC_RW;
2568 else if (Kind.isReadOnlyWithRel())
2569 MappingClass =
2570 TM.Options.XCOFFReadOnlyPointers ? XCOFF::XMC_RO : XCOFF::XMC_RW;
2571 else if (Kind.isReadOnly())
2572 MappingClass = XCOFF::XMC_RO;
2573 else
2574 report_fatal_error("XCOFF other section types not yet implemented.");
2575
2576 return getContext().getXCOFFSection(
2577 SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
2578 /* MultiSymbolsAllowed*/ true);
2579}
2580
2582 const GlobalObject *GO, const TargetMachine &TM) const {
2584 "Tried to get ER section for a defined global.");
2585
2586 SmallString<128> Name;
2587 getNameWithPrefix(Name, GO, TM);
2588
2589 // AIX TLS local-dynamic does not need the external reference for the
2590 // "_$TLSML" symbol.
2592 GO->hasName() && GO->getName() == "_$TLSML") {
2593 return getContext().getXCOFFSection(
2594 Name, SectionKind::getData(),
2596 }
2597
2600 if (GO->isThreadLocal())
2601 SMC = XCOFF::XMC_UL;
2602
2603 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2604 if (GVar->hasAttribute("toc-data"))
2605 SMC = XCOFF::XMC_TD;
2606
2607 // Externals go into a csect of type ER.
2608 return getContext().getXCOFFSection(
2611}
2612
2614 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2615 // Handle the XCOFF::TD case first, then deal with the rest.
2616 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2617 if (GVar->hasAttribute("toc-data")) {
2618 SmallString<128> Name;
2619 getNameWithPrefix(Name, GO, TM);
2620 XCOFF::SymbolType symType =
2622 return getContext().getXCOFFSection(
2623 Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, symType),
2624 /* MultiSymbolsAllowed*/ true);
2625 }
2626
2627 // Common symbols go into a csect with matching name which will get mapped
2628 // into the .bss section.
2629 // Zero-initialized local TLS symbols go into a csect with matching name which
2630 // will get mapped into the .tbss section.
2631 if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
2632 SmallString<128> Name;
2633 getNameWithPrefix(Name, GO, TM);
2634 XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
2635 : Kind.isCommon() ? XCOFF::XMC_RW
2636 : XCOFF::XMC_UL;
2637 return getContext().getXCOFFSection(
2638 Name, Kind, XCOFF::CsectProperties(SMC, XCOFF::XTY_CM));
2639 }
2640
2641 if (Kind.isText()) {
2642 if (TM.getFunctionSections()) {
2643 return static_cast<const MCSymbolXCOFF *>(
2645 ->getRepresentedCsect();
2646 }
2647 return TextSection;
2648 }
2649
2650 if (TM.Options.XCOFFReadOnlyPointers && Kind.isReadOnlyWithRel()) {
2651 if (!TM.getDataSections())
2653 "ReadOnlyPointers is supported only if data sections is turned on");
2654
2655 SmallString<128> Name;
2656 getNameWithPrefix(Name, GO, TM);
2657 return getContext().getXCOFFSection(
2660 }
2661
2662 // For BSS kind, zero initialized data must be emitted to the .data section
2663 // because external linkage control sections that get mapped to the .bss
2664 // section will be linked as tentative definitions, which is only appropriate
2665 // for SectionKind::Common.
2666 if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2667 if (TM.getDataSections()) {
2668 SmallString<128> Name;
2669 getNameWithPrefix(Name, GO, TM);
2670 return getContext().getXCOFFSection(
2671 Name, SectionKind::getData(),
2673 }
2674 return DataSection;
2675 }
2676
2677 if (Kind.isReadOnly()) {
2678 if (TM.getDataSections()) {
2679 SmallString<128> Name;
2680 getNameWithPrefix(Name, GO, TM);
2681 return getContext().getXCOFFSection(
2684 }
2685 return ReadOnlySection;
2686 }
2687
2688 // External/weak TLS data and initialized local TLS data are not eligible
2689 // to be put into common csect. If data sections are enabled, thread
2690 // data are emitted into separate sections. Otherwise, thread data
2691 // are emitted into the .tdata section.
2692 if (Kind.isThreadLocal()) {
2693 if (TM.getDataSections()) {
2694 SmallString<128> Name;
2695 getNameWithPrefix(Name, GO, TM);
2696 return getContext().getXCOFFSection(
2698 }
2699 return TLSDataSection;
2700 }
2701
2702 report_fatal_error("XCOFF other section types not yet implemented.");
2703}
2704
2706 const Function &F, const TargetMachine &TM) const {
2707 assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2708
2709 if (!TM.getFunctionSections())
2710 return ReadOnlySection;
2711
2712 // If the function can be removed, produce a unique section so that
2713 // the table doesn't prevent the removal.
2714 SmallString<128> NameStr(".rodata.jmp..");
2715 getNameWithPrefix(NameStr, &F, TM);
2716 return getContext().getXCOFFSection(
2717 NameStr, SectionKind::getReadOnly(),
2719}
2720
2722 bool UsesLabelDifference, const Function &F) const {
2723 return false;
2724}
2725
2726/// Given a mergeable constant with the specified size and relocation
2727/// information, return a section that it should be placed in.
2729 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
2730 const Function *F) const {
2731 // TODO: Enable emiting constant pool to unique sections when we support it.
2732 if (Alignment > Align(16))
2733 report_fatal_error("Alignments greater than 16 not yet supported.");
2734
2735 if (Alignment == Align(8)) {
2736 assert(ReadOnly8Section && "Section should always be initialized.");
2737 return ReadOnly8Section;
2738 }
2739
2740 if (Alignment == Align(16)) {
2741 assert(ReadOnly16Section && "Section should always be initialized.");
2742 return ReadOnly16Section;
2743 }
2744
2745 return ReadOnlySection;
2746}
2747
2749 const TargetMachine &TgtM,
2750 const Module &M) {
2754 (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4
2757 LSDAEncoding = 0;
2759
2760 // AIX debug for thread local location is not ready. And for integrated as
2761 // mode, the relocatable address for the thread local variable will cause
2762 // linker error. So disable the location attribute generation for thread local
2763 // variables for now.
2764 // FIXME: when TLS debug on AIX is ready, remove this setting.
2766}
2767
2769 unsigned Priority, const MCSymbol *KeySym) const {
2770 report_fatal_error("no static constructor section on AIX");
2771}
2772
2774 unsigned Priority, const MCSymbol *KeySym) const {
2775 report_fatal_error("no static destructor section on AIX");
2776}
2777
2780 assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2781
2782 switch (GV->getLinkage()) {
2785 return XCOFF::C_HIDEXT;
2789 return XCOFF::C_EXT;
2795 return XCOFF::C_WEAKEXT;
2798 "There is no mapping that implements AppendingLinkage for XCOFF.");
2799 }
2800 llvm_unreachable("Unknown linkage type!");
2801}
2802
2804 const GlobalValue *Func, const TargetMachine &TM) const {
2805 assert((isa<Function>(Func) || isa<GlobalIFunc>(Func) ||
2806 (isa<GlobalAlias>(Func) &&
2808 cast<GlobalAlias>(Func)->getAliaseeObject()))) &&
2809 "Func must be a function or an alias which has a function as base "
2810 "object.");
2811
2812 SmallString<128> NameStr;
2813 NameStr.push_back('.');
2814 getNameWithPrefix(NameStr, Func, TM);
2815
2816 // When -function-sections is enabled and explicit section is not specified,
2817 // it's not necessary to emit function entry point label any more. We will use
2818 // function entry point csect instead. And for function delcarations, the
2819 // undefined symbols gets treated as csect with XTY_ER property.
2820 if (((TM.getFunctionSections() && !Func->hasSection()) ||
2821 Func->isDeclarationForLinker()) &&
2822 (isa<Function>(Func) || isa<GlobalIFunc>(Func))) {
2823 return getContext()
2825 NameStr, SectionKind::getText(),
2826 XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclarationForLinker()
2828 : XCOFF::XTY_SD))
2830 }
2831
2832 return getContext().getOrCreateSymbol(NameStr);
2833}
2834
2836 const GlobalObject *F, const TargetMachine &TM) const {
2838 "F must be a function or ifunc object.");
2839 SmallString<128> NameStr;
2840 getNameWithPrefix(NameStr, F, TM);
2841 return getContext().getXCOFFSection(
2842 NameStr, SectionKind::getData(),
2844}
2845
2847 const MCSymbol *Sym, const TargetMachine &TM) const {
2848 const XCOFF::StorageMappingClass SMC = [](const MCSymbol *Sym,
2849 const TargetMachine &TM) {
2850 auto *XSym = static_cast<const MCSymbolXCOFF *>(Sym);
2851
2852 // The "_$TLSML" symbol for TLS local-dynamic mode requires XMC_TC,
2853 // otherwise the AIX assembler will complain.
2854 if (XSym->getSymbolTableName() == "_$TLSML")
2855 return XCOFF::XMC_TC;
2856
2857 // Use large code model toc entries for ehinfo symbols as they are
2858 // never referenced directly. The runtime loads their TOC entry
2859 // addresses from the trace-back table.
2860 if (XSym->isEHInfo())
2861 return XCOFF::XMC_TE;
2862
2863 // If the symbol does not have a code model specified use the module value.
2864 if (!XSym->hasPerSymbolCodeModel())
2865 return TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE
2866 : XCOFF::XMC_TC;
2867
2868 return XSym->getPerSymbolCodeModel() == MCSymbolXCOFF::CM_Large
2870 : XCOFF::XMC_TC;
2871 }(Sym, TM);
2872
2873 return getContext().getXCOFFSection(
2874 static_cast<const MCSymbolXCOFF *>(Sym)->getSymbolTableName(),
2876}
2877
2879 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2880 auto *LSDA = static_cast<MCSectionXCOFF *>(LSDASection);
2881 if (TM.getFunctionSections()) {
2882 // If option -ffunction-sections is on, append the function name to the
2883 // name of the LSDA csect so that each function has its own LSDA csect.
2884 // This helps the linker to garbage-collect EH info of unused functions.
2885 SmallString<128> NameStr = LSDA->getName();
2886 raw_svector_ostream(NameStr) << '.' << F.getName();
2887 LSDA = getContext().getXCOFFSection(NameStr, LSDA->getKind(),
2888 LSDA->getCsectProp());
2889 }
2890 return LSDA;
2891}
2892//===----------------------------------------------------------------------===//
2893// GOFF
2894//===----------------------------------------------------------------------===//
2896
2898 const TargetMachine &TM,
2899 const Module &M) {
2901
2902 // Construct the default names for the root SD and the ADA PR symbol.
2903 StringRef FileName = sys::path::stem(M.getSourceFileName());
2904 if (FileName.size() > 1 && FileName.starts_with('<') &&
2905 FileName.ends_with('>'))
2906 FileName = FileName.substr(1, FileName.size() - 2);
2907 DefaultRootSDName = Twine(FileName).concat("#C").str();
2908 DefaultADAPRName = Twine(FileName).concat("#S").str();
2909 MCSectionGOFF *RootSD =
2910 static_cast<MCSectionGOFF *>(TextSection)->getParent();
2911 MCSectionGOFF *ADAPR = static_cast<MCSectionGOFF *>(ADASection);
2912 RootSD->setName(DefaultRootSDName);
2913 ADAPR->setName(DefaultADAPRName);
2914 // Initialize the label for the text section.
2915 MCSymbolGOFF *TextLD = static_cast<MCSymbolGOFF *>(
2916 getContext().getOrCreateSymbol(RootSD->getName()));
2919 TextLD->setExternal(false);
2920 TextLD->setWeak(false);
2921 TextLD->setADA(ADAPR);
2922 TextSection->setBeginSymbol(TextLD);
2923 // Initialize the label for the ADA section.
2924 MCSymbolGOFF *ADASym = static_cast<MCSymbolGOFF *>(
2926 ADAPR->setBeginSymbol(ADASym);
2927}
2928
2930 bool UsesLabelDifference, const Function &F) const {
2931 return true;
2932}
2933
2935 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
2936 const Function *F) const {
2937 return TextSection;
2938}
2939
2944
2946 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2947 std::string Name = "GCC_except." + F.getName().str();
2948
2949 MCSectionGOFF *SD = getContext().getGOFFSection(
2952 MCSectionGOFF *WSA = getContext().getGOFFSection(
2957 SD);
2958 WSA->setAlignment(Align(8));
2959 return getContext().getGOFFSection(
2960 SectionKind::getData(), Name,
2963 WSA);
2964}
2965
2967 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2968 auto *Symbol = TM.getSymbol(GO);
2969
2970 // Read-only data stays in the code section only if it is local: references
2971 // from other translation units are always parts in the WSA.
2972 if (Kind.isBSS() || Kind.isData() || Kind.isReadOnlyWithRel() ||
2973 (Kind.isReadOnly() && !GO->hasLocalLinkage())) {
2974 GOFF::ESDBindingScope PRBindingScope =
2975 GO->hasExternalLinkage()
2979 GOFF::ESDBindingScope SDBindingScope =
2982 MaybeAlign Alignment;
2983 if (auto *F = dyn_cast<Function>(GO))
2984 Alignment = F->getAlign();
2985 else if (auto *V = dyn_cast<GlobalVariable>(GO))
2986 Alignment = V->getAlign();
2987 MCSectionGOFF *SD = getContext().getGOFFSection(
2988 SectionKind::getMetadata(), Symbol->getName(),
2989 GOFF::SDAttr{GOFF::ESD_TA_Unspecified, SDBindingScope});
2990 MCSectionGOFF *ED = getContext().getGOFFSection(
2995 SD);
2996 ED->setAlignment(Alignment.value_or(llvm::Align(8)));
2997 MCSectionGOFF *PR = getContext().getGOFFSection(
2998 Kind, Symbol->getName(),
2999 GOFF::PRAttr{false, GOFF::ESD_EXE_DATA, GOFF::ESD_BST_Strong,
3000 GOFF::ESD_LT_XPLink, PRBindingScope, 0},
3001 ED);
3002 // The binder rejects zero-length PR sections. Mark the PR so the writer
3003 // inflates it to a valid length if needed.
3005 return PR;
3006 }
3007 return TextSection;
3008}
3009
3010MCSection *
3012 // XL C/C++ compilers on z/OS support priorities from min-int to max-int, with
3013 // sinit as source priority 0. For clang, sinit has source priority 65535.
3014 // For GOFF, the priority sortkey field is an unsigned value. So, we
3015 // add min-int to get sorting to work properly but also subtract the
3016 // clang sinit (65535) value so internally xl sinit and clang sinit have
3017 // the same unsigned GOFF priority sortkey field value (i.e. 0x80000000).
3018 static constexpr const uint32_t ClangDefaultSinitPriority = 65535;
3019 uint32_t Prio = Priority + (0x80000000 - ClangDefaultSinitPriority);
3020
3021 std::string Name(".xtor");
3022 if (Priority != ClangDefaultSinitPriority)
3023 Name = llvm::Twine(Name).concat(".").concat(llvm::utostr(Priority)).str();
3024
3025 MCContext &Ctx = getContext();
3026 MCSectionGOFF *SInit = Ctx.getGOFFSection(
3032 static_cast<const MCSectionGOFF *>(TextSection)->getParent());
3033
3034 MCSectionGOFF *Xtor = Ctx.getGOFFSection(
3035 SectionKind::getData(), Name,
3038 SInit);
3039 return Xtor;
3040}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
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 const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define LLVM_LIFETIME_BOUND
Definition Compiler.h:464
This file contains the declarations for the subclasses of Constant, which represent the different fla...
@ Default
This file contains constants used for implementing Dwarf debug support.
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...
This file contains the MCSymbolGOFF class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
This file contains the declarations for metadata subclasses.
#define T
const char * Msg
This file defines the SmallString class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
std::unique_ptr< MCStreamer > && Streamer
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 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 void GetObjCImageInfo(const Module &M, unsigned &Version, unsigned &Flags, StringRef &Section)
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 std::tuple< StringRef, bool, unsigned, unsigned, unsigned > getGlobalObjectInfo(const GlobalObject *GO, const TargetMachine &TM, StringRef SectionName, SectionKind Kind)
static unsigned getWasmSectionFlags(SectionKind K, bool Retain)
static void checkMachOComdat(const GlobalValue *GV)
static std::string APIntToHexString(const APInt &AI)
static unsigned getELFSectionFlags(SectionKind K, const Triple &T)
static SmallString< 128 > getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool UniqueSectionName, const MachineJumpTableEntry *JTE)
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 std::string scalarConstantToHexString(const Constant *C)
static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind)
static const Comdat * getELFComdat(const GlobalValue *GV)
static MCSectionELF * selectELFSectionForGlobal(MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol, const MachineJumpTableEntry *MJTE=nullptr)
Class for arbitrary precision integers.
Definition APInt.h:78
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
@ Largest
The linker will choose the largest COMDAT.
Definition Comdat.h:39
@ SameSize
The data referenced by the COMDAT must be the same size.
Definition Comdat.h:41
@ Any
The linker may choose any COMDAT.
Definition Comdat.h:37
@ NoDeduplicate
No deduplication is performed.
Definition Comdat.h:40
@ ExactMatch
The data referenced by the COMDAT must be the same.
Definition Comdat.h:38
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
StringRef getInternalSymbolPrefix() const
Definition DataLayout.h:308
LLVM_ABI Align getPreferredAlign(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
This is the base abstract class for diagnostic reporting in the backend.
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
StringRef getSection() const
Get the custom section of this global if it has one.
bool hasMetadata() const
Return true if this GlobalObject has any metadata attached to it.
bool hasComdat() const
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this GlobalObject.
bool hasSection() const
Check if this global has a custom object file section.
bool hasExternalLinkage() const
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
LinkageTypes getLinkage() const
bool hasLocalLinkage() const
bool hasDefaultVisibility() const
bool hasPrivateLinkage() const
LLVM_ABI const Comdat * getComdat() const
Definition Globals.cpp:274
ThreadLocalMode getThreadLocalMode() const
bool isDeclarationForLinker() const
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI const GlobalObject * getAliaseeObject() const
Definition Globals.cpp:521
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
bool hasCommonLinkage() const
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition GlobalValue.h:61
@ CommonLinkage
Tentative definitions.
Definition GlobalValue.h:63
@ InternalLinkage
Rename collisions when linking (static functions).
Definition GlobalValue.h:60
@ LinkOnceAnyLinkage
Keep one copy of function when linking (inline)
Definition GlobalValue.h:55
@ WeakODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:58
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
@ WeakAnyLinkage
Keep one copy of named function when linking (weak)
Definition GlobalValue.h:57
@ AppendingLinkage
Special purpose, only applies to global arrays.
Definition GlobalValue.h:59
@ AvailableExternallyLinkage
Available for inspection, not emission.
Definition GlobalValue.h:54
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition GlobalValue.h:62
@ LinkOnceODRLinkage
Same, but only replaced by something equivalent.
Definition GlobalValue.h:56
LLVM_ABI 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:67
static const MCBinaryExpr * createAdd(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:342
static const MCBinaryExpr * createSub(const MCExpr *LHS, const MCExpr *RHS, MCContext &Ctx)
Definition MCExpr.h:427
static LLVM_ABI const MCConstantExpr * create(int64_t Value, MCContext &Ctx, bool PrintInHex=false, unsigned SizeInBytes=0)
Definition MCExpr.cpp:212
Context object for machine code objects.
Definition MCContext.h:83
LLVM_ABI 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.
LLVM_ABI MCSectionCOFF * getCOFFSection(StringRef Section, unsigned Characteristics, StringRef COMDATSymName, int Selection, unsigned UniqueID=MCSection::NonUniqueID)
MCSectionWasm * getWasmSection(const Twine &Section, SectionKind K, unsigned Flags=0)
Definition MCContext.h:640
LLVM_ABI MCSectionELF * getELFNamedSection(const Twine &Prefix, const Twine &Suffix, unsigned Type, unsigned Flags, unsigned EntrySize=0)
Get a section with the provided group identifier.
MCSectionELF * getELFSection(const Twine &Section, unsigned Type, unsigned Flags)
Definition MCContext.h:552
LLVM_ABI MCSectionXCOFF * getXCOFFSection(StringRef Section, SectionKind K, std::optional< XCOFF::CsectProperties > CsectProp=std::nullopt, bool MultiSymbolsAllowed=false, std::optional< XCOFF::DwarfSectionSubtypeFlags > DwarfSubtypeFlags=std::nullopt)
LLVM_ABI MCSymbol * getOrCreateSymbol(const Twine &Name)
Lookup the symbol inside with the specified Name.
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 * TextSection
Section directive for standard text.
MCSection * TLSDataSection
Section directive for Thread Local data. ELF, MachO, COFF, and Wasm.
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 * SixteenByteConstantSection
MCSection * ReadOnlySection
Section that is readonly and can contain arbitrary initialized data.
MCSection * BSSSection
Section that is default initialized to zero.
MCSection * EightByteConstantSection
MCContext & getContext() const
MCSection * DataSection
Section directive for standard data.
This represents a section on Windows.
MCSymbol * getCOMDATSymbol() const
This represents a section on linux, lots of unix variants and some bare metal systems.
unsigned getFlags() const
void setName(StringRef SectionName)
MCSectionGOFF * getParent() const
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.
MCSymbolXCOFF * getQualNameSymbol() const
Instances of this class represent a uniqued identifier for a section in the current translation unit.
Definition MCSection.h:580
void setAlignment(Align Value)
Definition MCSection.h:665
static constexpr unsigned NonUniqueID
Definition MCSection.h:585
void setBeginSymbol(MCSymbol *Sym)
Definition MCSection.h:657
StringRef getName() const
Definition MCSection.h:650
static const MCSpecifierExpr * create(const MCExpr *Expr, Spec S, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.cpp:743
Streaming machine code generation interface.
Definition MCStreamer.h:222
void setWeak(bool Value=true)
void setExternal(bool Value) const
void setCodeData(GOFF::ESDExecutable Value)
void setADA(MCSectionGOFF *AssociatedDataArea)
void setLinkage(GOFF::ESDLinkageType Value)
static const MCSymbolRefExpr * create(const MCSymbol *Symbol, MCContext &Ctx, SMLoc Loc=SMLoc())
Definition MCExpr.h:213
void setEHInfo() const
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition MCSymbol.h:42
StringRef getName() const
getName - Get the symbol name.
Definition MCSymbol.h:188
int64_t getConstant() const
Definition MCValue.h:44
const MCSymbol * getSubSym() const
Definition MCValue.h:51
Metadata node.
Definition Metadata.h:1081
const MDOperand & getOperand(unsigned I) const
Definition Metadata.h:1437
Metadata * get() const
Definition Metadata.h:931
unsigned getFunctionNumber() const
getFunctionNumber - Return a unique ID for the current 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.
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.
LLVM_ABI 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:68
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
@ Require
Adds a requirement that another module flag be present and have a specified value after linking is pe...
Definition Module.h:134
const std::string & getSourceFileName() const
Get the module's original source file name.
Definition Module.h:310
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition Module.cpp:177
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition Module.h:325
A tuple of MDNodes.
Definition Metadata.h:1797
PointerTy getPointer() const
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition SectionKind.h:22
static SectionKind getThreadData()
static SectionKind getMetadata()
bool isThreadBSSLocal() const
static SectionKind getText()
bool isBSSLocal() const
static SectionKind getData()
bool isText() const
static SectionKind getBSS()
static SectionKind getThreadBSS()
static SectionKind getReadOnly()
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
bool starts_with(StringRef Prefix) const
starts_with - Check if this string starts with the given Prefix.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
static LLVM_ABI bool shouldPreserveHotDataSectionPrefix(const LLVMContext &C)
Return -preserve-hot-data-section-prefix.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition StringRef.h:597
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition StringRef.h:258
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
constexpr size_t size() const
Get the string size.
Definition StringRef.h:144
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition StringRef.h:270
void initialize(MCContext &Ctx, const TargetMachine &TM, const Module &M) override
This method must be called before any actual lowering is done.
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
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
const MCExpr * lowerRelativeReference(const GlobalValue *LHS, const GlobalValue *RHS, int64_t Addend, std::optional< int64_t > PCRelativeOffset, const TargetMachine &TM) const override
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
MCSection * getNamedSection(StringRef Name, SectionKind Kind) const override
Get a section with the given name and kind, using format-appropriate defaults for section flags.
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const override
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment, const Function *F) const override
Given a mergeable constant with the specified size and relocation information, return a section that ...
void emitModuleMetadata(MCStreamer &Streamer, const Module &M) const override
Emit Obj-C garbage collection and linker options.
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
void emitLinkerDirectives(MCStreamer &Streamer, const Module &M) const override
Process linker options metadata and emit platform-specific bits.
MCSection * getUniqueSectionForFunction(const Function &F, const TargetMachine &TM) const override
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
MCSection * getSectionForConstantImpl(const DataLayout &DL, SectionKind Kind, const Constant *C, StringRef SectionSuffix) const
void emitModuleMetadata(MCStreamer &Streamer, const 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 * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment, const Function *F) const override
Given a constant with the SectionKind, return a section that it should be placed in.
MCSection * getStaticDtorSection(unsigned Priority, const MCSymbol *KeySym) const override
void emitPersonalityValue(MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym, const MachineModuleInfo *MMI) const override
void emitLinkerDirectives(MCStreamer &Streamer, const Module &M) const override
Process linker options metadata and emit platform-specific bits.
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...
MCSection * SelectSectionForGlobal(const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const override
const MCExpr * lowerSymbolDifference(const MCSymbol *LHS, const MCSymbol *RHS, int64_t Addend, std::optional< int64_t > PCRelativeOffset) const
MCSection * getNamedSection(StringRef Name, SectionKind Kind) const override
Get a section with the given name and kind, using format-appropriate defaults for section flags.
const MCExpr * lowerDSOLocalEquivalent(const MCSymbol *LHS, const MCSymbol *RHS, int64_t Addend, std::optional< int64_t > PCRelativeOffset, 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
void initialize(MCContext &Ctx, const TargetMachine &TM, const Module &M) override
This method must be called before any actual lowering is done.
virtual void emitPersonalityValueImpl(MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym, const MachineModuleInfo *MMI) const
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
bool isLargeConstant(const DataLayout &DL, SectionKind Kind, const Constant *C) const
Given a mergeable constant with the specified size and relocation information, return a section that ...
MCSection * getSectionForMachineBasicBlock(const Function &F, const MachineBasicBlock &MBB, const TargetMachine &TM) const override
Returns a unique section for the given machine basic block.
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...
void initialize(MCContext &Ctx, const TargetMachine &TM, const Module &M) 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 Function *F) const override
Given a constant with the SectionKind, return a section that it should be placed in.
MCSection * getStaticXtorSection(unsigned Priority) const
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
bool shouldPutJumpTableInFunctionSection(bool UsesLabelDifference, const Function &F) const override
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, const TargetMachine &TM) const override
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment, const Function *F) const override
Given a constant with the SectionKind, return a section that it should be placed in.
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...
void emitModuleMetadata(MCStreamer &Streamer, const Module &M) const override
Emit the module flags that specify the garbage collection information.
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.
MCSection * getSectionForCommandLines() const override
If supported, return the section to use for the llvm.commandline metadata.
void emitLinkerDirectives(MCStreamer &Streamer, const Module &M) const override
Process linker options metadata and emit platform-specific bits.
void initialize(MCContext &Ctx, const TargetMachine &TM, const Module &M) override
This method must be called before any actual lowering is done.
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.
MCSection * getNamedSection(StringRef Name, SectionKind Kind) const override
Get a section with the given name and kind, using format-appropriate defaults for section flags.
MCSection * getStaticCtorSection(unsigned Priority, const MCSymbol *KeySym) const override
MCSection * getNamedSection(StringRef Name, SectionKind Kind) const override
Get a section with the given name and kind, using format-appropriate defaults for section flags.
void initialize(MCContext &Ctx, const TargetMachine &TM, const Module &M) override
This method must be called before any actual lowering is done.
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)
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.
void initialize(MCContext &Ctx, const TargetMachine &TM, const Module &M) override
This method must be called before any actual lowering is done.
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
MCSection * getSectionForJumpTable(const Function &F, const TargetMachine &TM) const override
static MCSymbol * getEHInfoTableSymbol(const MachineFunction *MF)
MCSection * getSectionForConstant(const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment, const Function *F) const override
Given a constant with the SectionKind, return a section that it should be placed in.
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)
MCSymbol * getTargetSymbol(const GlobalValue *GV, const TargetMachine &TM) const override
For functions, this will always return a function descriptor symbol.
MCSection * getSectionForFunctionDescriptor(const GlobalObject *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.
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.
void emitCGProfileMetadata(MCStreamer &Streamer, const Module &M) const
Emit Call Graph Profile metadata.
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
virtual void initialize(MCContext &ctx, const TargetMachine &TM, const Module &M)
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 Function *F) const
Given a constant with the SectionKind, return a section that it should be placed in.
static StringRef getCustomSectionName(const GlobalObject *GO, const TargetMachine &TM)
Return the section name specified by 'pragma clang section' or the section attribute.
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...
void emitPseudoProbeDescMetadata(MCStreamer &Streamer, const Module &M, std::function< void(MCStreamer &Streamer)> COMDATSymEmitter=nullptr) const
Emit pseudo_probe_desc metadata.
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.
const Triple & getTargetTriple() const
bool getSeparateNamedSections() const
bool getUniqueSectionNames() const
bool getEnableStaticDataPartitioning() const
TargetOptions Options
MCSymbol * getSymbol(const GlobalValue *GV) const
CodeModel::Model getCodeModel() const
Returns the code model.
bool isLargeGlobalValue(const GlobalValue *GV) const
void getNameWithPrefix(SmallVectorImpl< char > &Name, const GlobalValue *GV, Mangler &Mang, bool MayAlwaysUsePrivate=false) const
unsigned UseInitArray
UseInitArray - Use .init_array instead of .ctors for static constructors.
MCTargetOptions MCOptions
Machine level options.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
@ loongarch32
Definition Triple.h:65
@ loongarch64
Definition Triple.h:66
bool isOSSolaris() const
Definition Triple.h:755
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition Triple.h:515
bool isOSFreeBSD() const
Definition Triple.h:749
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
Twine concat(const Twine &Suffix) const
Definition Twine.h:497
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM Value Representation.
Definition Value.h:75
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
bool hasName() const
Definition Value.h:263
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:315
A raw_ostream that writes to an std::string.
A raw_ostream that writes to an SmallVector or SmallString.
CallInst * Retain
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:298
@ IMAGE_SCN_LNK_REMOVE
Definition COFF.h:308
@ IMAGE_SCN_CNT_CODE
Definition COFF.h:303
@ IMAGE_SCN_MEM_READ
Definition COFF.h:336
@ IMAGE_SCN_MEM_EXECUTE
Definition COFF.h:335
@ IMAGE_SCN_CNT_UNINITIALIZED_DATA
Definition COFF.h:305
@ IMAGE_SCN_MEM_DISCARDABLE
Definition COFF.h:331
@ IMAGE_SCN_MEM_16BIT
Definition COFF.h:312
@ IMAGE_SCN_CNT_INITIALIZED_DATA
Definition COFF.h:304
@ IMAGE_SCN_LNK_COMDAT
Definition COFF.h:309
@ IMAGE_SCN_MEM_WRITE
Definition COFF.h:337
@ IMAGE_COMDAT_SELECT_NODUPLICATES
Definition COFF.h:455
@ IMAGE_COMDAT_SELECT_LARGEST
Definition COFF.h:460
@ IMAGE_COMDAT_SELECT_SAME_SIZE
Definition COFF.h:457
@ IMAGE_COMDAT_SELECT_ASSOCIATIVE
Definition COFF.h:459
@ IMAGE_COMDAT_SELECT_EXACT_MATCH
Definition COFF.h:458
@ IMAGE_COMDAT_SELECT_ANY
Definition COFF.h:456
@ SHF_MERGE
Definition ELF.h:1073
@ SHF_STRINGS
Definition ELF.h:1076
@ SHF_AARCH64_PURECODE
Definition ELF.h:1165
@ SHF_EXCLUDE
Definition ELF.h:1101
@ SHF_ALLOC
Definition ELF.h:1067
@ SHF_LINK_ORDER
Definition ELF.h:1082
@ SHF_GROUP
Definition ELF.h:1089
@ SHF_SUNW_NODISCARD
Definition ELF.h:1108
@ SHF_X86_64_LARGE
Definition ELF.h:1130
@ SHF_GNU_RETAIN
Definition ELF.h:1098
@ SHF_WRITE
Definition ELF.h:1064
@ SHF_TLS
Definition ELF.h:1092
@ SHF_ARM_PURECODE
Definition ELF.h:1162
@ SHF_EXECINSTR
Definition ELF.h:1070
@ SHT_LLVM_DEPENDENT_LIBRARIES
Definition ELF.h:996
@ SHT_PROGBITS
Definition ELF.h:965
@ SHT_LLVM_LINKER_OPTIONS
Definition ELF.h:993
@ SHT_NOBITS
Definition ELF.h:972
@ SHT_LLVM_OFFLOADING
Definition ELF.h:1004
@ SHT_LLVM_LTO
Definition ELF.h:1005
@ SHT_PREINIT_ARRAY
Definition ELF.h:978
@ SHT_INIT_ARRAY
Definition ELF.h:976
@ SHT_NOTE
Definition ELF.h:971
@ SHT_FINI_ARRAY
Definition ELF.h:977
@ ESD_LB_Deferred
Definition GOFF.h:129
@ ESD_LB_Initial
Definition GOFF.h:128
constexpr StringLiteral CLASS_WSA
@ ESD_BA_Merge
Definition GOFF.h:99
@ ESD_TS_ByteOriented
Definition GOFF.h:92
@ ESD_EXE_CODE
Definition GOFF.h:112
@ ESD_EXE_DATA
Definition GOFF.h:111
@ ESD_RQ_0
Definition GOFF.h:69
@ ESD_ALIGN_Doubleword
Definition GOFF.h:148
ESDBindingScope
Definition GOFF.h:134
@ ESD_BSC_Library
Definition GOFF.h:138
@ ESD_BSC_Unspecified
Definition GOFF.h:135
@ ESD_BSC_ImportExport
Definition GOFF.h:139
@ ESD_BSC_Section
Definition GOFF.h:136
constexpr StringLiteral CLASS_SINIT
@ ESD_LT_XPLink
Definition GOFF.h:142
@ ESD_NS_Parts
Definition GOFF.h:65
@ ESD_TA_Unspecified
Definition GOFF.h:103
@ ESD_BST_Strong
Definition GOFF.h:123
@ ESD_RMODE_64
Definition GOFF.h:88
@ 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
@ C_WEAKEXT
Definition XCOFF.h:200
StorageMappingClass
Storage Mapping Class definitions.
Definition XCOFF.h:104
@ XMC_TE
Symbol mapped at the end of TOC.
Definition XCOFF.h:129
@ XMC_DS
Descriptor csect.
Definition XCOFF.h:122
@ XMC_RW
Read Write Data.
Definition XCOFF.h:118
@ XMC_TL
Initialized thread-local variable.
Definition XCOFF.h:127
@ XMC_RO
Read Only Constant.
Definition XCOFF.h:107
@ XMC_UA
Unclassified - Treated as Read Write.
Definition XCOFF.h:123
@ XMC_TD
Scalar data item in the TOC.
Definition XCOFF.h:121
@ XMC_UL
Uninitialized thread-local variable.
Definition XCOFF.h:128
@ XMC_PR
Program Code.
Definition XCOFF.h:106
@ XMC_BS
BSS class (uninitialized static internal)
Definition XCOFF.h:124
@ XMC_TC
General TOC item.
Definition XCOFF.h:120
@ XTY_CM
Common csect definition. For uninitialized storage.
Definition XCOFF.h:246
@ XTY_SD
Csect definition for initialized storage.
Definition XCOFF.h:243
@ XTY_ER
External reference.
Definition XCOFF.h:242
initializer< Ty > init(const Ty &Val)
Calculates the starting offsets for various sections within the .debug_names section.
Definition Dwarf.h:35
@ DW_EH_PE_datarel
Definition Dwarf.h:984
@ DW_EH_PE_pcrel
Definition Dwarf.h:982
@ DW_EH_PE_sdata4
Definition Dwarf.h:979
@ DW_EH_PE_sdata8
Definition Dwarf.h:980
@ DW_EH_PE_absptr
Definition Dwarf.h:971
@ DW_EH_PE_udata4
Definition Dwarf.h:975
@ DW_EH_PE_udata8
Definition Dwarf.h:976
@ DW_EH_PE_indirect
Definition Dwarf.h:987
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > dyn_extract(Y &&MD)
Extract a Value from Metadata, if any.
Definition Metadata.h:707
std::enable_if_t< detail::IsValidPointer< X, Y >::value, X * > extract(Y &&MD)
Extract a Value from Metadata.
Definition Metadata.h:679
LLVM_ABI StringRef stem(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get stem.
Definition Path.cpp:596
@ WASM_SEG_FLAG_RETAIN
Definition Wasm.h:242
@ WASM_SEG_FLAG_TLS
Definition Wasm.h:241
@ WASM_SEG_FLAG_STRINGS
Definition Wasm.h:240
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
std::string utostr(uint64_t X, bool isNeg=false)
bool isa_and_nonnull(const Y &Val)
Definition Casting.h:676
LLVM_ABI std::string getInstrProfSectionName(InstrProfSectKind IPSK, Triple::ObjectFormatType OF, bool AddSegmentInfo=true)
Return the name of the profile section corresponding to IPSK.
@ DK_Lowering
bool isNoOpWithoutInvoke(EHPersonality Pers)
Return true if this personality may be safely removed if there are no invoke instructions remaining i...
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
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:2042
std::string encodeBase64(InputBytes const &Bytes)
Definition Base64.h:24
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
LLVM_ABI void emitLinkerFlagsForUsedCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &T, Mangler &M)
Definition Mangler.cpp:278
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
DWARFExpression::Operation Op
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
LLVM_ABI void emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV, const Triple &TT, Mangler &Mangler)
Definition Mangler.cpp:214
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI cl::opt< std::string > BBSectionsColdTextPrefix
@ MCSA_Weak
.weak
@ MCSA_Global
.type _foo, @gnu_unique_object
@ MCSA_ELF_TypeObject
.type _foo, STT_OBJECT # aka @object
@ MCSA_Hidden
.hidden (ELF)
LLVM_ABI 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:966
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
LLVM_ABI static const MBBSectionID ExceptionSectionID
LLVM_ABI static const MBBSectionID ColdSectionID
MachineJumpTableEntry - One jump table in the jump table info.
MachineFunctionDataHotness Hotness
The hotness of MJTE is inferred from the hotness of the source basic block(s) that reference it.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111