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