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