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"
31#include "llvm/IR/Comdat.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
37#include "llvm/IR/Function.h"
38#include "llvm/IR/GlobalAlias.h"
40#include "llvm/IR/GlobalValue.h"
42#include "llvm/IR/Mangler.h"
43#include "llvm/IR/Metadata.h"
44#include "llvm/IR/Module.h"
45#include "llvm/IR/Type.h"
46#include "llvm/MC/MCAsmInfo.h"
48#include "llvm/MC/MCContext.h"
49#include "llvm/MC/MCExpr.h"
57#include "llvm/MC/MCStreamer.h"
58#include "llvm/MC/MCSymbol.h"
59#include "llvm/MC/MCSymbolELF.h"
61#include "llvm/MC/MCValue.h"
62#include "llvm/MC/SectionKind.h"
64#include "llvm/Support/Base64.h"
68#include "llvm/Support/Format.h"
69#include "llvm/Support/Path.h"
73#include <cassert>
74#include <string>
75
76using namespace llvm;
77using namespace dwarf;
78
80
82 "jumptable-in-function-section", cl::Hidden, cl::init(false),
83 cl::desc("Putting Jump Table in function section"));
84
85static void GetObjCImageInfo(const Module &M, unsigned &Version,
86 unsigned &Flags, StringRef &Section) {
88 M.getModuleFlagsMetadata(ModuleFlags);
89
90 for (const auto &MFE: ModuleFlags) {
91 // Ignore flags with 'Require' behaviour.
92 if (MFE.Behavior == Module::Require)
93 continue;
94
95 StringRef Key = MFE.Key->getString();
96 if (Key == "Objective-C Image Info Version") {
97 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
98 } else if (Key == "Objective-C Garbage Collection" ||
99 Key == "Objective-C GC Only" ||
100 Key == "Objective-C Is Simulated" ||
101 Key == "Objective-C Class Properties" ||
102 Key == "Objective-C Image Swift Version") {
103 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
104 } else if (Key == "Objective-C Image Info Section") {
105 Section = cast<MDString>(MFE.Val)->getString();
106 }
107 // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
108 // "Objective-C Garbage Collection".
109 else if (Key == "Swift ABI Version") {
110 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
111 } else if (Key == "Swift Major Version") {
112 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
113 } else if (Key == "Swift Minor Version") {
114 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
115 }
116 }
117}
118
119//===----------------------------------------------------------------------===//
120// ELF
121//===----------------------------------------------------------------------===//
122
124 const TargetMachine &TgtM,
125 const Module &M) {
127
128 const CodeModel::Model CM = TgtM.getCodeModel();
130
131 switch (TgtM.getTargetTriple().getArch()) {
132 case Triple::arm:
133 case Triple::armeb:
134 case Triple::thumb:
135 case Triple::thumbeb:
136 if (M.getExceptionModel() == ExceptionHandling::ARM)
137 break;
138 // Fallthrough if not using EHABI
139 [[fallthrough]];
140 case Triple::m68k:
141 case Triple::ppc:
142 case Triple::ppcle:
143 case Triple::x86:
156 break;
157 case Triple::x86_64: {
158 // The large EH encoding forces 64-bit-wide EH pointers regardless of the
159 // code model, so treat it like the Large code model when selecting
160 // encodings below.
161 const CodeModel::Model EHCM =
163 if (isPositionIndependent()) {
166 ((EHCM == CodeModel::Small || EHCM == CodeModel::Medium)
173 ((EHCM == CodeModel::Small || EHCM == CodeModel::Medium)
176 } else {
178 (EHCM == CodeModel::Small || EHCM == CodeModel::Medium)
185 }
186 break;
187 }
188 case Triple::hexagon:
192 if (isPositionIndependent()) {
196 }
197 break;
198 case Triple::aarch64:
201 // The small model guarantees static code/data size < 4GB, but not where it
202 // will be in memory. Most of these could end up >2GB away so even a signed
203 // pc-relative 32-bit address is insufficient, theoretically.
204 //
205 // Use DW_EH_PE_indirect even for -fno-pic to avoid copy relocations.
207 (TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32
212 break;
213 case Triple::lanai:
217 break;
218 case Triple::mips:
219 case Triple::mipsel:
220 case Triple::mips64:
221 case Triple::mips64el:
222 // MIPS uses indirect pointer to refer personality functions and types, so
223 // that the eh_frame section can be read-only. DW.ref.personality will be
224 // generated for relocation.
226 // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
227 // identify N64 from just a triple.
230
231 // FreeBSD must be explicit about the data size and using pcrel since it's
232 // assembler/linker won't do the automatic conversion that the Linux tools
233 // do.
237 }
238 break;
239 case Triple::ppc64:
240 case Triple::ppc64le:
246 break;
247 case Triple::sparcel:
248 case Triple::sparc:
249 if (isPositionIndependent()) {
255 } else {
259 }
261 break;
262 case Triple::riscv32:
263 case Triple::riscv64:
272 break;
273 case Triple::sparcv9:
275 if (isPositionIndependent()) {
280 } else {
283 }
284 break;
285 case Triple::systemz:
286 // All currently-defined code models guarantee that 4-byte PC-relative
287 // values will be in range.
288 if (isPositionIndependent()) {
294 } else {
298 }
299 break;
307 break;
308 default:
309 break;
310 }
311
313 collectUsedGlobalVariables(M, Vec, false);
314 for (GlobalValue *GV : Vec)
315 if (auto *GO = dyn_cast<GlobalObject>(GV))
316 Used.insert(GO);
317}
318
320 const Module &M) const {
321 auto &C = getContext();
322
324
325 if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
326 auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
328
329 Streamer.switchSection(S);
330
331 for (const auto *Operand : DependentLibraries->operands()) {
332 Streamer.emitBytes(
333 cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
334 Streamer.emitInt8(0);
335 }
336 }
337
339
340 if (NamedMDNode *LLVMStats = M.getNamedMetadata("llvm.stats")) {
341 // Emit the metadata for llvm statistics into .llvm_stats section, which is
342 // formatted as a list of key/value pair, the value is base64 encoded.
343 auto *S = C.getObjectFileInfo()->getLLVMStatsSection();
344 Streamer.switchSection(S);
345 for (const auto *Operand : LLVMStats->operands()) {
346 const auto *MD = cast<MDNode>(Operand);
347 assert(MD->getNumOperands() % 2 == 0 &&
348 ("Operand num should be even for a list of key/value pair"));
349 for (size_t I = 0; I < MD->getNumOperands(); I += 2) {
350 // Encode the key string size.
351 auto *Key = cast<MDString>(MD->getOperand(I));
352 Streamer.emitULEB128IntValue(Key->getString().size());
353 Streamer.emitBytes(Key->getString());
354 // Encode the value into a Base64 string.
355 std::string Value = encodeBase64(
356 Twine(mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1))
357 ->getZExtValue())
358 .str());
359 Streamer.emitULEB128IntValue(Value.size());
360 Streamer.emitBytes(Value);
361 }
362 }
363 }
364
365 unsigned Version = 0;
366 unsigned Flags = 0;
367 StringRef Section;
368
369 GetObjCImageInfo(M, Version, Flags, Section);
370 if (!Section.empty()) {
371 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
372 Streamer.switchSection(S);
373 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
374 Streamer.emitInt32(Version);
375 Streamer.emitInt32(Flags);
376 Streamer.addBlankLine();
377 }
378
380}
381
383 const Module &M) const {
384 auto &C = getContext();
385 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
386 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
388
389 Streamer.switchSection(S);
390
391 for (const auto *Operand : LinkerOptions->operands()) {
392 if (cast<MDNode>(Operand)->getNumOperands() != 2)
393 report_fatal_error("invalid llvm.linker.options");
394 for (const auto &Option : cast<MDNode>(Operand)->operands()) {
395 Streamer.emitBytes(cast<MDString>(Option)->getString());
396 Streamer.emitInt8(0);
397 }
398 }
399 }
400}
401
403 const GlobalValue *GV, const TargetMachine &TM,
404 MachineModuleInfo *MMI) const {
405 unsigned Encoding = getPersonalityEncoding();
406 if ((Encoding & 0x80) == DW_EH_PE_indirect)
407 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
408 TM.getSymbol(GV)->getName());
409 if ((Encoding & 0x70) == DW_EH_PE_absptr)
410 return TM.getSymbol(GV);
411 report_fatal_error("We do not support this DWARF encoding yet!");
412}
413
415 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym,
416 const MachineModuleInfo *MMI) const {
417 SmallString<64> NameData("DW.ref.");
418 NameData += Sym->getName();
419 auto *Label =
420 static_cast<MCSymbolELF *>(getContext().getOrCreateSymbol(NameData));
421 Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
422 Streamer.emitSymbolAttribute(Label, MCSA_Weak);
423 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
424 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
425 ELF::SHT_PROGBITS, Flags, 0);
426 unsigned Size = DL.getPointerSize();
427 Streamer.switchSection(Sec);
428 Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0));
429 Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
431 Streamer.emitELFSize(Label, E);
432 Streamer.emitLabel(Label);
433
435}
436
438 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym,
439 const MachineModuleInfo *MMI) const {
440 Streamer.emitSymbolValue(Sym, DL.getPointerSize());
441}
442
444 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
446 if (Encoding & DW_EH_PE_indirect) {
448
449 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
450
451 // Add information about the stub reference to ELFMMI so that the stub
452 // gets emitted by the asmprinter.
454 if (!StubSym.getPointer()) {
455 MCSymbol *Sym = TM.getSymbol(GV);
457 }
458
461 Encoding & ~DW_EH_PE_indirect, Streamer);
462 }
463
465 MMI, Streamer);
466}
467
469 // N.B.: The defaults used in here are not the same ones used in MC.
470 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
471 // both gas and MC will produce a section with no flags. Given
472 // section(".eh_frame") gcc will produce:
473 //
474 // .section .eh_frame,"a",@progbits
475
476 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
477 /*AddSegmentInfo=*/false) ||
478 Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
479 /*AddSegmentInfo=*/false) ||
480 Name == getInstrProfSectionName(IPSK_covdata, Triple::ELF,
481 /*AddSegmentInfo=*/false) ||
482 Name == getInstrProfSectionName(IPSK_covname, Triple::ELF,
483 /*AddSegmentInfo=*/false) ||
484 Name == ".llvmbc" || Name == ".llvmcmd")
486
487 if (!Name.starts_with(".")) return K;
488
489 // Default implementation based on some magic section names.
490 if (Name == ".bss" || Name.starts_with(".bss.") ||
491 Name.starts_with(".gnu.linkonce.b.") ||
492 Name.starts_with(".llvm.linkonce.b.") || Name == ".sbss" ||
493 Name.starts_with(".sbss.") || Name.starts_with(".gnu.linkonce.sb.") ||
494 Name.starts_with(".llvm.linkonce.sb."))
495 return SectionKind::getBSS();
496
497 if (Name == ".tdata" || Name.starts_with(".tdata.") ||
498 Name.starts_with(".gnu.linkonce.td.") ||
499 Name.starts_with(".llvm.linkonce.td."))
501
502 if (Name == ".tbss" || Name.starts_with(".tbss.") ||
503 Name.starts_with(".gnu.linkonce.tb.") ||
504 Name.starts_with(".llvm.linkonce.tb."))
506
507 return K;
508}
509
511 return SectionName.consume_front(Prefix) &&
512 (SectionName.empty() || SectionName[0] == '.');
513}
514
515static unsigned getELFSectionType(StringRef Name, SectionKind K) {
516 // Use SHT_NOTE for section whose name starts with ".note" to allow
517 // emitting ELF notes from C variable declaration.
518 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
519 if (Name.starts_with(".note"))
520 return ELF::SHT_NOTE;
521
522 if (hasPrefix(Name, ".init_array"))
523 return ELF::SHT_INIT_ARRAY;
524
525 if (hasPrefix(Name, ".fini_array"))
526 return ELF::SHT_FINI_ARRAY;
527
528 if (hasPrefix(Name, ".preinit_array"))
530
531 if (hasPrefix(Name, ".llvm.offloading"))
533 if (Name == ".llvm.lto")
534 return ELF::SHT_LLVM_LTO;
535
536 if (K.isBSS() || K.isThreadBSS())
537 return ELF::SHT_NOBITS;
538
539 return ELF::SHT_PROGBITS;
540}
541
542static unsigned getELFSectionFlags(SectionKind K, const Triple &T) {
543 unsigned Flags = 0;
544
545 if (!K.isMetadata() && !K.isExclude())
546 Flags |= ELF::SHF_ALLOC;
547
548 if (K.isExclude())
549 Flags |= ELF::SHF_EXCLUDE;
550
551 if (K.isText())
552 Flags |= ELF::SHF_EXECINSTR;
553
554 if (K.isExecuteOnly()) {
555 if (T.isAArch64())
557 else if (T.isARM() || T.isThumb())
558 Flags |= ELF::SHF_ARM_PURECODE;
559 }
560
561 if (K.isWriteable())
562 Flags |= ELF::SHF_WRITE;
563
564 if (K.isThreadLocal())
565 Flags |= ELF::SHF_TLS;
566
567 if (K.isMergeableCString() || K.isMergeableConst())
568 Flags |= ELF::SHF_MERGE;
569
570 if (K.isMergeableCString())
571 Flags |= ELF::SHF_STRINGS;
572
573 return Flags;
574}
575
576MCSection *
578 SectionKind Kind) const {
579 unsigned Type = getELFSectionType(Name, Kind);
580 unsigned Flags = getELFSectionFlags(Kind, getContext().getTargetTriple());
581 return getContext().getELFSection(Name, Type, Flags);
582}
583
584static const Comdat *getELFComdat(const GlobalValue *GV) {
585 const Comdat *C = GV->getComdat();
586 if (!C)
587 return nullptr;
588
589 if (C->getSelectionKind() != Comdat::Any &&
590 C->getSelectionKind() != Comdat::NoDeduplicate)
591 report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
592 "SelectionKind::NoDeduplicate, '" +
593 C->getName() + "' cannot be lowered.");
594
595 return C;
596}
597
599 const TargetMachine &TM) {
600 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
601 if (!MD)
602 return nullptr;
603
604 auto *VM = cast<ValueAsMetadata>(MD->getOperand(0).get());
605 auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
606 return OtherGV ? static_cast<const MCSymbolELF *>(TM.getSymbol(OtherGV))
607 : nullptr;
608}
609
610static unsigned getEntrySizeForKind(SectionKind Kind) {
611 if (Kind.isMergeable1ByteCString())
612 return 1;
613 else if (Kind.isMergeable2ByteCString())
614 return 2;
615 else if (Kind.isMergeable4ByteCString())
616 return 4;
617 else if (Kind.isMergeableConst4())
618 return 4;
619 else if (Kind.isMergeableConst8())
620 return 8;
621 else if (Kind.isMergeableConst16())
622 return 16;
623 else if (Kind.isMergeableConst32())
624 return 32;
625 else {
626 // We shouldn't have mergeable C strings or mergeable constants that we
627 // didn't handle above.
628 assert(!Kind.isMergeableCString() && "unknown string width");
629 assert(!Kind.isMergeableConst() && "unknown data width");
630 return 0;
631 }
632}
633
634/// Return the section prefix name used by options FunctionsSections and
635/// DataSections.
637 if (Kind.isText())
638 return IsLarge ? ".ltext" : ".text";
639 if (Kind.isReadOnly())
640 return IsLarge ? ".lrodata" : ".rodata";
641 if (Kind.isBSS())
642 return IsLarge ? ".lbss" : ".bss";
643 if (Kind.isThreadData())
644 return ".tdata";
645 if (Kind.isThreadBSS())
646 return ".tbss";
647 if (Kind.isData())
648 return IsLarge ? ".ldata" : ".data";
649 if (Kind.isReadOnlyWithRel())
650 return IsLarge ? ".ldata.rel.ro" : ".data.rel.ro";
651 llvm_unreachable("Unknown section kind");
652}
653
654static SmallString<128>
656 Mangler &Mang, const TargetMachine &TM,
657 bool UniqueSectionName,
658 const MachineJumpTableEntry *JTE) {
659 SmallString<128> Name =
661 unsigned EntrySize = getEntrySizeForKind(Kind);
662 if (Kind.isMergeableCString()) {
663 // We also need alignment here.
664 // FIXME: this is getting the alignment of the character, not the
665 // alignment of the global!
666 Align Alignment = GO->getDataLayout().getPreferredAlign(
668
669 Name += ".str";
670 Name += utostr(EntrySize);
671 Name += ".";
672 Name += utostr(Alignment.value());
673 } else if (Kind.isMergeableConst()) {
674 Name += ".cst";
675 Name += utostr(EntrySize);
676 }
677
678 bool HasPrefix = false;
679 SmallString<32> SectionPrefix;
680 if (const auto *F = dyn_cast<Function>(GO)) {
681 // Jump table hotness takes precedence over its enclosing function's hotness
682 // if it's known. The function's section prefix is used if jump table entry
683 // hotness is unknown.
684 if (JTE && JTE->Hotness != MachineFunctionDataHotness::Unknown) {
685 switch (JTE->Hotness) {
687 raw_svector_ostream(SectionPrefix) << ".unlikely";
688 break;
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") || PreserveHotDataSectionPrefix);
713 }
714
715 if (AddSectionPrefix) {
716 Name += SectionPrefix;
717 HasPrefix = true;
718 }
719 }
720
721 if (UniqueSectionName) {
722 Name.push_back('.');
723 TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
724 } else if (HasPrefix)
725 // For distinguishing between .text.${text-section-prefix}. (with trailing
726 // dot) and .text.${function-name}
727 Name.push_back('.');
728 return Name;
729}
730
731namespace {
732class LoweringDiagnosticInfo : public DiagnosticInfo {
733 const Twine &Msg;
734
735public:
736 LoweringDiagnosticInfo(const Twine &DiagMsg LLVM_LIFETIME_BOUND,
737 DiagnosticSeverity Severity = DS_Error)
738 : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
739 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
740};
741}
742
743/// Calculate an appropriate unique ID for a section, and update Flags,
744/// EntrySize and NextUniqueID where appropriate.
745static unsigned
747 SectionKind Kind, const TargetMachine &TM,
748 MCContext &Ctx, Mangler &Mang, unsigned &Flags,
749 unsigned &EntrySize, unsigned &NextUniqueID,
750 const bool Retain, const bool ForceUnique) {
751 // Increment uniqueID if we are forced to emit a unique section.
752 // This works perfectly fine with section attribute or pragma section as the
753 // sections with the same name are grouped together by the assembler.
754 if (ForceUnique)
755 return NextUniqueID++;
756
757 // A section can have at most one associated section. Put each global with
758 // MD_associated in a unique section.
759 const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
760 if (Associated) {
761 Flags |= ELF::SHF_LINK_ORDER;
762 return NextUniqueID++;
763 }
764
765 if (Retain) {
766 if (TM.getTargetTriple().isOSSolaris())
768 else if (Ctx.getAsmInfo().useIntegratedAssembler() ||
769 Ctx.getAsmInfo().binutilsIsAtLeast(2, 36))
770 Flags |= ELF::SHF_GNU_RETAIN;
771 return NextUniqueID++;
772 }
773
774 // If two symbols with differing sizes end up in the same mergeable section
775 // that section can be assigned an incorrect entry size. To avoid this we
776 // usually put symbols of the same size into distinct mergeable sections with
777 // the same name. Doing so relies on the ",unique ," assembly feature. This
778 // feature is not available until binutils version 2.35
779 // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
780 const bool SupportsUnique = Ctx.getAsmInfo().useIntegratedAssembler() ||
781 Ctx.getAsmInfo().binutilsIsAtLeast(2, 35);
782 if (!SupportsUnique) {
783 Flags &= ~ELF::SHF_MERGE;
784 EntrySize = 0;
786 }
787
788 const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
789 const bool SeenSectionNameBefore =
790 Ctx.isELFGenericMergeableSection(SectionName);
791 // If this is the first occurrence of this section name, treat it as the
792 // generic section
793 if (!SymbolMergeable && !SeenSectionNameBefore) {
795 return NextUniqueID++;
796 else
798 }
799
800 // Symbols must be placed into sections with compatible entry sizes. Generate
801 // unique sections for symbols that have not been assigned to compatible
802 // sections.
803 const auto PreviousID =
804 Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
805 if (PreviousID &&
806 (!TM.getSeparateNamedSections() || *PreviousID == MCSection::NonUniqueID))
807 return *PreviousID;
808
809 // If the user has specified the same section name as would be created
810 // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
811 // to unique the section as the entry size for this symbol will be
812 // compatible with implicitly created sections.
813 SmallString<128> ImplicitSectionNameStem =
814 getELFSectionNameForGlobal(GO, Kind, Mang, TM, false, /*MJTE=*/nullptr);
815 if (SymbolMergeable &&
816 Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) &&
817 SectionName.starts_with(ImplicitSectionNameStem))
819
820 // We have seen this section name before, but with different flags or entity
821 // size. Create a new unique ID.
822 return NextUniqueID++;
823}
824
825static std::tuple<StringRef, bool, unsigned, unsigned, unsigned>
828 StringRef Group = "";
829 bool IsComdat = false;
830 unsigned Flags = 0;
831 if (const Comdat *C = getELFComdat(GO)) {
832 Flags |= ELF::SHF_GROUP;
833 Group = C->getName();
834 IsComdat = C->getSelectionKind() == Comdat::Any;
835 }
836 if (TM.isLargeGlobalValue(GO))
837 Flags |= ELF::SHF_X86_64_LARGE;
838
839 unsigned Type, EntrySize;
840 if (MDNode *MD = GO->getMetadata(LLVMContext::MD_elf_section_properties)) {
841 Type = cast<ConstantAsMetadata>(MD->getOperand(0))
842 ->getValue()
843 ->getUniqueInteger()
844 .getZExtValue();
845 EntrySize = cast<ConstantAsMetadata>(MD->getOperand(1))
846 ->getValue()
847 ->getUniqueInteger()
848 .getZExtValue();
849 } else {
851 EntrySize = getEntrySizeForKind(Kind);
852 }
853
854 return {Group, IsComdat, Flags, Type, EntrySize};
855}
856
858 SectionKind Kind,
859 const TargetMachine &TM,
860 MCContext &Ctx, Mangler &Mang,
861 unsigned &NextUniqueID,
862 bool Retain, bool ForceUnique) {
865
866 // Infer section flags from the section name if we can.
868
869 unsigned Flags = getELFSectionFlags(Kind, GO->getParent()->getTargetTriple());
870 auto [Group, IsComdat, ExtraFlags, Type, EntrySize] =
871 getGlobalObjectInfo(GO, TM, SectionName, Kind);
872 Flags |= ExtraFlags;
873
875 GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
876 Retain, ForceUnique);
877
878 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
879 MCSectionELF *Section =
880 Ctx.getELFSection(SectionName, Type, Flags, EntrySize, Group, IsComdat,
881 UniqueID, LinkedToSym);
882 // Make sure that we did not get some other section with incompatible sh_link.
883 // This should not be possible due to UniqueID code above.
884 assert(Section->getLinkedToSymbol() == LinkedToSym &&
885 "Associated symbol mismatch between sections");
886
887 if (!(Ctx.getAsmInfo().useIntegratedAssembler() ||
888 Ctx.getAsmInfo().binutilsIsAtLeast(2, 35))) {
889 // If we are using GNU as before 2.35, then this symbol might have
890 // been placed in an incompatible mergeable section. Emit an error if this
891 // is the case to avoid creating broken output.
892 if ((Section->getFlags() & ELF::SHF_MERGE) &&
893 (Section->getEntrySize() != getEntrySizeForKind(Kind)))
894 GO->getContext().diagnose(LoweringDiagnosticInfo(
895 "Symbol '" + GO->getName() + "' from module '" +
896 (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
897 "' required a section with entry-size=" +
898 Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
899 SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
900 ": Explicit assignment by pragma or attribute of an incompatible "
901 "symbol to this section?"));
902 }
903
904 return Section;
905}
906
908 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
910 NextUniqueID, Used.count(GO),
911 /* ForceUnique = */false);
912}
913
915 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
916 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
917 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol,
918 const MachineJumpTableEntry *MJTE = nullptr) {
919 bool UniqueSectionName = false;
921 if (EmitUniqueSection) {
922 if (TM.getUniqueSectionNames()) {
923 UniqueSectionName = true;
924 } else {
925 UniqueID = *NextUniqueID;
926 (*NextUniqueID)++;
927 }
928 }
929 SmallString<128> Name =
930 getELFSectionNameForGlobal(GO, Kind, Mang, TM, UniqueSectionName, MJTE);
931
932 auto [Group, IsComdat, ExtraFlags, Type, EntrySize] =
933 getGlobalObjectInfo(GO, TM, Name, Kind);
934 Flags |= ExtraFlags;
935
936 // Use 0 as the unique ID for execute-only text.
937 if (Kind.isExecuteOnly())
938 UniqueID = 0;
939 return Ctx.getELFSection(Name, Type, Flags, EntrySize, Group, IsComdat,
940 UniqueID, AssociatedSymbol);
941}
942
944 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
945 const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
946 unsigned Flags, unsigned *NextUniqueID) {
947 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
948 if (LinkedToSym) {
949 EmitUniqueSection = true;
950 Flags |= ELF::SHF_LINK_ORDER;
951 }
952 if (Retain) {
953 if (TM.getTargetTriple().isOSSolaris()) {
954 EmitUniqueSection = true;
956 } else if (Ctx.getAsmInfo().useIntegratedAssembler() ||
957 Ctx.getAsmInfo().binutilsIsAtLeast(2, 36)) {
958 EmitUniqueSection = true;
959 Flags |= ELF::SHF_GNU_RETAIN;
960 }
961 }
962 if (GO->hasMetadata(LLVMContext::MD_elf_section_properties))
963 EmitUniqueSection = true;
964
966 Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
967 NextUniqueID, LinkedToSym);
968 assert(Section->getLinkedToSymbol() == LinkedToSym);
969 return Section;
970}
971
973 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
974 unsigned Flags = getELFSectionFlags(Kind, GO->getParent()->getTargetTriple());
975
976 // If we have -ffunction-section or -fdata-section then we should emit the
977 // global value to a uniqued section specifically for it.
978 bool EmitUniqueSection = false;
979 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
980 if (Kind.isText())
981 EmitUniqueSection = TM.getFunctionSections();
982 else
983 EmitUniqueSection = TM.getDataSections();
984 }
985 EmitUniqueSection |= GO->hasComdat();
986 return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
987 Used.count(GO), EmitUniqueSection, Flags,
988 &NextUniqueID);
989}
990
992 const Function &F, const TargetMachine &TM) const {
994 unsigned Flags = getELFSectionFlags(Kind, F.getParent()->getTargetTriple());
995 // If the function's section names is pre-determined via pragma or a
996 // section attribute, call selectExplicitSectionGlobal.
997 if (F.hasSection())
999 &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
1000 Used.count(&F), /* ForceUnique = */true);
1001
1003 getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
1004 /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
1005}
1006
1008 const Function &F, const TargetMachine &TM) const {
1009 return getSectionForJumpTable(F, TM, /*JTE=*/nullptr);
1010}
1011
1013 const Function &F, const TargetMachine &TM,
1014 const MachineJumpTableEntry *JTE) const {
1015 // If the function can be removed, produce a unique section so that
1016 // the table doesn't prevent the removal.
1017 const Comdat *C = F.getComdat();
1018 bool EmitUniqueSection = TM.getFunctionSections() || C;
1019 if (!EmitUniqueSection && !TM.getEnableStaticDataPartitioning())
1020 return ReadOnlySection;
1021
1023 getMangler(), TM, EmitUniqueSection,
1024 ELF::SHF_ALLOC, &NextUniqueID,
1025 /* AssociatedSymbol */ nullptr, JTE);
1026}
1027
1029 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
1030 // If neither COMDAT nor function sections, use the monolithic LSDA section.
1031 // Re-use this path if LSDASection is null as in the Arm EHABI.
1032 if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
1033 return LSDASection;
1034
1035 const auto *LSDA = static_cast<const MCSectionELF *>(LSDASection);
1036 unsigned Flags = LSDA->getFlags();
1037 const MCSymbolELF *LinkedToSym = nullptr;
1038 StringRef Group;
1039 bool IsComdat = false;
1040 if (const Comdat *C = getELFComdat(&F)) {
1041 Flags |= ELF::SHF_GROUP;
1042 Group = C->getName();
1043 IsComdat = C->getSelectionKind() == Comdat::Any;
1044 }
1045 // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
1046 // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
1047 if (TM.getFunctionSections() &&
1048 (getContext().getAsmInfo().useIntegratedAssembler() &&
1049 getContext().getAsmInfo().binutilsIsAtLeast(2, 36))) {
1050 Flags |= ELF::SHF_LINK_ORDER;
1051 LinkedToSym = static_cast<const MCSymbolELF *>(&FnSym);
1052 }
1053
1054 // Append the function name as the suffix like GCC, assuming
1055 // -funique-section-names applies to .gcc_except_table sections.
1056 return getContext().getELFSection(
1057 (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
1058 : LSDA->getName()),
1059 LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
1060 LinkedToSym);
1061}
1062
1064 bool UsesLabelDifference, const Function &F) const {
1065 // We can always create relative relocations, so use another section
1066 // that can be marked non-executable.
1067 return false;
1068}
1069
1070/// Given a mergeable constant with the specified size and relocation
1071/// information, return a section that it should be placed in.
1073 SectionKind Kind,
1074 const Constant *C) const {
1075 if (!TM)
1076 return false;
1077 if (TM->getCodeModel() == CodeModel::Large)
1078 return TM->getTargetTriple().getArch() == Triple::x86_64;
1079 if (Kind.isMergeableCString() && C) {
1080 assert(C->getType()->isSized());
1081 return TM->isLargeDataSize(DL.getTypeAllocSize(C->getType()));
1082 }
1083 // Globals generated by the compiler, e.g. constant pool entries, are always
1084 // small under the x86-64 medium code model.
1085 return false;
1086}
1087
1089 const DataLayout &DL, SectionKind Kind, const Constant *C,
1090 StringRef SectionSuffix) const {
1091 auto &Context = getContext();
1092 unsigned MergeableCstFlags = ELF::SHF_ALLOC;
1093 if (Kind.isMergeableConst() || Kind.isMergeableCString())
1094 MergeableCstFlags |= ELF::SHF_MERGE;
1095 bool IsLarge = isLargeConstant(DL, Kind, C);
1096 if (IsLarge)
1097 MergeableCstFlags |= ELF::SHF_X86_64_LARGE;
1098
1099 StringRef CstPrefix = IsLarge ? ".lrodata" : ".rodata";
1100 SmallString<32> SectionSuffixStr;
1101 if (!SectionSuffix.empty()) {
1102 SectionSuffixStr.push_back('.');
1103 SectionSuffixStr += SectionSuffix;
1104 SectionSuffixStr.push_back('.');
1105 }
1106
1107 if (Kind.isMergeableConst4())
1108 return Context.getELFSection(CstPrefix + ".cst4" + SectionSuffixStr,
1109 ELF::SHT_PROGBITS, MergeableCstFlags, 4);
1110 if (Kind.isMergeableConst8())
1111 return Context.getELFSection(CstPrefix + ".cst8" + SectionSuffixStr,
1112 ELF::SHT_PROGBITS, MergeableCstFlags, 8);
1113 if (Kind.isMergeableConst16())
1114 return Context.getELFSection(CstPrefix + ".cst16" + SectionSuffixStr,
1115 ELF::SHT_PROGBITS, MergeableCstFlags, 16);
1116 if (Kind.isMergeableConst32())
1117 return Context.getELFSection(CstPrefix + ".cst32" + SectionSuffixStr,
1118 ELF::SHT_PROGBITS, MergeableCstFlags, 32);
1119 if (Kind.isReadOnly())
1120 return Context.getELFSection(
1121 CstPrefix + SectionSuffixStr, ELF::SHT_PROGBITS,
1122 ELF::SHF_ALLOC | (IsLarge ? ELF::SHF_X86_64_LARGE : 0));
1123
1124 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
1125 return Context.getELFSection(".data.rel.ro" + SectionSuffixStr,
1128}
1129
1131 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
1132 const Function *F) const {
1133 return getSectionForConstantImpl(DL, Kind, C, "");
1134}
1135
1137 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
1138 const Function *F, StringRef SectionSuffix) const {
1139 if (SectionSuffix.empty())
1140 return getSectionForConstant(DL, Kind, C, Alignment, F);
1141
1142 return getSectionForConstantImpl(DL, Kind, C, SectionSuffix);
1143}
1144
1145/// Returns a unique section for the given machine basic block.
1147 const Function &F, const MachineBasicBlock &MBB,
1148 const TargetMachine &TM) const {
1149 assert(MBB.isBeginSection() && "Basic block does not start a section!");
1151
1152 // For cold sections use the .text.split. prefix along with the parent
1153 // function name. All cold blocks for the same function go to the same
1154 // section. Similarly all exception blocks are grouped by symbol name
1155 // under the .text.eh prefix. For regular sections, we either use a unique
1156 // name, or a unique ID for the section.
1157 SmallString<128> Name;
1158 StringRef FunctionSectionName = MBB.getParent()->getSection()->getName();
1159 if (FunctionSectionName == ".text" ||
1160 FunctionSectionName.starts_with(".text.")) {
1161 // Function is in a regular .text section.
1162 StringRef FunctionName = MBB.getParent()->getName();
1163 if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
1165 Name += FunctionName;
1166 } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
1167 Name += ".text.eh.";
1168 Name += FunctionName;
1169 } else {
1170 Name += FunctionSectionName;
1171 if (TM.getUniqueBasicBlockSectionNames()) {
1172 if (!Name.ends_with("."))
1173 Name += ".";
1174 Name += MBB.getSymbol()->getName();
1175 } else {
1176 UniqueID = NextUniqueID++;
1177 }
1178 }
1179 } else {
1180 // If the original function has a custom non-dot-text section, then emit
1181 // all basic block sections into that section too, each with a unique id.
1182 Name = FunctionSectionName;
1183 UniqueID = NextUniqueID++;
1184 }
1185
1186 unsigned Flags =
1187 static_cast<const MCSectionELF *>(MBB.getParent()->getSection())
1188 ->getFlags();
1189 std::string GroupName;
1190 if (F.hasComdat()) {
1191 Flags |= ELF::SHF_GROUP;
1192 GroupName = F.getComdat()->getName().str();
1193 }
1194 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
1195 0 /* Entry Size */, GroupName,
1196 F.hasComdat(), UniqueID, nullptr);
1197}
1198
1199static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
1200 bool IsCtor, unsigned Priority,
1201 const MCSymbol *KeySym) {
1202 std::string Name;
1203 unsigned Type;
1204 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1205 StringRef Comdat = KeySym ? KeySym->getName() : "";
1206
1207 if (KeySym)
1208 Flags |= ELF::SHF_GROUP;
1209
1210 if (UseInitArray) {
1211 if (IsCtor) {
1213 Name = ".init_array";
1214 } else {
1216 Name = ".fini_array";
1217 }
1218 if (Priority != 65535) {
1219 Name += '.';
1220 Name += utostr(Priority);
1221 }
1222 } else {
1223 // The default scheme is .ctor / .dtor, so we have to invert the priority
1224 // numbering.
1225 if (IsCtor)
1226 Name = ".ctors";
1227 else
1228 Name = ".dtors";
1229 if (Priority != 65535)
1230 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1232 }
1233
1234 return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
1235}
1236
1238 unsigned Priority, const MCSymbol *KeySym) const {
1239 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
1240 KeySym);
1241}
1242
1244 unsigned Priority, const MCSymbol *KeySym) const {
1245 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
1246 KeySym);
1247}
1248
1250 const MCSymbol *LHS, const MCSymbol *RHS, int64_t Addend,
1251 std::optional<int64_t> PCRelativeOffset) const {
1252 auto &Ctx = getContext();
1253 const MCExpr *Res;
1254 // Return a relocatable expression with the PLT specifier, %plt(GV) or
1255 // %plt(GV-RHS).
1256 if (PCRelativeOffset && PLTPCRelativeSpecifier) {
1257 Res = MCSymbolRefExpr::create(LHS, Ctx);
1258 // The current location is RHS plus *PCRelativeOffset. Compensate for it.
1259 Addend += *PCRelativeOffset;
1260 if (Addend)
1261 Res = MCBinaryExpr::createAdd(Res, MCConstantExpr::create(Addend, Ctx),
1262 Ctx);
1264 }
1265
1267 return nullptr;
1270 MCSymbolRefExpr::create(RHS, Ctx), Ctx);
1271 if (Addend)
1272 Res =
1273 MCBinaryExpr::createAdd(Res, MCConstantExpr::create(Addend, Ctx), Ctx);
1274 return Res;
1275}
1276
1277// Reference the PLT entry of a function, optionally with a subtrahend (`RHS`).
1279 const MCSymbol *LHS, const MCSymbol *RHS, int64_t Addend,
1280 std::optional<int64_t> PCRelativeOffset, const TargetMachine &TM) const {
1281 if (RHS)
1282 return lowerSymbolDifference(LHS, RHS, Addend, PCRelativeOffset);
1283
1284 // Only the legacy MCSymbolRefExpr::VariantKind approach is implemented.
1285 // Reference LHS@plt or LHS@plt - RHS.
1288 return nullptr;
1289}
1290
1292 // Use ".GCC.command.line" since this feature is to support clang's
1293 // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1294 // same name.
1295 return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1297}
1298
1299void
1301 UseInitArray = UseInitArray_;
1302 MCContext &Ctx = getContext();
1303 if (!UseInitArray) {
1304 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
1306
1307 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
1309 return;
1310 }
1311
1312 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
1314 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
1316}
1317
1318//===----------------------------------------------------------------------===//
1319// MachO
1320//===----------------------------------------------------------------------===//
1321
1325
1327 const TargetMachine &TM,
1328 const Module &M) {
1330 if (TM.getRelocationModel() == Reloc::Static) {
1331 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1333 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1335 } else {
1336 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1339 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1342 }
1343
1349}
1350
1352 unsigned Priority, const MCSymbol *KeySym) const {
1353 return StaticDtorSection;
1354 // In userspace, we lower global destructors via atexit(), but kernel/kext
1355 // environments do not provide this function so we still need to support the
1356 // legacy way here.
1357 // See the -disable-atexit-based-global-dtor-lowering CodeGen flag for more
1358 // context.
1359}
1360
1362 const Module &M) const {
1363 // Emit the linker options if present.
1365
1367
1368 unsigned VersionVal = 0;
1369 unsigned ImageInfoFlags = 0;
1370 StringRef SectionVal;
1371
1372 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
1374
1375 // The section is mandatory. If we don't have it, then we don't have GC info.
1376 if (SectionVal.empty())
1377 return;
1378
1379 StringRef Segment, Section;
1380 unsigned TAA = 0, StubSize = 0;
1381 bool TAAParsed;
1383 SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
1384 // If invalid, report the error with report_fatal_error.
1385 report_fatal_error("Invalid section specifier '" + Section +
1386 "': " + toString(std::move(E)) + ".");
1387 }
1388
1389 // Get the section.
1391 Segment, Section, TAA, StubSize, SectionKind::getData());
1392 Streamer.switchSection(S);
1393 Streamer.emitLabel(getContext().
1394 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
1395 Streamer.emitInt32(VersionVal);
1396 Streamer.emitInt32(ImageInfoFlags);
1397 Streamer.addBlankLine();
1398}
1399
1400MCSection *
1402 SectionKind Kind) const {
1403 auto [Segment, SecName] = Name.split(',');
1404 return getContext().getMachOSection(Segment, SecName, 0, Kind);
1405}
1406
1408 MCStreamer &Streamer, const Module &M) const {
1409 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1410 for (const auto *Option : LinkerOptions->operands()) {
1411 SmallVector<std::string, 4> StrOptions;
1412 for (const auto &Piece : cast<MDNode>(Option)->operands())
1413 StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
1414 Streamer.emitLinkerOptions(StrOptions);
1415 }
1416 }
1417}
1418
1419static void checkMachOComdat(const GlobalValue *GV) {
1420 const Comdat *C = GV->getComdat();
1421 if (!C)
1422 return;
1423
1424 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1425 "' cannot be lowered.");
1426}
1427
1429 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1430
1433
1434 // Parse the section specifier and create it if valid.
1435 StringRef Segment, Section;
1436 unsigned TAA = 0, StubSize = 0;
1437 bool TAAParsed;
1438
1439 checkMachOComdat(GO);
1440
1442 SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
1443 // If invalid, report the error with report_fatal_error.
1444 report_fatal_error("Global variable '" + GO->getName() +
1445 "' has an invalid section specifier '" +
1446 GO->getSection() + "': " + toString(std::move(E)) + ".");
1447 }
1448
1449 // Get the section.
1450 MCSectionMachO *S =
1451 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1452
1453 // If TAA wasn't set by ParseSectionSpecifier() above,
1454 // use the value returned by getMachOSection() as a default.
1455 if (!TAAParsed)
1456 TAA = S->getTypeAndAttributes();
1457
1458 // Okay, now that we got the section, verify that the TAA & StubSize agree.
1459 // If the user declared multiple globals with different section flags, we need
1460 // to reject it here.
1461 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1462 // If invalid, report the error with report_fatal_error.
1463 report_fatal_error("Global variable '" + GO->getName() +
1464 "' section type or attributes does not match previous"
1465 " section specifier");
1466 }
1467
1468 return S;
1469}
1470
1472 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1473 checkMachOComdat(GO);
1474
1475 // Handle thread local data.
1476 if (Kind.isThreadBSS()) return TLSBSSSection;
1477 if (Kind.isThreadData()) return TLSDataSection;
1478
1479 if (Kind.isText())
1481
1482 // If this is weak/linkonce, put this in a coalescable section, either in text
1483 // or data depending on if it is writable.
1484 if (GO->isWeakForLinker()) {
1485 if (Kind.isReadOnly())
1486 return ConstTextCoalSection;
1487 if (Kind.isReadOnlyWithRel())
1488 return ConstDataCoalSection;
1489 return DataCoalSection;
1490 }
1491
1492 // FIXME: Alignment check should be handled by section classifier.
1493 if (Kind.isMergeable1ByteCString() &&
1495 cast<GlobalVariable>(GO)) < Align(32))
1496 return CStringSection;
1497
1498 // Do not put 16-bit arrays in the UString section if they have an
1499 // externally visible label, this runs into issues with certain linker
1500 // versions.
1501 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
1503 cast<GlobalVariable>(GO)) < Align(32))
1504 return UStringSection;
1505
1506 // With MachO only variables whose corresponding symbol starts with 'l' or
1507 // 'L' can be merged, so we only try merging GVs with private linkage.
1508 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1509 if (Kind.isMergeableConst4())
1511 if (Kind.isMergeableConst8())
1513 if (Kind.isMergeableConst16())
1515 }
1516
1517 // Otherwise, if it is readonly, but not something we can specially optimize,
1518 // just drop it in .const.
1519 if (Kind.isReadOnly())
1520 return ReadOnlySection;
1521
1522 // If this is marked const, put it into a const section. But if the dynamic
1523 // linker needs to write to it, put it in the data segment.
1524 if (Kind.isReadOnlyWithRel())
1525 return ConstDataSection;
1526
1527 // Put zero initialized globals with strong external linkage in the
1528 // DATA, __common section with the .zerofill directive.
1529 if (Kind.isBSSExtern())
1530 return DataCommonSection;
1531
1532 // Put zero initialized globals with local linkage in __DATA,__bss directive
1533 // with the .zerofill directive (aka .lcomm).
1534 if (Kind.isBSSLocal())
1535 return DataBSSSection;
1536
1537 // Otherwise, just drop the variable in the normal data section.
1538 return DataSection;
1539}
1540
1542 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
1543 const Function *F) const {
1544 // If this constant requires a relocation, we have to put it in the data
1545 // segment, not in the text segment.
1546 if (Kind.isData() || Kind.isReadOnlyWithRel())
1547 return ConstDataSection;
1548
1549 if (Kind.isMergeableConst4())
1551 if (Kind.isMergeableConst8())
1553 if (Kind.isMergeableConst16())
1555 return ReadOnlySection; // .const
1556}
1557
1562
1564 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1565 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1566 // The mach-o version of this method defaults to returning a stub reference.
1567
1568 if (Encoding & DW_EH_PE_indirect) {
1569 MachineModuleInfoMachO &MachOMMI =
1571
1572 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1573
1574 // Add information about the stub reference to MachOMMI so that the stub
1575 // gets emitted by the asmprinter.
1576 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1577 if (!StubSym.getPointer()) {
1578 MCSymbol *Sym = TM.getSymbol(GV);
1580 }
1581
1584 Encoding & ~DW_EH_PE_indirect, Streamer);
1585 }
1586
1588 MMI, Streamer);
1589}
1590
1592 const GlobalValue *GV, const TargetMachine &TM,
1593 MachineModuleInfo *MMI) const {
1594 // The mach-o version of this method defaults to returning a stub reference.
1595 MachineModuleInfoMachO &MachOMMI =
1597
1598 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1599
1600 // Add information about the stub reference to MachOMMI so that the stub
1601 // gets emitted by the asmprinter.
1602 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1603 if (!StubSym.getPointer()) {
1604 MCSymbol *Sym = TM.getSymbol(GV);
1606 }
1607
1608 return SSym;
1609}
1610
1612 const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
1613 int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1614 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1615 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1616 // through a non_lazy_ptr stub instead. One advantage is that it allows the
1617 // computation of deltas to final external symbols. Example:
1618 //
1619 // _extgotequiv:
1620 // .long _extfoo
1621 //
1622 // _delta:
1623 // .long _extgotequiv-_delta
1624 //
1625 // is transformed to:
1626 //
1627 // _delta:
1628 // .long L_extfoo$non_lazy_ptr-(_delta+0)
1629 //
1630 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
1631 // L_extfoo$non_lazy_ptr:
1632 // .indirect_symbol _extfoo
1633 // .long 0
1634 //
1635 // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1636 // may point to both local (same translation unit) and global (other
1637 // translation units) symbols. Example:
1638 //
1639 // .section __DATA,__pointers,non_lazy_symbol_pointers
1640 // L1:
1641 // .indirect_symbol _myGlobal
1642 // .long 0
1643 // L2:
1644 // .indirect_symbol _myLocal
1645 // .long _myLocal
1646 //
1647 // If the symbol is local, instead of the symbol's index, the assembler
1648 // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1649 // Then the linker will notice the constant in the table and will look at the
1650 // content of the symbol.
1651 MachineModuleInfoMachO &MachOMMI =
1653 MCContext &Ctx = getContext();
1654
1655 // The offset must consider the original displacement from the base symbol
1656 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1657 Offset = -MV.getConstant();
1658 const MCSymbol *BaseSym = MV.getSubSym();
1659
1660 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1661 // non_lazy_ptr stubs.
1662 SmallString<128> Name;
1663 StringRef Suffix = "$non_lazy_ptr";
1665 Name += Sym->getName();
1666 Name += Suffix;
1667 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1668
1669 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
1670
1671 if (!StubSym.getPointer())
1672 StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
1673 !GV->hasLocalLinkage());
1674
1675 const MCExpr *BSymExpr = MCSymbolRefExpr::create(BaseSym, Ctx);
1676 const MCExpr *LHS = MCSymbolRefExpr::create(Stub, Ctx);
1677
1678 if (!Offset)
1679 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1680
1681 const MCExpr *RHS =
1683 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1684}
1685
1686static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1687 const MCSection &Section) {
1689 return true;
1690
1691 // FIXME: we should be able to use private labels for sections that can't be
1692 // dead-stripped (there's no issue with blocking atomization there), but `ld
1693 // -r` sometimes drops the no_dead_strip attribute from sections so for safety
1694 // we don't allow it.
1695 return false;
1696}
1697
1699 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1700 const TargetMachine &TM) const {
1701 bool CannotUsePrivateLabel = true;
1702 if (auto *GO = GV->getAliaseeObject()) {
1704 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1705 CannotUsePrivateLabel = !canUsePrivateLabel(TM.getMCAsmInfo(), *TheSection);
1706 }
1707 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1708}
1709
1710//===----------------------------------------------------------------------===//
1711// COFF
1712//===----------------------------------------------------------------------===//
1713
1714static unsigned
1716 unsigned Flags = 0;
1718
1719 if (K.isMetadata())
1720 Flags |=
1722 else if (K.isExclude())
1723 Flags |=
1725 else if (K.isText())
1726 Flags |=
1731 else if (K.isBSS())
1732 Flags |=
1736 else if (K.isThreadLocal())
1737 Flags |=
1741 else if (K.isReadOnly() || K.isReadOnlyWithRel())
1742 Flags |=
1745 else if (K.isWriteable())
1746 Flags |=
1750
1751 return Flags;
1752}
1753
1755 const Comdat *C = GV->getComdat();
1756 assert(C && "expected GV to have a Comdat!");
1757
1758 StringRef ComdatGVName = C->getName();
1759 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1760 if (!ComdatGV)
1761 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1762 "' does not exist.");
1763
1764 if (ComdatGV->getComdat() != C)
1765 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1766 "' is not a key for its COMDAT.");
1767
1768 return ComdatGV;
1769}
1770
1771static int getSelectionForCOFF(const GlobalValue *GV) {
1772 if (const Comdat *C = GV->getComdat()) {
1773 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1774 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1775 ComdatKey = GA->getAliaseeObject();
1776 if (ComdatKey == GV) {
1777 switch (C->getSelectionKind()) {
1778 case Comdat::Any:
1780 case Comdat::ExactMatch:
1782 case Comdat::Largest:
1786 case Comdat::SameSize:
1788 }
1789 } else {
1791 }
1792 }
1793 return 0;
1794}
1795
1797 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1799 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::COFF,
1800 /*AddSegmentInfo=*/false) ||
1801 Name == getInstrProfSectionName(IPSK_covfun, Triple::COFF,
1802 /*AddSegmentInfo=*/false) ||
1803 Name == getInstrProfSectionName(IPSK_covdata, Triple::COFF,
1804 /*AddSegmentInfo=*/false) ||
1805 Name == getInstrProfSectionName(IPSK_covname, Triple::COFF,
1806 /*AddSegmentInfo=*/false) ||
1807 Name == ".llvmbc" || Name == ".llvmcmd")
1808 Kind = SectionKind::getMetadata();
1809 int Selection = 0;
1810 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1811 StringRef COMDATSymName = "";
1812 if (GO->hasComdat()) {
1814 const GlobalValue *ComdatGV;
1816 ComdatGV = getComdatGVForCOFF(GO);
1817 else
1818 ComdatGV = GO;
1819
1820 if (!ComdatGV->hasPrivateLinkage()) {
1821 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1822 COMDATSymName = Sym->getName();
1823 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1824 } else {
1825 Selection = 0;
1826 }
1827 }
1828
1829 return getContext().getCOFFSection(Name, Characteristics, COMDATSymName,
1830 Selection);
1831}
1832
1834 if (Kind.isText())
1835 return ".text";
1836 if (Kind.isBSS())
1837 return ".bss";
1838 if (Kind.isThreadLocal())
1839 return ".tls$";
1840 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1841 return ".rdata";
1842 return ".data";
1843}
1844
1846 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1847 // If we have -ffunction-sections then we should emit the global value to a
1848 // uniqued section specifically for it.
1849 bool EmitUniquedSection;
1850 if (Kind.isText())
1851 EmitUniquedSection = TM.getFunctionSections();
1852 else
1853 EmitUniquedSection = TM.getDataSections();
1854
1855 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1857
1858 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1859
1860 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1862 if (!Selection)
1864 const GlobalValue *ComdatGV;
1865 if (GO->hasComdat())
1866 ComdatGV = getComdatGVForCOFF(GO);
1867 else
1868 ComdatGV = GO;
1869
1871 if (EmitUniquedSection)
1872 UniqueID = NextUniqueID++;
1873
1874 if (!ComdatGV->hasPrivateLinkage()) {
1875 MCSymbol *Sym = TM.getSymbol(ComdatGV);
1876 StringRef COMDATSymName = Sym->getName();
1877
1878 if (const auto *F = dyn_cast<Function>(GO))
1879 if (std::optional<StringRef> Prefix = F->getSectionPrefix())
1880 raw_svector_ostream(Name) << '$' << *Prefix;
1881
1882 // Append "$symbol" to the section name *before* IR-level mangling is
1883 // applied when targetting mingw. This is what GCC does, and the ld.bfd
1884 // COFF linker will not properly handle comdats otherwise.
1885 if (getContext().getTargetTriple().isOSCygMing())
1886 raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1887
1888 return getContext().getCOFFSection(Name, Characteristics, COMDATSymName,
1890 } else {
1891 SmallString<256> TmpData;
1892 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1893 return getContext().getCOFFSection(Name, Characteristics, TmpData,
1895 }
1896 }
1897
1898 if (Kind.isText())
1899 return TextSection;
1900
1901 if (Kind.isThreadLocal())
1902 return TLSDataSection;
1903
1904 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1905 return ReadOnlySection;
1906
1907 // Note: we claim that common symbols are put in BSSSection, but they are
1908 // really emitted with the magic .comm directive, which creates a symbol table
1909 // entry but not a section.
1910 if (Kind.isBSS() || Kind.isCommon())
1911 return BSSSection;
1912
1913 return DataSection;
1914}
1915
1917 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1918 const TargetMachine &TM) const {
1919 bool CannotUsePrivateLabel = false;
1920 if (GV->hasPrivateLinkage() &&
1921 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1922 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1923 CannotUsePrivateLabel = true;
1924
1925 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1926}
1927
1929 const Function &F, const TargetMachine &TM) const {
1930 // If the function can be removed, produce a unique section so that
1931 // the table doesn't prevent the removal.
1932 const Comdat *C = F.getComdat();
1933 bool EmitUniqueSection = TM.getFunctionSections() || C;
1934 if (!EmitUniqueSection)
1935 return ReadOnlySection;
1936
1937 // FIXME: we should produce a symbol for F instead.
1938 if (F.hasPrivateLinkage())
1939 return ReadOnlySection;
1940
1941 MCSymbol *Sym = TM.getSymbol(&F);
1942 StringRef COMDATSymName = Sym->getName();
1943
1946 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1947 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1948 unsigned UniqueID = NextUniqueID++;
1949
1950 return getContext().getCOFFSection(SecName, Characteristics, COMDATSymName,
1952 UniqueID);
1953}
1954
1956 bool UsesLabelDifference, const Function &F) const {
1957 if (TM->getTargetTriple().getArch() == Triple::x86_64) {
1959 // We can always create relative relocations, so use another section
1960 // that can be marked non-executable.
1961 return false;
1962 }
1963 }
1965 UsesLabelDifference, F);
1966}
1967
1969 const Module &M) const {
1971
1972 unsigned Version = 0;
1973 unsigned Flags = 0;
1974 StringRef Section;
1975
1976 GetObjCImageInfo(M, Version, Flags, Section);
1977 if (!Section.empty()) {
1978 auto &C = getContext();
1979 auto *S = C.getCOFFSection(Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1981 Streamer.switchSection(S);
1982 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1983 Streamer.emitInt32(Version);
1984 Streamer.emitInt32(Flags);
1985 Streamer.addBlankLine();
1986 }
1987
1990 if (MCSymbol *Sym =
1991 static_cast<MCSectionCOFF *>(Streamer.getCurrentSectionOnly())
1992 ->getCOMDATSymbol())
1993 if (Sym->isUndefined()) {
1994 // COMDAT symbol must be external to perform deduplication.
1995 Streamer.emitSymbolAttribute(Sym, MCSA_Global);
1996 Streamer.emitLabel(Sym);
1997 }
1998 });
1999}
2000
2001MCSection *
2006
2008 const Module &M) const {
2009 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
2010 // Emit the linker options to the linker .drectve section. According to the
2011 // spec, this section is a space-separated string containing flags for
2012 // linker.
2014 Streamer.switchSection(Sec);
2015 for (const auto *Option : LinkerOptions->operands()) {
2016 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
2017 // Lead with a space for consistency with our dllexport implementation.
2018 std::string Directive(" ");
2019 Directive.append(std::string(cast<MDString>(Piece)->getString()));
2020 Streamer.emitBytes(Directive);
2021 }
2022 }
2023 }
2024
2025 // Emit /EXPORT: flags for each exported global as necessary.
2026 std::string Flags;
2027 for (const GlobalValue &GV : M.global_values()) {
2028 raw_string_ostream OS(Flags);
2029 emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
2030 getMangler());
2031 if (!Flags.empty()) {
2032 Streamer.switchSection(getDrectveSection());
2033 Streamer.emitBytes(Flags);
2034 }
2035 Flags.clear();
2036 }
2037
2038 // Emit /INCLUDE: flags for each used global as necessary.
2039 if (const auto *LU = M.getNamedGlobal("llvm.used")) {
2040 assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
2041 assert(isa<ArrayType>(LU->getValueType()) &&
2042 "expected llvm.used to be an array type");
2043 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
2044 for (const Value *Op : A->operands()) {
2045 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
2046 // Global symbols with internal or private linkage are not visible to
2047 // the linker, and thus would cause an error when the linker tried to
2048 // preserve the symbol due to the `/include:` directive.
2049 if (GV->hasLocalLinkage())
2050 continue;
2051
2052 raw_string_ostream OS(Flags);
2053 emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
2054 getMangler());
2055
2056 if (!Flags.empty()) {
2057 Streamer.switchSection(getDrectveSection());
2058 Streamer.emitBytes(Flags);
2059 }
2060 Flags.clear();
2061 }
2062 }
2063 }
2064}
2065
2067 const TargetMachine &TM,
2068 const Module &M) {
2070 const Triple &T = TM.getTargetTriple();
2071 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
2073 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
2076 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
2078 } else {
2079 StaticCtorSection = Ctx.getCOFFSection(
2082 StaticDtorSection = Ctx.getCOFFSection(
2085 }
2086}
2087
2089 const Triple &T, bool IsCtor,
2090 unsigned Priority,
2091 const MCSymbol *KeySym,
2093 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
2094 // If the priority is the default, use .CRT$XCU, possibly associative.
2095 if (Priority == 65535)
2096 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
2097
2098 // Otherwise, we need to compute a new section name. Low priorities should
2099 // run earlier. The linker will sort sections ASCII-betically, and we need a
2100 // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
2101 // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
2102 // low priorities need to sort before 'L', since the CRT uses that
2103 // internally, so we use ".CRT$XCA00001" for them. We have a contract with
2104 // the frontend that "init_seg(compiler)" corresponds to priority 200 and
2105 // "init_seg(lib)" corresponds to priority 400, and those respectively use
2106 // 'C' and 'L' without the priority suffix. Priorities between 200 and 400
2107 // use 'C' with the priority as a suffix.
2108 SmallString<24> Name;
2109 char LastLetter = 'T';
2110 bool AddPrioritySuffix = Priority != 200 && Priority != 400;
2111 if (Priority < 200)
2112 LastLetter = 'A';
2113 else if (Priority < 400)
2114 LastLetter = 'C';
2115 else if (Priority == 400)
2116 LastLetter = 'L';
2117 raw_svector_ostream OS(Name);
2118 OS << ".CRT$X" << (IsCtor ? "C" : "T") << LastLetter;
2119 if (AddPrioritySuffix)
2120 OS << format("%05u", Priority);
2121 MCSectionCOFF *Sec = Ctx.getCOFFSection(
2123 return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
2124 }
2125
2126 std::string Name = IsCtor ? ".ctors" : ".dtors";
2127 if (Priority != 65535)
2128 raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
2129
2130 return Ctx.getAssociativeCOFFSection(
2131 Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
2134 KeySym, 0);
2135}
2136
2138 unsigned Priority, const MCSymbol *KeySym) const {
2140 getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
2141 static_cast<MCSectionCOFF *>(StaticCtorSection));
2142}
2143
2145 unsigned Priority, const MCSymbol *KeySym) const {
2147 getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
2148 static_cast<MCSectionCOFF *>(StaticDtorSection));
2149}
2150
2152 const GlobalValue *LHS, const GlobalValue *RHS, int64_t Addend,
2153 std::optional<int64_t> PCRelativeOffset, const TargetMachine &TM) const {
2154 const Triple &T = LHS->getParent()->getTargetTriple();
2155 if (T.isOSCygMing())
2156 return nullptr;
2157
2158 // Our symbols should exist in address space zero, cowardly no-op if
2159 // otherwise.
2160 if (LHS->getType()->getPointerAddressSpace() != 0 ||
2161 RHS->getType()->getPointerAddressSpace() != 0)
2162 return nullptr;
2163
2164 const auto *GA = dyn_cast<GlobalAlias>(LHS);
2165 const GlobalObject *GO = GA ? dyn_cast_or_null<GlobalObject>(GA->getAliasee())
2167
2168 // Both ptrtoint instructions must wrap global objects:
2169 // - Only global variables that are dso_local are eligible for image relative
2170 // relocations.
2171 // - FIXME: Referring to a dllimport function produces an image-relative
2172 // relocation against the local import thunk rather than the canonical
2173 // function pointer, which lacks program-wide pointer identity. This is
2174 // sufficient for use cases like MSVC exception handling metadata (where the
2175 // function is only invoked), but is not theoretically sound in general.
2176 // We probably need something like dso_local_equivalent to explicitly
2177 // request a callable local entry point.
2178 // - The subtrahend refers to the special symbol __ImageBase, a
2179 // GlobalVariable. We expect __ImageBase to be a global variable without a
2180 // section, externally defined.
2181 //
2182 // It should look something like this: @__ImageBase = external constant i8
2183 if (!GO || (isa<GlobalVariable>(GO) && !TM.shouldAssumeDSOLocal(LHS)) ||
2184 GO->isThreadLocal() || !isa<GlobalVariable>(RHS) ||
2185 RHS->isThreadLocal() || RHS->getName() != "__ImageBase" ||
2186 !RHS->hasExternalLinkage() ||
2187 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
2188 return nullptr;
2189
2190 const MCExpr *Res = MCSymbolRefExpr::create(
2192 if (Addend != 0)
2194 Res, MCConstantExpr::create(Addend, getContext()), getContext());
2195 return Res;
2196}
2197
2198static std::string APIntToHexString(const APInt &AI) {
2199 unsigned Width = (AI.getBitWidth() / 8) * 2;
2200 std::string HexString = toString(AI, 16, /*Signed=*/false);
2201 llvm::transform(HexString, HexString.begin(), tolower);
2202 unsigned Size = HexString.size();
2203 assert(Width >= Size && "hex string is too large!");
2204 HexString.insert(HexString.begin(), Width - Size, '0');
2205
2206 return HexString;
2207}
2208
2209static std::string scalarConstantToHexString(const Constant *C) {
2210 Type *Ty = C->getType();
2211 if (isa<UndefValue>(C)) {
2212 return APIntToHexString(APInt::getZero(Ty->getPrimitiveSizeInBits()));
2213 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
2214 if (CFP->getType()->isFloatingPointTy())
2215 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
2216
2217 std::string HexString;
2218 unsigned NumElements =
2219 cast<FixedVectorType>(CFP->getType())->getNumElements();
2220 for (unsigned I = 0; I < NumElements; ++I)
2221 HexString += APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
2222 return HexString;
2223 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
2224 if (CI->getType()->isIntegerTy())
2225 return APIntToHexString(CI->getValue());
2226
2227 std::string HexString;
2228 unsigned NumElements =
2229 cast<FixedVectorType>(CI->getType())->getNumElements();
2230 for (unsigned I = 0; I < NumElements; ++I)
2231 HexString += APIntToHexString(CI->getValue());
2232 return HexString;
2233 } else {
2234 unsigned NumElements;
2235 if (auto *VTy = dyn_cast<VectorType>(Ty))
2236 NumElements = cast<FixedVectorType>(VTy)->getNumElements();
2237 else
2238 NumElements = Ty->getArrayNumElements();
2239 std::string HexString;
2240 for (int I = NumElements - 1, E = -1; I != E; --I)
2241 HexString += scalarConstantToHexString(C->getAggregateElement(I));
2242 return HexString;
2243 }
2244}
2245
2247 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
2248 const Function *F) const {
2249 if (Kind.isMergeableConst() && C &&
2250 getContext().getAsmInfo().hasCOFFComdatConstants()) {
2251 // This creates comdat sections with the given symbol name, but unless
2252 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
2253 // will be created with a null storage class, which makes GNU binutils
2254 // error out.
2255 const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
2258 std::string COMDATSymName;
2259 if (Kind.isMergeableConst4()) {
2260 if (Alignment <= 4) {
2261 COMDATSymName = "__real@" + scalarConstantToHexString(C);
2262 Alignment = Align(4);
2263 }
2264 } else if (Kind.isMergeableConst8()) {
2265 if (Alignment <= 8) {
2266 COMDATSymName = "__real@" + scalarConstantToHexString(C);
2267 Alignment = Align(8);
2268 }
2269 } else if (Kind.isMergeableConst16()) {
2270 // FIXME: These may not be appropriate for non-x86 architectures.
2271 if (Alignment <= 16) {
2272 COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
2273 Alignment = Align(16);
2274 }
2275 } else if (Kind.isMergeableConst32()) {
2276 if (Alignment <= 32) {
2277 COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
2278 Alignment = Align(32);
2279 }
2280 }
2281
2282 if (!COMDATSymName.empty())
2283 return getContext().getCOFFSection(".rdata", Characteristics,
2284 COMDATSymName,
2286 }
2287
2288 return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Alignment,
2289 F);
2290}
2291
2292//===----------------------------------------------------------------------===//
2293// Wasm
2294//===----------------------------------------------------------------------===//
2295
2296static const Comdat *getWasmComdat(const GlobalValue *GV) {
2297 const Comdat *C = GV->getComdat();
2298 if (!C)
2299 return nullptr;
2300
2301 if (C->getSelectionKind() != Comdat::Any)
2302 report_fatal_error("WebAssembly COMDATs only support "
2303 "SelectionKind::Any, '" + C->getName() + "' cannot be "
2304 "lowered.");
2305
2306 return C;
2307}
2308
2309static unsigned getWasmSectionFlags(SectionKind K, bool Retain) {
2310 unsigned Flags = 0;
2311
2312 if (K.isThreadLocal())
2313 Flags |= wasm::WASM_SEG_FLAG_TLS;
2314
2315 if (K.isMergeableCString())
2317
2318 if (Retain)
2320
2321 // TODO(sbc): Add suport for K.isMergeableConst()
2322
2323 return Flags;
2324}
2325
2327 const TargetMachine &TM,
2328 const Module &M) {
2330
2332 collectUsedGlobalVariables(M, Vec, false);
2333 for (GlobalValue *GV : Vec)
2334 if (auto *GO = dyn_cast<GlobalObject>(GV))
2335 Used.insert(GO);
2336}
2337
2338MCSection *
2340 SectionKind Kind) const {
2341 if (Kind.isMetadata())
2342 return getContext().getWasmSection(".custom_section." + Name, Kind);
2343 return getContext().getWasmSection(Name, Kind);
2344}
2345
2347 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2348 // We don't support explict section names for functions in the wasm object
2349 // format. Each function has to be in its own unique section.
2350 if (isa<Function>(GO)) {
2351 return SelectSectionForGlobal(GO, Kind, TM);
2352 }
2353
2354 StringRef Name = GO->getSection();
2355
2356 // Certain data sections we treat as named custom sections rather than
2357 // segments within the data section.
2358 // This could be avoided if all data segements (the wasm sense) were
2359 // represented as their own sections (in the llvm sense).
2360 // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
2361 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::Wasm,
2362 /*AddSegmentInfo=*/false) ||
2363 Name == getInstrProfSectionName(IPSK_covfun, Triple::Wasm,
2364 /*AddSegmentInfo=*/false) ||
2365 Name == ".llvmbc" || Name == ".llvmcmd")
2366 Kind = SectionKind::getMetadata();
2367
2368 StringRef Group = "";
2369 if (const Comdat *C = getWasmComdat(GO)) {
2370 Group = C->getName();
2371 }
2372
2373 unsigned Flags = getWasmSectionFlags(Kind, Used.count(GO));
2374 MCSectionWasm *Section = getContext().getWasmSection(Name, Kind, Flags, Group,
2376
2377 return Section;
2378}
2379
2380static MCSectionWasm *
2382 SectionKind Kind, Mangler &Mang,
2383 const TargetMachine &TM, bool EmitUniqueSection,
2384 unsigned *NextUniqueID, bool Retain) {
2385 StringRef Group = "";
2386 if (const Comdat *C = getWasmComdat(GO)) {
2387 Group = C->getName();
2388 }
2389
2390 bool UniqueSectionNames = TM.getUniqueSectionNames();
2391 SmallString<128> Name = getSectionPrefixForGlobal(Kind, /*IsLarge=*/false);
2392
2393 if (const auto *F = dyn_cast<Function>(GO)) {
2394 const auto &OptionalPrefix = F->getSectionPrefix();
2395 if (OptionalPrefix)
2396 raw_svector_ostream(Name) << '.' << *OptionalPrefix;
2397 }
2398
2399 if (EmitUniqueSection && UniqueSectionNames) {
2400 Name.push_back('.');
2401 TM.getNameWithPrefix(Name, GO, Mang, true);
2402 }
2404 if (EmitUniqueSection && !UniqueSectionNames) {
2405 UniqueID = *NextUniqueID;
2406 (*NextUniqueID)++;
2407 }
2408
2409 unsigned Flags = getWasmSectionFlags(Kind, Retain);
2410 return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
2411}
2412
2414 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2415
2416 if (Kind.isCommon())
2417 report_fatal_error("mergable sections not supported yet on wasm");
2418
2419 // If we have -ffunction-section or -fdata-section then we should emit the
2420 // global value to a uniqued section specifically for it.
2421 bool EmitUniqueSection = false;
2422 if (Kind.isText())
2423 EmitUniqueSection = TM.getFunctionSections();
2424 else
2425 EmitUniqueSection = TM.getDataSections();
2426 EmitUniqueSection |= GO->hasComdat();
2427 bool Retain = Used.count(GO);
2428 EmitUniqueSection |= Retain;
2429
2430 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2431 EmitUniqueSection, &NextUniqueID, Retain);
2432}
2433
2435 bool UsesLabelDifference, const Function &F) const {
2436 // We can always create relative relocations, so use another section
2437 // that can be marked non-executable.
2438 return false;
2439}
2440
2444
2445 // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2446 // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2448}
2449
2451 unsigned Priority, const MCSymbol *KeySym) const {
2452 return Priority == UINT16_MAX ?
2454 getContext().getWasmSection(".init_array." + utostr(Priority),
2456}
2457
2459 unsigned Priority, const MCSymbol *KeySym) const {
2460 report_fatal_error("@llvm.global_dtors should have been lowered already");
2461}
2462
2463//===----------------------------------------------------------------------===//
2464// XCOFF
2465//===----------------------------------------------------------------------===//
2467 const MachineFunction *MF) {
2468 if (!MF->getLandingPads().empty())
2469 return true;
2470
2471 const Function &F = MF->getFunction();
2472 if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2473 return false;
2474
2475 const GlobalValue *Per =
2476 dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
2477 assert(Per && "Personality routine is not a GlobalValue type.");
2479 return false;
2480
2481 return true;
2482}
2483
2485 const MachineFunction *MF) {
2486 const Function &F = MF->getFunction();
2487 if (!F.hasStackProtectorFnAttr())
2488 return false;
2489 // FIXME: check presence of canary word
2490 // There are cases that the stack protectors are not really inserted even if
2491 // the attributes are on.
2492 return true;
2493}
2494
2495MCSymbol *
2497 auto *EHInfoSym =
2498 static_cast<MCSymbolXCOFF *>(MF->getContext().getOrCreateSymbol(
2499 "__ehinfo." + Twine(MF->getFunctionNumber())));
2500 EHInfoSym->setEHInfo();
2501 return EHInfoSym;
2502}
2503
2504MCSymbol *
2506 const TargetMachine &TM) const {
2507 // We always use a qualname symbol for a GV that represents
2508 // a declaration, a function descriptor, or a common symbol. An IFunc is
2509 // lowered as a special trampoline function which has an entry point and a
2510 // descriptor.
2511 // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2512 // also return a qualname so that a label symbol could be avoided.
2513 // It is inherently ambiguous when the GO represents the address of a
2514 // function, as the GO could either represent a function descriptor or a
2515 // function entry point. We choose to always return a function descriptor
2516 // here.
2517 if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2518 if (GO->isDeclarationForLinker())
2519 return static_cast<const MCSectionXCOFF *>(
2521 ->getQualNameSymbol();
2522
2523 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
2524 if (GVar->hasAttribute("toc-data"))
2525 return static_cast<const MCSectionXCOFF *>(
2527 ->getQualNameSymbol();
2528
2529 if (isa<GlobalIFunc>(GO))
2530 return static_cast<const MCSectionXCOFF *>(
2532 ->getQualNameSymbol();
2533
2534 SectionKind GOKind = getKindForGlobal(GO, TM);
2535 if (GOKind.isText())
2536 return static_cast<const MCSectionXCOFF *>(
2538 ->getQualNameSymbol();
2539 if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
2540 GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
2541 return static_cast<const MCSectionXCOFF *>(
2542 SectionForGlobal(GO, GOKind, TM))
2543 ->getQualNameSymbol();
2544 }
2545
2546 // For all other cases, fall back to getSymbol to return the unqualified name.
2547 return nullptr;
2548}
2549
2551 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2552 if (!GO->hasSection())
2553 report_fatal_error("#pragma clang section is not yet supported");
2554
2556
2557 // Handle the XCOFF::TD case first, then deal with the rest.
2558 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2559 if (GVar->hasAttribute("toc-data"))
2560 return getContext().getXCOFFSection(
2561 SectionName, Kind,
2563 /* MultiSymbolsAllowed*/ true);
2564
2565 XCOFF::StorageMappingClass MappingClass;
2566 if (Kind.isText())
2567 MappingClass = XCOFF::XMC_PR;
2568 else if (Kind.isData() || Kind.isBSS())
2569 MappingClass = XCOFF::XMC_RW;
2570 else if (Kind.isReadOnlyWithRel())
2571 MappingClass =
2572 TM.Options.XCOFFReadOnlyPointers ? XCOFF::XMC_RO : XCOFF::XMC_RW;
2573 else if (Kind.isReadOnly())
2574 MappingClass = XCOFF::XMC_RO;
2575 else
2576 report_fatal_error("XCOFF other section types not yet implemented.");
2577
2578 return getContext().getXCOFFSection(
2579 SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
2580 /* MultiSymbolsAllowed*/ true);
2581}
2582
2584 const GlobalObject *GO, const TargetMachine &TM) const {
2586 "Tried to get ER section for a defined global.");
2587
2588 SmallString<128> Name;
2589 getNameWithPrefix(Name, GO, TM);
2590
2591 // AIX TLS local-dynamic does not need the external reference for the
2592 // "_$TLSML" symbol.
2594 GO->hasName() && GO->getName() == "_$TLSML") {
2595 return getContext().getXCOFFSection(
2596 Name, SectionKind::getData(),
2598 }
2599
2602 if (GO->isThreadLocal())
2603 SMC = XCOFF::XMC_UL;
2604
2605 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2606 if (GVar->hasAttribute("toc-data"))
2607 SMC = XCOFF::XMC_TD;
2608
2609 // Externals go into a csect of type ER.
2610 return getContext().getXCOFFSection(
2613}
2614
2616 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2617 // Handle the XCOFF::TD case first, then deal with the rest.
2618 if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2619 if (GVar->hasAttribute("toc-data")) {
2620 SmallString<128> Name;
2621 getNameWithPrefix(Name, GO, TM);
2622 XCOFF::SymbolType symType =
2624 return getContext().getXCOFFSection(
2625 Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, symType),
2626 /* MultiSymbolsAllowed*/ true);
2627 }
2628
2629 // Common symbols go into a csect with matching name which will get mapped
2630 // into the .bss section.
2631 // Zero-initialized local TLS symbols go into a csect with matching name which
2632 // will get mapped into the .tbss section.
2633 if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
2634 SmallString<128> Name;
2635 getNameWithPrefix(Name, GO, TM);
2636 XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
2637 : Kind.isCommon() ? XCOFF::XMC_RW
2638 : XCOFF::XMC_UL;
2639 return getContext().getXCOFFSection(
2640 Name, Kind, XCOFF::CsectProperties(SMC, XCOFF::XTY_CM));
2641 }
2642
2643 if (Kind.isText()) {
2644 if (TM.getFunctionSections()) {
2645 return static_cast<const MCSymbolXCOFF *>(
2647 ->getRepresentedCsect();
2648 }
2649 return TextSection;
2650 }
2651
2652 if (TM.Options.XCOFFReadOnlyPointers && Kind.isReadOnlyWithRel()) {
2653 if (!TM.getDataSections())
2655 "ReadOnlyPointers is supported only if data sections is turned on");
2656
2657 SmallString<128> Name;
2658 getNameWithPrefix(Name, GO, TM);
2659 return getContext().getXCOFFSection(
2662 }
2663
2664 // For BSS kind, zero initialized data must be emitted to the .data section
2665 // because external linkage control sections that get mapped to the .bss
2666 // section will be linked as tentative definitions, which is only appropriate
2667 // for SectionKind::Common.
2668 if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2669 if (TM.getDataSections()) {
2670 SmallString<128> Name;
2671 getNameWithPrefix(Name, GO, TM);
2672 return getContext().getXCOFFSection(
2673 Name, SectionKind::getData(),
2675 }
2676 return DataSection;
2677 }
2678
2679 if (Kind.isReadOnly()) {
2680 if (TM.getDataSections()) {
2681 SmallString<128> Name;
2682 getNameWithPrefix(Name, GO, TM);
2683 return getContext().getXCOFFSection(
2686 }
2687 return ReadOnlySection;
2688 }
2689
2690 // External/weak TLS data and initialized local TLS data are not eligible
2691 // to be put into common csect. If data sections are enabled, thread
2692 // data are emitted into separate sections. Otherwise, thread data
2693 // are emitted into the .tdata section.
2694 if (Kind.isThreadLocal()) {
2695 if (TM.getDataSections()) {
2696 SmallString<128> Name;
2697 getNameWithPrefix(Name, GO, TM);
2698 return getContext().getXCOFFSection(
2700 }
2701 return TLSDataSection;
2702 }
2703
2704 report_fatal_error("XCOFF other section types not yet implemented.");
2705}
2706
2708 const Function &F, const TargetMachine &TM) const {
2709 assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2710
2711 if (!TM.getFunctionSections())
2712 return ReadOnlySection;
2713
2714 // If the function can be removed, produce a unique section so that
2715 // the table doesn't prevent the removal.
2716 SmallString<128> NameStr(".rodata.jmp..");
2717 getNameWithPrefix(NameStr, &F, TM);
2718 return getContext().getXCOFFSection(
2719 NameStr, SectionKind::getReadOnly(),
2721}
2722
2724 bool UsesLabelDifference, const Function &F) const {
2725 return false;
2726}
2727
2728/// Given a mergeable constant with the specified size and relocation
2729/// information, return a section that it should be placed in.
2731 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
2732 const Function *F) const {
2733 // TODO: Enable emiting constant pool to unique sections when we support it.
2734 if (Alignment > Align(16))
2735 report_fatal_error("Alignments greater than 16 not yet supported.");
2736
2737 if (Alignment == Align(8)) {
2738 assert(ReadOnly8Section && "Section should always be initialized.");
2739 return ReadOnly8Section;
2740 }
2741
2742 if (Alignment == Align(16)) {
2743 assert(ReadOnly16Section && "Section should always be initialized.");
2744 return ReadOnly16Section;
2745 }
2746
2747 return ReadOnlySection;
2748}
2749
2751 const TargetMachine &TgtM,
2752 const Module &M) {
2756 (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4
2759 LSDAEncoding = 0;
2761
2762 // AIX debug for thread local location is not ready. And for integrated as
2763 // mode, the relocatable address for the thread local variable will cause
2764 // linker error. So disable the location attribute generation for thread local
2765 // variables for now.
2766 // FIXME: when TLS debug on AIX is ready, remove this setting.
2768}
2769
2771 unsigned Priority, const MCSymbol *KeySym) const {
2772 report_fatal_error("no static constructor section on AIX");
2773}
2774
2776 unsigned Priority, const MCSymbol *KeySym) const {
2777 report_fatal_error("no static destructor section on AIX");
2778}
2779
2782 assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2783
2784 switch (GV->getLinkage()) {
2787 return XCOFF::C_HIDEXT;
2791 return XCOFF::C_EXT;
2797 return XCOFF::C_WEAKEXT;
2800 "There is no mapping that implements AppendingLinkage for XCOFF.");
2801 }
2802 llvm_unreachable("Unknown linkage type!");
2803}
2804
2806 const GlobalValue *Func, const TargetMachine &TM) const {
2807 assert((isa<Function>(Func) || isa<GlobalIFunc>(Func) ||
2808 (isa<GlobalAlias>(Func) &&
2810 cast<GlobalAlias>(Func)->getAliaseeObject()))) &&
2811 "Func must be a function or an alias which has a function as base "
2812 "object.");
2813
2814 SmallString<128> NameStr;
2815 NameStr.push_back('.');
2816 getNameWithPrefix(NameStr, Func, TM);
2817
2818 // When -function-sections is enabled and explicit section is not specified,
2819 // it's not necessary to emit function entry point label any more. We will use
2820 // function entry point csect instead. And for function delcarations, the
2821 // undefined symbols gets treated as csect with XTY_ER property.
2822 if (((TM.getFunctionSections() && !Func->hasSection()) ||
2823 Func->isDeclarationForLinker()) &&
2824 (isa<Function>(Func) || isa<GlobalIFunc>(Func))) {
2825 return getContext()
2827 NameStr, SectionKind::getText(),
2828 XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclarationForLinker()
2830 : XCOFF::XTY_SD))
2832 }
2833
2834 return getContext().getOrCreateSymbol(NameStr);
2835}
2836
2838 const GlobalObject *F, const TargetMachine &TM) const {
2840 "F must be a function or ifunc object.");
2841 SmallString<128> NameStr;
2842 getNameWithPrefix(NameStr, F, TM);
2843 return getContext().getXCOFFSection(
2844 NameStr, SectionKind::getData(),
2846}
2847
2849 const MCSymbol *Sym, const TargetMachine &TM) const {
2850 const XCOFF::StorageMappingClass SMC = [](const MCSymbol *Sym,
2851 const TargetMachine &TM) {
2852 auto *XSym = static_cast<const MCSymbolXCOFF *>(Sym);
2853
2854 // The "_$TLSML" symbol for TLS local-dynamic mode requires XMC_TC,
2855 // otherwise the AIX assembler will complain.
2856 if (XSym->getSymbolTableName() == "_$TLSML")
2857 return XCOFF::XMC_TC;
2858
2859 // Use large code model toc entries for ehinfo symbols as they are
2860 // never referenced directly. The runtime loads their TOC entry
2861 // addresses from the trace-back table.
2862 if (XSym->isEHInfo())
2863 return XCOFF::XMC_TE;
2864
2865 // If the symbol does not have a code model specified use the module value.
2866 if (!XSym->hasPerSymbolCodeModel())
2867 return TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE
2868 : XCOFF::XMC_TC;
2869
2870 return XSym->getPerSymbolCodeModel() == MCSymbolXCOFF::CM_Large
2872 : XCOFF::XMC_TC;
2873 }(Sym, TM);
2874
2875 return getContext().getXCOFFSection(
2876 static_cast<const MCSymbolXCOFF *>(Sym)->getSymbolTableName(),
2878}
2879
2881 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2882 auto *LSDA = static_cast<MCSectionXCOFF *>(LSDASection);
2883 if (TM.getFunctionSections()) {
2884 // If option -ffunction-sections is on, append the function name to the
2885 // name of the LSDA csect so that each function has its own LSDA csect.
2886 // This helps the linker to garbage-collect EH info of unused functions.
2887 SmallString<128> NameStr = LSDA->getName();
2888 raw_svector_ostream(NameStr) << '.' << F.getName();
2889 LSDA = getContext().getXCOFFSection(NameStr, LSDA->getKind(),
2890 LSDA->getCsectProp());
2891 }
2892 return LSDA;
2893}
2894//===----------------------------------------------------------------------===//
2895// GOFF
2896//===----------------------------------------------------------------------===//
2898
2900 const TargetMachine &TM,
2901 const Module &M) {
2903
2904 // Construct the default names for the root SD and the ADA PR symbol.
2905 StringRef FileName = sys::path::stem(M.getSourceFileName());
2906 if (FileName.size() > 1 && FileName.starts_with('<') &&
2907 FileName.ends_with('>'))
2908 FileName = FileName.substr(1, FileName.size() - 2);
2909 DefaultRootSDName = Twine(FileName).concat("#C").str();
2910 DefaultADAPRName = Twine(FileName).concat("#S").str();
2911 MCSectionGOFF *RootSD =
2912 static_cast<MCSectionGOFF *>(TextSection)->getParent();
2913 MCSectionGOFF *ADAPR = static_cast<MCSectionGOFF *>(ADASection);
2914 RootSD->setName(DefaultRootSDName);
2915 ADAPR->setName(DefaultADAPRName);
2916 // Initialize the label for the text section.
2917 MCSymbolGOFF *TextLD = static_cast<MCSymbolGOFF *>(
2918 getContext().getOrCreateSymbol(RootSD->getName()));
2921 TextLD->setExternal(false);
2922 TextLD->setWeak(false);
2923 TextLD->setADA(ADAPR);
2924 TextSection->setBeginSymbol(TextLD);
2925 // Initialize the label for the ADA section.
2926 MCSymbolGOFF *ADASym = static_cast<MCSymbolGOFF *>(
2928 ADAPR->setBeginSymbol(ADASym);
2929}
2930
2932 bool UsesLabelDifference, const Function &F) const {
2933 return true;
2934}
2935
2937 const DataLayout &DL, SectionKind Kind, const Constant *C, Align &Alignment,
2938 const Function *F) const {
2939 return TextSection;
2940}
2941
2946
2948 const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
2949 std::string Name = "GCC_except." + F.getName().str();
2950
2951 MCSectionGOFF *SD = getContext().getGOFFSection(
2954 MCSectionGOFF *WSA = getContext().getGOFFSection(
2959 SD);
2960 WSA->setAlignment(Align(8));
2961 return getContext().getGOFFSection(
2962 SectionKind::getData(), Name,
2965 WSA);
2966}
2967
2969 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2970 auto *Symbol = TM.getSymbol(GO);
2971
2972 // Read-only data stays in the code section only if it is local: references
2973 // from other translation units are always parts in the WSA.
2974 if (Kind.isBSS() || Kind.isData() || Kind.isReadOnlyWithRel() ||
2975 (Kind.isReadOnly() && !GO->hasLocalLinkage())) {
2976 GOFF::ESDBindingScope PRBindingScope =
2977 GO->hasExternalLinkage()
2981 GOFF::ESDBindingScope SDBindingScope =
2984 MaybeAlign Alignment;
2985 if (auto *F = dyn_cast<Function>(GO))
2986 Alignment = F->getAlign();
2987 else if (auto *V = dyn_cast<GlobalVariable>(GO))
2988 Alignment = V->getAlign();
2989 MCSectionGOFF *SD = getContext().getGOFFSection(
2990 SectionKind::getMetadata(), Symbol->getName(),
2991 GOFF::SDAttr{GOFF::ESD_TA_Unspecified, SDBindingScope});
2992 MCSectionGOFF *ED = getContext().getGOFFSection(
2997 SD);
2998 ED->setAlignment(Alignment.value_or(llvm::Align(8)));
2999 MCSectionGOFF *PR = getContext().getGOFFSection(
3000 Kind, Symbol->getName(),
3001 GOFF::PRAttr{false, GOFF::ESD_EXE_DATA, GOFF::ESD_BST_Strong,
3002 GOFF::ESD_LT_XPLink, PRBindingScope, 0},
3003 ED);
3004 // The binder rejects zero-length PR sections. Mark the PR so the writer
3005 // inflates it to a valid length if needed.
3007 return PR;
3008 }
3009 return TextSection;
3010}
3011
3012MCSection *
3014 // XL C/C++ compilers on z/OS support priorities from min-int to max-int, with
3015 // sinit as source priority 0. For clang, sinit has source priority 65535.
3016 // For GOFF, the priority sortkey field is an unsigned value. So, we
3017 // add min-int to get sorting to work properly but also subtract the
3018 // clang sinit (65535) value so internally xl sinit and clang sinit have
3019 // the same unsigned GOFF priority sortkey field value (i.e. 0x80000000).
3020 static constexpr const uint32_t ClangDefaultSinitPriority = 65535;
3021 uint32_t Prio = Priority + (0x80000000 - ClangDefaultSinitPriority);
3022
3023 std::string Name(".xtor");
3024 if (Priority != ClangDefaultSinitPriority)
3025 Name = llvm::Twine(Name).concat(".").concat(llvm::utostr(Priority)).str();
3026
3027 MCContext &Ctx = getContext();
3028 MCSectionGOFF *SInit = Ctx.getGOFFSection(
3034 static_cast<const MCSectionGOFF *>(TextSection)->getParent());
3035
3036 MCSectionGOFF *Xtor = Ctx.getGOFFSection(
3037 SectionKind::getData(), Name,
3040 SInit);
3041 return Xtor;
3042}
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.
cl::opt< bool > PreserveHotDataSectionPrefix("preserve-hot-data-section-prefix", cl::Hidden, cl::init(true), cl::desc("If true, hot data section prefixes are preserved"))
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.
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:979
@ DW_EH_PE_pcrel
Definition Dwarf.h:977
@ DW_EH_PE_sdata4
Definition Dwarf.h:974
@ DW_EH_PE_sdata8
Definition Dwarf.h:975
@ DW_EH_PE_absptr
Definition Dwarf.h:966
@ DW_EH_PE_udata4
Definition Dwarf.h:970
@ DW_EH_PE_udata8
Definition Dwarf.h:971
@ DW_EH_PE_indirect
Definition Dwarf.h:982
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