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