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