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