1*0b57cec5SDimitry Andric //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
2*0b57cec5SDimitry Andric //
3*0b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4*0b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5*0b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6*0b57cec5SDimitry Andric //
7*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
8*0b57cec5SDimitry Andric //
9*0b57cec5SDimitry Andric // This file implements classes used to handle lowerings specific to common
10*0b57cec5SDimitry Andric // object file formats.
11*0b57cec5SDimitry Andric //
12*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
13*0b57cec5SDimitry Andric 
14*0b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
15*0b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
16*0b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
17*0b57cec5SDimitry Andric #include "llvm/ADT/StringExtras.h"
18*0b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
19*0b57cec5SDimitry Andric #include "llvm/ADT/Triple.h"
20*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/COFF.h"
21*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
22*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/ELF.h"
23*0b57cec5SDimitry Andric #include "llvm/BinaryFormat/MachO.h"
24fe6060f1SDimitry Andric #include "llvm/BinaryFormat/Wasm.h"
25e8d8bef9SDimitry Andric #include "llvm/CodeGen/BasicBlockSectionUtils.h"
265ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
275ffd83dbSDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
28*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
29*0b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfoImpls.h"
30*0b57cec5SDimitry Andric #include "llvm/IR/Comdat.h"
31*0b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
32*0b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
33*0b57cec5SDimitry Andric #include "llvm/IR/DerivedTypes.h"
345ffd83dbSDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
355ffd83dbSDimitry Andric #include "llvm/IR/DiagnosticPrinter.h"
36*0b57cec5SDimitry Andric #include "llvm/IR/Function.h"
37*0b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
38*0b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
39*0b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
40*0b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
41*0b57cec5SDimitry Andric #include "llvm/IR/Mangler.h"
42*0b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
43*0b57cec5SDimitry Andric #include "llvm/IR/Module.h"
44e8d8bef9SDimitry Andric #include "llvm/IR/PseudoProbe.h"
45*0b57cec5SDimitry Andric #include "llvm/IR/Type.h"
46*0b57cec5SDimitry Andric #include "llvm/MC/MCAsmInfo.h"
47*0b57cec5SDimitry Andric #include "llvm/MC/MCContext.h"
48*0b57cec5SDimitry Andric #include "llvm/MC/MCExpr.h"
49*0b57cec5SDimitry Andric #include "llvm/MC/MCSectionCOFF.h"
50*0b57cec5SDimitry Andric #include "llvm/MC/MCSectionELF.h"
51fe6060f1SDimitry Andric #include "llvm/MC/MCSectionGOFF.h"
52*0b57cec5SDimitry Andric #include "llvm/MC/MCSectionMachO.h"
53*0b57cec5SDimitry Andric #include "llvm/MC/MCSectionWasm.h"
548bcb0991SDimitry Andric #include "llvm/MC/MCSectionXCOFF.h"
55*0b57cec5SDimitry Andric #include "llvm/MC/MCStreamer.h"
56*0b57cec5SDimitry Andric #include "llvm/MC/MCSymbol.h"
57*0b57cec5SDimitry Andric #include "llvm/MC/MCSymbolELF.h"
58*0b57cec5SDimitry Andric #include "llvm/MC/MCValue.h"
59*0b57cec5SDimitry Andric #include "llvm/MC/SectionKind.h"
60*0b57cec5SDimitry Andric #include "llvm/ProfileData/InstrProf.h"
61bdd1243dSDimitry Andric #include "llvm/Support/Base64.h"
62*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
63*0b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
64*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
655ffd83dbSDimitry Andric #include "llvm/Support/Format.h"
66*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
67*0b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
68*0b57cec5SDimitry Andric #include <cassert>
69*0b57cec5SDimitry Andric #include <string>
70*0b57cec5SDimitry Andric 
71*0b57cec5SDimitry Andric using namespace llvm;
72*0b57cec5SDimitry Andric using namespace dwarf;
73*0b57cec5SDimitry Andric 
74*0b57cec5SDimitry Andric static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
75*0b57cec5SDimitry Andric                              StringRef &Section) {
76*0b57cec5SDimitry Andric   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
77*0b57cec5SDimitry Andric   M.getModuleFlagsMetadata(ModuleFlags);
78*0b57cec5SDimitry Andric 
79*0b57cec5SDimitry Andric   for (const auto &MFE: ModuleFlags) {
80*0b57cec5SDimitry Andric     // Ignore flags with 'Require' behaviour.
81*0b57cec5SDimitry Andric     if (MFE.Behavior == Module::Require)
82*0b57cec5SDimitry Andric       continue;
83*0b57cec5SDimitry Andric 
84*0b57cec5SDimitry Andric     StringRef Key = MFE.Key->getString();
85*0b57cec5SDimitry Andric     if (Key == "Objective-C Image Info Version") {
86*0b57cec5SDimitry Andric       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
87*0b57cec5SDimitry Andric     } else if (Key == "Objective-C Garbage Collection" ||
88*0b57cec5SDimitry Andric                Key == "Objective-C GC Only" ||
89*0b57cec5SDimitry Andric                Key == "Objective-C Is Simulated" ||
90*0b57cec5SDimitry Andric                Key == "Objective-C Class Properties" ||
91*0b57cec5SDimitry Andric                Key == "Objective-C Image Swift Version") {
92*0b57cec5SDimitry Andric       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
93*0b57cec5SDimitry Andric     } else if (Key == "Objective-C Image Info Section") {
94*0b57cec5SDimitry Andric       Section = cast<MDString>(MFE.Val)->getString();
95*0b57cec5SDimitry Andric     }
965ffd83dbSDimitry Andric     // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
975ffd83dbSDimitry Andric     // "Objective-C Garbage Collection".
985ffd83dbSDimitry Andric     else if (Key == "Swift ABI Version") {
995ffd83dbSDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
1005ffd83dbSDimitry Andric     } else if (Key == "Swift Major Version") {
1015ffd83dbSDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
1025ffd83dbSDimitry Andric     } else if (Key == "Swift Minor Version") {
1035ffd83dbSDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
1045ffd83dbSDimitry Andric     }
105*0b57cec5SDimitry Andric   }
106*0b57cec5SDimitry Andric }
107*0b57cec5SDimitry Andric 
108*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
109*0b57cec5SDimitry Andric //                                  ELF
110*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
111*0b57cec5SDimitry Andric 
11204eeddc0SDimitry Andric TargetLoweringObjectFileELF::TargetLoweringObjectFileELF() {
113e8d8bef9SDimitry Andric   SupportDSOLocalEquivalentLowering = true;
114e8d8bef9SDimitry Andric }
115e8d8bef9SDimitry Andric 
116*0b57cec5SDimitry Andric void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
117*0b57cec5SDimitry Andric                                              const TargetMachine &TgtM) {
118*0b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
119*0b57cec5SDimitry Andric 
120*0b57cec5SDimitry Andric   CodeModel::Model CM = TgtM.getCodeModel();
1215ffd83dbSDimitry Andric   InitializeELF(TgtM.Options.UseInitArray);
122*0b57cec5SDimitry Andric 
123*0b57cec5SDimitry Andric   switch (TgtM.getTargetTriple().getArch()) {
124*0b57cec5SDimitry Andric   case Triple::arm:
125*0b57cec5SDimitry Andric   case Triple::armeb:
126*0b57cec5SDimitry Andric   case Triple::thumb:
127*0b57cec5SDimitry Andric   case Triple::thumbeb:
128*0b57cec5SDimitry Andric     if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
129*0b57cec5SDimitry Andric       break;
130*0b57cec5SDimitry Andric     // Fallthrough if not using EHABI
131bdd1243dSDimitry Andric     [[fallthrough]];
132*0b57cec5SDimitry Andric   case Triple::ppc:
133e8d8bef9SDimitry Andric   case Triple::ppcle:
134*0b57cec5SDimitry Andric   case Triple::x86:
135*0b57cec5SDimitry Andric     PersonalityEncoding = isPositionIndependent()
136*0b57cec5SDimitry Andric                               ? dwarf::DW_EH_PE_indirect |
137*0b57cec5SDimitry Andric                                     dwarf::DW_EH_PE_pcrel |
138*0b57cec5SDimitry Andric                                     dwarf::DW_EH_PE_sdata4
139*0b57cec5SDimitry Andric                               : dwarf::DW_EH_PE_absptr;
140*0b57cec5SDimitry Andric     LSDAEncoding = isPositionIndependent()
141*0b57cec5SDimitry Andric                        ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
142*0b57cec5SDimitry Andric                        : dwarf::DW_EH_PE_absptr;
143*0b57cec5SDimitry Andric     TTypeEncoding = isPositionIndependent()
144*0b57cec5SDimitry Andric                         ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
145*0b57cec5SDimitry Andric                               dwarf::DW_EH_PE_sdata4
146*0b57cec5SDimitry Andric                         : dwarf::DW_EH_PE_absptr;
147*0b57cec5SDimitry Andric     break;
148*0b57cec5SDimitry Andric   case Triple::x86_64:
149*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
150*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
151*0b57cec5SDimitry Andric         ((CM == CodeModel::Small || CM == CodeModel::Medium)
152*0b57cec5SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
153*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel |
154*0b57cec5SDimitry Andric         (CM == CodeModel::Small
155*0b57cec5SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
156*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
157*0b57cec5SDimitry Andric         ((CM == CodeModel::Small || CM == CodeModel::Medium)
158fe6060f1SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
159*0b57cec5SDimitry Andric     } else {
160*0b57cec5SDimitry Andric       PersonalityEncoding =
161*0b57cec5SDimitry Andric         (CM == CodeModel::Small || CM == CodeModel::Medium)
162*0b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
163*0b57cec5SDimitry Andric       LSDAEncoding = (CM == CodeModel::Small)
164*0b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
165*0b57cec5SDimitry Andric       TTypeEncoding = (CM == CodeModel::Small)
166*0b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
167*0b57cec5SDimitry Andric     }
168*0b57cec5SDimitry Andric     break;
169*0b57cec5SDimitry Andric   case Triple::hexagon:
170*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
171*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_absptr;
172*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_absptr;
173*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
174*0b57cec5SDimitry Andric       PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
175*0b57cec5SDimitry Andric       LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
176*0b57cec5SDimitry Andric       TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
177*0b57cec5SDimitry Andric     }
178*0b57cec5SDimitry Andric     break;
179*0b57cec5SDimitry Andric   case Triple::aarch64:
180*0b57cec5SDimitry Andric   case Triple::aarch64_be:
1818bcb0991SDimitry Andric   case Triple::aarch64_32:
182*0b57cec5SDimitry Andric     // The small model guarantees static code/data size < 4GB, but not where it
183*0b57cec5SDimitry Andric     // will be in memory. Most of these could end up >2GB away so even a signed
184*0b57cec5SDimitry Andric     // pc-relative 32-bit address is insufficient, theoretically.
185*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
186e8d8bef9SDimitry Andric       // ILP32 uses sdata4 instead of sdata8
187e8d8bef9SDimitry Andric       if (TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32) {
188e8d8bef9SDimitry Andric         PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
189e8d8bef9SDimitry Andric                               dwarf::DW_EH_PE_sdata4;
190e8d8bef9SDimitry Andric         LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
191e8d8bef9SDimitry Andric         TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
192e8d8bef9SDimitry Andric                         dwarf::DW_EH_PE_sdata4;
193e8d8bef9SDimitry Andric       } else {
194*0b57cec5SDimitry Andric         PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
195*0b57cec5SDimitry Andric                               dwarf::DW_EH_PE_sdata8;
196*0b57cec5SDimitry Andric         LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
197*0b57cec5SDimitry Andric         TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
198*0b57cec5SDimitry Andric                         dwarf::DW_EH_PE_sdata8;
199e8d8bef9SDimitry Andric       }
200*0b57cec5SDimitry Andric     } else {
201*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
202*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
203*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
204*0b57cec5SDimitry Andric     }
205*0b57cec5SDimitry Andric     break;
206*0b57cec5SDimitry Andric   case Triple::lanai:
207*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_absptr;
208*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
209*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_absptr;
210*0b57cec5SDimitry Andric     break;
211*0b57cec5SDimitry Andric   case Triple::mips:
212*0b57cec5SDimitry Andric   case Triple::mipsel:
213*0b57cec5SDimitry Andric   case Triple::mips64:
214*0b57cec5SDimitry Andric   case Triple::mips64el:
215*0b57cec5SDimitry Andric     // MIPS uses indirect pointer to refer personality functions and types, so
216*0b57cec5SDimitry Andric     // that the eh_frame section can be read-only. DW.ref.personality will be
217*0b57cec5SDimitry Andric     // generated for relocation.
218*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect;
219*0b57cec5SDimitry Andric     // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
220*0b57cec5SDimitry Andric     //        identify N64 from just a triple.
221*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
222*0b57cec5SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
223*0b57cec5SDimitry Andric     // We don't support PC-relative LSDA references in GAS so we use the default
224*0b57cec5SDimitry Andric     // DW_EH_PE_absptr for those.
225*0b57cec5SDimitry Andric 
226*0b57cec5SDimitry Andric     // FreeBSD must be explicit about the data size and using pcrel since it's
227*0b57cec5SDimitry Andric     // assembler/linker won't do the automatic conversion that the Linux tools
228*0b57cec5SDimitry Andric     // do.
229*0b57cec5SDimitry Andric     if (TgtM.getTargetTriple().isOSFreeBSD()) {
230*0b57cec5SDimitry Andric       PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
231*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
232*0b57cec5SDimitry Andric     }
233*0b57cec5SDimitry Andric     break;
234*0b57cec5SDimitry Andric   case Triple::ppc64:
235*0b57cec5SDimitry Andric   case Triple::ppc64le:
236*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
237*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_udata8;
238*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
239*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
240*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_udata8;
241*0b57cec5SDimitry Andric     break;
242*0b57cec5SDimitry Andric   case Triple::sparcel:
243*0b57cec5SDimitry Andric   case Triple::sparc:
244*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
245*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
246*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
247*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
248*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
249*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
250*0b57cec5SDimitry Andric     } else {
251*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
252*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
253*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
254*0b57cec5SDimitry Andric     }
255*0b57cec5SDimitry Andric     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
256*0b57cec5SDimitry Andric     break;
257*0b57cec5SDimitry Andric   case Triple::riscv32:
258*0b57cec5SDimitry Andric   case Triple::riscv64:
259*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
260*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
261*0b57cec5SDimitry Andric                           dwarf::DW_EH_PE_sdata4;
262*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
263*0b57cec5SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
264*0b57cec5SDimitry Andric     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
265*0b57cec5SDimitry Andric     break;
266*0b57cec5SDimitry Andric   case Triple::sparcv9:
267*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
268*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
269*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
270*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
271*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
272*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
273*0b57cec5SDimitry Andric     } else {
274*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
275*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
276*0b57cec5SDimitry Andric     }
277*0b57cec5SDimitry Andric     break;
278*0b57cec5SDimitry Andric   case Triple::systemz:
279*0b57cec5SDimitry Andric     // All currently-defined code models guarantee that 4-byte PC-relative
280*0b57cec5SDimitry Andric     // values will be in range.
281*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
282*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
283*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
284*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
285*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
286*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
287*0b57cec5SDimitry Andric     } else {
288*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
289*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
290*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
291*0b57cec5SDimitry Andric     }
292*0b57cec5SDimitry Andric     break;
293bdd1243dSDimitry Andric   case Triple::loongarch32:
294bdd1243dSDimitry Andric   case Triple::loongarch64:
295bdd1243dSDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
296bdd1243dSDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
297bdd1243dSDimitry Andric                           dwarf::DW_EH_PE_sdata4;
298bdd1243dSDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
299bdd1243dSDimitry Andric                     dwarf::DW_EH_PE_sdata4;
300bdd1243dSDimitry Andric     break;
301*0b57cec5SDimitry Andric   default:
302*0b57cec5SDimitry Andric     break;
303*0b57cec5SDimitry Andric   }
304*0b57cec5SDimitry Andric }
305*0b57cec5SDimitry Andric 
306fe6060f1SDimitry Andric void TargetLoweringObjectFileELF::getModuleMetadata(Module &M) {
307fe6060f1SDimitry Andric   SmallVector<GlobalValue *, 4> Vec;
308fe6060f1SDimitry Andric   collectUsedGlobalVariables(M, Vec, false);
309fe6060f1SDimitry Andric   for (GlobalValue *GV : Vec)
310fe6060f1SDimitry Andric     if (auto *GO = dyn_cast<GlobalObject>(GV))
311fe6060f1SDimitry Andric       Used.insert(GO);
312fe6060f1SDimitry Andric }
313fe6060f1SDimitry Andric 
314*0b57cec5SDimitry Andric void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
315*0b57cec5SDimitry Andric                                                      Module &M) const {
316*0b57cec5SDimitry Andric   auto &C = getContext();
317*0b57cec5SDimitry Andric 
318*0b57cec5SDimitry Andric   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
319*0b57cec5SDimitry Andric     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
320*0b57cec5SDimitry Andric                               ELF::SHF_EXCLUDE);
321*0b57cec5SDimitry Andric 
32281ad6265SDimitry Andric     Streamer.switchSection(S);
323*0b57cec5SDimitry Andric 
324480093f4SDimitry Andric     for (const auto *Operand : LinkerOptions->operands()) {
325*0b57cec5SDimitry Andric       if (cast<MDNode>(Operand)->getNumOperands() != 2)
326*0b57cec5SDimitry Andric         report_fatal_error("invalid llvm.linker.options");
327*0b57cec5SDimitry Andric       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
3285ffd83dbSDimitry Andric         Streamer.emitBytes(cast<MDString>(Option)->getString());
3295ffd83dbSDimitry Andric         Streamer.emitInt8(0);
330*0b57cec5SDimitry Andric       }
331*0b57cec5SDimitry Andric     }
332*0b57cec5SDimitry Andric   }
333*0b57cec5SDimitry Andric 
334*0b57cec5SDimitry Andric   if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
335*0b57cec5SDimitry Andric     auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
336fe6060f1SDimitry Andric                               ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
337*0b57cec5SDimitry Andric 
33881ad6265SDimitry Andric     Streamer.switchSection(S);
339*0b57cec5SDimitry Andric 
340480093f4SDimitry Andric     for (const auto *Operand : DependentLibraries->operands()) {
3415ffd83dbSDimitry Andric       Streamer.emitBytes(
342*0b57cec5SDimitry Andric           cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
3435ffd83dbSDimitry Andric       Streamer.emitInt8(0);
344*0b57cec5SDimitry Andric     }
345*0b57cec5SDimitry Andric   }
346*0b57cec5SDimitry Andric 
347e8d8bef9SDimitry Andric   if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
348e8d8bef9SDimitry Andric     // Emit a descriptor for every function including functions that have an
349e8d8bef9SDimitry Andric     // available external linkage. We may not want this for imported functions
350e8d8bef9SDimitry Andric     // that has code in another thinLTO module but we don't have a good way to
351e8d8bef9SDimitry Andric     // tell them apart from inline functions defined in header files. Therefore
352e8d8bef9SDimitry Andric     // we put each descriptor in a separate comdat section and rely on the
353e8d8bef9SDimitry Andric     // linker to deduplicate.
354e8d8bef9SDimitry Andric     for (const auto *Operand : FuncInfo->operands()) {
355e8d8bef9SDimitry Andric       const auto *MD = cast<MDNode>(Operand);
356e8d8bef9SDimitry Andric       auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
357e8d8bef9SDimitry Andric       auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
358e8d8bef9SDimitry Andric       auto *Name = cast<MDString>(MD->getOperand(2));
359e8d8bef9SDimitry Andric       auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
360e8d8bef9SDimitry Andric           TM->getFunctionSections() ? Name->getString() : StringRef());
361e8d8bef9SDimitry Andric 
36281ad6265SDimitry Andric       Streamer.switchSection(S);
363e8d8bef9SDimitry Andric       Streamer.emitInt64(GUID->getZExtValue());
364e8d8bef9SDimitry Andric       Streamer.emitInt64(Hash->getZExtValue());
365e8d8bef9SDimitry Andric       Streamer.emitULEB128IntValue(Name->getString().size());
366e8d8bef9SDimitry Andric       Streamer.emitBytes(Name->getString());
367e8d8bef9SDimitry Andric     }
368e8d8bef9SDimitry Andric   }
369e8d8bef9SDimitry Andric 
370bdd1243dSDimitry Andric   if (NamedMDNode *LLVMStats = M.getNamedMetadata("llvm.stats")) {
371bdd1243dSDimitry Andric     // Emit the metadata for llvm statistics into .llvm_stats section, which is
372bdd1243dSDimitry Andric     // formatted as a list of key/value pair, the value is base64 encoded.
373bdd1243dSDimitry Andric     auto *S = C.getObjectFileInfo()->getLLVMStatsSection();
374bdd1243dSDimitry Andric     Streamer.switchSection(S);
375bdd1243dSDimitry Andric     for (const auto *Operand : LLVMStats->operands()) {
376bdd1243dSDimitry Andric       const auto *MD = cast<MDNode>(Operand);
377bdd1243dSDimitry Andric       assert(MD->getNumOperands() % 2 == 0 &&
378bdd1243dSDimitry Andric              ("Operand num should be even for a list of key/value pair"));
379bdd1243dSDimitry Andric       for (size_t I = 0; I < MD->getNumOperands(); I += 2) {
380bdd1243dSDimitry Andric         // Encode the key string size.
381bdd1243dSDimitry Andric         auto *Key = cast<MDString>(MD->getOperand(I));
382bdd1243dSDimitry Andric         Streamer.emitULEB128IntValue(Key->getString().size());
383bdd1243dSDimitry Andric         Streamer.emitBytes(Key->getString());
384bdd1243dSDimitry Andric         // Encode the value into a Base64 string.
385bdd1243dSDimitry Andric         std::string Value = encodeBase64(
386bdd1243dSDimitry Andric             Twine(mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1))
387bdd1243dSDimitry Andric                       ->getZExtValue())
388bdd1243dSDimitry Andric                 .str());
389bdd1243dSDimitry Andric         Streamer.emitULEB128IntValue(Value.size());
390bdd1243dSDimitry Andric         Streamer.emitBytes(Value);
391bdd1243dSDimitry Andric       }
392bdd1243dSDimitry Andric     }
393bdd1243dSDimitry Andric   }
394bdd1243dSDimitry Andric 
395*0b57cec5SDimitry Andric   unsigned Version = 0;
396*0b57cec5SDimitry Andric   unsigned Flags = 0;
397*0b57cec5SDimitry Andric   StringRef Section;
398*0b57cec5SDimitry Andric 
399*0b57cec5SDimitry Andric   GetObjCImageInfo(M, Version, Flags, Section);
400*0b57cec5SDimitry Andric   if (!Section.empty()) {
401*0b57cec5SDimitry Andric     auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
40281ad6265SDimitry Andric     Streamer.switchSection(S);
4035ffd83dbSDimitry Andric     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
4045ffd83dbSDimitry Andric     Streamer.emitInt32(Version);
4055ffd83dbSDimitry Andric     Streamer.emitInt32(Flags);
40681ad6265SDimitry Andric     Streamer.addBlankLine();
407*0b57cec5SDimitry Andric   }
408*0b57cec5SDimitry Andric 
409e8d8bef9SDimitry Andric   emitCGProfileMetadata(Streamer, M);
410*0b57cec5SDimitry Andric }
411*0b57cec5SDimitry Andric 
412*0b57cec5SDimitry Andric MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
413*0b57cec5SDimitry Andric     const GlobalValue *GV, const TargetMachine &TM,
414*0b57cec5SDimitry Andric     MachineModuleInfo *MMI) const {
415*0b57cec5SDimitry Andric   unsigned Encoding = getPersonalityEncoding();
416*0b57cec5SDimitry Andric   if ((Encoding & 0x80) == DW_EH_PE_indirect)
417*0b57cec5SDimitry Andric     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
418*0b57cec5SDimitry Andric                                           TM.getSymbol(GV)->getName());
419*0b57cec5SDimitry Andric   if ((Encoding & 0x70) == DW_EH_PE_absptr)
420*0b57cec5SDimitry Andric     return TM.getSymbol(GV);
421*0b57cec5SDimitry Andric   report_fatal_error("We do not support this DWARF encoding yet!");
422*0b57cec5SDimitry Andric }
423*0b57cec5SDimitry Andric 
424*0b57cec5SDimitry Andric void TargetLoweringObjectFileELF::emitPersonalityValue(
425*0b57cec5SDimitry Andric     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
426*0b57cec5SDimitry Andric   SmallString<64> NameData("DW.ref.");
427*0b57cec5SDimitry Andric   NameData += Sym->getName();
428*0b57cec5SDimitry Andric   MCSymbolELF *Label =
429*0b57cec5SDimitry Andric       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
4305ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
4315ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_Weak);
432*0b57cec5SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
433*0b57cec5SDimitry Andric   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
434*0b57cec5SDimitry Andric                                                    ELF::SHT_PROGBITS, Flags, 0);
435*0b57cec5SDimitry Andric   unsigned Size = DL.getPointerSize();
43681ad6265SDimitry Andric   Streamer.switchSection(Sec);
437bdd1243dSDimitry Andric   Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0));
4385ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
439*0b57cec5SDimitry Andric   const MCExpr *E = MCConstantExpr::create(Size, getContext());
440*0b57cec5SDimitry Andric   Streamer.emitELFSize(Label, E);
4415ffd83dbSDimitry Andric   Streamer.emitLabel(Label);
442*0b57cec5SDimitry Andric 
4435ffd83dbSDimitry Andric   Streamer.emitSymbolValue(Sym, Size);
444*0b57cec5SDimitry Andric }
445*0b57cec5SDimitry Andric 
446*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
447*0b57cec5SDimitry Andric     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
448*0b57cec5SDimitry Andric     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
449*0b57cec5SDimitry Andric   if (Encoding & DW_EH_PE_indirect) {
450*0b57cec5SDimitry Andric     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
451*0b57cec5SDimitry Andric 
452*0b57cec5SDimitry Andric     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
453*0b57cec5SDimitry Andric 
454*0b57cec5SDimitry Andric     // Add information about the stub reference to ELFMMI so that the stub
455*0b57cec5SDimitry Andric     // gets emitted by the asmprinter.
456*0b57cec5SDimitry Andric     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
457*0b57cec5SDimitry Andric     if (!StubSym.getPointer()) {
458*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(GV);
459*0b57cec5SDimitry Andric       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
460*0b57cec5SDimitry Andric     }
461*0b57cec5SDimitry Andric 
462*0b57cec5SDimitry Andric     return TargetLoweringObjectFile::
463*0b57cec5SDimitry Andric       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
464*0b57cec5SDimitry Andric                         Encoding & ~DW_EH_PE_indirect, Streamer);
465*0b57cec5SDimitry Andric   }
466*0b57cec5SDimitry Andric 
467*0b57cec5SDimitry Andric   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
468*0b57cec5SDimitry Andric                                                            MMI, Streamer);
469*0b57cec5SDimitry Andric }
470*0b57cec5SDimitry Andric 
471*0b57cec5SDimitry Andric static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
472*0b57cec5SDimitry Andric   // N.B.: The defaults used in here are not the same ones used in MC.
473*0b57cec5SDimitry Andric   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
474*0b57cec5SDimitry Andric   // both gas and MC will produce a section with no flags. Given
475*0b57cec5SDimitry Andric   // section(".eh_frame") gcc will produce:
476*0b57cec5SDimitry Andric   //
477*0b57cec5SDimitry Andric   //   .section   .eh_frame,"a",@progbits
478*0b57cec5SDimitry Andric 
479*0b57cec5SDimitry Andric   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
4805ffd83dbSDimitry Andric                                       /*AddSegmentInfo=*/false) ||
4815ffd83dbSDimitry Andric       Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
482e8d8bef9SDimitry Andric                                       /*AddSegmentInfo=*/false) ||
483e8d8bef9SDimitry Andric       Name == ".llvmbc" || Name == ".llvmcmd")
484*0b57cec5SDimitry Andric     return SectionKind::getMetadata();
485*0b57cec5SDimitry Andric 
486*0b57cec5SDimitry Andric   if (Name.empty() || Name[0] != '.') return K;
487*0b57cec5SDimitry Andric 
488*0b57cec5SDimitry Andric   // Default implementation based on some magic section names.
489*0b57cec5SDimitry Andric   if (Name == ".bss" ||
490*0b57cec5SDimitry Andric       Name.startswith(".bss.") ||
491*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.b.") ||
492*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.b.") ||
493*0b57cec5SDimitry Andric       Name == ".sbss" ||
494*0b57cec5SDimitry Andric       Name.startswith(".sbss.") ||
495*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.sb.") ||
496*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.sb."))
497*0b57cec5SDimitry Andric     return SectionKind::getBSS();
498*0b57cec5SDimitry Andric 
499*0b57cec5SDimitry Andric   if (Name == ".tdata" ||
500*0b57cec5SDimitry Andric       Name.startswith(".tdata.") ||
501*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.td.") ||
502*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.td."))
503*0b57cec5SDimitry Andric     return SectionKind::getThreadData();
504*0b57cec5SDimitry Andric 
505*0b57cec5SDimitry Andric   if (Name == ".tbss" ||
506*0b57cec5SDimitry Andric       Name.startswith(".tbss.") ||
507*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.tb.") ||
508*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.tb."))
509*0b57cec5SDimitry Andric     return SectionKind::getThreadBSS();
510*0b57cec5SDimitry Andric 
511*0b57cec5SDimitry Andric   return K;
512*0b57cec5SDimitry Andric }
513*0b57cec5SDimitry Andric 
51404eeddc0SDimitry Andric static bool hasPrefix(StringRef SectionName, StringRef Prefix) {
51504eeddc0SDimitry Andric   return SectionName.consume_front(Prefix) &&
51604eeddc0SDimitry Andric          (SectionName.empty() || SectionName[0] == '.');
51704eeddc0SDimitry Andric }
51804eeddc0SDimitry Andric 
519*0b57cec5SDimitry Andric static unsigned getELFSectionType(StringRef Name, SectionKind K) {
520*0b57cec5SDimitry Andric   // Use SHT_NOTE for section whose name starts with ".note" to allow
521*0b57cec5SDimitry Andric   // emitting ELF notes from C variable declaration.
522*0b57cec5SDimitry Andric   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
523*0b57cec5SDimitry Andric   if (Name.startswith(".note"))
524*0b57cec5SDimitry Andric     return ELF::SHT_NOTE;
525*0b57cec5SDimitry Andric 
52604eeddc0SDimitry Andric   if (hasPrefix(Name, ".init_array"))
527*0b57cec5SDimitry Andric     return ELF::SHT_INIT_ARRAY;
528*0b57cec5SDimitry Andric 
52904eeddc0SDimitry Andric   if (hasPrefix(Name, ".fini_array"))
530*0b57cec5SDimitry Andric     return ELF::SHT_FINI_ARRAY;
531*0b57cec5SDimitry Andric 
53204eeddc0SDimitry Andric   if (hasPrefix(Name, ".preinit_array"))
533*0b57cec5SDimitry Andric     return ELF::SHT_PREINIT_ARRAY;
534*0b57cec5SDimitry Andric 
535753f127fSDimitry Andric   if (hasPrefix(Name, ".llvm.offloading"))
536753f127fSDimitry Andric     return ELF::SHT_LLVM_OFFLOADING;
537753f127fSDimitry Andric 
538*0b57cec5SDimitry Andric   if (K.isBSS() || K.isThreadBSS())
539*0b57cec5SDimitry Andric     return ELF::SHT_NOBITS;
540*0b57cec5SDimitry Andric 
541*0b57cec5SDimitry Andric   return ELF::SHT_PROGBITS;
542*0b57cec5SDimitry Andric }
543*0b57cec5SDimitry Andric 
544*0b57cec5SDimitry Andric static unsigned getELFSectionFlags(SectionKind K) {
545*0b57cec5SDimitry Andric   unsigned Flags = 0;
546*0b57cec5SDimitry Andric 
54781ad6265SDimitry Andric   if (!K.isMetadata() && !K.isExclude())
548*0b57cec5SDimitry Andric     Flags |= ELF::SHF_ALLOC;
549*0b57cec5SDimitry Andric 
55081ad6265SDimitry Andric   if (K.isExclude())
55181ad6265SDimitry Andric     Flags |= ELF::SHF_EXCLUDE;
55281ad6265SDimitry Andric 
553*0b57cec5SDimitry Andric   if (K.isText())
554*0b57cec5SDimitry Andric     Flags |= ELF::SHF_EXECINSTR;
555*0b57cec5SDimitry Andric 
556*0b57cec5SDimitry Andric   if (K.isExecuteOnly())
557*0b57cec5SDimitry Andric     Flags |= ELF::SHF_ARM_PURECODE;
558*0b57cec5SDimitry Andric 
559*0b57cec5SDimitry Andric   if (K.isWriteable())
560*0b57cec5SDimitry Andric     Flags |= ELF::SHF_WRITE;
561*0b57cec5SDimitry Andric 
562*0b57cec5SDimitry Andric   if (K.isThreadLocal())
563*0b57cec5SDimitry Andric     Flags |= ELF::SHF_TLS;
564*0b57cec5SDimitry Andric 
565*0b57cec5SDimitry Andric   if (K.isMergeableCString() || K.isMergeableConst())
566*0b57cec5SDimitry Andric     Flags |= ELF::SHF_MERGE;
567*0b57cec5SDimitry Andric 
568*0b57cec5SDimitry Andric   if (K.isMergeableCString())
569*0b57cec5SDimitry Andric     Flags |= ELF::SHF_STRINGS;
570*0b57cec5SDimitry Andric 
571*0b57cec5SDimitry Andric   return Flags;
572*0b57cec5SDimitry Andric }
573*0b57cec5SDimitry Andric 
574*0b57cec5SDimitry Andric static const Comdat *getELFComdat(const GlobalValue *GV) {
575*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
576*0b57cec5SDimitry Andric   if (!C)
577*0b57cec5SDimitry Andric     return nullptr;
578*0b57cec5SDimitry Andric 
579fe6060f1SDimitry Andric   if (C->getSelectionKind() != Comdat::Any &&
580fe6060f1SDimitry Andric       C->getSelectionKind() != Comdat::NoDeduplicate)
581fe6060f1SDimitry Andric     report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
582fe6060f1SDimitry Andric                        "SelectionKind::NoDeduplicate, '" +
583*0b57cec5SDimitry Andric                        C->getName() + "' cannot be lowered.");
584*0b57cec5SDimitry Andric 
585*0b57cec5SDimitry Andric   return C;
586*0b57cec5SDimitry Andric }
587*0b57cec5SDimitry Andric 
5885ffd83dbSDimitry Andric static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
589*0b57cec5SDimitry Andric                                             const TargetMachine &TM) {
590*0b57cec5SDimitry Andric   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
591*0b57cec5SDimitry Andric   if (!MD)
592*0b57cec5SDimitry Andric     return nullptr;
593*0b57cec5SDimitry Andric 
594*0b57cec5SDimitry Andric   const MDOperand &Op = MD->getOperand(0);
595*0b57cec5SDimitry Andric   if (!Op.get())
596*0b57cec5SDimitry Andric     return nullptr;
597*0b57cec5SDimitry Andric 
598*0b57cec5SDimitry Andric   auto *VM = dyn_cast<ValueAsMetadata>(Op);
599*0b57cec5SDimitry Andric   if (!VM)
600*0b57cec5SDimitry Andric     report_fatal_error("MD_associated operand is not ValueAsMetadata");
601*0b57cec5SDimitry Andric 
6028bcb0991SDimitry Andric   auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
6038bcb0991SDimitry Andric   return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
604*0b57cec5SDimitry Andric }
605*0b57cec5SDimitry Andric 
606*0b57cec5SDimitry Andric static unsigned getEntrySizeForKind(SectionKind Kind) {
607*0b57cec5SDimitry Andric   if (Kind.isMergeable1ByteCString())
608*0b57cec5SDimitry Andric     return 1;
609*0b57cec5SDimitry Andric   else if (Kind.isMergeable2ByteCString())
610*0b57cec5SDimitry Andric     return 2;
611*0b57cec5SDimitry Andric   else if (Kind.isMergeable4ByteCString())
612*0b57cec5SDimitry Andric     return 4;
613*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst4())
614*0b57cec5SDimitry Andric     return 4;
615*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst8())
616*0b57cec5SDimitry Andric     return 8;
617*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst16())
618*0b57cec5SDimitry Andric     return 16;
619*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst32())
620*0b57cec5SDimitry Andric     return 32;
621*0b57cec5SDimitry Andric   else {
622*0b57cec5SDimitry Andric     // We shouldn't have mergeable C strings or mergeable constants that we
623*0b57cec5SDimitry Andric     // didn't handle above.
624*0b57cec5SDimitry Andric     assert(!Kind.isMergeableCString() && "unknown string width");
625*0b57cec5SDimitry Andric     assert(!Kind.isMergeableConst() && "unknown data width");
626*0b57cec5SDimitry Andric     return 0;
627*0b57cec5SDimitry Andric   }
628*0b57cec5SDimitry Andric }
629*0b57cec5SDimitry Andric 
6305ffd83dbSDimitry Andric /// Return the section prefix name used by options FunctionsSections and
6315ffd83dbSDimitry Andric /// DataSections.
6325ffd83dbSDimitry Andric static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
6335ffd83dbSDimitry Andric   if (Kind.isText())
6345ffd83dbSDimitry Andric     return ".text";
6355ffd83dbSDimitry Andric   if (Kind.isReadOnly())
6365ffd83dbSDimitry Andric     return ".rodata";
6375ffd83dbSDimitry Andric   if (Kind.isBSS())
6385ffd83dbSDimitry Andric     return ".bss";
6395ffd83dbSDimitry Andric   if (Kind.isThreadData())
6405ffd83dbSDimitry Andric     return ".tdata";
6415ffd83dbSDimitry Andric   if (Kind.isThreadBSS())
6425ffd83dbSDimitry Andric     return ".tbss";
6435ffd83dbSDimitry Andric   if (Kind.isData())
6445ffd83dbSDimitry Andric     return ".data";
6455ffd83dbSDimitry Andric   if (Kind.isReadOnlyWithRel())
6465ffd83dbSDimitry Andric     return ".data.rel.ro";
6475ffd83dbSDimitry Andric   llvm_unreachable("Unknown section kind");
6485ffd83dbSDimitry Andric }
6495ffd83dbSDimitry Andric 
6505ffd83dbSDimitry Andric static SmallString<128>
6515ffd83dbSDimitry Andric getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind,
6525ffd83dbSDimitry Andric                            Mangler &Mang, const TargetMachine &TM,
6535ffd83dbSDimitry Andric                            unsigned EntrySize, bool UniqueSectionName) {
6545ffd83dbSDimitry Andric   SmallString<128> Name;
6555ffd83dbSDimitry Andric   if (Kind.isMergeableCString()) {
6565ffd83dbSDimitry Andric     // We also need alignment here.
6575ffd83dbSDimitry Andric     // FIXME: this is getting the alignment of the character, not the
6585ffd83dbSDimitry Andric     // alignment of the global!
6595ffd83dbSDimitry Andric     Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
6605ffd83dbSDimitry Andric         cast<GlobalVariable>(GO));
6615ffd83dbSDimitry Andric 
6625ffd83dbSDimitry Andric     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
6635ffd83dbSDimitry Andric     Name = SizeSpec + utostr(Alignment.value());
6645ffd83dbSDimitry Andric   } else if (Kind.isMergeableConst()) {
6655ffd83dbSDimitry Andric     Name = ".rodata.cst";
6665ffd83dbSDimitry Andric     Name += utostr(EntrySize);
6675ffd83dbSDimitry Andric   } else {
6685ffd83dbSDimitry Andric     Name = getSectionPrefixForGlobal(Kind);
6695ffd83dbSDimitry Andric   }
6705ffd83dbSDimitry Andric 
6715ffd83dbSDimitry Andric   bool HasPrefix = false;
6725ffd83dbSDimitry Andric   if (const auto *F = dyn_cast<Function>(GO)) {
673bdd1243dSDimitry Andric     if (std::optional<StringRef> Prefix = F->getSectionPrefix()) {
674e8d8bef9SDimitry Andric       raw_svector_ostream(Name) << '.' << *Prefix;
6755ffd83dbSDimitry Andric       HasPrefix = true;
6765ffd83dbSDimitry Andric     }
6775ffd83dbSDimitry Andric   }
6785ffd83dbSDimitry Andric 
6795ffd83dbSDimitry Andric   if (UniqueSectionName) {
6805ffd83dbSDimitry Andric     Name.push_back('.');
6815ffd83dbSDimitry Andric     TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
6825ffd83dbSDimitry Andric   } else if (HasPrefix)
683fe6060f1SDimitry Andric     // For distinguishing between .text.${text-section-prefix}. (with trailing
684fe6060f1SDimitry Andric     // dot) and .text.${function-name}
6855ffd83dbSDimitry Andric     Name.push_back('.');
6865ffd83dbSDimitry Andric   return Name;
6875ffd83dbSDimitry Andric }
6885ffd83dbSDimitry Andric 
6895ffd83dbSDimitry Andric namespace {
6905ffd83dbSDimitry Andric class LoweringDiagnosticInfo : public DiagnosticInfo {
6915ffd83dbSDimitry Andric   const Twine &Msg;
6925ffd83dbSDimitry Andric 
6935ffd83dbSDimitry Andric public:
6945ffd83dbSDimitry Andric   LoweringDiagnosticInfo(const Twine &DiagMsg,
6955ffd83dbSDimitry Andric                          DiagnosticSeverity Severity = DS_Error)
6965ffd83dbSDimitry Andric       : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
6975ffd83dbSDimitry Andric   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
6985ffd83dbSDimitry Andric };
6995ffd83dbSDimitry Andric }
7005ffd83dbSDimitry Andric 
701fe6060f1SDimitry Andric /// Calculate an appropriate unique ID for a section, and update Flags,
702fe6060f1SDimitry Andric /// EntrySize and NextUniqueID where appropriate.
703fe6060f1SDimitry Andric static unsigned
704fe6060f1SDimitry Andric calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName,
705fe6060f1SDimitry Andric                                SectionKind Kind, const TargetMachine &TM,
706fe6060f1SDimitry Andric                                MCContext &Ctx, Mangler &Mang, unsigned &Flags,
707fe6060f1SDimitry Andric                                unsigned &EntrySize, unsigned &NextUniqueID,
708fe6060f1SDimitry Andric                                const bool Retain, const bool ForceUnique) {
709fe6060f1SDimitry Andric   // Increment uniqueID if we are forced to emit a unique section.
710fe6060f1SDimitry Andric   // This works perfectly fine with section attribute or pragma section as the
711fe6060f1SDimitry Andric   // sections with the same name are grouped together by the assembler.
712fe6060f1SDimitry Andric   if (ForceUnique)
713fe6060f1SDimitry Andric     return NextUniqueID++;
714fe6060f1SDimitry Andric 
715fe6060f1SDimitry Andric   // A section can have at most one associated section. Put each global with
716fe6060f1SDimitry Andric   // MD_associated in a unique section.
717fe6060f1SDimitry Andric   const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
718fe6060f1SDimitry Andric   if (Associated) {
719fe6060f1SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
720fe6060f1SDimitry Andric     return NextUniqueID++;
721fe6060f1SDimitry Andric   }
722fe6060f1SDimitry Andric 
723fe6060f1SDimitry Andric   if (Retain) {
72481ad6265SDimitry Andric     if (TM.getTargetTriple().isOSSolaris())
72581ad6265SDimitry Andric       Flags |= ELF::SHF_SUNW_NODISCARD;
72681ad6265SDimitry Andric     else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
72781ad6265SDimitry Andric              Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36))
728fe6060f1SDimitry Andric       Flags |= ELF::SHF_GNU_RETAIN;
729fe6060f1SDimitry Andric     return NextUniqueID++;
730fe6060f1SDimitry Andric   }
731fe6060f1SDimitry Andric 
732fe6060f1SDimitry Andric   // If two symbols with differing sizes end up in the same mergeable section
733fe6060f1SDimitry Andric   // that section can be assigned an incorrect entry size. To avoid this we
734fe6060f1SDimitry Andric   // usually put symbols of the same size into distinct mergeable sections with
735fe6060f1SDimitry Andric   // the same name. Doing so relies on the ",unique ," assembly feature. This
736fe6060f1SDimitry Andric   // feature is not avalible until bintuils version 2.35
737fe6060f1SDimitry Andric   // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
738fe6060f1SDimitry Andric   const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
739fe6060f1SDimitry Andric                               Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
740fe6060f1SDimitry Andric   if (!SupportsUnique) {
741fe6060f1SDimitry Andric     Flags &= ~ELF::SHF_MERGE;
742fe6060f1SDimitry Andric     EntrySize = 0;
743fe6060f1SDimitry Andric     return MCContext::GenericSectionID;
744fe6060f1SDimitry Andric   }
745fe6060f1SDimitry Andric 
746fe6060f1SDimitry Andric   const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
747fe6060f1SDimitry Andric   const bool SeenSectionNameBefore =
748fe6060f1SDimitry Andric       Ctx.isELFGenericMergeableSection(SectionName);
749fe6060f1SDimitry Andric   // If this is the first ocurrence of this section name, treat it as the
750fe6060f1SDimitry Andric   // generic section
751fe6060f1SDimitry Andric   if (!SymbolMergeable && !SeenSectionNameBefore)
752fe6060f1SDimitry Andric     return MCContext::GenericSectionID;
753fe6060f1SDimitry Andric 
754fe6060f1SDimitry Andric   // Symbols must be placed into sections with compatible entry sizes. Generate
755fe6060f1SDimitry Andric   // unique sections for symbols that have not been assigned to compatible
756fe6060f1SDimitry Andric   // sections.
757fe6060f1SDimitry Andric   const auto PreviousID =
758fe6060f1SDimitry Andric       Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
759fe6060f1SDimitry Andric   if (PreviousID)
760fe6060f1SDimitry Andric     return *PreviousID;
761fe6060f1SDimitry Andric 
762fe6060f1SDimitry Andric   // If the user has specified the same section name as would be created
763fe6060f1SDimitry Andric   // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
764fe6060f1SDimitry Andric   // to unique the section as the entry size for this symbol will be
765fe6060f1SDimitry Andric   // compatible with implicitly created sections.
766fe6060f1SDimitry Andric   SmallString<128> ImplicitSectionNameStem =
767fe6060f1SDimitry Andric       getELFSectionNameForGlobal(GO, Kind, Mang, TM, EntrySize, false);
768fe6060f1SDimitry Andric   if (SymbolMergeable &&
769fe6060f1SDimitry Andric       Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) &&
770fe6060f1SDimitry Andric       SectionName.startswith(ImplicitSectionNameStem))
771fe6060f1SDimitry Andric     return MCContext::GenericSectionID;
772fe6060f1SDimitry Andric 
773fe6060f1SDimitry Andric   // We have seen this section name before, but with different flags or entity
774fe6060f1SDimitry Andric   // size. Create a new unique ID.
775fe6060f1SDimitry Andric   return NextUniqueID++;
776fe6060f1SDimitry Andric }
777fe6060f1SDimitry Andric 
778fe6060f1SDimitry Andric static MCSection *selectExplicitSectionGlobal(
779fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM,
780fe6060f1SDimitry Andric     MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID,
781fe6060f1SDimitry Andric     bool Retain, bool ForceUnique) {
782*0b57cec5SDimitry Andric   StringRef SectionName = GO->getSection();
783*0b57cec5SDimitry Andric 
784*0b57cec5SDimitry Andric   // Check if '#pragma clang section' name is applicable.
785*0b57cec5SDimitry Andric   // Note that pragma directive overrides -ffunction-section, -fdata-section
786*0b57cec5SDimitry Andric   // and so section name is exactly as user specified and not uniqued.
787*0b57cec5SDimitry Andric   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
788*0b57cec5SDimitry Andric   if (GV && GV->hasImplicitSection()) {
789*0b57cec5SDimitry Andric     auto Attrs = GV->getAttributes();
790*0b57cec5SDimitry Andric     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
791*0b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
792*0b57cec5SDimitry Andric     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
793*0b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
7948bcb0991SDimitry Andric     } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
7958bcb0991SDimitry Andric       SectionName = Attrs.getAttribute("relro-section").getValueAsString();
796*0b57cec5SDimitry Andric     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
797*0b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("data-section").getValueAsString();
798*0b57cec5SDimitry Andric     }
799*0b57cec5SDimitry Andric   }
800*0b57cec5SDimitry Andric   const Function *F = dyn_cast<Function>(GO);
801*0b57cec5SDimitry Andric   if (F && F->hasFnAttribute("implicit-section-name")) {
802*0b57cec5SDimitry Andric     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
803*0b57cec5SDimitry Andric   }
804*0b57cec5SDimitry Andric 
805*0b57cec5SDimitry Andric   // Infer section flags from the section name if we can.
806*0b57cec5SDimitry Andric   Kind = getELFKindForNamedSection(SectionName, Kind);
807*0b57cec5SDimitry Andric 
808*0b57cec5SDimitry Andric   StringRef Group = "";
809fe6060f1SDimitry Andric   bool IsComdat = false;
810*0b57cec5SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
811*0b57cec5SDimitry Andric   if (const Comdat *C = getELFComdat(GO)) {
812*0b57cec5SDimitry Andric     Group = C->getName();
813fe6060f1SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
814*0b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
815*0b57cec5SDimitry Andric   }
816*0b57cec5SDimitry Andric 
8175ffd83dbSDimitry Andric   unsigned EntrySize = getEntrySizeForKind(Kind);
818fe6060f1SDimitry Andric   const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
819fe6060f1SDimitry Andric       GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
820fe6060f1SDimitry Andric       Retain, ForceUnique);
8215ffd83dbSDimitry Andric 
8225ffd83dbSDimitry Andric   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
823fe6060f1SDimitry Andric   MCSectionELF *Section = Ctx.getELFSection(
824fe6060f1SDimitry Andric       SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
825fe6060f1SDimitry Andric       Group, IsComdat, UniqueID, LinkedToSym);
826*0b57cec5SDimitry Andric   // Make sure that we did not get some other section with incompatible sh_link.
827*0b57cec5SDimitry Andric   // This should not be possible due to UniqueID code above.
8285ffd83dbSDimitry Andric   assert(Section->getLinkedToSymbol() == LinkedToSym &&
829*0b57cec5SDimitry Andric          "Associated symbol mismatch between sections");
8305ffd83dbSDimitry Andric 
831fe6060f1SDimitry Andric   if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
832fe6060f1SDimitry Andric         Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
833e8d8bef9SDimitry Andric     // If we are using GNU as before 2.35, then this symbol might have
8345ffd83dbSDimitry Andric     // been placed in an incompatible mergeable section. Emit an error if this
8355ffd83dbSDimitry Andric     // is the case to avoid creating broken output.
8365ffd83dbSDimitry Andric     if ((Section->getFlags() & ELF::SHF_MERGE) &&
8375ffd83dbSDimitry Andric         (Section->getEntrySize() != getEntrySizeForKind(Kind)))
8385ffd83dbSDimitry Andric       GO->getContext().diagnose(LoweringDiagnosticInfo(
8395ffd83dbSDimitry Andric           "Symbol '" + GO->getName() + "' from module '" +
8405ffd83dbSDimitry Andric           (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
8415ffd83dbSDimitry Andric           "' required a section with entry-size=" +
8425ffd83dbSDimitry Andric           Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
8435ffd83dbSDimitry Andric           SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
8445ffd83dbSDimitry Andric           ": Explicit assignment by pragma or attribute of an incompatible "
8455ffd83dbSDimitry Andric           "symbol to this section?"));
846*0b57cec5SDimitry Andric   }
847*0b57cec5SDimitry Andric 
8485ffd83dbSDimitry Andric   return Section;
849*0b57cec5SDimitry Andric }
850*0b57cec5SDimitry Andric 
851fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
852fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
853fe6060f1SDimitry Andric   return selectExplicitSectionGlobal(GO, Kind, TM, getContext(), getMangler(),
854fe6060f1SDimitry Andric                                      NextUniqueID, Used.count(GO),
855fe6060f1SDimitry Andric                                      /* ForceUnique = */false);
856fe6060f1SDimitry Andric }
857fe6060f1SDimitry Andric 
858*0b57cec5SDimitry Andric static MCSectionELF *selectELFSectionForGlobal(
859*0b57cec5SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
860*0b57cec5SDimitry Andric     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
861*0b57cec5SDimitry Andric     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
862*0b57cec5SDimitry Andric 
863*0b57cec5SDimitry Andric   StringRef Group = "";
864fe6060f1SDimitry Andric   bool IsComdat = false;
865*0b57cec5SDimitry Andric   if (const Comdat *C = getELFComdat(GO)) {
866*0b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
867*0b57cec5SDimitry Andric     Group = C->getName();
868fe6060f1SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
869*0b57cec5SDimitry Andric   }
870*0b57cec5SDimitry Andric 
871*0b57cec5SDimitry Andric   // Get the section entry size based on the kind.
872*0b57cec5SDimitry Andric   unsigned EntrySize = getEntrySizeForKind(Kind);
873*0b57cec5SDimitry Andric 
8745ffd83dbSDimitry Andric   bool UniqueSectionName = false;
875*0b57cec5SDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
876*0b57cec5SDimitry Andric   if (EmitUniqueSection) {
877*0b57cec5SDimitry Andric     if (TM.getUniqueSectionNames()) {
8785ffd83dbSDimitry Andric       UniqueSectionName = true;
879*0b57cec5SDimitry Andric     } else {
880*0b57cec5SDimitry Andric       UniqueID = *NextUniqueID;
881*0b57cec5SDimitry Andric       (*NextUniqueID)++;
882*0b57cec5SDimitry Andric     }
883*0b57cec5SDimitry Andric   }
8845ffd83dbSDimitry Andric   SmallString<128> Name = getELFSectionNameForGlobal(
8855ffd83dbSDimitry Andric       GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
8865ffd83dbSDimitry Andric 
887*0b57cec5SDimitry Andric   // Use 0 as the unique ID for execute-only text.
888*0b57cec5SDimitry Andric   if (Kind.isExecuteOnly())
889*0b57cec5SDimitry Andric     UniqueID = 0;
890*0b57cec5SDimitry Andric   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
891fe6060f1SDimitry Andric                            EntrySize, Group, IsComdat, UniqueID,
892fe6060f1SDimitry Andric                            AssociatedSymbol);
893fe6060f1SDimitry Andric }
894fe6060f1SDimitry Andric 
895fe6060f1SDimitry Andric static MCSection *selectELFSectionForGlobal(
896fe6060f1SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
897fe6060f1SDimitry Andric     const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
898fe6060f1SDimitry Andric     unsigned Flags, unsigned *NextUniqueID) {
899fe6060f1SDimitry Andric   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
900fe6060f1SDimitry Andric   if (LinkedToSym) {
901fe6060f1SDimitry Andric     EmitUniqueSection = true;
902fe6060f1SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
903fe6060f1SDimitry Andric   }
90481ad6265SDimitry Andric   if (Retain) {
90581ad6265SDimitry Andric     if (TM.getTargetTriple().isOSSolaris()) {
90681ad6265SDimitry Andric       EmitUniqueSection = true;
90781ad6265SDimitry Andric       Flags |= ELF::SHF_SUNW_NODISCARD;
90881ad6265SDimitry Andric     } else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
90981ad6265SDimitry Andric                Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) {
910fe6060f1SDimitry Andric       EmitUniqueSection = true;
911fe6060f1SDimitry Andric       Flags |= ELF::SHF_GNU_RETAIN;
912fe6060f1SDimitry Andric     }
91381ad6265SDimitry Andric   }
914fe6060f1SDimitry Andric 
915fe6060f1SDimitry Andric   MCSectionELF *Section = selectELFSectionForGlobal(
916fe6060f1SDimitry Andric       Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
917fe6060f1SDimitry Andric       NextUniqueID, LinkedToSym);
918fe6060f1SDimitry Andric   assert(Section->getLinkedToSymbol() == LinkedToSym);
919fe6060f1SDimitry Andric   return Section;
920*0b57cec5SDimitry Andric }
921*0b57cec5SDimitry Andric 
922*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
923*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
924*0b57cec5SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
925*0b57cec5SDimitry Andric 
926*0b57cec5SDimitry Andric   // If we have -ffunction-section or -fdata-section then we should emit the
927*0b57cec5SDimitry Andric   // global value to a uniqued section specifically for it.
928*0b57cec5SDimitry Andric   bool EmitUniqueSection = false;
929*0b57cec5SDimitry Andric   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
930*0b57cec5SDimitry Andric     if (Kind.isText())
931*0b57cec5SDimitry Andric       EmitUniqueSection = TM.getFunctionSections();
932*0b57cec5SDimitry Andric     else
933*0b57cec5SDimitry Andric       EmitUniqueSection = TM.getDataSections();
934*0b57cec5SDimitry Andric   }
935*0b57cec5SDimitry Andric   EmitUniqueSection |= GO->hasComdat();
936fe6060f1SDimitry Andric   return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
937fe6060f1SDimitry Andric                                    Used.count(GO), EmitUniqueSection, Flags,
938fe6060f1SDimitry Andric                                    &NextUniqueID);
939*0b57cec5SDimitry Andric }
940*0b57cec5SDimitry Andric 
941fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileELF::getUniqueSectionForFunction(
942fe6060f1SDimitry Andric     const Function &F, const TargetMachine &TM) const {
943fe6060f1SDimitry Andric   SectionKind Kind = SectionKind::getText();
944fe6060f1SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
945fe6060f1SDimitry Andric   // If the function's section names is pre-determined via pragma or a
946fe6060f1SDimitry Andric   // section attribute, call selectExplicitSectionGlobal.
947fe6060f1SDimitry Andric   if (F.hasSection() || F.hasFnAttribute("implicit-section-name"))
948fe6060f1SDimitry Andric     return selectExplicitSectionGlobal(
949fe6060f1SDimitry Andric         &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
950fe6060f1SDimitry Andric         Used.count(&F), /* ForceUnique = */true);
951fe6060f1SDimitry Andric   else
952fe6060f1SDimitry Andric     return selectELFSectionForGlobal(
953fe6060f1SDimitry Andric         getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
954fe6060f1SDimitry Andric         /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
955*0b57cec5SDimitry Andric }
956*0b57cec5SDimitry Andric 
957*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
958*0b57cec5SDimitry Andric     const Function &F, const TargetMachine &TM) const {
959*0b57cec5SDimitry Andric   // If the function can be removed, produce a unique section so that
960*0b57cec5SDimitry Andric   // the table doesn't prevent the removal.
961*0b57cec5SDimitry Andric   const Comdat *C = F.getComdat();
962*0b57cec5SDimitry Andric   bool EmitUniqueSection = TM.getFunctionSections() || C;
963*0b57cec5SDimitry Andric   if (!EmitUniqueSection)
964*0b57cec5SDimitry Andric     return ReadOnlySection;
965*0b57cec5SDimitry Andric 
966*0b57cec5SDimitry Andric   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
967*0b57cec5SDimitry Andric                                    getMangler(), TM, EmitUniqueSection,
968*0b57cec5SDimitry Andric                                    ELF::SHF_ALLOC, &NextUniqueID,
969*0b57cec5SDimitry Andric                                    /* AssociatedSymbol */ nullptr);
970*0b57cec5SDimitry Andric }
971*0b57cec5SDimitry Andric 
972fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForLSDA(
973fe6060f1SDimitry Andric     const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
974e8d8bef9SDimitry Andric   // If neither COMDAT nor function sections, use the monolithic LSDA section.
975e8d8bef9SDimitry Andric   // Re-use this path if LSDASection is null as in the Arm EHABI.
976e8d8bef9SDimitry Andric   if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
977e8d8bef9SDimitry Andric     return LSDASection;
978e8d8bef9SDimitry Andric 
979e8d8bef9SDimitry Andric   const auto *LSDA = cast<MCSectionELF>(LSDASection);
980e8d8bef9SDimitry Andric   unsigned Flags = LSDA->getFlags();
981fe6060f1SDimitry Andric   const MCSymbolELF *LinkedToSym = nullptr;
982e8d8bef9SDimitry Andric   StringRef Group;
983fe6060f1SDimitry Andric   bool IsComdat = false;
984fe6060f1SDimitry Andric   if (const Comdat *C = getELFComdat(&F)) {
985e8d8bef9SDimitry Andric     Flags |= ELF::SHF_GROUP;
986fe6060f1SDimitry Andric     Group = C->getName();
987fe6060f1SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
988fe6060f1SDimitry Andric   }
989fe6060f1SDimitry Andric   // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
990fe6060f1SDimitry Andric   // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
991fe6060f1SDimitry Andric   if (TM.getFunctionSections() &&
992fe6060f1SDimitry Andric       (getContext().getAsmInfo()->useIntegratedAssembler() &&
993fe6060f1SDimitry Andric        getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
994fe6060f1SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
995fe6060f1SDimitry Andric     LinkedToSym = cast<MCSymbolELF>(&FnSym);
996e8d8bef9SDimitry Andric   }
997e8d8bef9SDimitry Andric 
998e8d8bef9SDimitry Andric   // Append the function name as the suffix like GCC, assuming
999e8d8bef9SDimitry Andric   // -funique-section-names applies to .gcc_except_table sections.
1000fe6060f1SDimitry Andric   return getContext().getELFSection(
1001fe6060f1SDimitry Andric       (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
1002fe6060f1SDimitry Andric                                   : LSDA->getName()),
1003fe6060f1SDimitry Andric       LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
1004fe6060f1SDimitry Andric       LinkedToSym);
1005e8d8bef9SDimitry Andric }
1006e8d8bef9SDimitry Andric 
1007*0b57cec5SDimitry Andric bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
1008*0b57cec5SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
1009*0b57cec5SDimitry Andric   // We can always create relative relocations, so use another section
1010*0b57cec5SDimitry Andric   // that can be marked non-executable.
1011*0b57cec5SDimitry Andric   return false;
1012*0b57cec5SDimitry Andric }
1013*0b57cec5SDimitry Andric 
1014*0b57cec5SDimitry Andric /// Given a mergeable constant with the specified size and relocation
1015*0b57cec5SDimitry Andric /// information, return a section that it should be placed in.
1016*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
1017*0b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
10185ffd83dbSDimitry Andric     Align &Alignment) const {
1019*0b57cec5SDimitry Andric   if (Kind.isMergeableConst4() && MergeableConst4Section)
1020*0b57cec5SDimitry Andric     return MergeableConst4Section;
1021*0b57cec5SDimitry Andric   if (Kind.isMergeableConst8() && MergeableConst8Section)
1022*0b57cec5SDimitry Andric     return MergeableConst8Section;
1023*0b57cec5SDimitry Andric   if (Kind.isMergeableConst16() && MergeableConst16Section)
1024*0b57cec5SDimitry Andric     return MergeableConst16Section;
1025*0b57cec5SDimitry Andric   if (Kind.isMergeableConst32() && MergeableConst32Section)
1026*0b57cec5SDimitry Andric     return MergeableConst32Section;
1027*0b57cec5SDimitry Andric   if (Kind.isReadOnly())
1028*0b57cec5SDimitry Andric     return ReadOnlySection;
1029*0b57cec5SDimitry Andric 
1030*0b57cec5SDimitry Andric   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
1031*0b57cec5SDimitry Andric   return DataRelROSection;
1032*0b57cec5SDimitry Andric }
1033*0b57cec5SDimitry Andric 
10345ffd83dbSDimitry Andric /// Returns a unique section for the given machine basic block.
10355ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock(
10365ffd83dbSDimitry Andric     const Function &F, const MachineBasicBlock &MBB,
10375ffd83dbSDimitry Andric     const TargetMachine &TM) const {
10385ffd83dbSDimitry Andric   assert(MBB.isBeginSection() && "Basic block does not start a section!");
10395ffd83dbSDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
10405ffd83dbSDimitry Andric 
1041e8d8bef9SDimitry Andric   // For cold sections use the .text.split. prefix along with the parent
10425ffd83dbSDimitry Andric   // function name. All cold blocks for the same function go to the same
10435ffd83dbSDimitry Andric   // section. Similarly all exception blocks are grouped by symbol name
10445ffd83dbSDimitry Andric   // under the .text.eh prefix. For regular sections, we either use a unique
10455ffd83dbSDimitry Andric   // name, or a unique ID for the section.
10465ffd83dbSDimitry Andric   SmallString<128> Name;
10475ffd83dbSDimitry Andric   if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
1048e8d8bef9SDimitry Andric     Name += BBSectionsColdTextPrefix;
10495ffd83dbSDimitry Andric     Name += MBB.getParent()->getName();
10505ffd83dbSDimitry Andric   } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
10515ffd83dbSDimitry Andric     Name += ".text.eh.";
10525ffd83dbSDimitry Andric     Name += MBB.getParent()->getName();
10535ffd83dbSDimitry Andric   } else {
10545ffd83dbSDimitry Andric     Name += MBB.getParent()->getSection()->getName();
10555ffd83dbSDimitry Andric     if (TM.getUniqueBasicBlockSectionNames()) {
1056fe6060f1SDimitry Andric       if (!Name.endswith("."))
10575ffd83dbSDimitry Andric         Name += ".";
10585ffd83dbSDimitry Andric       Name += MBB.getSymbol()->getName();
10595ffd83dbSDimitry Andric     } else {
10605ffd83dbSDimitry Andric       UniqueID = NextUniqueID++;
10615ffd83dbSDimitry Andric     }
10625ffd83dbSDimitry Andric   }
10635ffd83dbSDimitry Andric 
10645ffd83dbSDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
1065e8d8bef9SDimitry Andric   std::string GroupName;
10665ffd83dbSDimitry Andric   if (F.hasComdat()) {
10675ffd83dbSDimitry Andric     Flags |= ELF::SHF_GROUP;
10685ffd83dbSDimitry Andric     GroupName = F.getComdat()->getName().str();
10695ffd83dbSDimitry Andric   }
10705ffd83dbSDimitry Andric   return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
1071fe6060f1SDimitry Andric                                     0 /* Entry Size */, GroupName,
1072fe6060f1SDimitry Andric                                     F.hasComdat(), UniqueID, nullptr);
10735ffd83dbSDimitry Andric }
10745ffd83dbSDimitry Andric 
1075*0b57cec5SDimitry Andric static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
1076*0b57cec5SDimitry Andric                                               bool IsCtor, unsigned Priority,
1077*0b57cec5SDimitry Andric                                               const MCSymbol *KeySym) {
1078*0b57cec5SDimitry Andric   std::string Name;
1079*0b57cec5SDimitry Andric   unsigned Type;
1080*0b57cec5SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1081fe6060f1SDimitry Andric   StringRef Comdat = KeySym ? KeySym->getName() : "";
1082*0b57cec5SDimitry Andric 
1083*0b57cec5SDimitry Andric   if (KeySym)
1084*0b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
1085*0b57cec5SDimitry Andric 
1086*0b57cec5SDimitry Andric   if (UseInitArray) {
1087*0b57cec5SDimitry Andric     if (IsCtor) {
1088*0b57cec5SDimitry Andric       Type = ELF::SHT_INIT_ARRAY;
1089*0b57cec5SDimitry Andric       Name = ".init_array";
1090*0b57cec5SDimitry Andric     } else {
1091*0b57cec5SDimitry Andric       Type = ELF::SHT_FINI_ARRAY;
1092*0b57cec5SDimitry Andric       Name = ".fini_array";
1093*0b57cec5SDimitry Andric     }
1094*0b57cec5SDimitry Andric     if (Priority != 65535) {
1095*0b57cec5SDimitry Andric       Name += '.';
1096*0b57cec5SDimitry Andric       Name += utostr(Priority);
1097*0b57cec5SDimitry Andric     }
1098*0b57cec5SDimitry Andric   } else {
1099*0b57cec5SDimitry Andric     // The default scheme is .ctor / .dtor, so we have to invert the priority
1100*0b57cec5SDimitry Andric     // numbering.
1101*0b57cec5SDimitry Andric     if (IsCtor)
1102*0b57cec5SDimitry Andric       Name = ".ctors";
1103*0b57cec5SDimitry Andric     else
1104*0b57cec5SDimitry Andric       Name = ".dtors";
1105*0b57cec5SDimitry Andric     if (Priority != 65535)
1106*0b57cec5SDimitry Andric       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1107*0b57cec5SDimitry Andric     Type = ELF::SHT_PROGBITS;
1108*0b57cec5SDimitry Andric   }
1109*0b57cec5SDimitry Andric 
1110fe6060f1SDimitry Andric   return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
1111*0b57cec5SDimitry Andric }
1112*0b57cec5SDimitry Andric 
1113*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
1114*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1115*0b57cec5SDimitry Andric   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
1116*0b57cec5SDimitry Andric                                   KeySym);
1117*0b57cec5SDimitry Andric }
1118*0b57cec5SDimitry Andric 
1119*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
1120*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1121*0b57cec5SDimitry Andric   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
1122*0b57cec5SDimitry Andric                                   KeySym);
1123*0b57cec5SDimitry Andric }
1124*0b57cec5SDimitry Andric 
1125*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
1126*0b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
1127*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1128*0b57cec5SDimitry Andric   // We may only use a PLT-relative relocation to refer to unnamed_addr
1129*0b57cec5SDimitry Andric   // functions.
1130*0b57cec5SDimitry Andric   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1131*0b57cec5SDimitry Andric     return nullptr;
1132*0b57cec5SDimitry Andric 
11334824e7fdSDimitry Andric   // Basic correctness checks.
1134*0b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1135*0b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1136*0b57cec5SDimitry Andric       RHS->isThreadLocal())
1137*0b57cec5SDimitry Andric     return nullptr;
1138*0b57cec5SDimitry Andric 
1139*0b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
1140*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
1141*0b57cec5SDimitry Andric                               getContext()),
1142*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1143*0b57cec5SDimitry Andric }
1144*0b57cec5SDimitry Andric 
1145e8d8bef9SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent(
1146e8d8bef9SDimitry Andric     const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
1147e8d8bef9SDimitry Andric   assert(supportDSOLocalEquivalentLowering());
1148e8d8bef9SDimitry Andric 
1149e8d8bef9SDimitry Andric   const auto *GV = Equiv->getGlobalValue();
1150e8d8bef9SDimitry Andric 
1151e8d8bef9SDimitry Andric   // A PLT entry is not needed for dso_local globals.
1152e8d8bef9SDimitry Andric   if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
1153e8d8bef9SDimitry Andric     return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
1154e8d8bef9SDimitry Andric 
1155e8d8bef9SDimitry Andric   return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind,
1156e8d8bef9SDimitry Andric                                  getContext());
1157e8d8bef9SDimitry Andric }
1158e8d8bef9SDimitry Andric 
1159*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
1160*0b57cec5SDimitry Andric   // Use ".GCC.command.line" since this feature is to support clang's
1161*0b57cec5SDimitry Andric   // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1162*0b57cec5SDimitry Andric   // same name.
1163*0b57cec5SDimitry Andric   return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1164fe6060f1SDimitry Andric                                     ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
1165*0b57cec5SDimitry Andric }
1166*0b57cec5SDimitry Andric 
1167*0b57cec5SDimitry Andric void
1168*0b57cec5SDimitry Andric TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
1169*0b57cec5SDimitry Andric   UseInitArray = UseInitArray_;
1170*0b57cec5SDimitry Andric   MCContext &Ctx = getContext();
1171*0b57cec5SDimitry Andric   if (!UseInitArray) {
1172*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
1173*0b57cec5SDimitry Andric                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1174*0b57cec5SDimitry Andric 
1175*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
1176*0b57cec5SDimitry Andric                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1177*0b57cec5SDimitry Andric     return;
1178*0b57cec5SDimitry Andric   }
1179*0b57cec5SDimitry Andric 
1180*0b57cec5SDimitry Andric   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
1181*0b57cec5SDimitry Andric                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1182*0b57cec5SDimitry Andric   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
1183*0b57cec5SDimitry Andric                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1184*0b57cec5SDimitry Andric }
1185*0b57cec5SDimitry Andric 
1186*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1187*0b57cec5SDimitry Andric //                                 MachO
1188*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1189*0b57cec5SDimitry Andric 
119004eeddc0SDimitry Andric TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() {
1191*0b57cec5SDimitry Andric   SupportIndirectSymViaGOTPCRel = true;
1192*0b57cec5SDimitry Andric }
1193*0b57cec5SDimitry Andric 
1194*0b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
1195*0b57cec5SDimitry Andric                                                const TargetMachine &TM) {
1196*0b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TM);
1197*0b57cec5SDimitry Andric   if (TM.getRelocationModel() == Reloc::Static) {
1198*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1199*0b57cec5SDimitry Andric                                             SectionKind::getData());
1200*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1201*0b57cec5SDimitry Andric                                             SectionKind::getData());
1202*0b57cec5SDimitry Andric   } else {
1203*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1204*0b57cec5SDimitry Andric                                             MachO::S_MOD_INIT_FUNC_POINTERS,
1205*0b57cec5SDimitry Andric                                             SectionKind::getData());
1206*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1207*0b57cec5SDimitry Andric                                             MachO::S_MOD_TERM_FUNC_POINTERS,
1208*0b57cec5SDimitry Andric                                             SectionKind::getData());
1209*0b57cec5SDimitry Andric   }
1210*0b57cec5SDimitry Andric 
1211*0b57cec5SDimitry Andric   PersonalityEncoding =
1212*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1213*0b57cec5SDimitry Andric   LSDAEncoding = dwarf::DW_EH_PE_pcrel;
1214*0b57cec5SDimitry Andric   TTypeEncoding =
1215*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1216*0b57cec5SDimitry Andric }
1217*0b57cec5SDimitry Andric 
121881ad6265SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getStaticDtorSection(
121981ad6265SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
122081ad6265SDimitry Andric   // TODO(yln): Remove -lower-global-dtors-via-cxa-atexit fallback flag
122181ad6265SDimitry Andric   // (LowerGlobalDtorsViaCxaAtExit) and always issue a fatal error here.
122281ad6265SDimitry Andric   if (TM->Options.LowerGlobalDtorsViaCxaAtExit)
122381ad6265SDimitry Andric     report_fatal_error("@llvm.global_dtors should have been lowered already");
122481ad6265SDimitry Andric   return StaticDtorSection;
122581ad6265SDimitry Andric }
122681ad6265SDimitry Andric 
1227*0b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
1228*0b57cec5SDimitry Andric                                                        Module &M) const {
1229*0b57cec5SDimitry Andric   // Emit the linker options if present.
1230*0b57cec5SDimitry Andric   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1231480093f4SDimitry Andric     for (const auto *Option : LinkerOptions->operands()) {
1232*0b57cec5SDimitry Andric       SmallVector<std::string, 4> StrOptions;
1233*0b57cec5SDimitry Andric       for (const auto &Piece : cast<MDNode>(Option)->operands())
12345ffd83dbSDimitry Andric         StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
12355ffd83dbSDimitry Andric       Streamer.emitLinkerOptions(StrOptions);
1236*0b57cec5SDimitry Andric     }
1237*0b57cec5SDimitry Andric   }
1238*0b57cec5SDimitry Andric 
1239*0b57cec5SDimitry Andric   unsigned VersionVal = 0;
1240*0b57cec5SDimitry Andric   unsigned ImageInfoFlags = 0;
1241*0b57cec5SDimitry Andric   StringRef SectionVal;
1242*0b57cec5SDimitry Andric 
1243*0b57cec5SDimitry Andric   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
124404eeddc0SDimitry Andric   emitCGProfileMetadata(Streamer, M);
1245*0b57cec5SDimitry Andric 
1246*0b57cec5SDimitry Andric   // The section is mandatory. If we don't have it, then we don't have GC info.
1247*0b57cec5SDimitry Andric   if (SectionVal.empty())
1248*0b57cec5SDimitry Andric     return;
1249*0b57cec5SDimitry Andric 
1250*0b57cec5SDimitry Andric   StringRef Segment, Section;
1251*0b57cec5SDimitry Andric   unsigned TAA = 0, StubSize = 0;
1252*0b57cec5SDimitry Andric   bool TAAParsed;
1253fe6060f1SDimitry Andric   if (Error E = MCSectionMachO::ParseSectionSpecifier(
1254fe6060f1SDimitry Andric           SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
1255*0b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
1256fe6060f1SDimitry Andric     report_fatal_error("Invalid section specifier '" + Section +
1257fe6060f1SDimitry Andric                        "': " + toString(std::move(E)) + ".");
1258fe6060f1SDimitry Andric   }
1259*0b57cec5SDimitry Andric 
1260*0b57cec5SDimitry Andric   // Get the section.
1261*0b57cec5SDimitry Andric   MCSectionMachO *S = getContext().getMachOSection(
1262*0b57cec5SDimitry Andric       Segment, Section, TAA, StubSize, SectionKind::getData());
126381ad6265SDimitry Andric   Streamer.switchSection(S);
12645ffd83dbSDimitry Andric   Streamer.emitLabel(getContext().
1265*0b57cec5SDimitry Andric                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
12665ffd83dbSDimitry Andric   Streamer.emitInt32(VersionVal);
12675ffd83dbSDimitry Andric   Streamer.emitInt32(ImageInfoFlags);
126881ad6265SDimitry Andric   Streamer.addBlankLine();
1269*0b57cec5SDimitry Andric }
1270*0b57cec5SDimitry Andric 
1271*0b57cec5SDimitry Andric static void checkMachOComdat(const GlobalValue *GV) {
1272*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
1273*0b57cec5SDimitry Andric   if (!C)
1274*0b57cec5SDimitry Andric     return;
1275*0b57cec5SDimitry Andric 
1276*0b57cec5SDimitry Andric   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1277*0b57cec5SDimitry Andric                      "' cannot be lowered.");
1278*0b57cec5SDimitry Andric }
1279*0b57cec5SDimitry Andric 
1280*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
1281*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1282fe6060f1SDimitry Andric 
1283fe6060f1SDimitry Andric   StringRef SectionName = GO->getSection();
1284fe6060f1SDimitry Andric 
1285fe6060f1SDimitry Andric   const Function *F = dyn_cast<Function>(GO);
1286fe6060f1SDimitry Andric   if (F && F->hasFnAttribute("implicit-section-name")) {
1287fe6060f1SDimitry Andric     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
1288fe6060f1SDimitry Andric   }
1289fe6060f1SDimitry Andric 
1290*0b57cec5SDimitry Andric   // Parse the section specifier and create it if valid.
1291*0b57cec5SDimitry Andric   StringRef Segment, Section;
1292*0b57cec5SDimitry Andric   unsigned TAA = 0, StubSize = 0;
1293*0b57cec5SDimitry Andric   bool TAAParsed;
1294*0b57cec5SDimitry Andric 
1295*0b57cec5SDimitry Andric   checkMachOComdat(GO);
1296*0b57cec5SDimitry Andric 
1297fe6060f1SDimitry Andric   if (Error E = MCSectionMachO::ParseSectionSpecifier(
1298fe6060f1SDimitry Andric           SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
1299*0b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
1300*0b57cec5SDimitry Andric     report_fatal_error("Global variable '" + GO->getName() +
1301*0b57cec5SDimitry Andric                        "' has an invalid section specifier '" +
1302fe6060f1SDimitry Andric                        GO->getSection() + "': " + toString(std::move(E)) + ".");
1303*0b57cec5SDimitry Andric   }
1304*0b57cec5SDimitry Andric 
1305*0b57cec5SDimitry Andric   // Get the section.
1306*0b57cec5SDimitry Andric   MCSectionMachO *S =
1307*0b57cec5SDimitry Andric       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1308*0b57cec5SDimitry Andric 
1309*0b57cec5SDimitry Andric   // If TAA wasn't set by ParseSectionSpecifier() above,
1310*0b57cec5SDimitry Andric   // use the value returned by getMachOSection() as a default.
1311*0b57cec5SDimitry Andric   if (!TAAParsed)
1312*0b57cec5SDimitry Andric     TAA = S->getTypeAndAttributes();
1313*0b57cec5SDimitry Andric 
1314*0b57cec5SDimitry Andric   // Okay, now that we got the section, verify that the TAA & StubSize agree.
1315*0b57cec5SDimitry Andric   // If the user declared multiple globals with different section flags, we need
1316*0b57cec5SDimitry Andric   // to reject it here.
1317*0b57cec5SDimitry Andric   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1318*0b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
1319*0b57cec5SDimitry Andric     report_fatal_error("Global variable '" + GO->getName() +
1320*0b57cec5SDimitry Andric                        "' section type or attributes does not match previous"
1321*0b57cec5SDimitry Andric                        " section specifier");
1322*0b57cec5SDimitry Andric   }
1323*0b57cec5SDimitry Andric 
1324*0b57cec5SDimitry Andric   return S;
1325*0b57cec5SDimitry Andric }
1326*0b57cec5SDimitry Andric 
1327*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
1328*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1329*0b57cec5SDimitry Andric   checkMachOComdat(GO);
1330*0b57cec5SDimitry Andric 
1331*0b57cec5SDimitry Andric   // Handle thread local data.
1332*0b57cec5SDimitry Andric   if (Kind.isThreadBSS()) return TLSBSSSection;
1333*0b57cec5SDimitry Andric   if (Kind.isThreadData()) return TLSDataSection;
1334*0b57cec5SDimitry Andric 
1335*0b57cec5SDimitry Andric   if (Kind.isText())
1336*0b57cec5SDimitry Andric     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
1337*0b57cec5SDimitry Andric 
1338*0b57cec5SDimitry Andric   // If this is weak/linkonce, put this in a coalescable section, either in text
1339*0b57cec5SDimitry Andric   // or data depending on if it is writable.
1340*0b57cec5SDimitry Andric   if (GO->isWeakForLinker()) {
1341*0b57cec5SDimitry Andric     if (Kind.isReadOnly())
1342*0b57cec5SDimitry Andric       return ConstTextCoalSection;
1343*0b57cec5SDimitry Andric     if (Kind.isReadOnlyWithRel())
1344*0b57cec5SDimitry Andric       return ConstDataCoalSection;
1345*0b57cec5SDimitry Andric     return DataCoalSection;
1346*0b57cec5SDimitry Andric   }
1347*0b57cec5SDimitry Andric 
1348*0b57cec5SDimitry Andric   // FIXME: Alignment check should be handled by section classifier.
1349*0b57cec5SDimitry Andric   if (Kind.isMergeable1ByteCString() &&
13505ffd83dbSDimitry Andric       GO->getParent()->getDataLayout().getPreferredAlign(
13515ffd83dbSDimitry Andric           cast<GlobalVariable>(GO)) < Align(32))
1352*0b57cec5SDimitry Andric     return CStringSection;
1353*0b57cec5SDimitry Andric 
1354*0b57cec5SDimitry Andric   // Do not put 16-bit arrays in the UString section if they have an
1355*0b57cec5SDimitry Andric   // externally visible label, this runs into issues with certain linker
1356*0b57cec5SDimitry Andric   // versions.
1357*0b57cec5SDimitry Andric   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
13585ffd83dbSDimitry Andric       GO->getParent()->getDataLayout().getPreferredAlign(
13595ffd83dbSDimitry Andric           cast<GlobalVariable>(GO)) < Align(32))
1360*0b57cec5SDimitry Andric     return UStringSection;
1361*0b57cec5SDimitry Andric 
1362*0b57cec5SDimitry Andric   // With MachO only variables whose corresponding symbol starts with 'l' or
1363*0b57cec5SDimitry Andric   // 'L' can be merged, so we only try merging GVs with private linkage.
1364*0b57cec5SDimitry Andric   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1365*0b57cec5SDimitry Andric     if (Kind.isMergeableConst4())
1366*0b57cec5SDimitry Andric       return FourByteConstantSection;
1367*0b57cec5SDimitry Andric     if (Kind.isMergeableConst8())
1368*0b57cec5SDimitry Andric       return EightByteConstantSection;
1369*0b57cec5SDimitry Andric     if (Kind.isMergeableConst16())
1370*0b57cec5SDimitry Andric       return SixteenByteConstantSection;
1371*0b57cec5SDimitry Andric   }
1372*0b57cec5SDimitry Andric 
1373*0b57cec5SDimitry Andric   // Otherwise, if it is readonly, but not something we can specially optimize,
1374*0b57cec5SDimitry Andric   // just drop it in .const.
1375*0b57cec5SDimitry Andric   if (Kind.isReadOnly())
1376*0b57cec5SDimitry Andric     return ReadOnlySection;
1377*0b57cec5SDimitry Andric 
1378*0b57cec5SDimitry Andric   // If this is marked const, put it into a const section.  But if the dynamic
1379*0b57cec5SDimitry Andric   // linker needs to write to it, put it in the data segment.
1380*0b57cec5SDimitry Andric   if (Kind.isReadOnlyWithRel())
1381*0b57cec5SDimitry Andric     return ConstDataSection;
1382*0b57cec5SDimitry Andric 
1383*0b57cec5SDimitry Andric   // Put zero initialized globals with strong external linkage in the
1384*0b57cec5SDimitry Andric   // DATA, __common section with the .zerofill directive.
1385*0b57cec5SDimitry Andric   if (Kind.isBSSExtern())
1386*0b57cec5SDimitry Andric     return DataCommonSection;
1387*0b57cec5SDimitry Andric 
1388*0b57cec5SDimitry Andric   // Put zero initialized globals with local linkage in __DATA,__bss directive
1389*0b57cec5SDimitry Andric   // with the .zerofill directive (aka .lcomm).
1390*0b57cec5SDimitry Andric   if (Kind.isBSSLocal())
1391*0b57cec5SDimitry Andric     return DataBSSSection;
1392*0b57cec5SDimitry Andric 
1393*0b57cec5SDimitry Andric   // Otherwise, just drop the variable in the normal data section.
1394*0b57cec5SDimitry Andric   return DataSection;
1395*0b57cec5SDimitry Andric }
1396*0b57cec5SDimitry Andric 
1397*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
1398*0b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
13995ffd83dbSDimitry Andric     Align &Alignment) const {
1400*0b57cec5SDimitry Andric   // If this constant requires a relocation, we have to put it in the data
1401*0b57cec5SDimitry Andric   // segment, not in the text segment.
1402*0b57cec5SDimitry Andric   if (Kind.isData() || Kind.isReadOnlyWithRel())
1403*0b57cec5SDimitry Andric     return ConstDataSection;
1404*0b57cec5SDimitry Andric 
1405*0b57cec5SDimitry Andric   if (Kind.isMergeableConst4())
1406*0b57cec5SDimitry Andric     return FourByteConstantSection;
1407*0b57cec5SDimitry Andric   if (Kind.isMergeableConst8())
1408*0b57cec5SDimitry Andric     return EightByteConstantSection;
1409*0b57cec5SDimitry Andric   if (Kind.isMergeableConst16())
1410*0b57cec5SDimitry Andric     return SixteenByteConstantSection;
1411*0b57cec5SDimitry Andric   return ReadOnlySection;  // .const
1412*0b57cec5SDimitry Andric }
1413*0b57cec5SDimitry Andric 
1414*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1415*0b57cec5SDimitry Andric     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1416*0b57cec5SDimitry Andric     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1417*0b57cec5SDimitry Andric   // The mach-o version of this method defaults to returning a stub reference.
1418*0b57cec5SDimitry Andric 
1419*0b57cec5SDimitry Andric   if (Encoding & DW_EH_PE_indirect) {
1420*0b57cec5SDimitry Andric     MachineModuleInfoMachO &MachOMMI =
1421*0b57cec5SDimitry Andric       MMI->getObjFileInfo<MachineModuleInfoMachO>();
1422*0b57cec5SDimitry Andric 
1423*0b57cec5SDimitry Andric     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1424*0b57cec5SDimitry Andric 
1425*0b57cec5SDimitry Andric     // Add information about the stub reference to MachOMMI so that the stub
1426*0b57cec5SDimitry Andric     // gets emitted by the asmprinter.
1427*0b57cec5SDimitry Andric     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1428*0b57cec5SDimitry Andric     if (!StubSym.getPointer()) {
1429*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(GV);
1430*0b57cec5SDimitry Andric       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1431*0b57cec5SDimitry Andric     }
1432*0b57cec5SDimitry Andric 
1433*0b57cec5SDimitry Andric     return TargetLoweringObjectFile::
1434*0b57cec5SDimitry Andric       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
1435*0b57cec5SDimitry Andric                         Encoding & ~DW_EH_PE_indirect, Streamer);
1436*0b57cec5SDimitry Andric   }
1437*0b57cec5SDimitry Andric 
1438*0b57cec5SDimitry Andric   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1439*0b57cec5SDimitry Andric                                                            MMI, Streamer);
1440*0b57cec5SDimitry Andric }
1441*0b57cec5SDimitry Andric 
1442*0b57cec5SDimitry Andric MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1443*0b57cec5SDimitry Andric     const GlobalValue *GV, const TargetMachine &TM,
1444*0b57cec5SDimitry Andric     MachineModuleInfo *MMI) const {
1445*0b57cec5SDimitry Andric   // The mach-o version of this method defaults to returning a stub reference.
1446*0b57cec5SDimitry Andric   MachineModuleInfoMachO &MachOMMI =
1447*0b57cec5SDimitry Andric     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1448*0b57cec5SDimitry Andric 
1449*0b57cec5SDimitry Andric   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1450*0b57cec5SDimitry Andric 
1451*0b57cec5SDimitry Andric   // Add information about the stub reference to MachOMMI so that the stub
1452*0b57cec5SDimitry Andric   // gets emitted by the asmprinter.
1453*0b57cec5SDimitry Andric   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1454*0b57cec5SDimitry Andric   if (!StubSym.getPointer()) {
1455*0b57cec5SDimitry Andric     MCSymbol *Sym = TM.getSymbol(GV);
1456*0b57cec5SDimitry Andric     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1457*0b57cec5SDimitry Andric   }
1458*0b57cec5SDimitry Andric 
1459*0b57cec5SDimitry Andric   return SSym;
1460*0b57cec5SDimitry Andric }
1461*0b57cec5SDimitry Andric 
1462*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
14638bcb0991SDimitry Andric     const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
14648bcb0991SDimitry Andric     int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1465*0b57cec5SDimitry Andric   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1466*0b57cec5SDimitry Andric   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1467*0b57cec5SDimitry Andric   // through a non_lazy_ptr stub instead. One advantage is that it allows the
1468*0b57cec5SDimitry Andric   // computation of deltas to final external symbols. Example:
1469*0b57cec5SDimitry Andric   //
1470*0b57cec5SDimitry Andric   //    _extgotequiv:
1471*0b57cec5SDimitry Andric   //       .long   _extfoo
1472*0b57cec5SDimitry Andric   //
1473*0b57cec5SDimitry Andric   //    _delta:
1474*0b57cec5SDimitry Andric   //       .long   _extgotequiv-_delta
1475*0b57cec5SDimitry Andric   //
1476*0b57cec5SDimitry Andric   // is transformed to:
1477*0b57cec5SDimitry Andric   //
1478*0b57cec5SDimitry Andric   //    _delta:
1479*0b57cec5SDimitry Andric   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
1480*0b57cec5SDimitry Andric   //
1481*0b57cec5SDimitry Andric   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
1482*0b57cec5SDimitry Andric   //    L_extfoo$non_lazy_ptr:
1483*0b57cec5SDimitry Andric   //       .indirect_symbol        _extfoo
1484*0b57cec5SDimitry Andric   //       .long   0
1485*0b57cec5SDimitry Andric   //
1486*0b57cec5SDimitry Andric   // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1487*0b57cec5SDimitry Andric   // may point to both local (same translation unit) and global (other
1488*0b57cec5SDimitry Andric   // translation units) symbols. Example:
1489*0b57cec5SDimitry Andric   //
1490*0b57cec5SDimitry Andric   // .section __DATA,__pointers,non_lazy_symbol_pointers
1491*0b57cec5SDimitry Andric   // L1:
1492*0b57cec5SDimitry Andric   //    .indirect_symbol _myGlobal
1493*0b57cec5SDimitry Andric   //    .long 0
1494*0b57cec5SDimitry Andric   // L2:
1495*0b57cec5SDimitry Andric   //    .indirect_symbol _myLocal
1496*0b57cec5SDimitry Andric   //    .long _myLocal
1497*0b57cec5SDimitry Andric   //
1498*0b57cec5SDimitry Andric   // If the symbol is local, instead of the symbol's index, the assembler
1499*0b57cec5SDimitry Andric   // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1500*0b57cec5SDimitry Andric   // Then the linker will notice the constant in the table and will look at the
1501*0b57cec5SDimitry Andric   // content of the symbol.
1502*0b57cec5SDimitry Andric   MachineModuleInfoMachO &MachOMMI =
1503*0b57cec5SDimitry Andric     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1504*0b57cec5SDimitry Andric   MCContext &Ctx = getContext();
1505*0b57cec5SDimitry Andric 
1506*0b57cec5SDimitry Andric   // The offset must consider the original displacement from the base symbol
1507*0b57cec5SDimitry Andric   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1508*0b57cec5SDimitry Andric   Offset = -MV.getConstant();
1509*0b57cec5SDimitry Andric   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1510*0b57cec5SDimitry Andric 
1511*0b57cec5SDimitry Andric   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1512*0b57cec5SDimitry Andric   // non_lazy_ptr stubs.
1513*0b57cec5SDimitry Andric   SmallString<128> Name;
1514*0b57cec5SDimitry Andric   StringRef Suffix = "$non_lazy_ptr";
1515*0b57cec5SDimitry Andric   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1516*0b57cec5SDimitry Andric   Name += Sym->getName();
1517*0b57cec5SDimitry Andric   Name += Suffix;
1518*0b57cec5SDimitry Andric   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1519*0b57cec5SDimitry Andric 
1520*0b57cec5SDimitry Andric   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
15218bcb0991SDimitry Andric 
15228bcb0991SDimitry Andric   if (!StubSym.getPointer())
1523*0b57cec5SDimitry Andric     StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
15248bcb0991SDimitry Andric                                                  !GV->hasLocalLinkage());
1525*0b57cec5SDimitry Andric 
1526*0b57cec5SDimitry Andric   const MCExpr *BSymExpr =
1527*0b57cec5SDimitry Andric     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
1528*0b57cec5SDimitry Andric   const MCExpr *LHS =
1529*0b57cec5SDimitry Andric     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
1530*0b57cec5SDimitry Andric 
1531*0b57cec5SDimitry Andric   if (!Offset)
1532*0b57cec5SDimitry Andric     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1533*0b57cec5SDimitry Andric 
1534*0b57cec5SDimitry Andric   const MCExpr *RHS =
1535*0b57cec5SDimitry Andric     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1536*0b57cec5SDimitry Andric   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1537*0b57cec5SDimitry Andric }
1538*0b57cec5SDimitry Andric 
1539*0b57cec5SDimitry Andric static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1540*0b57cec5SDimitry Andric                                const MCSection &Section) {
1541*0b57cec5SDimitry Andric   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1542*0b57cec5SDimitry Andric     return true;
1543*0b57cec5SDimitry Andric 
1544fe6060f1SDimitry Andric   // FIXME: we should be able to use private labels for sections that can't be
1545fe6060f1SDimitry Andric   // dead-stripped (there's no issue with blocking atomization there), but `ld
1546fe6060f1SDimitry Andric   // -r` sometimes drops the no_dead_strip attribute from sections so for safety
1547fe6060f1SDimitry Andric   // we don't allow it.
1548*0b57cec5SDimitry Andric   return false;
1549*0b57cec5SDimitry Andric }
1550*0b57cec5SDimitry Andric 
1551*0b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::getNameWithPrefix(
1552*0b57cec5SDimitry Andric     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1553*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1554*0b57cec5SDimitry Andric   bool CannotUsePrivateLabel = true;
1555349cc55cSDimitry Andric   if (auto *GO = GV->getAliaseeObject()) {
1556*0b57cec5SDimitry Andric     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1557*0b57cec5SDimitry Andric     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1558*0b57cec5SDimitry Andric     CannotUsePrivateLabel =
1559*0b57cec5SDimitry Andric         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1560*0b57cec5SDimitry Andric   }
1561*0b57cec5SDimitry Andric   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1562*0b57cec5SDimitry Andric }
1563*0b57cec5SDimitry Andric 
1564*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1565*0b57cec5SDimitry Andric //                                  COFF
1566*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1567*0b57cec5SDimitry Andric 
1568*0b57cec5SDimitry Andric static unsigned
1569*0b57cec5SDimitry Andric getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1570*0b57cec5SDimitry Andric   unsigned Flags = 0;
1571*0b57cec5SDimitry Andric   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1572*0b57cec5SDimitry Andric 
1573*0b57cec5SDimitry Andric   if (K.isMetadata())
1574*0b57cec5SDimitry Andric     Flags |=
1575*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_DISCARDABLE;
157681ad6265SDimitry Andric   else if (K.isExclude())
157781ad6265SDimitry Andric     Flags |=
157881ad6265SDimitry Andric       COFF::IMAGE_SCN_LNK_REMOVE | COFF::IMAGE_SCN_MEM_DISCARDABLE;
1579*0b57cec5SDimitry Andric   else if (K.isText())
1580*0b57cec5SDimitry Andric     Flags |=
1581*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_EXECUTE |
1582*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1583*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_CODE |
1584*0b57cec5SDimitry Andric       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
1585*0b57cec5SDimitry Andric   else if (K.isBSS())
1586*0b57cec5SDimitry Andric     Flags |=
1587*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1588*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1589*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
1590*0b57cec5SDimitry Andric   else if (K.isThreadLocal())
1591*0b57cec5SDimitry Andric     Flags |=
1592*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1593*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1594*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
1595*0b57cec5SDimitry Andric   else if (K.isReadOnly() || K.isReadOnlyWithRel())
1596*0b57cec5SDimitry Andric     Flags |=
1597*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1598*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ;
1599*0b57cec5SDimitry Andric   else if (K.isWriteable())
1600*0b57cec5SDimitry Andric     Flags |=
1601*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1602*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1603*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
1604*0b57cec5SDimitry Andric 
1605*0b57cec5SDimitry Andric   return Flags;
1606*0b57cec5SDimitry Andric }
1607*0b57cec5SDimitry Andric 
1608*0b57cec5SDimitry Andric static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1609*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
1610*0b57cec5SDimitry Andric   assert(C && "expected GV to have a Comdat!");
1611*0b57cec5SDimitry Andric 
1612*0b57cec5SDimitry Andric   StringRef ComdatGVName = C->getName();
1613*0b57cec5SDimitry Andric   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1614*0b57cec5SDimitry Andric   if (!ComdatGV)
1615*0b57cec5SDimitry Andric     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1616*0b57cec5SDimitry Andric                        "' does not exist.");
1617*0b57cec5SDimitry Andric 
1618*0b57cec5SDimitry Andric   if (ComdatGV->getComdat() != C)
1619*0b57cec5SDimitry Andric     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1620*0b57cec5SDimitry Andric                        "' is not a key for its COMDAT.");
1621*0b57cec5SDimitry Andric 
1622*0b57cec5SDimitry Andric   return ComdatGV;
1623*0b57cec5SDimitry Andric }
1624*0b57cec5SDimitry Andric 
1625*0b57cec5SDimitry Andric static int getSelectionForCOFF(const GlobalValue *GV) {
1626*0b57cec5SDimitry Andric   if (const Comdat *C = GV->getComdat()) {
1627*0b57cec5SDimitry Andric     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1628*0b57cec5SDimitry Andric     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1629349cc55cSDimitry Andric       ComdatKey = GA->getAliaseeObject();
1630*0b57cec5SDimitry Andric     if (ComdatKey == GV) {
1631*0b57cec5SDimitry Andric       switch (C->getSelectionKind()) {
1632*0b57cec5SDimitry Andric       case Comdat::Any:
1633*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_ANY;
1634*0b57cec5SDimitry Andric       case Comdat::ExactMatch:
1635*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1636*0b57cec5SDimitry Andric       case Comdat::Largest:
1637*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1638fe6060f1SDimitry Andric       case Comdat::NoDeduplicate:
1639*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1640*0b57cec5SDimitry Andric       case Comdat::SameSize:
1641*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1642*0b57cec5SDimitry Andric       }
1643*0b57cec5SDimitry Andric     } else {
1644*0b57cec5SDimitry Andric       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1645*0b57cec5SDimitry Andric     }
1646*0b57cec5SDimitry Andric   }
1647*0b57cec5SDimitry Andric   return 0;
1648*0b57cec5SDimitry Andric }
1649*0b57cec5SDimitry Andric 
1650*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1651*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1652*0b57cec5SDimitry Andric   int Selection = 0;
1653*0b57cec5SDimitry Andric   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1654*0b57cec5SDimitry Andric   StringRef Name = GO->getSection();
1655*0b57cec5SDimitry Andric   StringRef COMDATSymName = "";
1656*0b57cec5SDimitry Andric   if (GO->hasComdat()) {
1657*0b57cec5SDimitry Andric     Selection = getSelectionForCOFF(GO);
1658*0b57cec5SDimitry Andric     const GlobalValue *ComdatGV;
1659*0b57cec5SDimitry Andric     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1660*0b57cec5SDimitry Andric       ComdatGV = getComdatGVForCOFF(GO);
1661*0b57cec5SDimitry Andric     else
1662*0b57cec5SDimitry Andric       ComdatGV = GO;
1663*0b57cec5SDimitry Andric 
1664*0b57cec5SDimitry Andric     if (!ComdatGV->hasPrivateLinkage()) {
1665*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1666*0b57cec5SDimitry Andric       COMDATSymName = Sym->getName();
1667*0b57cec5SDimitry Andric       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1668*0b57cec5SDimitry Andric     } else {
1669*0b57cec5SDimitry Andric       Selection = 0;
1670*0b57cec5SDimitry Andric     }
1671*0b57cec5SDimitry Andric   }
1672*0b57cec5SDimitry Andric 
1673*0b57cec5SDimitry Andric   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1674*0b57cec5SDimitry Andric                                      Selection);
1675*0b57cec5SDimitry Andric }
1676*0b57cec5SDimitry Andric 
1677*0b57cec5SDimitry Andric static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1678*0b57cec5SDimitry Andric   if (Kind.isText())
1679*0b57cec5SDimitry Andric     return ".text";
1680*0b57cec5SDimitry Andric   if (Kind.isBSS())
1681*0b57cec5SDimitry Andric     return ".bss";
1682*0b57cec5SDimitry Andric   if (Kind.isThreadLocal())
1683*0b57cec5SDimitry Andric     return ".tls$";
1684*0b57cec5SDimitry Andric   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1685*0b57cec5SDimitry Andric     return ".rdata";
1686*0b57cec5SDimitry Andric   return ".data";
1687*0b57cec5SDimitry Andric }
1688*0b57cec5SDimitry Andric 
1689*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1690*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1691*0b57cec5SDimitry Andric   // If we have -ffunction-sections then we should emit the global value to a
1692*0b57cec5SDimitry Andric   // uniqued section specifically for it.
1693*0b57cec5SDimitry Andric   bool EmitUniquedSection;
1694*0b57cec5SDimitry Andric   if (Kind.isText())
1695*0b57cec5SDimitry Andric     EmitUniquedSection = TM.getFunctionSections();
1696*0b57cec5SDimitry Andric   else
1697*0b57cec5SDimitry Andric     EmitUniquedSection = TM.getDataSections();
1698*0b57cec5SDimitry Andric 
1699*0b57cec5SDimitry Andric   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1700*0b57cec5SDimitry Andric     SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1701*0b57cec5SDimitry Andric 
1702*0b57cec5SDimitry Andric     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1703*0b57cec5SDimitry Andric 
1704*0b57cec5SDimitry Andric     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1705*0b57cec5SDimitry Andric     int Selection = getSelectionForCOFF(GO);
1706*0b57cec5SDimitry Andric     if (!Selection)
1707*0b57cec5SDimitry Andric       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1708*0b57cec5SDimitry Andric     const GlobalValue *ComdatGV;
1709*0b57cec5SDimitry Andric     if (GO->hasComdat())
1710*0b57cec5SDimitry Andric       ComdatGV = getComdatGVForCOFF(GO);
1711*0b57cec5SDimitry Andric     else
1712*0b57cec5SDimitry Andric       ComdatGV = GO;
1713*0b57cec5SDimitry Andric 
1714*0b57cec5SDimitry Andric     unsigned UniqueID = MCContext::GenericSectionID;
1715*0b57cec5SDimitry Andric     if (EmitUniquedSection)
1716*0b57cec5SDimitry Andric       UniqueID = NextUniqueID++;
1717*0b57cec5SDimitry Andric 
1718*0b57cec5SDimitry Andric     if (!ComdatGV->hasPrivateLinkage()) {
1719*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1720*0b57cec5SDimitry Andric       StringRef COMDATSymName = Sym->getName();
1721*0b57cec5SDimitry Andric 
1722e8d8bef9SDimitry Andric       if (const auto *F = dyn_cast<Function>(GO))
1723bdd1243dSDimitry Andric         if (std::optional<StringRef> Prefix = F->getSectionPrefix())
1724e8d8bef9SDimitry Andric           raw_svector_ostream(Name) << '$' << *Prefix;
1725e8d8bef9SDimitry Andric 
1726*0b57cec5SDimitry Andric       // Append "$symbol" to the section name *before* IR-level mangling is
1727*0b57cec5SDimitry Andric       // applied when targetting mingw. This is what GCC does, and the ld.bfd
1728*0b57cec5SDimitry Andric       // COFF linker will not properly handle comdats otherwise.
1729fe6060f1SDimitry Andric       if (getContext().getTargetTriple().isWindowsGNUEnvironment())
1730*0b57cec5SDimitry Andric         raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1731*0b57cec5SDimitry Andric 
1732*0b57cec5SDimitry Andric       return getContext().getCOFFSection(Name, Characteristics, Kind,
1733*0b57cec5SDimitry Andric                                          COMDATSymName, Selection, UniqueID);
1734*0b57cec5SDimitry Andric     } else {
1735*0b57cec5SDimitry Andric       SmallString<256> TmpData;
1736*0b57cec5SDimitry Andric       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1737*0b57cec5SDimitry Andric       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1738*0b57cec5SDimitry Andric                                          Selection, UniqueID);
1739*0b57cec5SDimitry Andric     }
1740*0b57cec5SDimitry Andric   }
1741*0b57cec5SDimitry Andric 
1742*0b57cec5SDimitry Andric   if (Kind.isText())
1743*0b57cec5SDimitry Andric     return TextSection;
1744*0b57cec5SDimitry Andric 
1745*0b57cec5SDimitry Andric   if (Kind.isThreadLocal())
1746*0b57cec5SDimitry Andric     return TLSDataSection;
1747*0b57cec5SDimitry Andric 
1748*0b57cec5SDimitry Andric   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1749*0b57cec5SDimitry Andric     return ReadOnlySection;
1750*0b57cec5SDimitry Andric 
1751*0b57cec5SDimitry Andric   // Note: we claim that common symbols are put in BSSSection, but they are
1752*0b57cec5SDimitry Andric   // really emitted with the magic .comm directive, which creates a symbol table
1753*0b57cec5SDimitry Andric   // entry but not a section.
1754*0b57cec5SDimitry Andric   if (Kind.isBSS() || Kind.isCommon())
1755*0b57cec5SDimitry Andric     return BSSSection;
1756*0b57cec5SDimitry Andric 
1757*0b57cec5SDimitry Andric   return DataSection;
1758*0b57cec5SDimitry Andric }
1759*0b57cec5SDimitry Andric 
1760*0b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1761*0b57cec5SDimitry Andric     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1762*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1763*0b57cec5SDimitry Andric   bool CannotUsePrivateLabel = false;
1764*0b57cec5SDimitry Andric   if (GV->hasPrivateLinkage() &&
1765*0b57cec5SDimitry Andric       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1766*0b57cec5SDimitry Andric        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1767*0b57cec5SDimitry Andric     CannotUsePrivateLabel = true;
1768*0b57cec5SDimitry Andric 
1769*0b57cec5SDimitry Andric   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1770*0b57cec5SDimitry Andric }
1771*0b57cec5SDimitry Andric 
1772*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1773*0b57cec5SDimitry Andric     const Function &F, const TargetMachine &TM) const {
1774*0b57cec5SDimitry Andric   // If the function can be removed, produce a unique section so that
1775*0b57cec5SDimitry Andric   // the table doesn't prevent the removal.
1776*0b57cec5SDimitry Andric   const Comdat *C = F.getComdat();
1777*0b57cec5SDimitry Andric   bool EmitUniqueSection = TM.getFunctionSections() || C;
1778*0b57cec5SDimitry Andric   if (!EmitUniqueSection)
1779*0b57cec5SDimitry Andric     return ReadOnlySection;
1780*0b57cec5SDimitry Andric 
1781*0b57cec5SDimitry Andric   // FIXME: we should produce a symbol for F instead.
1782*0b57cec5SDimitry Andric   if (F.hasPrivateLinkage())
1783*0b57cec5SDimitry Andric     return ReadOnlySection;
1784*0b57cec5SDimitry Andric 
1785*0b57cec5SDimitry Andric   MCSymbol *Sym = TM.getSymbol(&F);
1786*0b57cec5SDimitry Andric   StringRef COMDATSymName = Sym->getName();
1787*0b57cec5SDimitry Andric 
1788*0b57cec5SDimitry Andric   SectionKind Kind = SectionKind::getReadOnly();
1789*0b57cec5SDimitry Andric   StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
1790*0b57cec5SDimitry Andric   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1791*0b57cec5SDimitry Andric   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1792*0b57cec5SDimitry Andric   unsigned UniqueID = NextUniqueID++;
1793*0b57cec5SDimitry Andric 
1794*0b57cec5SDimitry Andric   return getContext().getCOFFSection(
1795*0b57cec5SDimitry Andric       SecName, Characteristics, Kind, COMDATSymName,
1796*0b57cec5SDimitry Andric       COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1797*0b57cec5SDimitry Andric }
1798*0b57cec5SDimitry Andric 
1799*0b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1800*0b57cec5SDimitry Andric                                                       Module &M) const {
1801e8d8bef9SDimitry Andric   emitLinkerDirectives(Streamer, M);
1802e8d8bef9SDimitry Andric 
1803e8d8bef9SDimitry Andric   unsigned Version = 0;
1804e8d8bef9SDimitry Andric   unsigned Flags = 0;
1805e8d8bef9SDimitry Andric   StringRef Section;
1806e8d8bef9SDimitry Andric 
1807e8d8bef9SDimitry Andric   GetObjCImageInfo(M, Version, Flags, Section);
1808e8d8bef9SDimitry Andric   if (!Section.empty()) {
1809e8d8bef9SDimitry Andric     auto &C = getContext();
1810e8d8bef9SDimitry Andric     auto *S = C.getCOFFSection(Section,
1811e8d8bef9SDimitry Andric                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1812e8d8bef9SDimitry Andric                                    COFF::IMAGE_SCN_MEM_READ,
1813e8d8bef9SDimitry Andric                                SectionKind::getReadOnly());
181481ad6265SDimitry Andric     Streamer.switchSection(S);
1815e8d8bef9SDimitry Andric     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1816e8d8bef9SDimitry Andric     Streamer.emitInt32(Version);
1817e8d8bef9SDimitry Andric     Streamer.emitInt32(Flags);
181881ad6265SDimitry Andric     Streamer.addBlankLine();
1819e8d8bef9SDimitry Andric   }
1820e8d8bef9SDimitry Andric 
1821e8d8bef9SDimitry Andric   emitCGProfileMetadata(Streamer, M);
1822e8d8bef9SDimitry Andric }
1823e8d8bef9SDimitry Andric 
1824e8d8bef9SDimitry Andric void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
1825e8d8bef9SDimitry Andric     MCStreamer &Streamer, Module &M) const {
1826*0b57cec5SDimitry Andric   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1827*0b57cec5SDimitry Andric     // Emit the linker options to the linker .drectve section.  According to the
1828*0b57cec5SDimitry Andric     // spec, this section is a space-separated string containing flags for
1829*0b57cec5SDimitry Andric     // linker.
1830*0b57cec5SDimitry Andric     MCSection *Sec = getDrectveSection();
183181ad6265SDimitry Andric     Streamer.switchSection(Sec);
1832480093f4SDimitry Andric     for (const auto *Option : LinkerOptions->operands()) {
1833*0b57cec5SDimitry Andric       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1834*0b57cec5SDimitry Andric         // Lead with a space for consistency with our dllexport implementation.
1835*0b57cec5SDimitry Andric         std::string Directive(" ");
18365ffd83dbSDimitry Andric         Directive.append(std::string(cast<MDString>(Piece)->getString()));
18375ffd83dbSDimitry Andric         Streamer.emitBytes(Directive);
1838*0b57cec5SDimitry Andric       }
1839*0b57cec5SDimitry Andric     }
1840*0b57cec5SDimitry Andric   }
1841*0b57cec5SDimitry Andric 
1842e8d8bef9SDimitry Andric   // Emit /EXPORT: flags for each exported global as necessary.
1843e8d8bef9SDimitry Andric   std::string Flags;
1844e8d8bef9SDimitry Andric   for (const GlobalValue &GV : M.global_values()) {
1845e8d8bef9SDimitry Andric     raw_string_ostream OS(Flags);
1846fe6060f1SDimitry Andric     emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
1847fe6060f1SDimitry Andric                                  getMangler());
1848e8d8bef9SDimitry Andric     OS.flush();
1849e8d8bef9SDimitry Andric     if (!Flags.empty()) {
185081ad6265SDimitry Andric       Streamer.switchSection(getDrectveSection());
1851e8d8bef9SDimitry Andric       Streamer.emitBytes(Flags);
1852e8d8bef9SDimitry Andric     }
1853e8d8bef9SDimitry Andric     Flags.clear();
1854e8d8bef9SDimitry Andric   }
1855*0b57cec5SDimitry Andric 
1856e8d8bef9SDimitry Andric   // Emit /INCLUDE: flags for each used global as necessary.
1857e8d8bef9SDimitry Andric   if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1858e8d8bef9SDimitry Andric     assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
1859e8d8bef9SDimitry Andric     assert(isa<ArrayType>(LU->getValueType()) &&
1860e8d8bef9SDimitry Andric            "expected llvm.used to be an array type");
1861e8d8bef9SDimitry Andric     if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1862e8d8bef9SDimitry Andric       for (const Value *Op : A->operands()) {
1863e8d8bef9SDimitry Andric         const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1864e8d8bef9SDimitry Andric         // Global symbols with internal or private linkage are not visible to
1865e8d8bef9SDimitry Andric         // the linker, and thus would cause an error when the linker tried to
1866e8d8bef9SDimitry Andric         // preserve the symbol due to the `/include:` directive.
1867e8d8bef9SDimitry Andric         if (GV->hasLocalLinkage())
1868e8d8bef9SDimitry Andric           continue;
1869*0b57cec5SDimitry Andric 
1870e8d8bef9SDimitry Andric         raw_string_ostream OS(Flags);
1871fe6060f1SDimitry Andric         emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
1872fe6060f1SDimitry Andric                                    getMangler());
1873e8d8bef9SDimitry Andric         OS.flush();
1874e8d8bef9SDimitry Andric 
1875e8d8bef9SDimitry Andric         if (!Flags.empty()) {
187681ad6265SDimitry Andric           Streamer.switchSection(getDrectveSection());
1877e8d8bef9SDimitry Andric           Streamer.emitBytes(Flags);
1878e8d8bef9SDimitry Andric         }
1879e8d8bef9SDimitry Andric         Flags.clear();
1880e8d8bef9SDimitry Andric       }
1881e8d8bef9SDimitry Andric     }
1882e8d8bef9SDimitry Andric   }
1883*0b57cec5SDimitry Andric }
1884*0b57cec5SDimitry Andric 
1885*0b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1886*0b57cec5SDimitry Andric                                               const TargetMachine &TM) {
1887*0b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TM);
1888e8d8bef9SDimitry Andric   this->TM = &TM;
1889*0b57cec5SDimitry Andric   const Triple &T = TM.getTargetTriple();
1890*0b57cec5SDimitry Andric   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1891*0b57cec5SDimitry Andric     StaticCtorSection =
1892*0b57cec5SDimitry Andric         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1893*0b57cec5SDimitry Andric                                            COFF::IMAGE_SCN_MEM_READ,
1894*0b57cec5SDimitry Andric                            SectionKind::getReadOnly());
1895*0b57cec5SDimitry Andric     StaticDtorSection =
1896*0b57cec5SDimitry Andric         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1897*0b57cec5SDimitry Andric                                            COFF::IMAGE_SCN_MEM_READ,
1898*0b57cec5SDimitry Andric                            SectionKind::getReadOnly());
1899*0b57cec5SDimitry Andric   } else {
1900*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getCOFFSection(
1901*0b57cec5SDimitry Andric         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1902*0b57cec5SDimitry Andric                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1903*0b57cec5SDimitry Andric         SectionKind::getData());
1904*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getCOFFSection(
1905*0b57cec5SDimitry Andric         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1906*0b57cec5SDimitry Andric                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1907*0b57cec5SDimitry Andric         SectionKind::getData());
1908*0b57cec5SDimitry Andric   }
1909*0b57cec5SDimitry Andric }
1910*0b57cec5SDimitry Andric 
1911*0b57cec5SDimitry Andric static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1912*0b57cec5SDimitry Andric                                                    const Triple &T, bool IsCtor,
1913*0b57cec5SDimitry Andric                                                    unsigned Priority,
1914*0b57cec5SDimitry Andric                                                    const MCSymbol *KeySym,
1915*0b57cec5SDimitry Andric                                                    MCSectionCOFF *Default) {
1916*0b57cec5SDimitry Andric   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1917*0b57cec5SDimitry Andric     // If the priority is the default, use .CRT$XCU, possibly associative.
1918*0b57cec5SDimitry Andric     if (Priority == 65535)
1919*0b57cec5SDimitry Andric       return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1920*0b57cec5SDimitry Andric 
1921*0b57cec5SDimitry Andric     // Otherwise, we need to compute a new section name. Low priorities should
1922*0b57cec5SDimitry Andric     // run earlier. The linker will sort sections ASCII-betically, and we need a
1923*0b57cec5SDimitry Andric     // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1924*0b57cec5SDimitry Andric     // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1925*0b57cec5SDimitry Andric     // low priorities need to sort before 'L', since the CRT uses that
1926bdd1243dSDimitry Andric     // internally, so we use ".CRT$XCA00001" for them. We have a contract with
1927bdd1243dSDimitry Andric     // the frontend that "init_seg(compiler)" corresponds to priority 200 and
1928bdd1243dSDimitry Andric     // "init_seg(lib)" corresponds to priority 400, and those respectively use
1929bdd1243dSDimitry Andric     // 'C' and 'L' without the priority suffix. Priorities between 200 and 400
1930bdd1243dSDimitry Andric     // use 'C' with the priority as a suffix.
1931*0b57cec5SDimitry Andric     SmallString<24> Name;
1932bdd1243dSDimitry Andric     char LastLetter = 'T';
1933bdd1243dSDimitry Andric     bool AddPrioritySuffix = Priority != 200 && Priority != 400;
1934bdd1243dSDimitry Andric     if (Priority < 200)
1935bdd1243dSDimitry Andric       LastLetter = 'A';
1936bdd1243dSDimitry Andric     else if (Priority < 400)
1937bdd1243dSDimitry Andric       LastLetter = 'C';
1938bdd1243dSDimitry Andric     else if (Priority == 400)
1939bdd1243dSDimitry Andric       LastLetter = 'L';
1940*0b57cec5SDimitry Andric     raw_svector_ostream OS(Name);
1941bdd1243dSDimitry Andric     OS << ".CRT$X" << (IsCtor ? "C" : "T") << LastLetter;
1942bdd1243dSDimitry Andric     if (AddPrioritySuffix)
1943bdd1243dSDimitry Andric       OS << format("%05u", Priority);
1944*0b57cec5SDimitry Andric     MCSectionCOFF *Sec = Ctx.getCOFFSection(
1945*0b57cec5SDimitry Andric         Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1946*0b57cec5SDimitry Andric         SectionKind::getReadOnly());
1947*0b57cec5SDimitry Andric     return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1948*0b57cec5SDimitry Andric   }
1949*0b57cec5SDimitry Andric 
1950*0b57cec5SDimitry Andric   std::string Name = IsCtor ? ".ctors" : ".dtors";
1951*0b57cec5SDimitry Andric   if (Priority != 65535)
1952*0b57cec5SDimitry Andric     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1953*0b57cec5SDimitry Andric 
1954*0b57cec5SDimitry Andric   return Ctx.getAssociativeCOFFSection(
1955*0b57cec5SDimitry Andric       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1956*0b57cec5SDimitry Andric                                    COFF::IMAGE_SCN_MEM_READ |
1957*0b57cec5SDimitry Andric                                    COFF::IMAGE_SCN_MEM_WRITE,
1958*0b57cec5SDimitry Andric                          SectionKind::getData()),
1959*0b57cec5SDimitry Andric       KeySym, 0);
1960*0b57cec5SDimitry Andric }
1961*0b57cec5SDimitry Andric 
1962*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1963*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1964fe6060f1SDimitry Andric   return getCOFFStaticStructorSection(
1965fe6060f1SDimitry Andric       getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
1966*0b57cec5SDimitry Andric       cast<MCSectionCOFF>(StaticCtorSection));
1967*0b57cec5SDimitry Andric }
1968*0b57cec5SDimitry Andric 
1969*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1970*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1971fe6060f1SDimitry Andric   return getCOFFStaticStructorSection(
1972fe6060f1SDimitry Andric       getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
1973*0b57cec5SDimitry Andric       cast<MCSectionCOFF>(StaticDtorSection));
1974*0b57cec5SDimitry Andric }
1975*0b57cec5SDimitry Andric 
1976*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1977*0b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
1978*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1979*0b57cec5SDimitry Andric   const Triple &T = TM.getTargetTriple();
1980*0b57cec5SDimitry Andric   if (T.isOSCygMing())
1981*0b57cec5SDimitry Andric     return nullptr;
1982*0b57cec5SDimitry Andric 
1983*0b57cec5SDimitry Andric   // Our symbols should exist in address space zero, cowardly no-op if
1984*0b57cec5SDimitry Andric   // otherwise.
1985*0b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1986*0b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0)
1987*0b57cec5SDimitry Andric     return nullptr;
1988*0b57cec5SDimitry Andric 
1989*0b57cec5SDimitry Andric   // Both ptrtoint instructions must wrap global objects:
1990*0b57cec5SDimitry Andric   // - Only global variables are eligible for image relative relocations.
1991*0b57cec5SDimitry Andric   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1992*0b57cec5SDimitry Andric   // We expect __ImageBase to be a global variable without a section, externally
1993*0b57cec5SDimitry Andric   // defined.
1994*0b57cec5SDimitry Andric   //
1995*0b57cec5SDimitry Andric   // It should look something like this: @__ImageBase = external constant i8
1996*0b57cec5SDimitry Andric   if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1997*0b57cec5SDimitry Andric       LHS->isThreadLocal() || RHS->isThreadLocal() ||
1998*0b57cec5SDimitry Andric       RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1999*0b57cec5SDimitry Andric       cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
2000*0b57cec5SDimitry Andric     return nullptr;
2001*0b57cec5SDimitry Andric 
2002*0b57cec5SDimitry Andric   return MCSymbolRefExpr::create(TM.getSymbol(LHS),
2003*0b57cec5SDimitry Andric                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
2004*0b57cec5SDimitry Andric                                  getContext());
2005*0b57cec5SDimitry Andric }
2006*0b57cec5SDimitry Andric 
2007*0b57cec5SDimitry Andric static std::string APIntToHexString(const APInt &AI) {
2008*0b57cec5SDimitry Andric   unsigned Width = (AI.getBitWidth() / 8) * 2;
2009fe6060f1SDimitry Andric   std::string HexString = toString(AI, 16, /*Signed=*/false);
20105ffd83dbSDimitry Andric   llvm::transform(HexString, HexString.begin(), tolower);
2011*0b57cec5SDimitry Andric   unsigned Size = HexString.size();
2012*0b57cec5SDimitry Andric   assert(Width >= Size && "hex string is too large!");
2013*0b57cec5SDimitry Andric   HexString.insert(HexString.begin(), Width - Size, '0');
2014*0b57cec5SDimitry Andric 
2015*0b57cec5SDimitry Andric   return HexString;
2016*0b57cec5SDimitry Andric }
2017*0b57cec5SDimitry Andric 
2018*0b57cec5SDimitry Andric static std::string scalarConstantToHexString(const Constant *C) {
2019*0b57cec5SDimitry Andric   Type *Ty = C->getType();
2020*0b57cec5SDimitry Andric   if (isa<UndefValue>(C)) {
2021349cc55cSDimitry Andric     return APIntToHexString(APInt::getZero(Ty->getPrimitiveSizeInBits()));
2022*0b57cec5SDimitry Andric   } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
2023*0b57cec5SDimitry Andric     return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
2024*0b57cec5SDimitry Andric   } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
2025*0b57cec5SDimitry Andric     return APIntToHexString(CI->getValue());
2026*0b57cec5SDimitry Andric   } else {
2027*0b57cec5SDimitry Andric     unsigned NumElements;
20285ffd83dbSDimitry Andric     if (auto *VTy = dyn_cast<VectorType>(Ty))
20295ffd83dbSDimitry Andric       NumElements = cast<FixedVectorType>(VTy)->getNumElements();
2030*0b57cec5SDimitry Andric     else
2031*0b57cec5SDimitry Andric       NumElements = Ty->getArrayNumElements();
2032*0b57cec5SDimitry Andric     std::string HexString;
2033*0b57cec5SDimitry Andric     for (int I = NumElements - 1, E = -1; I != E; --I)
2034*0b57cec5SDimitry Andric       HexString += scalarConstantToHexString(C->getAggregateElement(I));
2035*0b57cec5SDimitry Andric     return HexString;
2036*0b57cec5SDimitry Andric   }
2037*0b57cec5SDimitry Andric }
2038*0b57cec5SDimitry Andric 
2039*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
2040*0b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
20415ffd83dbSDimitry Andric     Align &Alignment) const {
2042*0b57cec5SDimitry Andric   if (Kind.isMergeableConst() && C &&
2043*0b57cec5SDimitry Andric       getContext().getAsmInfo()->hasCOFFComdatConstants()) {
2044*0b57cec5SDimitry Andric     // This creates comdat sections with the given symbol name, but unless
2045*0b57cec5SDimitry Andric     // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
2046*0b57cec5SDimitry Andric     // will be created with a null storage class, which makes GNU binutils
2047*0b57cec5SDimitry Andric     // error out.
2048*0b57cec5SDimitry Andric     const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
2049*0b57cec5SDimitry Andric                                      COFF::IMAGE_SCN_MEM_READ |
2050*0b57cec5SDimitry Andric                                      COFF::IMAGE_SCN_LNK_COMDAT;
2051*0b57cec5SDimitry Andric     std::string COMDATSymName;
2052*0b57cec5SDimitry Andric     if (Kind.isMergeableConst4()) {
20535ffd83dbSDimitry Andric       if (Alignment <= 4) {
2054*0b57cec5SDimitry Andric         COMDATSymName = "__real@" + scalarConstantToHexString(C);
20555ffd83dbSDimitry Andric         Alignment = Align(4);
2056*0b57cec5SDimitry Andric       }
2057*0b57cec5SDimitry Andric     } else if (Kind.isMergeableConst8()) {
20585ffd83dbSDimitry Andric       if (Alignment <= 8) {
2059*0b57cec5SDimitry Andric         COMDATSymName = "__real@" + scalarConstantToHexString(C);
20605ffd83dbSDimitry Andric         Alignment = Align(8);
2061*0b57cec5SDimitry Andric       }
2062*0b57cec5SDimitry Andric     } else if (Kind.isMergeableConst16()) {
2063*0b57cec5SDimitry Andric       // FIXME: These may not be appropriate for non-x86 architectures.
20645ffd83dbSDimitry Andric       if (Alignment <= 16) {
2065*0b57cec5SDimitry Andric         COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
20665ffd83dbSDimitry Andric         Alignment = Align(16);
2067*0b57cec5SDimitry Andric       }
2068*0b57cec5SDimitry Andric     } else if (Kind.isMergeableConst32()) {
20695ffd83dbSDimitry Andric       if (Alignment <= 32) {
2070*0b57cec5SDimitry Andric         COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
20715ffd83dbSDimitry Andric         Alignment = Align(32);
2072*0b57cec5SDimitry Andric       }
2073*0b57cec5SDimitry Andric     }
2074*0b57cec5SDimitry Andric 
2075*0b57cec5SDimitry Andric     if (!COMDATSymName.empty())
2076*0b57cec5SDimitry Andric       return getContext().getCOFFSection(".rdata", Characteristics, Kind,
2077*0b57cec5SDimitry Andric                                          COMDATSymName,
2078*0b57cec5SDimitry Andric                                          COFF::IMAGE_COMDAT_SELECT_ANY);
2079*0b57cec5SDimitry Andric   }
2080*0b57cec5SDimitry Andric 
20815ffd83dbSDimitry Andric   return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C,
20825ffd83dbSDimitry Andric                                                          Alignment);
2083*0b57cec5SDimitry Andric }
2084*0b57cec5SDimitry Andric 
2085*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2086*0b57cec5SDimitry Andric //                                  Wasm
2087*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2088*0b57cec5SDimitry Andric 
2089*0b57cec5SDimitry Andric static const Comdat *getWasmComdat(const GlobalValue *GV) {
2090*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
2091*0b57cec5SDimitry Andric   if (!C)
2092*0b57cec5SDimitry Andric     return nullptr;
2093*0b57cec5SDimitry Andric 
2094*0b57cec5SDimitry Andric   if (C->getSelectionKind() != Comdat::Any)
2095*0b57cec5SDimitry Andric     report_fatal_error("WebAssembly COMDATs only support "
2096*0b57cec5SDimitry Andric                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
2097*0b57cec5SDimitry Andric                        "lowered.");
2098*0b57cec5SDimitry Andric 
2099*0b57cec5SDimitry Andric   return C;
2100*0b57cec5SDimitry Andric }
2101*0b57cec5SDimitry Andric 
2102fe6060f1SDimitry Andric static unsigned getWasmSectionFlags(SectionKind K) {
2103fe6060f1SDimitry Andric   unsigned Flags = 0;
2104fe6060f1SDimitry Andric 
2105fe6060f1SDimitry Andric   if (K.isThreadLocal())
2106fe6060f1SDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_TLS;
2107fe6060f1SDimitry Andric 
2108fe6060f1SDimitry Andric   if (K.isMergeableCString())
2109fe6060f1SDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_STRINGS;
2110fe6060f1SDimitry Andric 
2111fe6060f1SDimitry Andric   // TODO(sbc): Add suport for K.isMergeableConst()
2112fe6060f1SDimitry Andric 
2113fe6060f1SDimitry Andric   return Flags;
2114fe6060f1SDimitry Andric }
2115fe6060f1SDimitry Andric 
2116*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
2117*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2118*0b57cec5SDimitry Andric   // We don't support explict section names for functions in the wasm object
2119*0b57cec5SDimitry Andric   // format.  Each function has to be in its own unique section.
2120*0b57cec5SDimitry Andric   if (isa<Function>(GO)) {
2121*0b57cec5SDimitry Andric     return SelectSectionForGlobal(GO, Kind, TM);
2122*0b57cec5SDimitry Andric   }
2123*0b57cec5SDimitry Andric 
2124*0b57cec5SDimitry Andric   StringRef Name = GO->getSection();
2125*0b57cec5SDimitry Andric 
21265ffd83dbSDimitry Andric   // Certain data sections we treat as named custom sections rather than
21275ffd83dbSDimitry Andric   // segments within the data section.
21285ffd83dbSDimitry Andric   // This could be avoided if all data segements (the wasm sense) were
21295ffd83dbSDimitry Andric   // represented as their own sections (in the llvm sense).
21305ffd83dbSDimitry Andric   // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
21315ffd83dbSDimitry Andric   if (Name == ".llvmcmd" || Name == ".llvmbc")
21325ffd83dbSDimitry Andric     Kind = SectionKind::getMetadata();
2133*0b57cec5SDimitry Andric 
2134*0b57cec5SDimitry Andric   StringRef Group = "";
2135*0b57cec5SDimitry Andric   if (const Comdat *C = getWasmComdat(GO)) {
2136*0b57cec5SDimitry Andric     Group = C->getName();
2137*0b57cec5SDimitry Andric   }
2138*0b57cec5SDimitry Andric 
2139fe6060f1SDimitry Andric   unsigned Flags = getWasmSectionFlags(Kind);
2140fe6060f1SDimitry Andric   MCSectionWasm *Section = getContext().getWasmSection(
2141fe6060f1SDimitry Andric       Name, Kind, Flags, Group, MCContext::GenericSectionID);
2142*0b57cec5SDimitry Andric 
2143*0b57cec5SDimitry Andric   return Section;
2144*0b57cec5SDimitry Andric }
2145*0b57cec5SDimitry Andric 
2146*0b57cec5SDimitry Andric static MCSectionWasm *selectWasmSectionForGlobal(
2147*0b57cec5SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
2148*0b57cec5SDimitry Andric     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
2149*0b57cec5SDimitry Andric   StringRef Group = "";
2150*0b57cec5SDimitry Andric   if (const Comdat *C = getWasmComdat(GO)) {
2151*0b57cec5SDimitry Andric     Group = C->getName();
2152*0b57cec5SDimitry Andric   }
2153*0b57cec5SDimitry Andric 
2154*0b57cec5SDimitry Andric   bool UniqueSectionNames = TM.getUniqueSectionNames();
2155*0b57cec5SDimitry Andric   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
2156*0b57cec5SDimitry Andric 
2157*0b57cec5SDimitry Andric   if (const auto *F = dyn_cast<Function>(GO)) {
2158*0b57cec5SDimitry Andric     const auto &OptionalPrefix = F->getSectionPrefix();
2159*0b57cec5SDimitry Andric     if (OptionalPrefix)
2160e8d8bef9SDimitry Andric       raw_svector_ostream(Name) << '.' << *OptionalPrefix;
2161*0b57cec5SDimitry Andric   }
2162*0b57cec5SDimitry Andric 
2163*0b57cec5SDimitry Andric   if (EmitUniqueSection && UniqueSectionNames) {
2164*0b57cec5SDimitry Andric     Name.push_back('.');
2165*0b57cec5SDimitry Andric     TM.getNameWithPrefix(Name, GO, Mang, true);
2166*0b57cec5SDimitry Andric   }
2167*0b57cec5SDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
2168*0b57cec5SDimitry Andric   if (EmitUniqueSection && !UniqueSectionNames) {
2169*0b57cec5SDimitry Andric     UniqueID = *NextUniqueID;
2170*0b57cec5SDimitry Andric     (*NextUniqueID)++;
2171*0b57cec5SDimitry Andric   }
2172*0b57cec5SDimitry Andric 
2173fe6060f1SDimitry Andric   unsigned Flags = getWasmSectionFlags(Kind);
2174fe6060f1SDimitry Andric   return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
2175*0b57cec5SDimitry Andric }
2176*0b57cec5SDimitry Andric 
2177*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
2178*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2179*0b57cec5SDimitry Andric 
2180*0b57cec5SDimitry Andric   if (Kind.isCommon())
2181*0b57cec5SDimitry Andric     report_fatal_error("mergable sections not supported yet on wasm");
2182*0b57cec5SDimitry Andric 
2183*0b57cec5SDimitry Andric   // If we have -ffunction-section or -fdata-section then we should emit the
2184*0b57cec5SDimitry Andric   // global value to a uniqued section specifically for it.
2185*0b57cec5SDimitry Andric   bool EmitUniqueSection = false;
2186*0b57cec5SDimitry Andric   if (Kind.isText())
2187*0b57cec5SDimitry Andric     EmitUniqueSection = TM.getFunctionSections();
2188*0b57cec5SDimitry Andric   else
2189*0b57cec5SDimitry Andric     EmitUniqueSection = TM.getDataSections();
2190*0b57cec5SDimitry Andric   EmitUniqueSection |= GO->hasComdat();
2191*0b57cec5SDimitry Andric 
2192*0b57cec5SDimitry Andric   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2193*0b57cec5SDimitry Andric                                     EmitUniqueSection, &NextUniqueID);
2194*0b57cec5SDimitry Andric }
2195*0b57cec5SDimitry Andric 
2196*0b57cec5SDimitry Andric bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
2197*0b57cec5SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
2198*0b57cec5SDimitry Andric   // We can always create relative relocations, so use another section
2199*0b57cec5SDimitry Andric   // that can be marked non-executable.
2200*0b57cec5SDimitry Andric   return false;
2201*0b57cec5SDimitry Andric }
2202*0b57cec5SDimitry Andric 
2203*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
2204*0b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
2205*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
2206*0b57cec5SDimitry Andric   // We may only use a PLT-relative relocation to refer to unnamed_addr
2207*0b57cec5SDimitry Andric   // functions.
2208*0b57cec5SDimitry Andric   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
2209*0b57cec5SDimitry Andric     return nullptr;
2210*0b57cec5SDimitry Andric 
22114824e7fdSDimitry Andric   // Basic correctness checks.
2212*0b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
2213*0b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
2214*0b57cec5SDimitry Andric       RHS->isThreadLocal())
2215*0b57cec5SDimitry Andric     return nullptr;
2216*0b57cec5SDimitry Andric 
2217*0b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
2218*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
2219*0b57cec5SDimitry Andric                               getContext()),
2220*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
2221*0b57cec5SDimitry Andric }
2222*0b57cec5SDimitry Andric 
2223*0b57cec5SDimitry Andric void TargetLoweringObjectFileWasm::InitializeWasm() {
2224*0b57cec5SDimitry Andric   StaticCtorSection =
2225*0b57cec5SDimitry Andric       getContext().getWasmSection(".init_array", SectionKind::getData());
2226*0b57cec5SDimitry Andric 
2227*0b57cec5SDimitry Andric   // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2228*0b57cec5SDimitry Andric   // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2229*0b57cec5SDimitry Andric   TTypeEncoding = dwarf::DW_EH_PE_absptr;
2230*0b57cec5SDimitry Andric }
2231*0b57cec5SDimitry Andric 
2232*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
2233*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
2234*0b57cec5SDimitry Andric   return Priority == UINT16_MAX ?
2235*0b57cec5SDimitry Andric          StaticCtorSection :
2236*0b57cec5SDimitry Andric          getContext().getWasmSection(".init_array." + utostr(Priority),
2237*0b57cec5SDimitry Andric                                      SectionKind::getData());
2238*0b57cec5SDimitry Andric }
2239*0b57cec5SDimitry Andric 
2240*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
2241*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
224281ad6265SDimitry Andric   report_fatal_error("@llvm.global_dtors should have been lowered already");
2243*0b57cec5SDimitry Andric }
22448bcb0991SDimitry Andric 
22458bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
22468bcb0991SDimitry Andric //                                  XCOFF
22478bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
2248e8d8bef9SDimitry Andric bool TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(
2249e8d8bef9SDimitry Andric     const MachineFunction *MF) {
2250e8d8bef9SDimitry Andric   if (!MF->getLandingPads().empty())
2251e8d8bef9SDimitry Andric     return true;
2252e8d8bef9SDimitry Andric 
2253e8d8bef9SDimitry Andric   const Function &F = MF->getFunction();
2254e8d8bef9SDimitry Andric   if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2255e8d8bef9SDimitry Andric     return false;
2256e8d8bef9SDimitry Andric 
2257fe6060f1SDimitry Andric   const GlobalValue *Per =
2258fe6060f1SDimitry Andric       dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
2259fe6060f1SDimitry Andric   assert(Per && "Personality routine is not a GlobalValue type.");
2260e8d8bef9SDimitry Andric   if (isNoOpWithoutInvoke(classifyEHPersonality(Per)))
2261e8d8bef9SDimitry Andric     return false;
2262e8d8bef9SDimitry Andric 
2263e8d8bef9SDimitry Andric   return true;
2264e8d8bef9SDimitry Andric }
2265e8d8bef9SDimitry Andric 
2266fe6060f1SDimitry Andric bool TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(
2267fe6060f1SDimitry Andric     const MachineFunction *MF) {
2268fe6060f1SDimitry Andric   const Function &F = MF->getFunction();
2269fe6060f1SDimitry Andric   if (!F.hasStackProtectorFnAttr())
2270fe6060f1SDimitry Andric     return false;
2271fe6060f1SDimitry Andric   // FIXME: check presence of canary word
2272fe6060f1SDimitry Andric   // There are cases that the stack protectors are not really inserted even if
2273fe6060f1SDimitry Andric   // the attributes are on.
2274fe6060f1SDimitry Andric   return true;
2275fe6060f1SDimitry Andric }
2276fe6060f1SDimitry Andric 
2277e8d8bef9SDimitry Andric MCSymbol *
2278e8d8bef9SDimitry Andric TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(const MachineFunction *MF) {
2279e8d8bef9SDimitry Andric   return MF->getMMI().getContext().getOrCreateSymbol(
2280e8d8bef9SDimitry Andric       "__ehinfo." + Twine(MF->getFunctionNumber()));
2281e8d8bef9SDimitry Andric }
2282e8d8bef9SDimitry Andric 
22835ffd83dbSDimitry Andric MCSymbol *
22845ffd83dbSDimitry Andric TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV,
22855ffd83dbSDimitry Andric                                                const TargetMachine &TM) const {
22865ffd83dbSDimitry Andric   // We always use a qualname symbol for a GV that represents
22875ffd83dbSDimitry Andric   // a declaration, a function descriptor, or a common symbol.
2288e8d8bef9SDimitry Andric   // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2289e8d8bef9SDimitry Andric   // also return a qualname so that a label symbol could be avoided.
22905ffd83dbSDimitry Andric   // It is inherently ambiguous when the GO represents the address of a
22915ffd83dbSDimitry Andric   // function, as the GO could either represent a function descriptor or a
22925ffd83dbSDimitry Andric   // function entry point. We choose to always return a function descriptor
22935ffd83dbSDimitry Andric   // here.
22945ffd83dbSDimitry Andric   if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2295bdd1243dSDimitry Andric     if (GO->isDeclarationForLinker())
2296bdd1243dSDimitry Andric       return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
2297bdd1243dSDimitry Andric           ->getQualNameSymbol();
2298bdd1243dSDimitry Andric 
2299fe6060f1SDimitry Andric     if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
2300fe6060f1SDimitry Andric       if (GVar->hasAttribute("toc-data"))
2301fe6060f1SDimitry Andric         return cast<MCSectionXCOFF>(
2302fe6060f1SDimitry Andric                    SectionForGlobal(GVar, SectionKind::getData(), TM))
2303fe6060f1SDimitry Andric             ->getQualNameSymbol();
2304fe6060f1SDimitry Andric 
23055ffd83dbSDimitry Andric     SectionKind GOKind = getKindForGlobal(GO, TM);
23065ffd83dbSDimitry Andric     if (GOKind.isText())
23075ffd83dbSDimitry Andric       return cast<MCSectionXCOFF>(
23085ffd83dbSDimitry Andric                  getSectionForFunctionDescriptor(cast<Function>(GO), TM))
23095ffd83dbSDimitry Andric           ->getQualNameSymbol();
2310fe6060f1SDimitry Andric     if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
2311fe6060f1SDimitry Andric         GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
23125ffd83dbSDimitry Andric       return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
23135ffd83dbSDimitry Andric           ->getQualNameSymbol();
23145ffd83dbSDimitry Andric   }
23155ffd83dbSDimitry Andric 
23165ffd83dbSDimitry Andric   // For all other cases, fall back to getSymbol to return the unqualified name.
23175ffd83dbSDimitry Andric   return nullptr;
23185ffd83dbSDimitry Andric }
23195ffd83dbSDimitry Andric 
23208bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
23218bcb0991SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2322e8d8bef9SDimitry Andric   if (!GO->hasSection())
2323e8d8bef9SDimitry Andric     report_fatal_error("#pragma clang section is not yet supported");
2324e8d8bef9SDimitry Andric 
2325e8d8bef9SDimitry Andric   StringRef SectionName = GO->getSection();
2326fe6060f1SDimitry Andric 
2327fe6060f1SDimitry Andric   // Handle the XCOFF::TD case first, then deal with the rest.
2328fe6060f1SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2329fe6060f1SDimitry Andric     if (GVar->hasAttribute("toc-data"))
2330fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2331fe6060f1SDimitry Andric           SectionName, Kind,
2332fe6060f1SDimitry Andric           XCOFF::CsectProperties(/*MappingClass*/ XCOFF::XMC_TD, XCOFF::XTY_SD),
2333fe6060f1SDimitry Andric           /* MultiSymbolsAllowed*/ true);
2334fe6060f1SDimitry Andric 
2335e8d8bef9SDimitry Andric   XCOFF::StorageMappingClass MappingClass;
2336e8d8bef9SDimitry Andric   if (Kind.isText())
2337e8d8bef9SDimitry Andric     MappingClass = XCOFF::XMC_PR;
2338e8d8bef9SDimitry Andric   else if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS())
2339e8d8bef9SDimitry Andric     MappingClass = XCOFF::XMC_RW;
2340e8d8bef9SDimitry Andric   else if (Kind.isReadOnly())
2341e8d8bef9SDimitry Andric     MappingClass = XCOFF::XMC_RO;
2342e8d8bef9SDimitry Andric   else
2343e8d8bef9SDimitry Andric     report_fatal_error("XCOFF other section types not yet implemented.");
2344e8d8bef9SDimitry Andric 
2345fe6060f1SDimitry Andric   return getContext().getXCOFFSection(
2346fe6060f1SDimitry Andric       SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
2347fe6060f1SDimitry Andric       /* MultiSymbolsAllowed*/ true);
23488bcb0991SDimitry Andric }
23498bcb0991SDimitry Andric 
23505ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference(
23515ffd83dbSDimitry Andric     const GlobalObject *GO, const TargetMachine &TM) const {
23525ffd83dbSDimitry Andric   assert(GO->isDeclarationForLinker() &&
23535ffd83dbSDimitry Andric          "Tried to get ER section for a defined global.");
23545ffd83dbSDimitry Andric 
23555ffd83dbSDimitry Andric   SmallString<128> Name;
23565ffd83dbSDimitry Andric   getNameWithPrefix(Name, GO, TM);
23575ffd83dbSDimitry Andric 
2358fe6060f1SDimitry Andric   XCOFF::StorageMappingClass SMC =
2359fe6060f1SDimitry Andric       isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA;
2360fe6060f1SDimitry Andric   if (GO->isThreadLocal())
2361fe6060f1SDimitry Andric     SMC = XCOFF::XMC_UL;
2362fe6060f1SDimitry Andric 
2363bdd1243dSDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2364bdd1243dSDimitry Andric     if (GVar->hasAttribute("toc-data"))
2365bdd1243dSDimitry Andric       SMC = XCOFF::XMC_TD;
2366bdd1243dSDimitry Andric 
23675ffd83dbSDimitry Andric   // Externals go into a csect of type ER.
23685ffd83dbSDimitry Andric   return getContext().getXCOFFSection(
2369fe6060f1SDimitry Andric       Name, SectionKind::getMetadata(),
2370fe6060f1SDimitry Andric       XCOFF::CsectProperties(SMC, XCOFF::XTY_ER));
23715ffd83dbSDimitry Andric }
23725ffd83dbSDimitry Andric 
23738bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
23748bcb0991SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2375fe6060f1SDimitry Andric   // Handle the XCOFF::TD case first, then deal with the rest.
2376fe6060f1SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2377fe6060f1SDimitry Andric     if (GVar->hasAttribute("toc-data")) {
23788bcb0991SDimitry Andric       SmallString<128> Name;
23798bcb0991SDimitry Andric       getNameWithPrefix(Name, GO, TM);
23808bcb0991SDimitry Andric       return getContext().getXCOFFSection(
2381fe6060f1SDimitry Andric           Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, XCOFF::XTY_SD),
2382fe6060f1SDimitry Andric           /* MultiSymbolsAllowed*/ true);
2383fe6060f1SDimitry Andric     }
2384fe6060f1SDimitry Andric 
2385fe6060f1SDimitry Andric   // Common symbols go into a csect with matching name which will get mapped
2386fe6060f1SDimitry Andric   // into the .bss section.
2387fe6060f1SDimitry Andric   // Zero-initialized local TLS symbols go into a csect with matching name which
2388fe6060f1SDimitry Andric   // will get mapped into the .tbss section.
2389fe6060f1SDimitry Andric   if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
2390fe6060f1SDimitry Andric     SmallString<128> Name;
2391fe6060f1SDimitry Andric     getNameWithPrefix(Name, GO, TM);
2392fe6060f1SDimitry Andric     XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
2393fe6060f1SDimitry Andric                                      : Kind.isCommon() ? XCOFF::XMC_RW
2394fe6060f1SDimitry Andric                                                        : XCOFF::XMC_UL;
2395fe6060f1SDimitry Andric     return getContext().getXCOFFSection(
2396fe6060f1SDimitry Andric         Name, Kind, XCOFF::CsectProperties(SMC, XCOFF::XTY_CM));
23978bcb0991SDimitry Andric   }
23988bcb0991SDimitry Andric 
2399480093f4SDimitry Andric   if (Kind.isMergeableCString()) {
24005ffd83dbSDimitry Andric     Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
2401480093f4SDimitry Andric         cast<GlobalVariable>(GO));
2402480093f4SDimitry Andric 
2403480093f4SDimitry Andric     unsigned EntrySize = getEntrySizeForKind(Kind);
2404480093f4SDimitry Andric     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
2405480093f4SDimitry Andric     SmallString<128> Name;
24065ffd83dbSDimitry Andric     Name = SizeSpec + utostr(Alignment.value());
2407480093f4SDimitry Andric 
2408e8d8bef9SDimitry Andric     if (TM.getDataSections())
2409e8d8bef9SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2410e8d8bef9SDimitry Andric 
2411480093f4SDimitry Andric     return getContext().getXCOFFSection(
2412fe6060f1SDimitry Andric         Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD),
2413e8d8bef9SDimitry Andric         /* MultiSymbolsAllowed*/ !TM.getDataSections());
2414480093f4SDimitry Andric   }
2415480093f4SDimitry Andric 
2416e8d8bef9SDimitry Andric   if (Kind.isText()) {
2417e8d8bef9SDimitry Andric     if (TM.getFunctionSections()) {
2418e8d8bef9SDimitry Andric       return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
2419e8d8bef9SDimitry Andric           ->getRepresentedCsect();
2420e8d8bef9SDimitry Andric     }
24218bcb0991SDimitry Andric     return TextSection;
2422e8d8bef9SDimitry Andric   }
24238bcb0991SDimitry Andric 
2424e8d8bef9SDimitry Andric   // TODO: We may put Kind.isReadOnlyWithRel() under option control, because
2425e8d8bef9SDimitry Andric   // user may want to have read-only data with relocations placed into a
2426e8d8bef9SDimitry Andric   // read-only section by the compiler.
2427e8d8bef9SDimitry Andric   // For BSS kind, zero initialized data must be emitted to the .data section
2428e8d8bef9SDimitry Andric   // because external linkage control sections that get mapped to the .bss
2429e8d8bef9SDimitry Andric   // section will be linked as tentative defintions, which is only appropriate
2430e8d8bef9SDimitry Andric   // for SectionKind::Common.
2431e8d8bef9SDimitry Andric   if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2432e8d8bef9SDimitry Andric     if (TM.getDataSections()) {
2433e8d8bef9SDimitry Andric       SmallString<128> Name;
2434e8d8bef9SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2435fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2436fe6060f1SDimitry Andric           Name, SectionKind::getData(),
2437fe6060f1SDimitry Andric           XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD));
2438e8d8bef9SDimitry Andric     }
24398bcb0991SDimitry Andric     return DataSection;
2440e8d8bef9SDimitry Andric   }
24418bcb0991SDimitry Andric 
2442e8d8bef9SDimitry Andric   if (Kind.isReadOnly()) {
2443e8d8bef9SDimitry Andric     if (TM.getDataSections()) {
2444e8d8bef9SDimitry Andric       SmallString<128> Name;
2445e8d8bef9SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2446fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2447fe6060f1SDimitry Andric           Name, SectionKind::getReadOnly(),
2448fe6060f1SDimitry Andric           XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
2449e8d8bef9SDimitry Andric     }
2450480093f4SDimitry Andric     return ReadOnlySection;
2451e8d8bef9SDimitry Andric   }
2452480093f4SDimitry Andric 
2453fe6060f1SDimitry Andric   // External/weak TLS data and initialized local TLS data are not eligible
2454fe6060f1SDimitry Andric   // to be put into common csect. If data sections are enabled, thread
2455fe6060f1SDimitry Andric   // data are emitted into separate sections. Otherwise, thread data
2456fe6060f1SDimitry Andric   // are emitted into the .tdata section.
2457fe6060f1SDimitry Andric   if (Kind.isThreadLocal()) {
2458fe6060f1SDimitry Andric     if (TM.getDataSections()) {
2459fe6060f1SDimitry Andric       SmallString<128> Name;
2460fe6060f1SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2461fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2462fe6060f1SDimitry Andric           Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TL, XCOFF::XTY_SD));
2463fe6060f1SDimitry Andric     }
2464fe6060f1SDimitry Andric     return TLSDataSection;
2465fe6060f1SDimitry Andric   }
2466fe6060f1SDimitry Andric 
24678bcb0991SDimitry Andric   report_fatal_error("XCOFF other section types not yet implemented.");
24688bcb0991SDimitry Andric }
24698bcb0991SDimitry Andric 
2470480093f4SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
2471480093f4SDimitry Andric     const Function &F, const TargetMachine &TM) const {
2472480093f4SDimitry Andric   assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2473e8d8bef9SDimitry Andric 
2474e8d8bef9SDimitry Andric   if (!TM.getFunctionSections())
2475480093f4SDimitry Andric     return ReadOnlySection;
2476e8d8bef9SDimitry Andric 
2477e8d8bef9SDimitry Andric   // If the function can be removed, produce a unique section so that
2478e8d8bef9SDimitry Andric   // the table doesn't prevent the removal.
2479e8d8bef9SDimitry Andric   SmallString<128> NameStr(".rodata.jmp..");
2480e8d8bef9SDimitry Andric   getNameWithPrefix(NameStr, &F, TM);
2481fe6060f1SDimitry Andric   return getContext().getXCOFFSection(
2482fe6060f1SDimitry Andric       NameStr, SectionKind::getReadOnly(),
2483fe6060f1SDimitry Andric       XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
2484480093f4SDimitry Andric }
2485480093f4SDimitry Andric 
24868bcb0991SDimitry Andric bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
24878bcb0991SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
2488480093f4SDimitry Andric   return false;
2489480093f4SDimitry Andric }
2490480093f4SDimitry Andric 
2491480093f4SDimitry Andric /// Given a mergeable constant with the specified size and relocation
2492480093f4SDimitry Andric /// information, return a section that it should be placed in.
2493480093f4SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant(
2494480093f4SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
24955ffd83dbSDimitry Andric     Align &Alignment) const {
2496480093f4SDimitry Andric   // TODO: Enable emiting constant pool to unique sections when we support it.
2497349cc55cSDimitry Andric   if (Alignment > Align(16))
2498349cc55cSDimitry Andric     report_fatal_error("Alignments greater than 16 not yet supported.");
2499349cc55cSDimitry Andric 
2500349cc55cSDimitry Andric   if (Alignment == Align(8)) {
2501349cc55cSDimitry Andric     assert(ReadOnly8Section && "Section should always be initialized.");
2502349cc55cSDimitry Andric     return ReadOnly8Section;
2503349cc55cSDimitry Andric   }
2504349cc55cSDimitry Andric 
2505349cc55cSDimitry Andric   if (Alignment == Align(16)) {
2506349cc55cSDimitry Andric     assert(ReadOnly16Section && "Section should always be initialized.");
2507349cc55cSDimitry Andric     return ReadOnly16Section;
2508349cc55cSDimitry Andric   }
2509349cc55cSDimitry Andric 
2510480093f4SDimitry Andric   return ReadOnlySection;
25118bcb0991SDimitry Andric }
25128bcb0991SDimitry Andric 
25138bcb0991SDimitry Andric void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
25148bcb0991SDimitry Andric                                                const TargetMachine &TgtM) {
25158bcb0991SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
2516e8d8bef9SDimitry Andric   TTypeEncoding =
2517e8d8bef9SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_datarel |
2518e8d8bef9SDimitry Andric       (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4
2519e8d8bef9SDimitry Andric                                             : dwarf::DW_EH_PE_sdata8);
25208bcb0991SDimitry Andric   PersonalityEncoding = 0;
25218bcb0991SDimitry Andric   LSDAEncoding = 0;
2522e8d8bef9SDimitry Andric   CallSiteEncoding = dwarf::DW_EH_PE_udata4;
2523bdd1243dSDimitry Andric 
2524bdd1243dSDimitry Andric   // AIX debug for thread local location is not ready. And for integrated as
2525bdd1243dSDimitry Andric   // mode, the relocatable address for the thread local variable will cause
2526bdd1243dSDimitry Andric   // linker error. So disable the location attribute generation for thread local
2527bdd1243dSDimitry Andric   // variables for now.
2528bdd1243dSDimitry Andric   // FIXME: when TLS debug on AIX is ready, remove this setting.
2529bdd1243dSDimitry Andric   SupportDebugThreadLocalLocation = false;
25308bcb0991SDimitry Andric }
25318bcb0991SDimitry Andric 
25328bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
25338bcb0991SDimitry Andric 	unsigned Priority, const MCSymbol *KeySym) const {
2534e8d8bef9SDimitry Andric   report_fatal_error("no static constructor section on AIX");
25358bcb0991SDimitry Andric }
25368bcb0991SDimitry Andric 
25378bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
25388bcb0991SDimitry Andric 	unsigned Priority, const MCSymbol *KeySym) const {
2539e8d8bef9SDimitry Andric   report_fatal_error("no static destructor section on AIX");
25408bcb0991SDimitry Andric }
25418bcb0991SDimitry Andric 
25428bcb0991SDimitry Andric const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
25438bcb0991SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
25448bcb0991SDimitry Andric     const TargetMachine &TM) const {
2545349cc55cSDimitry Andric   /* Not implemented yet, but don't crash, return nullptr. */
2546349cc55cSDimitry Andric   return nullptr;
25478bcb0991SDimitry Andric }
25488bcb0991SDimitry Andric 
2549e8d8bef9SDimitry Andric XCOFF::StorageClass
2550e8d8bef9SDimitry Andric TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) {
2551e8d8bef9SDimitry Andric   assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2552e8d8bef9SDimitry Andric 
2553e8d8bef9SDimitry Andric   switch (GV->getLinkage()) {
25548bcb0991SDimitry Andric   case GlobalValue::InternalLinkage:
2555480093f4SDimitry Andric   case GlobalValue::PrivateLinkage:
25568bcb0991SDimitry Andric     return XCOFF::C_HIDEXT;
25578bcb0991SDimitry Andric   case GlobalValue::ExternalLinkage:
25588bcb0991SDimitry Andric   case GlobalValue::CommonLinkage:
25595ffd83dbSDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
25608bcb0991SDimitry Andric     return XCOFF::C_EXT;
25618bcb0991SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
25625ffd83dbSDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
25635ffd83dbSDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
25645ffd83dbSDimitry Andric   case GlobalValue::WeakAnyLinkage:
25655ffd83dbSDimitry Andric   case GlobalValue::WeakODRLinkage:
25668bcb0991SDimitry Andric     return XCOFF::C_WEAKEXT;
25675ffd83dbSDimitry Andric   case GlobalValue::AppendingLinkage:
25688bcb0991SDimitry Andric     report_fatal_error(
25695ffd83dbSDimitry Andric         "There is no mapping that implements AppendingLinkage for XCOFF.");
25708bcb0991SDimitry Andric   }
25715ffd83dbSDimitry Andric   llvm_unreachable("Unknown linkage type!");
25725ffd83dbSDimitry Andric }
25735ffd83dbSDimitry Andric 
25745ffd83dbSDimitry Andric MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol(
2575e8d8bef9SDimitry Andric     const GlobalValue *Func, const TargetMachine &TM) const {
2576349cc55cSDimitry Andric   assert((isa<Function>(Func) ||
2577e8d8bef9SDimitry Andric           (isa<GlobalAlias>(Func) &&
2578349cc55cSDimitry Andric            isa_and_nonnull<Function>(
2579349cc55cSDimitry Andric                cast<GlobalAlias>(Func)->getAliaseeObject()))) &&
2580e8d8bef9SDimitry Andric          "Func must be a function or an alias which has a function as base "
2581e8d8bef9SDimitry Andric          "object.");
2582e8d8bef9SDimitry Andric 
25835ffd83dbSDimitry Andric   SmallString<128> NameStr;
25845ffd83dbSDimitry Andric   NameStr.push_back('.');
2585e8d8bef9SDimitry Andric   getNameWithPrefix(NameStr, Func, TM);
2586e8d8bef9SDimitry Andric 
2587e8d8bef9SDimitry Andric   // When -function-sections is enabled and explicit section is not specified,
2588e8d8bef9SDimitry Andric   // it's not necessary to emit function entry point label any more. We will use
2589e8d8bef9SDimitry Andric   // function entry point csect instead. And for function delcarations, the
2590e8d8bef9SDimitry Andric   // undefined symbols gets treated as csect with XTY_ER property.
2591e8d8bef9SDimitry Andric   if (((TM.getFunctionSections() && !Func->hasSection()) ||
2592e8d8bef9SDimitry Andric        Func->isDeclaration()) &&
2593e8d8bef9SDimitry Andric       isa<Function>(Func)) {
2594e8d8bef9SDimitry Andric     return getContext()
2595fe6060f1SDimitry Andric         .getXCOFFSection(
2596fe6060f1SDimitry Andric             NameStr, SectionKind::getText(),
2597fe6060f1SDimitry Andric             XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclaration()
2598fe6060f1SDimitry Andric                                                       ? XCOFF::XTY_ER
2599fe6060f1SDimitry Andric                                                       : XCOFF::XTY_SD))
2600e8d8bef9SDimitry Andric         ->getQualNameSymbol();
2601e8d8bef9SDimitry Andric   }
2602e8d8bef9SDimitry Andric 
26035ffd83dbSDimitry Andric   return getContext().getOrCreateSymbol(NameStr);
26045ffd83dbSDimitry Andric }
26055ffd83dbSDimitry Andric 
26065ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
26075ffd83dbSDimitry Andric     const Function *F, const TargetMachine &TM) const {
26085ffd83dbSDimitry Andric   SmallString<128> NameStr;
26095ffd83dbSDimitry Andric   getNameWithPrefix(NameStr, F, TM);
2610fe6060f1SDimitry Andric   return getContext().getXCOFFSection(
2611fe6060f1SDimitry Andric       NameStr, SectionKind::getData(),
2612fe6060f1SDimitry Andric       XCOFF::CsectProperties(XCOFF::XMC_DS, XCOFF::XTY_SD));
26135ffd83dbSDimitry Andric }
26145ffd83dbSDimitry Andric 
26155ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
2616e8d8bef9SDimitry Andric     const MCSymbol *Sym, const TargetMachine &TM) const {
2617e8d8bef9SDimitry Andric   // Use TE storage-mapping class when large code model is enabled so that
2618e8d8bef9SDimitry Andric   // the chance of needing -bbigtoc is decreased.
26195ffd83dbSDimitry Andric   return getContext().getXCOFFSection(
2620fe6060f1SDimitry Andric       cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(),
2621fe6060f1SDimitry Andric       XCOFF::CsectProperties(
2622e8d8bef9SDimitry Andric           TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE : XCOFF::XMC_TC,
2623fe6060f1SDimitry Andric           XCOFF::XTY_SD));
2624fe6060f1SDimitry Andric }
2625fe6060f1SDimitry Andric 
262681ad6265SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForLSDA(
262781ad6265SDimitry Andric     const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
262881ad6265SDimitry Andric   auto *LSDA = cast<MCSectionXCOFF>(LSDASection);
262981ad6265SDimitry Andric   if (TM.getFunctionSections()) {
263081ad6265SDimitry Andric     // If option -ffunction-sections is on, append the function name to the
263181ad6265SDimitry Andric     // name of the LSDA csect so that each function has its own LSDA csect.
263281ad6265SDimitry Andric     // This helps the linker to garbage-collect EH info of unused functions.
263381ad6265SDimitry Andric     SmallString<128> NameStr = LSDA->getName();
263481ad6265SDimitry Andric     raw_svector_ostream(NameStr) << '.' << F.getName();
263581ad6265SDimitry Andric     LSDA = getContext().getXCOFFSection(NameStr, LSDA->getKind(),
263681ad6265SDimitry Andric                                         LSDA->getCsectProp());
263781ad6265SDimitry Andric   }
263881ad6265SDimitry Andric   return LSDA;
263981ad6265SDimitry Andric }
2640fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
2641fe6060f1SDimitry Andric //                                  GOFF
2642fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
264381ad6265SDimitry Andric TargetLoweringObjectFileGOFF::TargetLoweringObjectFileGOFF() = default;
2644fe6060f1SDimitry Andric 
2645fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::getExplicitSectionGlobal(
2646fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2647fe6060f1SDimitry Andric   return SelectSectionForGlobal(GO, Kind, TM);
2648fe6060f1SDimitry Andric }
2649fe6060f1SDimitry Andric 
2650fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::SelectSectionForGlobal(
2651fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2652fe6060f1SDimitry Andric   auto *Symbol = TM.getSymbol(GO);
2653fe6060f1SDimitry Andric   if (Kind.isBSS())
265481ad6265SDimitry Andric     return getContext().getGOFFSection(Symbol->getName(), SectionKind::getBSS(),
265581ad6265SDimitry Andric                                        nullptr, nullptr);
2656fe6060f1SDimitry Andric 
2657fe6060f1SDimitry Andric   return getContext().getObjectFileInfo()->getTextSection();
26588bcb0991SDimitry Andric }
2659