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