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