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"
61*0b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
62*0b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
63*0b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
645ffd83dbSDimitry Andric #include "llvm/Support/Format.h"
65*0b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
66*0b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
67*0b57cec5SDimitry Andric #include <cassert>
68*0b57cec5SDimitry Andric #include <string>
69*0b57cec5SDimitry Andric 
70*0b57cec5SDimitry Andric using namespace llvm;
71*0b57cec5SDimitry Andric using namespace dwarf;
72*0b57cec5SDimitry Andric 
73*0b57cec5SDimitry Andric static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
74*0b57cec5SDimitry Andric                              StringRef &Section) {
75*0b57cec5SDimitry Andric   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
76*0b57cec5SDimitry Andric   M.getModuleFlagsMetadata(ModuleFlags);
77*0b57cec5SDimitry Andric 
78*0b57cec5SDimitry Andric   for (const auto &MFE: ModuleFlags) {
79*0b57cec5SDimitry Andric     // Ignore flags with 'Require' behaviour.
80*0b57cec5SDimitry Andric     if (MFE.Behavior == Module::Require)
81*0b57cec5SDimitry Andric       continue;
82*0b57cec5SDimitry Andric 
83*0b57cec5SDimitry Andric     StringRef Key = MFE.Key->getString();
84*0b57cec5SDimitry Andric     if (Key == "Objective-C Image Info Version") {
85*0b57cec5SDimitry Andric       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
86*0b57cec5SDimitry Andric     } else if (Key == "Objective-C Garbage Collection" ||
87*0b57cec5SDimitry Andric                Key == "Objective-C GC Only" ||
88*0b57cec5SDimitry Andric                Key == "Objective-C Is Simulated" ||
89*0b57cec5SDimitry Andric                Key == "Objective-C Class Properties" ||
90*0b57cec5SDimitry Andric                Key == "Objective-C Image Swift Version") {
91*0b57cec5SDimitry Andric       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
92*0b57cec5SDimitry Andric     } else if (Key == "Objective-C Image Info Section") {
93*0b57cec5SDimitry Andric       Section = cast<MDString>(MFE.Val)->getString();
94*0b57cec5SDimitry Andric     }
955ffd83dbSDimitry Andric     // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
965ffd83dbSDimitry Andric     // "Objective-C Garbage Collection".
975ffd83dbSDimitry Andric     else if (Key == "Swift ABI Version") {
985ffd83dbSDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
995ffd83dbSDimitry Andric     } else if (Key == "Swift Major Version") {
1005ffd83dbSDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
1015ffd83dbSDimitry Andric     } else if (Key == "Swift Minor Version") {
1025ffd83dbSDimitry Andric       Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
1035ffd83dbSDimitry Andric     }
104*0b57cec5SDimitry Andric   }
105*0b57cec5SDimitry Andric }
106*0b57cec5SDimitry Andric 
107*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
108*0b57cec5SDimitry Andric //                                  ELF
109*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
110*0b57cec5SDimitry Andric 
11104eeddc0SDimitry Andric TargetLoweringObjectFileELF::TargetLoweringObjectFileELF() {
112e8d8bef9SDimitry Andric   SupportDSOLocalEquivalentLowering = true;
113e8d8bef9SDimitry Andric }
114e8d8bef9SDimitry Andric 
115*0b57cec5SDimitry Andric void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
116*0b57cec5SDimitry Andric                                              const TargetMachine &TgtM) {
117*0b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
118*0b57cec5SDimitry Andric 
119*0b57cec5SDimitry Andric   CodeModel::Model CM = TgtM.getCodeModel();
1205ffd83dbSDimitry Andric   InitializeELF(TgtM.Options.UseInitArray);
121*0b57cec5SDimitry Andric 
122*0b57cec5SDimitry Andric   switch (TgtM.getTargetTriple().getArch()) {
123*0b57cec5SDimitry Andric   case Triple::arm:
124*0b57cec5SDimitry Andric   case Triple::armeb:
125*0b57cec5SDimitry Andric   case Triple::thumb:
126*0b57cec5SDimitry Andric   case Triple::thumbeb:
127*0b57cec5SDimitry Andric     if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
128*0b57cec5SDimitry Andric       break;
129*0b57cec5SDimitry Andric     // Fallthrough if not using EHABI
130*0b57cec5SDimitry Andric     LLVM_FALLTHROUGH;
131*0b57cec5SDimitry Andric   case Triple::ppc:
132e8d8bef9SDimitry Andric   case Triple::ppcle:
133*0b57cec5SDimitry Andric   case Triple::x86:
134*0b57cec5SDimitry Andric     PersonalityEncoding = isPositionIndependent()
135*0b57cec5SDimitry Andric                               ? dwarf::DW_EH_PE_indirect |
136*0b57cec5SDimitry Andric                                     dwarf::DW_EH_PE_pcrel |
137*0b57cec5SDimitry Andric                                     dwarf::DW_EH_PE_sdata4
138*0b57cec5SDimitry Andric                               : dwarf::DW_EH_PE_absptr;
139*0b57cec5SDimitry Andric     LSDAEncoding = isPositionIndependent()
140*0b57cec5SDimitry Andric                        ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
141*0b57cec5SDimitry Andric                        : dwarf::DW_EH_PE_absptr;
142*0b57cec5SDimitry Andric     TTypeEncoding = isPositionIndependent()
143*0b57cec5SDimitry Andric                         ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
144*0b57cec5SDimitry Andric                               dwarf::DW_EH_PE_sdata4
145*0b57cec5SDimitry Andric                         : dwarf::DW_EH_PE_absptr;
146*0b57cec5SDimitry Andric     break;
147*0b57cec5SDimitry Andric   case Triple::x86_64:
148*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
149*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
150*0b57cec5SDimitry Andric         ((CM == CodeModel::Small || CM == CodeModel::Medium)
151*0b57cec5SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
152*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel |
153*0b57cec5SDimitry Andric         (CM == CodeModel::Small
154*0b57cec5SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
155*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
156*0b57cec5SDimitry Andric         ((CM == CodeModel::Small || CM == CodeModel::Medium)
157fe6060f1SDimitry Andric          ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
158*0b57cec5SDimitry Andric     } else {
159*0b57cec5SDimitry Andric       PersonalityEncoding =
160*0b57cec5SDimitry Andric         (CM == CodeModel::Small || CM == CodeModel::Medium)
161*0b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
162*0b57cec5SDimitry Andric       LSDAEncoding = (CM == CodeModel::Small)
163*0b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
164*0b57cec5SDimitry Andric       TTypeEncoding = (CM == CodeModel::Small)
165*0b57cec5SDimitry Andric         ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
166*0b57cec5SDimitry Andric     }
167*0b57cec5SDimitry Andric     break;
168*0b57cec5SDimitry Andric   case Triple::hexagon:
169*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
170*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_absptr;
171*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_absptr;
172*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
173*0b57cec5SDimitry Andric       PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
174*0b57cec5SDimitry Andric       LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
175*0b57cec5SDimitry Andric       TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
176*0b57cec5SDimitry Andric     }
177*0b57cec5SDimitry Andric     break;
178*0b57cec5SDimitry Andric   case Triple::aarch64:
179*0b57cec5SDimitry Andric   case Triple::aarch64_be:
1808bcb0991SDimitry Andric   case Triple::aarch64_32:
181*0b57cec5SDimitry Andric     // The small model guarantees static code/data size < 4GB, but not where it
182*0b57cec5SDimitry Andric     // will be in memory. Most of these could end up >2GB away so even a signed
183*0b57cec5SDimitry Andric     // pc-relative 32-bit address is insufficient, theoretically.
184*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
185e8d8bef9SDimitry Andric       // ILP32 uses sdata4 instead of sdata8
186e8d8bef9SDimitry Andric       if (TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32) {
187e8d8bef9SDimitry Andric         PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
188e8d8bef9SDimitry Andric                               dwarf::DW_EH_PE_sdata4;
189e8d8bef9SDimitry Andric         LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
190e8d8bef9SDimitry Andric         TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
191e8d8bef9SDimitry Andric                         dwarf::DW_EH_PE_sdata4;
192e8d8bef9SDimitry Andric       } else {
193*0b57cec5SDimitry Andric         PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
194*0b57cec5SDimitry Andric                               dwarf::DW_EH_PE_sdata8;
195*0b57cec5SDimitry Andric         LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8;
196*0b57cec5SDimitry Andric         TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
197*0b57cec5SDimitry Andric                         dwarf::DW_EH_PE_sdata8;
198e8d8bef9SDimitry Andric       }
199*0b57cec5SDimitry Andric     } else {
200*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
201*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
202*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
203*0b57cec5SDimitry Andric     }
204*0b57cec5SDimitry Andric     break;
205*0b57cec5SDimitry Andric   case Triple::lanai:
206*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_absptr;
207*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_absptr;
208*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_absptr;
209*0b57cec5SDimitry Andric     break;
210*0b57cec5SDimitry Andric   case Triple::mips:
211*0b57cec5SDimitry Andric   case Triple::mipsel:
212*0b57cec5SDimitry Andric   case Triple::mips64:
213*0b57cec5SDimitry Andric   case Triple::mips64el:
214*0b57cec5SDimitry Andric     // MIPS uses indirect pointer to refer personality functions and types, so
215*0b57cec5SDimitry Andric     // that the eh_frame section can be read-only. DW.ref.personality will be
216*0b57cec5SDimitry Andric     // generated for relocation.
217*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect;
218*0b57cec5SDimitry Andric     // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
219*0b57cec5SDimitry Andric     //        identify N64 from just a triple.
220*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
221*0b57cec5SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
222*0b57cec5SDimitry Andric     // We don't support PC-relative LSDA references in GAS so we use the default
223*0b57cec5SDimitry Andric     // DW_EH_PE_absptr for those.
224*0b57cec5SDimitry Andric 
225*0b57cec5SDimitry Andric     // FreeBSD must be explicit about the data size and using pcrel since it's
226*0b57cec5SDimitry Andric     // assembler/linker won't do the automatic conversion that the Linux tools
227*0b57cec5SDimitry Andric     // do.
228*0b57cec5SDimitry Andric     if (TgtM.getTargetTriple().isOSFreeBSD()) {
229*0b57cec5SDimitry Andric       PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
230*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
231*0b57cec5SDimitry Andric     }
232*0b57cec5SDimitry Andric     break;
233*0b57cec5SDimitry Andric   case Triple::ppc64:
234*0b57cec5SDimitry Andric   case Triple::ppc64le:
235*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
236*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_udata8;
237*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
238*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
239*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_udata8;
240*0b57cec5SDimitry Andric     break;
241*0b57cec5SDimitry Andric   case Triple::sparcel:
242*0b57cec5SDimitry Andric   case Triple::sparc:
243*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
244*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
245*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
246*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
247*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
248*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
249*0b57cec5SDimitry Andric     } else {
250*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
251*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
252*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
253*0b57cec5SDimitry Andric     }
254*0b57cec5SDimitry Andric     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
255*0b57cec5SDimitry Andric     break;
256*0b57cec5SDimitry Andric   case Triple::riscv32:
257*0b57cec5SDimitry Andric   case Triple::riscv64:
258*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
259*0b57cec5SDimitry Andric     PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
260*0b57cec5SDimitry Andric                           dwarf::DW_EH_PE_sdata4;
261*0b57cec5SDimitry Andric     TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
262*0b57cec5SDimitry Andric                     dwarf::DW_EH_PE_sdata4;
263*0b57cec5SDimitry Andric     CallSiteEncoding = dwarf::DW_EH_PE_udata4;
264*0b57cec5SDimitry Andric     break;
265*0b57cec5SDimitry Andric   case Triple::sparcv9:
266*0b57cec5SDimitry Andric     LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
267*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
268*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
269*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
270*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
271*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
272*0b57cec5SDimitry Andric     } else {
273*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
274*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
275*0b57cec5SDimitry Andric     }
276*0b57cec5SDimitry Andric     break;
277*0b57cec5SDimitry Andric   case Triple::systemz:
278*0b57cec5SDimitry Andric     // All currently-defined code models guarantee that 4-byte PC-relative
279*0b57cec5SDimitry Andric     // values will be in range.
280*0b57cec5SDimitry Andric     if (isPositionIndependent()) {
281*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
282*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
283*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
284*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
285*0b57cec5SDimitry Andric         dwarf::DW_EH_PE_sdata4;
286*0b57cec5SDimitry Andric     } else {
287*0b57cec5SDimitry Andric       PersonalityEncoding = dwarf::DW_EH_PE_absptr;
288*0b57cec5SDimitry Andric       LSDAEncoding = dwarf::DW_EH_PE_absptr;
289*0b57cec5SDimitry Andric       TTypeEncoding = dwarf::DW_EH_PE_absptr;
290*0b57cec5SDimitry Andric     }
291*0b57cec5SDimitry Andric     break;
292*0b57cec5SDimitry Andric   default:
293*0b57cec5SDimitry Andric     break;
294*0b57cec5SDimitry Andric   }
295*0b57cec5SDimitry Andric }
296*0b57cec5SDimitry Andric 
297fe6060f1SDimitry Andric void TargetLoweringObjectFileELF::getModuleMetadata(Module &M) {
298fe6060f1SDimitry Andric   SmallVector<GlobalValue *, 4> Vec;
299fe6060f1SDimitry Andric   collectUsedGlobalVariables(M, Vec, false);
300fe6060f1SDimitry Andric   for (GlobalValue *GV : Vec)
301fe6060f1SDimitry Andric     if (auto *GO = dyn_cast<GlobalObject>(GV))
302fe6060f1SDimitry Andric       Used.insert(GO);
303fe6060f1SDimitry Andric }
304fe6060f1SDimitry Andric 
305*0b57cec5SDimitry Andric void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
306*0b57cec5SDimitry Andric                                                      Module &M) const {
307*0b57cec5SDimitry Andric   auto &C = getContext();
308*0b57cec5SDimitry Andric 
309*0b57cec5SDimitry Andric   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
310*0b57cec5SDimitry Andric     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
311*0b57cec5SDimitry Andric                               ELF::SHF_EXCLUDE);
312*0b57cec5SDimitry Andric 
313*0b57cec5SDimitry Andric     Streamer.SwitchSection(S);
314*0b57cec5SDimitry Andric 
315480093f4SDimitry Andric     for (const auto *Operand : LinkerOptions->operands()) {
316*0b57cec5SDimitry Andric       if (cast<MDNode>(Operand)->getNumOperands() != 2)
317*0b57cec5SDimitry Andric         report_fatal_error("invalid llvm.linker.options");
318*0b57cec5SDimitry Andric       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
3195ffd83dbSDimitry Andric         Streamer.emitBytes(cast<MDString>(Option)->getString());
3205ffd83dbSDimitry Andric         Streamer.emitInt8(0);
321*0b57cec5SDimitry Andric       }
322*0b57cec5SDimitry Andric     }
323*0b57cec5SDimitry Andric   }
324*0b57cec5SDimitry Andric 
325*0b57cec5SDimitry Andric   if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
326*0b57cec5SDimitry Andric     auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
327fe6060f1SDimitry Andric                               ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
328*0b57cec5SDimitry Andric 
329*0b57cec5SDimitry Andric     Streamer.SwitchSection(S);
330*0b57cec5SDimitry Andric 
331480093f4SDimitry Andric     for (const auto *Operand : DependentLibraries->operands()) {
3325ffd83dbSDimitry Andric       Streamer.emitBytes(
333*0b57cec5SDimitry Andric           cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
3345ffd83dbSDimitry Andric       Streamer.emitInt8(0);
335*0b57cec5SDimitry Andric     }
336*0b57cec5SDimitry Andric   }
337*0b57cec5SDimitry Andric 
338e8d8bef9SDimitry Andric   if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
339e8d8bef9SDimitry Andric     // Emit a descriptor for every function including functions that have an
340e8d8bef9SDimitry Andric     // available external linkage. We may not want this for imported functions
341e8d8bef9SDimitry Andric     // that has code in another thinLTO module but we don't have a good way to
342e8d8bef9SDimitry Andric     // tell them apart from inline functions defined in header files. Therefore
343e8d8bef9SDimitry Andric     // we put each descriptor in a separate comdat section and rely on the
344e8d8bef9SDimitry Andric     // linker to deduplicate.
345e8d8bef9SDimitry Andric     for (const auto *Operand : FuncInfo->operands()) {
346e8d8bef9SDimitry Andric       const auto *MD = cast<MDNode>(Operand);
347e8d8bef9SDimitry Andric       auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
348e8d8bef9SDimitry Andric       auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
349e8d8bef9SDimitry Andric       auto *Name = cast<MDString>(MD->getOperand(2));
350e8d8bef9SDimitry Andric       auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
351e8d8bef9SDimitry Andric           TM->getFunctionSections() ? Name->getString() : StringRef());
352e8d8bef9SDimitry Andric 
353e8d8bef9SDimitry Andric       Streamer.SwitchSection(S);
354e8d8bef9SDimitry Andric       Streamer.emitInt64(GUID->getZExtValue());
355e8d8bef9SDimitry Andric       Streamer.emitInt64(Hash->getZExtValue());
356e8d8bef9SDimitry Andric       Streamer.emitULEB128IntValue(Name->getString().size());
357e8d8bef9SDimitry Andric       Streamer.emitBytes(Name->getString());
358e8d8bef9SDimitry Andric     }
359e8d8bef9SDimitry Andric   }
360e8d8bef9SDimitry Andric 
361*0b57cec5SDimitry Andric   unsigned Version = 0;
362*0b57cec5SDimitry Andric   unsigned Flags = 0;
363*0b57cec5SDimitry Andric   StringRef Section;
364*0b57cec5SDimitry Andric 
365*0b57cec5SDimitry Andric   GetObjCImageInfo(M, Version, Flags, Section);
366*0b57cec5SDimitry Andric   if (!Section.empty()) {
367*0b57cec5SDimitry Andric     auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
368*0b57cec5SDimitry Andric     Streamer.SwitchSection(S);
3695ffd83dbSDimitry Andric     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
3705ffd83dbSDimitry Andric     Streamer.emitInt32(Version);
3715ffd83dbSDimitry Andric     Streamer.emitInt32(Flags);
372*0b57cec5SDimitry Andric     Streamer.AddBlankLine();
373*0b57cec5SDimitry Andric   }
374*0b57cec5SDimitry Andric 
375e8d8bef9SDimitry Andric   emitCGProfileMetadata(Streamer, M);
376*0b57cec5SDimitry Andric }
377*0b57cec5SDimitry Andric 
378*0b57cec5SDimitry Andric MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
379*0b57cec5SDimitry Andric     const GlobalValue *GV, const TargetMachine &TM,
380*0b57cec5SDimitry Andric     MachineModuleInfo *MMI) const {
381*0b57cec5SDimitry Andric   unsigned Encoding = getPersonalityEncoding();
382*0b57cec5SDimitry Andric   if ((Encoding & 0x80) == DW_EH_PE_indirect)
383*0b57cec5SDimitry Andric     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
384*0b57cec5SDimitry Andric                                           TM.getSymbol(GV)->getName());
385*0b57cec5SDimitry Andric   if ((Encoding & 0x70) == DW_EH_PE_absptr)
386*0b57cec5SDimitry Andric     return TM.getSymbol(GV);
387*0b57cec5SDimitry Andric   report_fatal_error("We do not support this DWARF encoding yet!");
388*0b57cec5SDimitry Andric }
389*0b57cec5SDimitry Andric 
390*0b57cec5SDimitry Andric void TargetLoweringObjectFileELF::emitPersonalityValue(
391*0b57cec5SDimitry Andric     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
392*0b57cec5SDimitry Andric   SmallString<64> NameData("DW.ref.");
393*0b57cec5SDimitry Andric   NameData += Sym->getName();
394*0b57cec5SDimitry Andric   MCSymbolELF *Label =
395*0b57cec5SDimitry Andric       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
3965ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
3975ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_Weak);
398*0b57cec5SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
399*0b57cec5SDimitry Andric   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
400*0b57cec5SDimitry Andric                                                    ELF::SHT_PROGBITS, Flags, 0);
401*0b57cec5SDimitry Andric   unsigned Size = DL.getPointerSize();
402*0b57cec5SDimitry Andric   Streamer.SwitchSection(Sec);
4035ffd83dbSDimitry Andric   Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0).value());
4045ffd83dbSDimitry Andric   Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
405*0b57cec5SDimitry Andric   const MCExpr *E = MCConstantExpr::create(Size, getContext());
406*0b57cec5SDimitry Andric   Streamer.emitELFSize(Label, E);
4075ffd83dbSDimitry Andric   Streamer.emitLabel(Label);
408*0b57cec5SDimitry Andric 
4095ffd83dbSDimitry Andric   Streamer.emitSymbolValue(Sym, Size);
410*0b57cec5SDimitry Andric }
411*0b57cec5SDimitry Andric 
412*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
413*0b57cec5SDimitry Andric     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
414*0b57cec5SDimitry Andric     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
415*0b57cec5SDimitry Andric   if (Encoding & DW_EH_PE_indirect) {
416*0b57cec5SDimitry Andric     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
417*0b57cec5SDimitry Andric 
418*0b57cec5SDimitry Andric     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
419*0b57cec5SDimitry Andric 
420*0b57cec5SDimitry Andric     // Add information about the stub reference to ELFMMI so that the stub
421*0b57cec5SDimitry Andric     // gets emitted by the asmprinter.
422*0b57cec5SDimitry Andric     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
423*0b57cec5SDimitry Andric     if (!StubSym.getPointer()) {
424*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(GV);
425*0b57cec5SDimitry Andric       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
426*0b57cec5SDimitry Andric     }
427*0b57cec5SDimitry Andric 
428*0b57cec5SDimitry Andric     return TargetLoweringObjectFile::
429*0b57cec5SDimitry Andric       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
430*0b57cec5SDimitry Andric                         Encoding & ~DW_EH_PE_indirect, Streamer);
431*0b57cec5SDimitry Andric   }
432*0b57cec5SDimitry Andric 
433*0b57cec5SDimitry Andric   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
434*0b57cec5SDimitry Andric                                                            MMI, Streamer);
435*0b57cec5SDimitry Andric }
436*0b57cec5SDimitry Andric 
437*0b57cec5SDimitry Andric static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
438*0b57cec5SDimitry Andric   // N.B.: The defaults used in here are not the same ones used in MC.
439*0b57cec5SDimitry Andric   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
440*0b57cec5SDimitry Andric   // both gas and MC will produce a section with no flags. Given
441*0b57cec5SDimitry Andric   // section(".eh_frame") gcc will produce:
442*0b57cec5SDimitry Andric   //
443*0b57cec5SDimitry Andric   //   .section   .eh_frame,"a",@progbits
444*0b57cec5SDimitry Andric 
445*0b57cec5SDimitry Andric   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
4465ffd83dbSDimitry Andric                                       /*AddSegmentInfo=*/false) ||
4475ffd83dbSDimitry Andric       Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
448e8d8bef9SDimitry Andric                                       /*AddSegmentInfo=*/false) ||
449e8d8bef9SDimitry Andric       Name == ".llvmbc" || Name == ".llvmcmd")
450*0b57cec5SDimitry Andric     return SectionKind::getMetadata();
451*0b57cec5SDimitry Andric 
452*0b57cec5SDimitry Andric   if (Name.empty() || Name[0] != '.') return K;
453*0b57cec5SDimitry Andric 
454*0b57cec5SDimitry Andric   // Default implementation based on some magic section names.
455*0b57cec5SDimitry Andric   if (Name == ".bss" ||
456*0b57cec5SDimitry Andric       Name.startswith(".bss.") ||
457*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.b.") ||
458*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.b.") ||
459*0b57cec5SDimitry Andric       Name == ".sbss" ||
460*0b57cec5SDimitry Andric       Name.startswith(".sbss.") ||
461*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.sb.") ||
462*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.sb."))
463*0b57cec5SDimitry Andric     return SectionKind::getBSS();
464*0b57cec5SDimitry Andric 
465*0b57cec5SDimitry Andric   if (Name == ".tdata" ||
466*0b57cec5SDimitry Andric       Name.startswith(".tdata.") ||
467*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.td.") ||
468*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.td."))
469*0b57cec5SDimitry Andric     return SectionKind::getThreadData();
470*0b57cec5SDimitry Andric 
471*0b57cec5SDimitry Andric   if (Name == ".tbss" ||
472*0b57cec5SDimitry Andric       Name.startswith(".tbss.") ||
473*0b57cec5SDimitry Andric       Name.startswith(".gnu.linkonce.tb.") ||
474*0b57cec5SDimitry Andric       Name.startswith(".llvm.linkonce.tb."))
475*0b57cec5SDimitry Andric     return SectionKind::getThreadBSS();
476*0b57cec5SDimitry Andric 
477*0b57cec5SDimitry Andric   return K;
478*0b57cec5SDimitry Andric }
479*0b57cec5SDimitry Andric 
48004eeddc0SDimitry Andric static bool hasPrefix(StringRef SectionName, StringRef Prefix) {
48104eeddc0SDimitry Andric   return SectionName.consume_front(Prefix) &&
48204eeddc0SDimitry Andric          (SectionName.empty() || SectionName[0] == '.');
48304eeddc0SDimitry Andric }
48404eeddc0SDimitry Andric 
485*0b57cec5SDimitry Andric static unsigned getELFSectionType(StringRef Name, SectionKind K) {
486*0b57cec5SDimitry Andric   // Use SHT_NOTE for section whose name starts with ".note" to allow
487*0b57cec5SDimitry Andric   // emitting ELF notes from C variable declaration.
488*0b57cec5SDimitry Andric   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
489*0b57cec5SDimitry Andric   if (Name.startswith(".note"))
490*0b57cec5SDimitry Andric     return ELF::SHT_NOTE;
491*0b57cec5SDimitry Andric 
49204eeddc0SDimitry Andric   if (hasPrefix(Name, ".init_array"))
493*0b57cec5SDimitry Andric     return ELF::SHT_INIT_ARRAY;
494*0b57cec5SDimitry Andric 
49504eeddc0SDimitry Andric   if (hasPrefix(Name, ".fini_array"))
496*0b57cec5SDimitry Andric     return ELF::SHT_FINI_ARRAY;
497*0b57cec5SDimitry Andric 
49804eeddc0SDimitry Andric   if (hasPrefix(Name, ".preinit_array"))
499*0b57cec5SDimitry Andric     return ELF::SHT_PREINIT_ARRAY;
500*0b57cec5SDimitry Andric 
501*0b57cec5SDimitry Andric   if (K.isBSS() || K.isThreadBSS())
502*0b57cec5SDimitry Andric     return ELF::SHT_NOBITS;
503*0b57cec5SDimitry Andric 
504*0b57cec5SDimitry Andric   return ELF::SHT_PROGBITS;
505*0b57cec5SDimitry Andric }
506*0b57cec5SDimitry Andric 
507*0b57cec5SDimitry Andric static unsigned getELFSectionFlags(SectionKind K) {
508*0b57cec5SDimitry Andric   unsigned Flags = 0;
509*0b57cec5SDimitry Andric 
510*0b57cec5SDimitry Andric   if (!K.isMetadata())
511*0b57cec5SDimitry Andric     Flags |= ELF::SHF_ALLOC;
512*0b57cec5SDimitry Andric 
513*0b57cec5SDimitry Andric   if (K.isText())
514*0b57cec5SDimitry Andric     Flags |= ELF::SHF_EXECINSTR;
515*0b57cec5SDimitry Andric 
516*0b57cec5SDimitry Andric   if (K.isExecuteOnly())
517*0b57cec5SDimitry Andric     Flags |= ELF::SHF_ARM_PURECODE;
518*0b57cec5SDimitry Andric 
519*0b57cec5SDimitry Andric   if (K.isWriteable())
520*0b57cec5SDimitry Andric     Flags |= ELF::SHF_WRITE;
521*0b57cec5SDimitry Andric 
522*0b57cec5SDimitry Andric   if (K.isThreadLocal())
523*0b57cec5SDimitry Andric     Flags |= ELF::SHF_TLS;
524*0b57cec5SDimitry Andric 
525*0b57cec5SDimitry Andric   if (K.isMergeableCString() || K.isMergeableConst())
526*0b57cec5SDimitry Andric     Flags |= ELF::SHF_MERGE;
527*0b57cec5SDimitry Andric 
528*0b57cec5SDimitry Andric   if (K.isMergeableCString())
529*0b57cec5SDimitry Andric     Flags |= ELF::SHF_STRINGS;
530*0b57cec5SDimitry Andric 
531*0b57cec5SDimitry Andric   return Flags;
532*0b57cec5SDimitry Andric }
533*0b57cec5SDimitry Andric 
534*0b57cec5SDimitry Andric static const Comdat *getELFComdat(const GlobalValue *GV) {
535*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
536*0b57cec5SDimitry Andric   if (!C)
537*0b57cec5SDimitry Andric     return nullptr;
538*0b57cec5SDimitry Andric 
539fe6060f1SDimitry Andric   if (C->getSelectionKind() != Comdat::Any &&
540fe6060f1SDimitry Andric       C->getSelectionKind() != Comdat::NoDeduplicate)
541fe6060f1SDimitry Andric     report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
542fe6060f1SDimitry Andric                        "SelectionKind::NoDeduplicate, '" +
543*0b57cec5SDimitry Andric                        C->getName() + "' cannot be lowered.");
544*0b57cec5SDimitry Andric 
545*0b57cec5SDimitry Andric   return C;
546*0b57cec5SDimitry Andric }
547*0b57cec5SDimitry Andric 
5485ffd83dbSDimitry Andric static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
549*0b57cec5SDimitry Andric                                             const TargetMachine &TM) {
550*0b57cec5SDimitry Andric   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
551*0b57cec5SDimitry Andric   if (!MD)
552*0b57cec5SDimitry Andric     return nullptr;
553*0b57cec5SDimitry Andric 
554*0b57cec5SDimitry Andric   const MDOperand &Op = MD->getOperand(0);
555*0b57cec5SDimitry Andric   if (!Op.get())
556*0b57cec5SDimitry Andric     return nullptr;
557*0b57cec5SDimitry Andric 
558*0b57cec5SDimitry Andric   auto *VM = dyn_cast<ValueAsMetadata>(Op);
559*0b57cec5SDimitry Andric   if (!VM)
560*0b57cec5SDimitry Andric     report_fatal_error("MD_associated operand is not ValueAsMetadata");
561*0b57cec5SDimitry Andric 
5628bcb0991SDimitry Andric   auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
5638bcb0991SDimitry Andric   return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
564*0b57cec5SDimitry Andric }
565*0b57cec5SDimitry Andric 
566*0b57cec5SDimitry Andric static unsigned getEntrySizeForKind(SectionKind Kind) {
567*0b57cec5SDimitry Andric   if (Kind.isMergeable1ByteCString())
568*0b57cec5SDimitry Andric     return 1;
569*0b57cec5SDimitry Andric   else if (Kind.isMergeable2ByteCString())
570*0b57cec5SDimitry Andric     return 2;
571*0b57cec5SDimitry Andric   else if (Kind.isMergeable4ByteCString())
572*0b57cec5SDimitry Andric     return 4;
573*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst4())
574*0b57cec5SDimitry Andric     return 4;
575*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst8())
576*0b57cec5SDimitry Andric     return 8;
577*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst16())
578*0b57cec5SDimitry Andric     return 16;
579*0b57cec5SDimitry Andric   else if (Kind.isMergeableConst32())
580*0b57cec5SDimitry Andric     return 32;
581*0b57cec5SDimitry Andric   else {
582*0b57cec5SDimitry Andric     // We shouldn't have mergeable C strings or mergeable constants that we
583*0b57cec5SDimitry Andric     // didn't handle above.
584*0b57cec5SDimitry Andric     assert(!Kind.isMergeableCString() && "unknown string width");
585*0b57cec5SDimitry Andric     assert(!Kind.isMergeableConst() && "unknown data width");
586*0b57cec5SDimitry Andric     return 0;
587*0b57cec5SDimitry Andric   }
588*0b57cec5SDimitry Andric }
589*0b57cec5SDimitry Andric 
5905ffd83dbSDimitry Andric /// Return the section prefix name used by options FunctionsSections and
5915ffd83dbSDimitry Andric /// DataSections.
5925ffd83dbSDimitry Andric static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
5935ffd83dbSDimitry Andric   if (Kind.isText())
5945ffd83dbSDimitry Andric     return ".text";
5955ffd83dbSDimitry Andric   if (Kind.isReadOnly())
5965ffd83dbSDimitry Andric     return ".rodata";
5975ffd83dbSDimitry Andric   if (Kind.isBSS())
5985ffd83dbSDimitry Andric     return ".bss";
5995ffd83dbSDimitry Andric   if (Kind.isThreadData())
6005ffd83dbSDimitry Andric     return ".tdata";
6015ffd83dbSDimitry Andric   if (Kind.isThreadBSS())
6025ffd83dbSDimitry Andric     return ".tbss";
6035ffd83dbSDimitry Andric   if (Kind.isData())
6045ffd83dbSDimitry Andric     return ".data";
6055ffd83dbSDimitry Andric   if (Kind.isReadOnlyWithRel())
6065ffd83dbSDimitry Andric     return ".data.rel.ro";
6075ffd83dbSDimitry Andric   llvm_unreachable("Unknown section kind");
6085ffd83dbSDimitry Andric }
6095ffd83dbSDimitry Andric 
6105ffd83dbSDimitry Andric static SmallString<128>
6115ffd83dbSDimitry Andric getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind,
6125ffd83dbSDimitry Andric                            Mangler &Mang, const TargetMachine &TM,
6135ffd83dbSDimitry Andric                            unsigned EntrySize, bool UniqueSectionName) {
6145ffd83dbSDimitry Andric   SmallString<128> Name;
6155ffd83dbSDimitry Andric   if (Kind.isMergeableCString()) {
6165ffd83dbSDimitry Andric     // We also need alignment here.
6175ffd83dbSDimitry Andric     // FIXME: this is getting the alignment of the character, not the
6185ffd83dbSDimitry Andric     // alignment of the global!
6195ffd83dbSDimitry Andric     Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
6205ffd83dbSDimitry Andric         cast<GlobalVariable>(GO));
6215ffd83dbSDimitry Andric 
6225ffd83dbSDimitry Andric     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
6235ffd83dbSDimitry Andric     Name = SizeSpec + utostr(Alignment.value());
6245ffd83dbSDimitry Andric   } else if (Kind.isMergeableConst()) {
6255ffd83dbSDimitry Andric     Name = ".rodata.cst";
6265ffd83dbSDimitry Andric     Name += utostr(EntrySize);
6275ffd83dbSDimitry Andric   } else {
6285ffd83dbSDimitry Andric     Name = getSectionPrefixForGlobal(Kind);
6295ffd83dbSDimitry Andric   }
6305ffd83dbSDimitry Andric 
6315ffd83dbSDimitry Andric   bool HasPrefix = false;
6325ffd83dbSDimitry Andric   if (const auto *F = dyn_cast<Function>(GO)) {
6335ffd83dbSDimitry Andric     if (Optional<StringRef> Prefix = F->getSectionPrefix()) {
634e8d8bef9SDimitry Andric       raw_svector_ostream(Name) << '.' << *Prefix;
6355ffd83dbSDimitry Andric       HasPrefix = true;
6365ffd83dbSDimitry Andric     }
6375ffd83dbSDimitry Andric   }
6385ffd83dbSDimitry Andric 
6395ffd83dbSDimitry Andric   if (UniqueSectionName) {
6405ffd83dbSDimitry Andric     Name.push_back('.');
6415ffd83dbSDimitry Andric     TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
6425ffd83dbSDimitry Andric   } else if (HasPrefix)
643fe6060f1SDimitry Andric     // For distinguishing between .text.${text-section-prefix}. (with trailing
644fe6060f1SDimitry Andric     // dot) and .text.${function-name}
6455ffd83dbSDimitry Andric     Name.push_back('.');
6465ffd83dbSDimitry Andric   return Name;
6475ffd83dbSDimitry Andric }
6485ffd83dbSDimitry Andric 
6495ffd83dbSDimitry Andric namespace {
6505ffd83dbSDimitry Andric class LoweringDiagnosticInfo : public DiagnosticInfo {
6515ffd83dbSDimitry Andric   const Twine &Msg;
6525ffd83dbSDimitry Andric 
6535ffd83dbSDimitry Andric public:
6545ffd83dbSDimitry Andric   LoweringDiagnosticInfo(const Twine &DiagMsg,
6555ffd83dbSDimitry Andric                          DiagnosticSeverity Severity = DS_Error)
6565ffd83dbSDimitry Andric       : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
6575ffd83dbSDimitry Andric   void print(DiagnosticPrinter &DP) const override { DP << Msg; }
6585ffd83dbSDimitry Andric };
6595ffd83dbSDimitry Andric }
6605ffd83dbSDimitry Andric 
661fe6060f1SDimitry Andric /// Calculate an appropriate unique ID for a section, and update Flags,
662fe6060f1SDimitry Andric /// EntrySize and NextUniqueID where appropriate.
663fe6060f1SDimitry Andric static unsigned
664fe6060f1SDimitry Andric calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName,
665fe6060f1SDimitry Andric                                SectionKind Kind, const TargetMachine &TM,
666fe6060f1SDimitry Andric                                MCContext &Ctx, Mangler &Mang, unsigned &Flags,
667fe6060f1SDimitry Andric                                unsigned &EntrySize, unsigned &NextUniqueID,
668fe6060f1SDimitry Andric                                const bool Retain, const bool ForceUnique) {
669fe6060f1SDimitry Andric   // Increment uniqueID if we are forced to emit a unique section.
670fe6060f1SDimitry Andric   // This works perfectly fine with section attribute or pragma section as the
671fe6060f1SDimitry Andric   // sections with the same name are grouped together by the assembler.
672fe6060f1SDimitry Andric   if (ForceUnique)
673fe6060f1SDimitry Andric     return NextUniqueID++;
674fe6060f1SDimitry Andric 
675fe6060f1SDimitry Andric   // A section can have at most one associated section. Put each global with
676fe6060f1SDimitry Andric   // MD_associated in a unique section.
677fe6060f1SDimitry Andric   const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
678fe6060f1SDimitry Andric   if (Associated) {
679fe6060f1SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
680fe6060f1SDimitry Andric     return NextUniqueID++;
681fe6060f1SDimitry Andric   }
682fe6060f1SDimitry Andric 
683fe6060f1SDimitry Andric   if (Retain) {
6846e75b2fbSDimitry Andric     if ((Ctx.getAsmInfo()->useIntegratedAssembler() ||
6856e75b2fbSDimitry Andric          Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) &&
6866e75b2fbSDimitry Andric         !TM.getTargetTriple().isOSSolaris())
687fe6060f1SDimitry Andric       Flags |= ELF::SHF_GNU_RETAIN;
688fe6060f1SDimitry Andric     return NextUniqueID++;
689fe6060f1SDimitry Andric   }
690fe6060f1SDimitry Andric 
691fe6060f1SDimitry Andric   // If two symbols with differing sizes end up in the same mergeable section
692fe6060f1SDimitry Andric   // that section can be assigned an incorrect entry size. To avoid this we
693fe6060f1SDimitry Andric   // usually put symbols of the same size into distinct mergeable sections with
694fe6060f1SDimitry Andric   // the same name. Doing so relies on the ",unique ," assembly feature. This
695fe6060f1SDimitry Andric   // feature is not avalible until bintuils version 2.35
696fe6060f1SDimitry Andric   // (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
697fe6060f1SDimitry Andric   const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
698fe6060f1SDimitry Andric                               Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
699fe6060f1SDimitry Andric   if (!SupportsUnique) {
700fe6060f1SDimitry Andric     Flags &= ~ELF::SHF_MERGE;
701fe6060f1SDimitry Andric     EntrySize = 0;
702fe6060f1SDimitry Andric     return MCContext::GenericSectionID;
703fe6060f1SDimitry Andric   }
704fe6060f1SDimitry Andric 
705fe6060f1SDimitry Andric   const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
706fe6060f1SDimitry Andric   const bool SeenSectionNameBefore =
707fe6060f1SDimitry Andric       Ctx.isELFGenericMergeableSection(SectionName);
708fe6060f1SDimitry Andric   // If this is the first ocurrence of this section name, treat it as the
709fe6060f1SDimitry Andric   // generic section
710fe6060f1SDimitry Andric   if (!SymbolMergeable && !SeenSectionNameBefore)
711fe6060f1SDimitry Andric     return MCContext::GenericSectionID;
712fe6060f1SDimitry Andric 
713fe6060f1SDimitry Andric   // Symbols must be placed into sections with compatible entry sizes. Generate
714fe6060f1SDimitry Andric   // unique sections for symbols that have not been assigned to compatible
715fe6060f1SDimitry Andric   // sections.
716fe6060f1SDimitry Andric   const auto PreviousID =
717fe6060f1SDimitry Andric       Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
718fe6060f1SDimitry Andric   if (PreviousID)
719fe6060f1SDimitry Andric     return *PreviousID;
720fe6060f1SDimitry Andric 
721fe6060f1SDimitry Andric   // If the user has specified the same section name as would be created
722fe6060f1SDimitry Andric   // implicitly for this symbol e.g. .rodata.str1.1, then we don't need
723fe6060f1SDimitry Andric   // to unique the section as the entry size for this symbol will be
724fe6060f1SDimitry Andric   // compatible with implicitly created sections.
725fe6060f1SDimitry Andric   SmallString<128> ImplicitSectionNameStem =
726fe6060f1SDimitry Andric       getELFSectionNameForGlobal(GO, Kind, Mang, TM, EntrySize, false);
727fe6060f1SDimitry Andric   if (SymbolMergeable &&
728fe6060f1SDimitry Andric       Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) &&
729fe6060f1SDimitry Andric       SectionName.startswith(ImplicitSectionNameStem))
730fe6060f1SDimitry Andric     return MCContext::GenericSectionID;
731fe6060f1SDimitry Andric 
732fe6060f1SDimitry Andric   // We have seen this section name before, but with different flags or entity
733fe6060f1SDimitry Andric   // size. Create a new unique ID.
734fe6060f1SDimitry Andric   return NextUniqueID++;
735fe6060f1SDimitry Andric }
736fe6060f1SDimitry Andric 
737fe6060f1SDimitry Andric static MCSection *selectExplicitSectionGlobal(
738fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM,
739fe6060f1SDimitry Andric     MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID,
740fe6060f1SDimitry Andric     bool Retain, bool ForceUnique) {
741*0b57cec5SDimitry Andric   StringRef SectionName = GO->getSection();
742*0b57cec5SDimitry Andric 
743*0b57cec5SDimitry Andric   // Check if '#pragma clang section' name is applicable.
744*0b57cec5SDimitry Andric   // Note that pragma directive overrides -ffunction-section, -fdata-section
745*0b57cec5SDimitry Andric   // and so section name is exactly as user specified and not uniqued.
746*0b57cec5SDimitry Andric   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
747*0b57cec5SDimitry Andric   if (GV && GV->hasImplicitSection()) {
748*0b57cec5SDimitry Andric     auto Attrs = GV->getAttributes();
749*0b57cec5SDimitry Andric     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
750*0b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
751*0b57cec5SDimitry Andric     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
752*0b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
7538bcb0991SDimitry Andric     } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
7548bcb0991SDimitry Andric       SectionName = Attrs.getAttribute("relro-section").getValueAsString();
755*0b57cec5SDimitry Andric     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
756*0b57cec5SDimitry Andric       SectionName = Attrs.getAttribute("data-section").getValueAsString();
757*0b57cec5SDimitry Andric     }
758*0b57cec5SDimitry Andric   }
759*0b57cec5SDimitry Andric   const Function *F = dyn_cast<Function>(GO);
760*0b57cec5SDimitry Andric   if (F && F->hasFnAttribute("implicit-section-name")) {
761*0b57cec5SDimitry Andric     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
762*0b57cec5SDimitry Andric   }
763*0b57cec5SDimitry Andric 
764*0b57cec5SDimitry Andric   // Infer section flags from the section name if we can.
765*0b57cec5SDimitry Andric   Kind = getELFKindForNamedSection(SectionName, Kind);
766*0b57cec5SDimitry Andric 
767*0b57cec5SDimitry Andric   StringRef Group = "";
768fe6060f1SDimitry Andric   bool IsComdat = false;
769*0b57cec5SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
770*0b57cec5SDimitry Andric   if (const Comdat *C = getELFComdat(GO)) {
771*0b57cec5SDimitry Andric     Group = C->getName();
772fe6060f1SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
773*0b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
774*0b57cec5SDimitry Andric   }
775*0b57cec5SDimitry Andric 
7765ffd83dbSDimitry Andric   unsigned EntrySize = getEntrySizeForKind(Kind);
777fe6060f1SDimitry Andric   const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
778fe6060f1SDimitry Andric       GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
779fe6060f1SDimitry Andric       Retain, ForceUnique);
7805ffd83dbSDimitry Andric 
7815ffd83dbSDimitry Andric   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
782fe6060f1SDimitry Andric   MCSectionELF *Section = Ctx.getELFSection(
783fe6060f1SDimitry Andric       SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
784fe6060f1SDimitry Andric       Group, IsComdat, UniqueID, LinkedToSym);
785*0b57cec5SDimitry Andric   // Make sure that we did not get some other section with incompatible sh_link.
786*0b57cec5SDimitry Andric   // This should not be possible due to UniqueID code above.
7875ffd83dbSDimitry Andric   assert(Section->getLinkedToSymbol() == LinkedToSym &&
788*0b57cec5SDimitry Andric          "Associated symbol mismatch between sections");
7895ffd83dbSDimitry Andric 
790fe6060f1SDimitry Andric   if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
791fe6060f1SDimitry Andric         Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
792e8d8bef9SDimitry Andric     // If we are using GNU as before 2.35, then this symbol might have
7935ffd83dbSDimitry Andric     // been placed in an incompatible mergeable section. Emit an error if this
7945ffd83dbSDimitry Andric     // is the case to avoid creating broken output.
7955ffd83dbSDimitry Andric     if ((Section->getFlags() & ELF::SHF_MERGE) &&
7965ffd83dbSDimitry Andric         (Section->getEntrySize() != getEntrySizeForKind(Kind)))
7975ffd83dbSDimitry Andric       GO->getContext().diagnose(LoweringDiagnosticInfo(
7985ffd83dbSDimitry Andric           "Symbol '" + GO->getName() + "' from module '" +
7995ffd83dbSDimitry Andric           (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
8005ffd83dbSDimitry Andric           "' required a section with entry-size=" +
8015ffd83dbSDimitry Andric           Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
8025ffd83dbSDimitry Andric           SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
8035ffd83dbSDimitry Andric           ": Explicit assignment by pragma or attribute of an incompatible "
8045ffd83dbSDimitry Andric           "symbol to this section?"));
805*0b57cec5SDimitry Andric   }
806*0b57cec5SDimitry Andric 
8075ffd83dbSDimitry Andric   return Section;
808*0b57cec5SDimitry Andric }
809*0b57cec5SDimitry Andric 
810fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
811fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
812fe6060f1SDimitry Andric   return selectExplicitSectionGlobal(GO, Kind, TM, getContext(), getMangler(),
813fe6060f1SDimitry Andric                                      NextUniqueID, Used.count(GO),
814fe6060f1SDimitry Andric                                      /* ForceUnique = */false);
815fe6060f1SDimitry Andric }
816fe6060f1SDimitry Andric 
817*0b57cec5SDimitry Andric static MCSectionELF *selectELFSectionForGlobal(
818*0b57cec5SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
819*0b57cec5SDimitry Andric     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
820*0b57cec5SDimitry Andric     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
821*0b57cec5SDimitry Andric 
822*0b57cec5SDimitry Andric   StringRef Group = "";
823fe6060f1SDimitry Andric   bool IsComdat = false;
824*0b57cec5SDimitry Andric   if (const Comdat *C = getELFComdat(GO)) {
825*0b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
826*0b57cec5SDimitry Andric     Group = C->getName();
827fe6060f1SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
828*0b57cec5SDimitry Andric   }
829*0b57cec5SDimitry Andric 
830*0b57cec5SDimitry Andric   // Get the section entry size based on the kind.
831*0b57cec5SDimitry Andric   unsigned EntrySize = getEntrySizeForKind(Kind);
832*0b57cec5SDimitry Andric 
8335ffd83dbSDimitry Andric   bool UniqueSectionName = false;
834*0b57cec5SDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
835*0b57cec5SDimitry Andric   if (EmitUniqueSection) {
836*0b57cec5SDimitry Andric     if (TM.getUniqueSectionNames()) {
8375ffd83dbSDimitry Andric       UniqueSectionName = true;
838*0b57cec5SDimitry Andric     } else {
839*0b57cec5SDimitry Andric       UniqueID = *NextUniqueID;
840*0b57cec5SDimitry Andric       (*NextUniqueID)++;
841*0b57cec5SDimitry Andric     }
842*0b57cec5SDimitry Andric   }
8435ffd83dbSDimitry Andric   SmallString<128> Name = getELFSectionNameForGlobal(
8445ffd83dbSDimitry Andric       GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
8455ffd83dbSDimitry Andric 
846*0b57cec5SDimitry Andric   // Use 0 as the unique ID for execute-only text.
847*0b57cec5SDimitry Andric   if (Kind.isExecuteOnly())
848*0b57cec5SDimitry Andric     UniqueID = 0;
849*0b57cec5SDimitry Andric   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
850fe6060f1SDimitry Andric                            EntrySize, Group, IsComdat, UniqueID,
851fe6060f1SDimitry Andric                            AssociatedSymbol);
852fe6060f1SDimitry Andric }
853fe6060f1SDimitry Andric 
854fe6060f1SDimitry Andric static MCSection *selectELFSectionForGlobal(
855fe6060f1SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
856fe6060f1SDimitry Andric     const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
857fe6060f1SDimitry Andric     unsigned Flags, unsigned *NextUniqueID) {
858fe6060f1SDimitry Andric   const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
859fe6060f1SDimitry Andric   if (LinkedToSym) {
860fe6060f1SDimitry Andric     EmitUniqueSection = true;
861fe6060f1SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
862fe6060f1SDimitry Andric   }
8636e75b2fbSDimitry Andric   if (Retain &&
8646e75b2fbSDimitry Andric       (Ctx.getAsmInfo()->useIntegratedAssembler() ||
8656e75b2fbSDimitry Andric        Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) &&
8666e75b2fbSDimitry Andric       !TM.getTargetTriple().isOSSolaris()) {
867fe6060f1SDimitry Andric     EmitUniqueSection = true;
868fe6060f1SDimitry Andric     Flags |= ELF::SHF_GNU_RETAIN;
869fe6060f1SDimitry Andric   }
870fe6060f1SDimitry Andric 
871fe6060f1SDimitry Andric   MCSectionELF *Section = selectELFSectionForGlobal(
872fe6060f1SDimitry Andric       Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
873fe6060f1SDimitry Andric       NextUniqueID, LinkedToSym);
874fe6060f1SDimitry Andric   assert(Section->getLinkedToSymbol() == LinkedToSym);
875fe6060f1SDimitry Andric   return Section;
876*0b57cec5SDimitry Andric }
877*0b57cec5SDimitry Andric 
878*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
879*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
880*0b57cec5SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
881*0b57cec5SDimitry Andric 
882*0b57cec5SDimitry Andric   // If we have -ffunction-section or -fdata-section then we should emit the
883*0b57cec5SDimitry Andric   // global value to a uniqued section specifically for it.
884*0b57cec5SDimitry Andric   bool EmitUniqueSection = false;
885*0b57cec5SDimitry Andric   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
886*0b57cec5SDimitry Andric     if (Kind.isText())
887*0b57cec5SDimitry Andric       EmitUniqueSection = TM.getFunctionSections();
888*0b57cec5SDimitry Andric     else
889*0b57cec5SDimitry Andric       EmitUniqueSection = TM.getDataSections();
890*0b57cec5SDimitry Andric   }
891*0b57cec5SDimitry Andric   EmitUniqueSection |= GO->hasComdat();
892fe6060f1SDimitry Andric   return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
893fe6060f1SDimitry Andric                                    Used.count(GO), EmitUniqueSection, Flags,
894fe6060f1SDimitry Andric                                    &NextUniqueID);
895*0b57cec5SDimitry Andric }
896*0b57cec5SDimitry Andric 
897fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileELF::getUniqueSectionForFunction(
898fe6060f1SDimitry Andric     const Function &F, const TargetMachine &TM) const {
899fe6060f1SDimitry Andric   SectionKind Kind = SectionKind::getText();
900fe6060f1SDimitry Andric   unsigned Flags = getELFSectionFlags(Kind);
901fe6060f1SDimitry Andric   // If the function's section names is pre-determined via pragma or a
902fe6060f1SDimitry Andric   // section attribute, call selectExplicitSectionGlobal.
903fe6060f1SDimitry Andric   if (F.hasSection() || F.hasFnAttribute("implicit-section-name"))
904fe6060f1SDimitry Andric     return selectExplicitSectionGlobal(
905fe6060f1SDimitry Andric         &F, Kind, TM, getContext(), getMangler(), NextUniqueID,
906fe6060f1SDimitry Andric         Used.count(&F), /* ForceUnique = */true);
907fe6060f1SDimitry Andric   else
908fe6060f1SDimitry Andric     return selectELFSectionForGlobal(
909fe6060f1SDimitry Andric         getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
910fe6060f1SDimitry Andric         /*EmitUniqueSection=*/true, Flags, &NextUniqueID);
911*0b57cec5SDimitry Andric }
912*0b57cec5SDimitry Andric 
913*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
914*0b57cec5SDimitry Andric     const Function &F, const TargetMachine &TM) const {
915*0b57cec5SDimitry Andric   // If the function can be removed, produce a unique section so that
916*0b57cec5SDimitry Andric   // the table doesn't prevent the removal.
917*0b57cec5SDimitry Andric   const Comdat *C = F.getComdat();
918*0b57cec5SDimitry Andric   bool EmitUniqueSection = TM.getFunctionSections() || C;
919*0b57cec5SDimitry Andric   if (!EmitUniqueSection)
920*0b57cec5SDimitry Andric     return ReadOnlySection;
921*0b57cec5SDimitry Andric 
922*0b57cec5SDimitry Andric   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
923*0b57cec5SDimitry Andric                                    getMangler(), TM, EmitUniqueSection,
924*0b57cec5SDimitry Andric                                    ELF::SHF_ALLOC, &NextUniqueID,
925*0b57cec5SDimitry Andric                                    /* AssociatedSymbol */ nullptr);
926*0b57cec5SDimitry Andric }
927*0b57cec5SDimitry Andric 
928fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForLSDA(
929fe6060f1SDimitry Andric     const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
930e8d8bef9SDimitry Andric   // If neither COMDAT nor function sections, use the monolithic LSDA section.
931e8d8bef9SDimitry Andric   // Re-use this path if LSDASection is null as in the Arm EHABI.
932e8d8bef9SDimitry Andric   if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
933e8d8bef9SDimitry Andric     return LSDASection;
934e8d8bef9SDimitry Andric 
935e8d8bef9SDimitry Andric   const auto *LSDA = cast<MCSectionELF>(LSDASection);
936e8d8bef9SDimitry Andric   unsigned Flags = LSDA->getFlags();
937fe6060f1SDimitry Andric   const MCSymbolELF *LinkedToSym = nullptr;
938e8d8bef9SDimitry Andric   StringRef Group;
939fe6060f1SDimitry Andric   bool IsComdat = false;
940fe6060f1SDimitry Andric   if (const Comdat *C = getELFComdat(&F)) {
941e8d8bef9SDimitry Andric     Flags |= ELF::SHF_GROUP;
942fe6060f1SDimitry Andric     Group = C->getName();
943fe6060f1SDimitry Andric     IsComdat = C->getSelectionKind() == Comdat::Any;
944fe6060f1SDimitry Andric   }
945fe6060f1SDimitry Andric   // Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
946fe6060f1SDimitry Andric   // or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
947fe6060f1SDimitry Andric   if (TM.getFunctionSections() &&
948fe6060f1SDimitry Andric       (getContext().getAsmInfo()->useIntegratedAssembler() &&
949fe6060f1SDimitry Andric        getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
950fe6060f1SDimitry Andric     Flags |= ELF::SHF_LINK_ORDER;
951fe6060f1SDimitry Andric     LinkedToSym = cast<MCSymbolELF>(&FnSym);
952e8d8bef9SDimitry Andric   }
953e8d8bef9SDimitry Andric 
954e8d8bef9SDimitry Andric   // Append the function name as the suffix like GCC, assuming
955e8d8bef9SDimitry Andric   // -funique-section-names applies to .gcc_except_table sections.
956fe6060f1SDimitry Andric   return getContext().getELFSection(
957fe6060f1SDimitry Andric       (TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
958fe6060f1SDimitry Andric                                   : LSDA->getName()),
959fe6060f1SDimitry Andric       LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
960fe6060f1SDimitry Andric       LinkedToSym);
961e8d8bef9SDimitry Andric }
962e8d8bef9SDimitry Andric 
963*0b57cec5SDimitry Andric bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
964*0b57cec5SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
965*0b57cec5SDimitry Andric   // We can always create relative relocations, so use another section
966*0b57cec5SDimitry Andric   // that can be marked non-executable.
967*0b57cec5SDimitry Andric   return false;
968*0b57cec5SDimitry Andric }
969*0b57cec5SDimitry Andric 
970*0b57cec5SDimitry Andric /// Given a mergeable constant with the specified size and relocation
971*0b57cec5SDimitry Andric /// information, return a section that it should be placed in.
972*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
973*0b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
9745ffd83dbSDimitry Andric     Align &Alignment) const {
975*0b57cec5SDimitry Andric   if (Kind.isMergeableConst4() && MergeableConst4Section)
976*0b57cec5SDimitry Andric     return MergeableConst4Section;
977*0b57cec5SDimitry Andric   if (Kind.isMergeableConst8() && MergeableConst8Section)
978*0b57cec5SDimitry Andric     return MergeableConst8Section;
979*0b57cec5SDimitry Andric   if (Kind.isMergeableConst16() && MergeableConst16Section)
980*0b57cec5SDimitry Andric     return MergeableConst16Section;
981*0b57cec5SDimitry Andric   if (Kind.isMergeableConst32() && MergeableConst32Section)
982*0b57cec5SDimitry Andric     return MergeableConst32Section;
983*0b57cec5SDimitry Andric   if (Kind.isReadOnly())
984*0b57cec5SDimitry Andric     return ReadOnlySection;
985*0b57cec5SDimitry Andric 
986*0b57cec5SDimitry Andric   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
987*0b57cec5SDimitry Andric   return DataRelROSection;
988*0b57cec5SDimitry Andric }
989*0b57cec5SDimitry Andric 
9905ffd83dbSDimitry Andric /// Returns a unique section for the given machine basic block.
9915ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock(
9925ffd83dbSDimitry Andric     const Function &F, const MachineBasicBlock &MBB,
9935ffd83dbSDimitry Andric     const TargetMachine &TM) const {
9945ffd83dbSDimitry Andric   assert(MBB.isBeginSection() && "Basic block does not start a section!");
9955ffd83dbSDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
9965ffd83dbSDimitry Andric 
997e8d8bef9SDimitry Andric   // For cold sections use the .text.split. prefix along with the parent
9985ffd83dbSDimitry Andric   // function name. All cold blocks for the same function go to the same
9995ffd83dbSDimitry Andric   // section. Similarly all exception blocks are grouped by symbol name
10005ffd83dbSDimitry Andric   // under the .text.eh prefix. For regular sections, we either use a unique
10015ffd83dbSDimitry Andric   // name, or a unique ID for the section.
10025ffd83dbSDimitry Andric   SmallString<128> Name;
10035ffd83dbSDimitry Andric   if (MBB.getSectionID() == MBBSectionID::ColdSectionID) {
1004e8d8bef9SDimitry Andric     Name += BBSectionsColdTextPrefix;
10055ffd83dbSDimitry Andric     Name += MBB.getParent()->getName();
10065ffd83dbSDimitry Andric   } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) {
10075ffd83dbSDimitry Andric     Name += ".text.eh.";
10085ffd83dbSDimitry Andric     Name += MBB.getParent()->getName();
10095ffd83dbSDimitry Andric   } else {
10105ffd83dbSDimitry Andric     Name += MBB.getParent()->getSection()->getName();
10115ffd83dbSDimitry Andric     if (TM.getUniqueBasicBlockSectionNames()) {
1012fe6060f1SDimitry Andric       if (!Name.endswith("."))
10135ffd83dbSDimitry Andric         Name += ".";
10145ffd83dbSDimitry Andric       Name += MBB.getSymbol()->getName();
10155ffd83dbSDimitry Andric     } else {
10165ffd83dbSDimitry Andric       UniqueID = NextUniqueID++;
10175ffd83dbSDimitry Andric     }
10185ffd83dbSDimitry Andric   }
10195ffd83dbSDimitry Andric 
10205ffd83dbSDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR;
1021e8d8bef9SDimitry Andric   std::string GroupName;
10225ffd83dbSDimitry Andric   if (F.hasComdat()) {
10235ffd83dbSDimitry Andric     Flags |= ELF::SHF_GROUP;
10245ffd83dbSDimitry Andric     GroupName = F.getComdat()->getName().str();
10255ffd83dbSDimitry Andric   }
10265ffd83dbSDimitry Andric   return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags,
1027fe6060f1SDimitry Andric                                     0 /* Entry Size */, GroupName,
1028fe6060f1SDimitry Andric                                     F.hasComdat(), UniqueID, nullptr);
10295ffd83dbSDimitry Andric }
10305ffd83dbSDimitry Andric 
1031*0b57cec5SDimitry Andric static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
1032*0b57cec5SDimitry Andric                                               bool IsCtor, unsigned Priority,
1033*0b57cec5SDimitry Andric                                               const MCSymbol *KeySym) {
1034*0b57cec5SDimitry Andric   std::string Name;
1035*0b57cec5SDimitry Andric   unsigned Type;
1036*0b57cec5SDimitry Andric   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
1037fe6060f1SDimitry Andric   StringRef Comdat = KeySym ? KeySym->getName() : "";
1038*0b57cec5SDimitry Andric 
1039*0b57cec5SDimitry Andric   if (KeySym)
1040*0b57cec5SDimitry Andric     Flags |= ELF::SHF_GROUP;
1041*0b57cec5SDimitry Andric 
1042*0b57cec5SDimitry Andric   if (UseInitArray) {
1043*0b57cec5SDimitry Andric     if (IsCtor) {
1044*0b57cec5SDimitry Andric       Type = ELF::SHT_INIT_ARRAY;
1045*0b57cec5SDimitry Andric       Name = ".init_array";
1046*0b57cec5SDimitry Andric     } else {
1047*0b57cec5SDimitry Andric       Type = ELF::SHT_FINI_ARRAY;
1048*0b57cec5SDimitry Andric       Name = ".fini_array";
1049*0b57cec5SDimitry Andric     }
1050*0b57cec5SDimitry Andric     if (Priority != 65535) {
1051*0b57cec5SDimitry Andric       Name += '.';
1052*0b57cec5SDimitry Andric       Name += utostr(Priority);
1053*0b57cec5SDimitry Andric     }
1054*0b57cec5SDimitry Andric   } else {
1055*0b57cec5SDimitry Andric     // The default scheme is .ctor / .dtor, so we have to invert the priority
1056*0b57cec5SDimitry Andric     // numbering.
1057*0b57cec5SDimitry Andric     if (IsCtor)
1058*0b57cec5SDimitry Andric       Name = ".ctors";
1059*0b57cec5SDimitry Andric     else
1060*0b57cec5SDimitry Andric       Name = ".dtors";
1061*0b57cec5SDimitry Andric     if (Priority != 65535)
1062*0b57cec5SDimitry Andric       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1063*0b57cec5SDimitry Andric     Type = ELF::SHT_PROGBITS;
1064*0b57cec5SDimitry Andric   }
1065*0b57cec5SDimitry Andric 
1066fe6060f1SDimitry Andric   return Ctx.getELFSection(Name, Type, Flags, 0, Comdat, /*IsComdat=*/true);
1067*0b57cec5SDimitry Andric }
1068*0b57cec5SDimitry Andric 
1069*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
1070*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1071*0b57cec5SDimitry Andric   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
1072*0b57cec5SDimitry Andric                                   KeySym);
1073*0b57cec5SDimitry Andric }
1074*0b57cec5SDimitry Andric 
1075*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
1076*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1077*0b57cec5SDimitry Andric   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
1078*0b57cec5SDimitry Andric                                   KeySym);
1079*0b57cec5SDimitry Andric }
1080*0b57cec5SDimitry Andric 
1081*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
1082*0b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
1083*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1084*0b57cec5SDimitry Andric   // We may only use a PLT-relative relocation to refer to unnamed_addr
1085*0b57cec5SDimitry Andric   // functions.
1086*0b57cec5SDimitry Andric   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1087*0b57cec5SDimitry Andric     return nullptr;
1088*0b57cec5SDimitry Andric 
10894824e7fdSDimitry Andric   // Basic correctness checks.
1090*0b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1091*0b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1092*0b57cec5SDimitry Andric       RHS->isThreadLocal())
1093*0b57cec5SDimitry Andric     return nullptr;
1094*0b57cec5SDimitry Andric 
1095*0b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
1096*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
1097*0b57cec5SDimitry Andric                               getContext()),
1098*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1099*0b57cec5SDimitry Andric }
1100*0b57cec5SDimitry Andric 
1101e8d8bef9SDimitry Andric const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent(
1102e8d8bef9SDimitry Andric     const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const {
1103e8d8bef9SDimitry Andric   assert(supportDSOLocalEquivalentLowering());
1104e8d8bef9SDimitry Andric 
1105e8d8bef9SDimitry Andric   const auto *GV = Equiv->getGlobalValue();
1106e8d8bef9SDimitry Andric 
1107e8d8bef9SDimitry Andric   // A PLT entry is not needed for dso_local globals.
1108e8d8bef9SDimitry Andric   if (GV->isDSOLocal() || GV->isImplicitDSOLocal())
1109e8d8bef9SDimitry Andric     return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext());
1110e8d8bef9SDimitry Andric 
1111e8d8bef9SDimitry Andric   return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind,
1112e8d8bef9SDimitry Andric                                  getContext());
1113e8d8bef9SDimitry Andric }
1114e8d8bef9SDimitry Andric 
1115*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const {
1116*0b57cec5SDimitry Andric   // Use ".GCC.command.line" since this feature is to support clang's
1117*0b57cec5SDimitry Andric   // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
1118*0b57cec5SDimitry Andric   // same name.
1119*0b57cec5SDimitry Andric   return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS,
1120fe6060f1SDimitry Andric                                     ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
1121*0b57cec5SDimitry Andric }
1122*0b57cec5SDimitry Andric 
1123*0b57cec5SDimitry Andric void
1124*0b57cec5SDimitry Andric TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
1125*0b57cec5SDimitry Andric   UseInitArray = UseInitArray_;
1126*0b57cec5SDimitry Andric   MCContext &Ctx = getContext();
1127*0b57cec5SDimitry Andric   if (!UseInitArray) {
1128*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
1129*0b57cec5SDimitry Andric                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1130*0b57cec5SDimitry Andric 
1131*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
1132*0b57cec5SDimitry Andric                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
1133*0b57cec5SDimitry Andric     return;
1134*0b57cec5SDimitry Andric   }
1135*0b57cec5SDimitry Andric 
1136*0b57cec5SDimitry Andric   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
1137*0b57cec5SDimitry Andric                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1138*0b57cec5SDimitry Andric   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
1139*0b57cec5SDimitry Andric                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
1140*0b57cec5SDimitry Andric }
1141*0b57cec5SDimitry Andric 
1142*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1143*0b57cec5SDimitry Andric //                                 MachO
1144*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1145*0b57cec5SDimitry Andric 
114604eeddc0SDimitry Andric TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() {
1147*0b57cec5SDimitry Andric   SupportIndirectSymViaGOTPCRel = true;
1148*0b57cec5SDimitry Andric }
1149*0b57cec5SDimitry Andric 
1150*0b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
1151*0b57cec5SDimitry Andric                                                const TargetMachine &TM) {
1152*0b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TM);
1153*0b57cec5SDimitry Andric   if (TM.getRelocationModel() == Reloc::Static) {
1154*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
1155*0b57cec5SDimitry Andric                                             SectionKind::getData());
1156*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
1157*0b57cec5SDimitry Andric                                             SectionKind::getData());
1158*0b57cec5SDimitry Andric   } else {
1159*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
1160*0b57cec5SDimitry Andric                                             MachO::S_MOD_INIT_FUNC_POINTERS,
1161*0b57cec5SDimitry Andric                                             SectionKind::getData());
1162*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
1163*0b57cec5SDimitry Andric                                             MachO::S_MOD_TERM_FUNC_POINTERS,
1164*0b57cec5SDimitry Andric                                             SectionKind::getData());
1165*0b57cec5SDimitry Andric   }
1166*0b57cec5SDimitry Andric 
1167*0b57cec5SDimitry Andric   PersonalityEncoding =
1168*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1169*0b57cec5SDimitry Andric   LSDAEncoding = dwarf::DW_EH_PE_pcrel;
1170*0b57cec5SDimitry Andric   TTypeEncoding =
1171*0b57cec5SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
1172*0b57cec5SDimitry Andric }
1173*0b57cec5SDimitry Andric 
1174*0b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
1175*0b57cec5SDimitry Andric                                                        Module &M) const {
1176*0b57cec5SDimitry Andric   // Emit the linker options if present.
1177*0b57cec5SDimitry Andric   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1178480093f4SDimitry Andric     for (const auto *Option : LinkerOptions->operands()) {
1179*0b57cec5SDimitry Andric       SmallVector<std::string, 4> StrOptions;
1180*0b57cec5SDimitry Andric       for (const auto &Piece : cast<MDNode>(Option)->operands())
11815ffd83dbSDimitry Andric         StrOptions.push_back(std::string(cast<MDString>(Piece)->getString()));
11825ffd83dbSDimitry Andric       Streamer.emitLinkerOptions(StrOptions);
1183*0b57cec5SDimitry Andric     }
1184*0b57cec5SDimitry Andric   }
1185*0b57cec5SDimitry Andric 
1186*0b57cec5SDimitry Andric   unsigned VersionVal = 0;
1187*0b57cec5SDimitry Andric   unsigned ImageInfoFlags = 0;
1188*0b57cec5SDimitry Andric   StringRef SectionVal;
1189*0b57cec5SDimitry Andric 
1190*0b57cec5SDimitry Andric   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
119104eeddc0SDimitry Andric   emitCGProfileMetadata(Streamer, M);
1192*0b57cec5SDimitry Andric 
1193*0b57cec5SDimitry Andric   // The section is mandatory. If we don't have it, then we don't have GC info.
1194*0b57cec5SDimitry Andric   if (SectionVal.empty())
1195*0b57cec5SDimitry Andric     return;
1196*0b57cec5SDimitry Andric 
1197*0b57cec5SDimitry Andric   StringRef Segment, Section;
1198*0b57cec5SDimitry Andric   unsigned TAA = 0, StubSize = 0;
1199*0b57cec5SDimitry Andric   bool TAAParsed;
1200fe6060f1SDimitry Andric   if (Error E = MCSectionMachO::ParseSectionSpecifier(
1201fe6060f1SDimitry Andric           SectionVal, Segment, Section, TAA, TAAParsed, StubSize)) {
1202*0b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
1203fe6060f1SDimitry Andric     report_fatal_error("Invalid section specifier '" + Section +
1204fe6060f1SDimitry Andric                        "': " + toString(std::move(E)) + ".");
1205fe6060f1SDimitry Andric   }
1206*0b57cec5SDimitry Andric 
1207*0b57cec5SDimitry Andric   // Get the section.
1208*0b57cec5SDimitry Andric   MCSectionMachO *S = getContext().getMachOSection(
1209*0b57cec5SDimitry Andric       Segment, Section, TAA, StubSize, SectionKind::getData());
1210*0b57cec5SDimitry Andric   Streamer.SwitchSection(S);
12115ffd83dbSDimitry Andric   Streamer.emitLabel(getContext().
1212*0b57cec5SDimitry Andric                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
12135ffd83dbSDimitry Andric   Streamer.emitInt32(VersionVal);
12145ffd83dbSDimitry Andric   Streamer.emitInt32(ImageInfoFlags);
1215*0b57cec5SDimitry Andric   Streamer.AddBlankLine();
1216*0b57cec5SDimitry Andric }
1217*0b57cec5SDimitry Andric 
1218*0b57cec5SDimitry Andric static void checkMachOComdat(const GlobalValue *GV) {
1219*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
1220*0b57cec5SDimitry Andric   if (!C)
1221*0b57cec5SDimitry Andric     return;
1222*0b57cec5SDimitry Andric 
1223*0b57cec5SDimitry Andric   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
1224*0b57cec5SDimitry Andric                      "' cannot be lowered.");
1225*0b57cec5SDimitry Andric }
1226*0b57cec5SDimitry Andric 
1227*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
1228*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1229fe6060f1SDimitry Andric 
1230fe6060f1SDimitry Andric   StringRef SectionName = GO->getSection();
1231fe6060f1SDimitry Andric 
1232fe6060f1SDimitry Andric   const Function *F = dyn_cast<Function>(GO);
1233fe6060f1SDimitry Andric   if (F && F->hasFnAttribute("implicit-section-name")) {
1234fe6060f1SDimitry Andric     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
1235fe6060f1SDimitry Andric   }
1236fe6060f1SDimitry Andric 
1237*0b57cec5SDimitry Andric   // Parse the section specifier and create it if valid.
1238*0b57cec5SDimitry Andric   StringRef Segment, Section;
1239*0b57cec5SDimitry Andric   unsigned TAA = 0, StubSize = 0;
1240*0b57cec5SDimitry Andric   bool TAAParsed;
1241*0b57cec5SDimitry Andric 
1242*0b57cec5SDimitry Andric   checkMachOComdat(GO);
1243*0b57cec5SDimitry Andric 
1244fe6060f1SDimitry Andric   if (Error E = MCSectionMachO::ParseSectionSpecifier(
1245fe6060f1SDimitry Andric           SectionName, Segment, Section, TAA, TAAParsed, StubSize)) {
1246*0b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
1247*0b57cec5SDimitry Andric     report_fatal_error("Global variable '" + GO->getName() +
1248*0b57cec5SDimitry Andric                        "' has an invalid section specifier '" +
1249fe6060f1SDimitry Andric                        GO->getSection() + "': " + toString(std::move(E)) + ".");
1250*0b57cec5SDimitry Andric   }
1251*0b57cec5SDimitry Andric 
1252*0b57cec5SDimitry Andric   // Get the section.
1253*0b57cec5SDimitry Andric   MCSectionMachO *S =
1254*0b57cec5SDimitry Andric       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
1255*0b57cec5SDimitry Andric 
1256*0b57cec5SDimitry Andric   // If TAA wasn't set by ParseSectionSpecifier() above,
1257*0b57cec5SDimitry Andric   // use the value returned by getMachOSection() as a default.
1258*0b57cec5SDimitry Andric   if (!TAAParsed)
1259*0b57cec5SDimitry Andric     TAA = S->getTypeAndAttributes();
1260*0b57cec5SDimitry Andric 
1261*0b57cec5SDimitry Andric   // Okay, now that we got the section, verify that the TAA & StubSize agree.
1262*0b57cec5SDimitry Andric   // If the user declared multiple globals with different section flags, we need
1263*0b57cec5SDimitry Andric   // to reject it here.
1264*0b57cec5SDimitry Andric   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
1265*0b57cec5SDimitry Andric     // If invalid, report the error with report_fatal_error.
1266*0b57cec5SDimitry Andric     report_fatal_error("Global variable '" + GO->getName() +
1267*0b57cec5SDimitry Andric                        "' section type or attributes does not match previous"
1268*0b57cec5SDimitry Andric                        " section specifier");
1269*0b57cec5SDimitry Andric   }
1270*0b57cec5SDimitry Andric 
1271*0b57cec5SDimitry Andric   return S;
1272*0b57cec5SDimitry Andric }
1273*0b57cec5SDimitry Andric 
1274*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
1275*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1276*0b57cec5SDimitry Andric   checkMachOComdat(GO);
1277*0b57cec5SDimitry Andric 
1278*0b57cec5SDimitry Andric   // Handle thread local data.
1279*0b57cec5SDimitry Andric   if (Kind.isThreadBSS()) return TLSBSSSection;
1280*0b57cec5SDimitry Andric   if (Kind.isThreadData()) return TLSDataSection;
1281*0b57cec5SDimitry Andric 
1282*0b57cec5SDimitry Andric   if (Kind.isText())
1283*0b57cec5SDimitry Andric     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
1284*0b57cec5SDimitry Andric 
1285*0b57cec5SDimitry Andric   // If this is weak/linkonce, put this in a coalescable section, either in text
1286*0b57cec5SDimitry Andric   // or data depending on if it is writable.
1287*0b57cec5SDimitry Andric   if (GO->isWeakForLinker()) {
1288*0b57cec5SDimitry Andric     if (Kind.isReadOnly())
1289*0b57cec5SDimitry Andric       return ConstTextCoalSection;
1290*0b57cec5SDimitry Andric     if (Kind.isReadOnlyWithRel())
1291*0b57cec5SDimitry Andric       return ConstDataCoalSection;
1292*0b57cec5SDimitry Andric     return DataCoalSection;
1293*0b57cec5SDimitry Andric   }
1294*0b57cec5SDimitry Andric 
1295*0b57cec5SDimitry Andric   // FIXME: Alignment check should be handled by section classifier.
1296*0b57cec5SDimitry Andric   if (Kind.isMergeable1ByteCString() &&
12975ffd83dbSDimitry Andric       GO->getParent()->getDataLayout().getPreferredAlign(
12985ffd83dbSDimitry Andric           cast<GlobalVariable>(GO)) < Align(32))
1299*0b57cec5SDimitry Andric     return CStringSection;
1300*0b57cec5SDimitry Andric 
1301*0b57cec5SDimitry Andric   // Do not put 16-bit arrays in the UString section if they have an
1302*0b57cec5SDimitry Andric   // externally visible label, this runs into issues with certain linker
1303*0b57cec5SDimitry Andric   // versions.
1304*0b57cec5SDimitry Andric   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
13055ffd83dbSDimitry Andric       GO->getParent()->getDataLayout().getPreferredAlign(
13065ffd83dbSDimitry Andric           cast<GlobalVariable>(GO)) < Align(32))
1307*0b57cec5SDimitry Andric     return UStringSection;
1308*0b57cec5SDimitry Andric 
1309*0b57cec5SDimitry Andric   // With MachO only variables whose corresponding symbol starts with 'l' or
1310*0b57cec5SDimitry Andric   // 'L' can be merged, so we only try merging GVs with private linkage.
1311*0b57cec5SDimitry Andric   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
1312*0b57cec5SDimitry Andric     if (Kind.isMergeableConst4())
1313*0b57cec5SDimitry Andric       return FourByteConstantSection;
1314*0b57cec5SDimitry Andric     if (Kind.isMergeableConst8())
1315*0b57cec5SDimitry Andric       return EightByteConstantSection;
1316*0b57cec5SDimitry Andric     if (Kind.isMergeableConst16())
1317*0b57cec5SDimitry Andric       return SixteenByteConstantSection;
1318*0b57cec5SDimitry Andric   }
1319*0b57cec5SDimitry Andric 
1320*0b57cec5SDimitry Andric   // Otherwise, if it is readonly, but not something we can specially optimize,
1321*0b57cec5SDimitry Andric   // just drop it in .const.
1322*0b57cec5SDimitry Andric   if (Kind.isReadOnly())
1323*0b57cec5SDimitry Andric     return ReadOnlySection;
1324*0b57cec5SDimitry Andric 
1325*0b57cec5SDimitry Andric   // If this is marked const, put it into a const section.  But if the dynamic
1326*0b57cec5SDimitry Andric   // linker needs to write to it, put it in the data segment.
1327*0b57cec5SDimitry Andric   if (Kind.isReadOnlyWithRel())
1328*0b57cec5SDimitry Andric     return ConstDataSection;
1329*0b57cec5SDimitry Andric 
1330*0b57cec5SDimitry Andric   // Put zero initialized globals with strong external linkage in the
1331*0b57cec5SDimitry Andric   // DATA, __common section with the .zerofill directive.
1332*0b57cec5SDimitry Andric   if (Kind.isBSSExtern())
1333*0b57cec5SDimitry Andric     return DataCommonSection;
1334*0b57cec5SDimitry Andric 
1335*0b57cec5SDimitry Andric   // Put zero initialized globals with local linkage in __DATA,__bss directive
1336*0b57cec5SDimitry Andric   // with the .zerofill directive (aka .lcomm).
1337*0b57cec5SDimitry Andric   if (Kind.isBSSLocal())
1338*0b57cec5SDimitry Andric     return DataBSSSection;
1339*0b57cec5SDimitry Andric 
1340*0b57cec5SDimitry Andric   // Otherwise, just drop the variable in the normal data section.
1341*0b57cec5SDimitry Andric   return DataSection;
1342*0b57cec5SDimitry Andric }
1343*0b57cec5SDimitry Andric 
1344*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
1345*0b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
13465ffd83dbSDimitry Andric     Align &Alignment) const {
1347*0b57cec5SDimitry Andric   // If this constant requires a relocation, we have to put it in the data
1348*0b57cec5SDimitry Andric   // segment, not in the text segment.
1349*0b57cec5SDimitry Andric   if (Kind.isData() || Kind.isReadOnlyWithRel())
1350*0b57cec5SDimitry Andric     return ConstDataSection;
1351*0b57cec5SDimitry Andric 
1352*0b57cec5SDimitry Andric   if (Kind.isMergeableConst4())
1353*0b57cec5SDimitry Andric     return FourByteConstantSection;
1354*0b57cec5SDimitry Andric   if (Kind.isMergeableConst8())
1355*0b57cec5SDimitry Andric     return EightByteConstantSection;
1356*0b57cec5SDimitry Andric   if (Kind.isMergeableConst16())
1357*0b57cec5SDimitry Andric     return SixteenByteConstantSection;
1358*0b57cec5SDimitry Andric   return ReadOnlySection;  // .const
1359*0b57cec5SDimitry Andric }
1360*0b57cec5SDimitry Andric 
1361*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1362*0b57cec5SDimitry Andric     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
1363*0b57cec5SDimitry Andric     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1364*0b57cec5SDimitry Andric   // The mach-o version of this method defaults to returning a stub reference.
1365*0b57cec5SDimitry Andric 
1366*0b57cec5SDimitry Andric   if (Encoding & DW_EH_PE_indirect) {
1367*0b57cec5SDimitry Andric     MachineModuleInfoMachO &MachOMMI =
1368*0b57cec5SDimitry Andric       MMI->getObjFileInfo<MachineModuleInfoMachO>();
1369*0b57cec5SDimitry Andric 
1370*0b57cec5SDimitry Andric     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1371*0b57cec5SDimitry Andric 
1372*0b57cec5SDimitry Andric     // Add information about the stub reference to MachOMMI so that the stub
1373*0b57cec5SDimitry Andric     // gets emitted by the asmprinter.
1374*0b57cec5SDimitry Andric     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1375*0b57cec5SDimitry Andric     if (!StubSym.getPointer()) {
1376*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(GV);
1377*0b57cec5SDimitry Andric       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1378*0b57cec5SDimitry Andric     }
1379*0b57cec5SDimitry Andric 
1380*0b57cec5SDimitry Andric     return TargetLoweringObjectFile::
1381*0b57cec5SDimitry Andric       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
1382*0b57cec5SDimitry Andric                         Encoding & ~DW_EH_PE_indirect, Streamer);
1383*0b57cec5SDimitry Andric   }
1384*0b57cec5SDimitry Andric 
1385*0b57cec5SDimitry Andric   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
1386*0b57cec5SDimitry Andric                                                            MMI, Streamer);
1387*0b57cec5SDimitry Andric }
1388*0b57cec5SDimitry Andric 
1389*0b57cec5SDimitry Andric MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1390*0b57cec5SDimitry Andric     const GlobalValue *GV, const TargetMachine &TM,
1391*0b57cec5SDimitry Andric     MachineModuleInfo *MMI) const {
1392*0b57cec5SDimitry Andric   // The mach-o version of this method defaults to returning a stub reference.
1393*0b57cec5SDimitry Andric   MachineModuleInfoMachO &MachOMMI =
1394*0b57cec5SDimitry Andric     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1395*0b57cec5SDimitry Andric 
1396*0b57cec5SDimitry Andric   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
1397*0b57cec5SDimitry Andric 
1398*0b57cec5SDimitry Andric   // Add information about the stub reference to MachOMMI so that the stub
1399*0b57cec5SDimitry Andric   // gets emitted by the asmprinter.
1400*0b57cec5SDimitry Andric   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
1401*0b57cec5SDimitry Andric   if (!StubSym.getPointer()) {
1402*0b57cec5SDimitry Andric     MCSymbol *Sym = TM.getSymbol(GV);
1403*0b57cec5SDimitry Andric     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
1404*0b57cec5SDimitry Andric   }
1405*0b57cec5SDimitry Andric 
1406*0b57cec5SDimitry Andric   return SSym;
1407*0b57cec5SDimitry Andric }
1408*0b57cec5SDimitry Andric 
1409*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
14108bcb0991SDimitry Andric     const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV,
14118bcb0991SDimitry Andric     int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const {
1412*0b57cec5SDimitry Andric   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1413*0b57cec5SDimitry Andric   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1414*0b57cec5SDimitry Andric   // through a non_lazy_ptr stub instead. One advantage is that it allows the
1415*0b57cec5SDimitry Andric   // computation of deltas to final external symbols. Example:
1416*0b57cec5SDimitry Andric   //
1417*0b57cec5SDimitry Andric   //    _extgotequiv:
1418*0b57cec5SDimitry Andric   //       .long   _extfoo
1419*0b57cec5SDimitry Andric   //
1420*0b57cec5SDimitry Andric   //    _delta:
1421*0b57cec5SDimitry Andric   //       .long   _extgotequiv-_delta
1422*0b57cec5SDimitry Andric   //
1423*0b57cec5SDimitry Andric   // is transformed to:
1424*0b57cec5SDimitry Andric   //
1425*0b57cec5SDimitry Andric   //    _delta:
1426*0b57cec5SDimitry Andric   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
1427*0b57cec5SDimitry Andric   //
1428*0b57cec5SDimitry Andric   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
1429*0b57cec5SDimitry Andric   //    L_extfoo$non_lazy_ptr:
1430*0b57cec5SDimitry Andric   //       .indirect_symbol        _extfoo
1431*0b57cec5SDimitry Andric   //       .long   0
1432*0b57cec5SDimitry Andric   //
1433*0b57cec5SDimitry Andric   // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1434*0b57cec5SDimitry Andric   // may point to both local (same translation unit) and global (other
1435*0b57cec5SDimitry Andric   // translation units) symbols. Example:
1436*0b57cec5SDimitry Andric   //
1437*0b57cec5SDimitry Andric   // .section __DATA,__pointers,non_lazy_symbol_pointers
1438*0b57cec5SDimitry Andric   // L1:
1439*0b57cec5SDimitry Andric   //    .indirect_symbol _myGlobal
1440*0b57cec5SDimitry Andric   //    .long 0
1441*0b57cec5SDimitry Andric   // L2:
1442*0b57cec5SDimitry Andric   //    .indirect_symbol _myLocal
1443*0b57cec5SDimitry Andric   //    .long _myLocal
1444*0b57cec5SDimitry Andric   //
1445*0b57cec5SDimitry Andric   // If the symbol is local, instead of the symbol's index, the assembler
1446*0b57cec5SDimitry Andric   // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1447*0b57cec5SDimitry Andric   // Then the linker will notice the constant in the table and will look at the
1448*0b57cec5SDimitry Andric   // content of the symbol.
1449*0b57cec5SDimitry Andric   MachineModuleInfoMachO &MachOMMI =
1450*0b57cec5SDimitry Andric     MMI->getObjFileInfo<MachineModuleInfoMachO>();
1451*0b57cec5SDimitry Andric   MCContext &Ctx = getContext();
1452*0b57cec5SDimitry Andric 
1453*0b57cec5SDimitry Andric   // The offset must consider the original displacement from the base symbol
1454*0b57cec5SDimitry Andric   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1455*0b57cec5SDimitry Andric   Offset = -MV.getConstant();
1456*0b57cec5SDimitry Andric   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
1457*0b57cec5SDimitry Andric 
1458*0b57cec5SDimitry Andric   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1459*0b57cec5SDimitry Andric   // non_lazy_ptr stubs.
1460*0b57cec5SDimitry Andric   SmallString<128> Name;
1461*0b57cec5SDimitry Andric   StringRef Suffix = "$non_lazy_ptr";
1462*0b57cec5SDimitry Andric   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
1463*0b57cec5SDimitry Andric   Name += Sym->getName();
1464*0b57cec5SDimitry Andric   Name += Suffix;
1465*0b57cec5SDimitry Andric   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
1466*0b57cec5SDimitry Andric 
1467*0b57cec5SDimitry Andric   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
14688bcb0991SDimitry Andric 
14698bcb0991SDimitry Andric   if (!StubSym.getPointer())
1470*0b57cec5SDimitry Andric     StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym),
14718bcb0991SDimitry Andric                                                  !GV->hasLocalLinkage());
1472*0b57cec5SDimitry Andric 
1473*0b57cec5SDimitry Andric   const MCExpr *BSymExpr =
1474*0b57cec5SDimitry Andric     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
1475*0b57cec5SDimitry Andric   const MCExpr *LHS =
1476*0b57cec5SDimitry Andric     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
1477*0b57cec5SDimitry Andric 
1478*0b57cec5SDimitry Andric   if (!Offset)
1479*0b57cec5SDimitry Andric     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
1480*0b57cec5SDimitry Andric 
1481*0b57cec5SDimitry Andric   const MCExpr *RHS =
1482*0b57cec5SDimitry Andric     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
1483*0b57cec5SDimitry Andric   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
1484*0b57cec5SDimitry Andric }
1485*0b57cec5SDimitry Andric 
1486*0b57cec5SDimitry Andric static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
1487*0b57cec5SDimitry Andric                                const MCSection &Section) {
1488*0b57cec5SDimitry Andric   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
1489*0b57cec5SDimitry Andric     return true;
1490*0b57cec5SDimitry Andric 
1491fe6060f1SDimitry Andric   // FIXME: we should be able to use private labels for sections that can't be
1492fe6060f1SDimitry Andric   // dead-stripped (there's no issue with blocking atomization there), but `ld
1493fe6060f1SDimitry Andric   // -r` sometimes drops the no_dead_strip attribute from sections so for safety
1494fe6060f1SDimitry Andric   // we don't allow it.
1495*0b57cec5SDimitry Andric   return false;
1496*0b57cec5SDimitry Andric }
1497*0b57cec5SDimitry Andric 
1498*0b57cec5SDimitry Andric void TargetLoweringObjectFileMachO::getNameWithPrefix(
1499*0b57cec5SDimitry Andric     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1500*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1501*0b57cec5SDimitry Andric   bool CannotUsePrivateLabel = true;
1502349cc55cSDimitry Andric   if (auto *GO = GV->getAliaseeObject()) {
1503*0b57cec5SDimitry Andric     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
1504*0b57cec5SDimitry Andric     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
1505*0b57cec5SDimitry Andric     CannotUsePrivateLabel =
1506*0b57cec5SDimitry Andric         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
1507*0b57cec5SDimitry Andric   }
1508*0b57cec5SDimitry Andric   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1509*0b57cec5SDimitry Andric }
1510*0b57cec5SDimitry Andric 
1511*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1512*0b57cec5SDimitry Andric //                                  COFF
1513*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
1514*0b57cec5SDimitry Andric 
1515*0b57cec5SDimitry Andric static unsigned
1516*0b57cec5SDimitry Andric getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
1517*0b57cec5SDimitry Andric   unsigned Flags = 0;
1518*0b57cec5SDimitry Andric   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
1519*0b57cec5SDimitry Andric 
1520*0b57cec5SDimitry Andric   if (K.isMetadata())
1521*0b57cec5SDimitry Andric     Flags |=
1522*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_DISCARDABLE;
1523*0b57cec5SDimitry Andric   else if (K.isText())
1524*0b57cec5SDimitry Andric     Flags |=
1525*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_EXECUTE |
1526*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1527*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_CODE |
1528*0b57cec5SDimitry Andric       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
1529*0b57cec5SDimitry Andric   else if (K.isBSS())
1530*0b57cec5SDimitry Andric     Flags |=
1531*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
1532*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1533*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
1534*0b57cec5SDimitry Andric   else if (K.isThreadLocal())
1535*0b57cec5SDimitry Andric     Flags |=
1536*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1537*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1538*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
1539*0b57cec5SDimitry Andric   else if (K.isReadOnly() || K.isReadOnlyWithRel())
1540*0b57cec5SDimitry Andric     Flags |=
1541*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1542*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ;
1543*0b57cec5SDimitry Andric   else if (K.isWriteable())
1544*0b57cec5SDimitry Andric     Flags |=
1545*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1546*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_READ |
1547*0b57cec5SDimitry Andric       COFF::IMAGE_SCN_MEM_WRITE;
1548*0b57cec5SDimitry Andric 
1549*0b57cec5SDimitry Andric   return Flags;
1550*0b57cec5SDimitry Andric }
1551*0b57cec5SDimitry Andric 
1552*0b57cec5SDimitry Andric static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
1553*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
1554*0b57cec5SDimitry Andric   assert(C && "expected GV to have a Comdat!");
1555*0b57cec5SDimitry Andric 
1556*0b57cec5SDimitry Andric   StringRef ComdatGVName = C->getName();
1557*0b57cec5SDimitry Andric   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
1558*0b57cec5SDimitry Andric   if (!ComdatGV)
1559*0b57cec5SDimitry Andric     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1560*0b57cec5SDimitry Andric                        "' does not exist.");
1561*0b57cec5SDimitry Andric 
1562*0b57cec5SDimitry Andric   if (ComdatGV->getComdat() != C)
1563*0b57cec5SDimitry Andric     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
1564*0b57cec5SDimitry Andric                        "' is not a key for its COMDAT.");
1565*0b57cec5SDimitry Andric 
1566*0b57cec5SDimitry Andric   return ComdatGV;
1567*0b57cec5SDimitry Andric }
1568*0b57cec5SDimitry Andric 
1569*0b57cec5SDimitry Andric static int getSelectionForCOFF(const GlobalValue *GV) {
1570*0b57cec5SDimitry Andric   if (const Comdat *C = GV->getComdat()) {
1571*0b57cec5SDimitry Andric     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
1572*0b57cec5SDimitry Andric     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
1573349cc55cSDimitry Andric       ComdatKey = GA->getAliaseeObject();
1574*0b57cec5SDimitry Andric     if (ComdatKey == GV) {
1575*0b57cec5SDimitry Andric       switch (C->getSelectionKind()) {
1576*0b57cec5SDimitry Andric       case Comdat::Any:
1577*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_ANY;
1578*0b57cec5SDimitry Andric       case Comdat::ExactMatch:
1579*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1580*0b57cec5SDimitry Andric       case Comdat::Largest:
1581*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1582fe6060f1SDimitry Andric       case Comdat::NoDeduplicate:
1583*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1584*0b57cec5SDimitry Andric       case Comdat::SameSize:
1585*0b57cec5SDimitry Andric         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1586*0b57cec5SDimitry Andric       }
1587*0b57cec5SDimitry Andric     } else {
1588*0b57cec5SDimitry Andric       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1589*0b57cec5SDimitry Andric     }
1590*0b57cec5SDimitry Andric   }
1591*0b57cec5SDimitry Andric   return 0;
1592*0b57cec5SDimitry Andric }
1593*0b57cec5SDimitry Andric 
1594*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1595*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1596*0b57cec5SDimitry Andric   int Selection = 0;
1597*0b57cec5SDimitry Andric   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1598*0b57cec5SDimitry Andric   StringRef Name = GO->getSection();
1599*0b57cec5SDimitry Andric   StringRef COMDATSymName = "";
1600*0b57cec5SDimitry Andric   if (GO->hasComdat()) {
1601*0b57cec5SDimitry Andric     Selection = getSelectionForCOFF(GO);
1602*0b57cec5SDimitry Andric     const GlobalValue *ComdatGV;
1603*0b57cec5SDimitry Andric     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
1604*0b57cec5SDimitry Andric       ComdatGV = getComdatGVForCOFF(GO);
1605*0b57cec5SDimitry Andric     else
1606*0b57cec5SDimitry Andric       ComdatGV = GO;
1607*0b57cec5SDimitry Andric 
1608*0b57cec5SDimitry Andric     if (!ComdatGV->hasPrivateLinkage()) {
1609*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1610*0b57cec5SDimitry Andric       COMDATSymName = Sym->getName();
1611*0b57cec5SDimitry Andric       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1612*0b57cec5SDimitry Andric     } else {
1613*0b57cec5SDimitry Andric       Selection = 0;
1614*0b57cec5SDimitry Andric     }
1615*0b57cec5SDimitry Andric   }
1616*0b57cec5SDimitry Andric 
1617*0b57cec5SDimitry Andric   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
1618*0b57cec5SDimitry Andric                                      Selection);
1619*0b57cec5SDimitry Andric }
1620*0b57cec5SDimitry Andric 
1621*0b57cec5SDimitry Andric static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
1622*0b57cec5SDimitry Andric   if (Kind.isText())
1623*0b57cec5SDimitry Andric     return ".text";
1624*0b57cec5SDimitry Andric   if (Kind.isBSS())
1625*0b57cec5SDimitry Andric     return ".bss";
1626*0b57cec5SDimitry Andric   if (Kind.isThreadLocal())
1627*0b57cec5SDimitry Andric     return ".tls$";
1628*0b57cec5SDimitry Andric   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1629*0b57cec5SDimitry Andric     return ".rdata";
1630*0b57cec5SDimitry Andric   return ".data";
1631*0b57cec5SDimitry Andric }
1632*0b57cec5SDimitry Andric 
1633*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1634*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1635*0b57cec5SDimitry Andric   // If we have -ffunction-sections then we should emit the global value to a
1636*0b57cec5SDimitry Andric   // uniqued section specifically for it.
1637*0b57cec5SDimitry Andric   bool EmitUniquedSection;
1638*0b57cec5SDimitry Andric   if (Kind.isText())
1639*0b57cec5SDimitry Andric     EmitUniquedSection = TM.getFunctionSections();
1640*0b57cec5SDimitry Andric   else
1641*0b57cec5SDimitry Andric     EmitUniquedSection = TM.getDataSections();
1642*0b57cec5SDimitry Andric 
1643*0b57cec5SDimitry Andric   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
1644*0b57cec5SDimitry Andric     SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
1645*0b57cec5SDimitry Andric 
1646*0b57cec5SDimitry Andric     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1647*0b57cec5SDimitry Andric 
1648*0b57cec5SDimitry Andric     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1649*0b57cec5SDimitry Andric     int Selection = getSelectionForCOFF(GO);
1650*0b57cec5SDimitry Andric     if (!Selection)
1651*0b57cec5SDimitry Andric       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1652*0b57cec5SDimitry Andric     const GlobalValue *ComdatGV;
1653*0b57cec5SDimitry Andric     if (GO->hasComdat())
1654*0b57cec5SDimitry Andric       ComdatGV = getComdatGVForCOFF(GO);
1655*0b57cec5SDimitry Andric     else
1656*0b57cec5SDimitry Andric       ComdatGV = GO;
1657*0b57cec5SDimitry Andric 
1658*0b57cec5SDimitry Andric     unsigned UniqueID = MCContext::GenericSectionID;
1659*0b57cec5SDimitry Andric     if (EmitUniquedSection)
1660*0b57cec5SDimitry Andric       UniqueID = NextUniqueID++;
1661*0b57cec5SDimitry Andric 
1662*0b57cec5SDimitry Andric     if (!ComdatGV->hasPrivateLinkage()) {
1663*0b57cec5SDimitry Andric       MCSymbol *Sym = TM.getSymbol(ComdatGV);
1664*0b57cec5SDimitry Andric       StringRef COMDATSymName = Sym->getName();
1665*0b57cec5SDimitry Andric 
1666e8d8bef9SDimitry Andric       if (const auto *F = dyn_cast<Function>(GO))
1667e8d8bef9SDimitry Andric         if (Optional<StringRef> Prefix = F->getSectionPrefix())
1668e8d8bef9SDimitry Andric           raw_svector_ostream(Name) << '$' << *Prefix;
1669e8d8bef9SDimitry Andric 
1670*0b57cec5SDimitry Andric       // Append "$symbol" to the section name *before* IR-level mangling is
1671*0b57cec5SDimitry Andric       // applied when targetting mingw. This is what GCC does, and the ld.bfd
1672*0b57cec5SDimitry Andric       // COFF linker will not properly handle comdats otherwise.
1673fe6060f1SDimitry Andric       if (getContext().getTargetTriple().isWindowsGNUEnvironment())
1674*0b57cec5SDimitry Andric         raw_svector_ostream(Name) << '$' << ComdatGV->getName();
1675*0b57cec5SDimitry Andric 
1676*0b57cec5SDimitry Andric       return getContext().getCOFFSection(Name, Characteristics, Kind,
1677*0b57cec5SDimitry Andric                                          COMDATSymName, Selection, UniqueID);
1678*0b57cec5SDimitry Andric     } else {
1679*0b57cec5SDimitry Andric       SmallString<256> TmpData;
1680*0b57cec5SDimitry Andric       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
1681*0b57cec5SDimitry Andric       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
1682*0b57cec5SDimitry Andric                                          Selection, UniqueID);
1683*0b57cec5SDimitry Andric     }
1684*0b57cec5SDimitry Andric   }
1685*0b57cec5SDimitry Andric 
1686*0b57cec5SDimitry Andric   if (Kind.isText())
1687*0b57cec5SDimitry Andric     return TextSection;
1688*0b57cec5SDimitry Andric 
1689*0b57cec5SDimitry Andric   if (Kind.isThreadLocal())
1690*0b57cec5SDimitry Andric     return TLSDataSection;
1691*0b57cec5SDimitry Andric 
1692*0b57cec5SDimitry Andric   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1693*0b57cec5SDimitry Andric     return ReadOnlySection;
1694*0b57cec5SDimitry Andric 
1695*0b57cec5SDimitry Andric   // Note: we claim that common symbols are put in BSSSection, but they are
1696*0b57cec5SDimitry Andric   // really emitted with the magic .comm directive, which creates a symbol table
1697*0b57cec5SDimitry Andric   // entry but not a section.
1698*0b57cec5SDimitry Andric   if (Kind.isBSS() || Kind.isCommon())
1699*0b57cec5SDimitry Andric     return BSSSection;
1700*0b57cec5SDimitry Andric 
1701*0b57cec5SDimitry Andric   return DataSection;
1702*0b57cec5SDimitry Andric }
1703*0b57cec5SDimitry Andric 
1704*0b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1705*0b57cec5SDimitry Andric     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
1706*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1707*0b57cec5SDimitry Andric   bool CannotUsePrivateLabel = false;
1708*0b57cec5SDimitry Andric   if (GV->hasPrivateLinkage() &&
1709*0b57cec5SDimitry Andric       ((isa<Function>(GV) && TM.getFunctionSections()) ||
1710*0b57cec5SDimitry Andric        (isa<GlobalVariable>(GV) && TM.getDataSections())))
1711*0b57cec5SDimitry Andric     CannotUsePrivateLabel = true;
1712*0b57cec5SDimitry Andric 
1713*0b57cec5SDimitry Andric   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
1714*0b57cec5SDimitry Andric }
1715*0b57cec5SDimitry Andric 
1716*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1717*0b57cec5SDimitry Andric     const Function &F, const TargetMachine &TM) const {
1718*0b57cec5SDimitry Andric   // If the function can be removed, produce a unique section so that
1719*0b57cec5SDimitry Andric   // the table doesn't prevent the removal.
1720*0b57cec5SDimitry Andric   const Comdat *C = F.getComdat();
1721*0b57cec5SDimitry Andric   bool EmitUniqueSection = TM.getFunctionSections() || C;
1722*0b57cec5SDimitry Andric   if (!EmitUniqueSection)
1723*0b57cec5SDimitry Andric     return ReadOnlySection;
1724*0b57cec5SDimitry Andric 
1725*0b57cec5SDimitry Andric   // FIXME: we should produce a symbol for F instead.
1726*0b57cec5SDimitry Andric   if (F.hasPrivateLinkage())
1727*0b57cec5SDimitry Andric     return ReadOnlySection;
1728*0b57cec5SDimitry Andric 
1729*0b57cec5SDimitry Andric   MCSymbol *Sym = TM.getSymbol(&F);
1730*0b57cec5SDimitry Andric   StringRef COMDATSymName = Sym->getName();
1731*0b57cec5SDimitry Andric 
1732*0b57cec5SDimitry Andric   SectionKind Kind = SectionKind::getReadOnly();
1733*0b57cec5SDimitry Andric   StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
1734*0b57cec5SDimitry Andric   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
1735*0b57cec5SDimitry Andric   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1736*0b57cec5SDimitry Andric   unsigned UniqueID = NextUniqueID++;
1737*0b57cec5SDimitry Andric 
1738*0b57cec5SDimitry Andric   return getContext().getCOFFSection(
1739*0b57cec5SDimitry Andric       SecName, Characteristics, Kind, COMDATSymName,
1740*0b57cec5SDimitry Andric       COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
1741*0b57cec5SDimitry Andric }
1742*0b57cec5SDimitry Andric 
1743*0b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
1744*0b57cec5SDimitry Andric                                                       Module &M) const {
1745e8d8bef9SDimitry Andric   emitLinkerDirectives(Streamer, M);
1746e8d8bef9SDimitry Andric 
1747e8d8bef9SDimitry Andric   unsigned Version = 0;
1748e8d8bef9SDimitry Andric   unsigned Flags = 0;
1749e8d8bef9SDimitry Andric   StringRef Section;
1750e8d8bef9SDimitry Andric 
1751e8d8bef9SDimitry Andric   GetObjCImageInfo(M, Version, Flags, Section);
1752e8d8bef9SDimitry Andric   if (!Section.empty()) {
1753e8d8bef9SDimitry Andric     auto &C = getContext();
1754e8d8bef9SDimitry Andric     auto *S = C.getCOFFSection(Section,
1755e8d8bef9SDimitry Andric                                COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1756e8d8bef9SDimitry Andric                                    COFF::IMAGE_SCN_MEM_READ,
1757e8d8bef9SDimitry Andric                                SectionKind::getReadOnly());
1758e8d8bef9SDimitry Andric     Streamer.SwitchSection(S);
1759e8d8bef9SDimitry Andric     Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1760e8d8bef9SDimitry Andric     Streamer.emitInt32(Version);
1761e8d8bef9SDimitry Andric     Streamer.emitInt32(Flags);
1762e8d8bef9SDimitry Andric     Streamer.AddBlankLine();
1763e8d8bef9SDimitry Andric   }
1764e8d8bef9SDimitry Andric 
1765e8d8bef9SDimitry Andric   emitCGProfileMetadata(Streamer, M);
1766e8d8bef9SDimitry Andric }
1767e8d8bef9SDimitry Andric 
1768e8d8bef9SDimitry Andric void TargetLoweringObjectFileCOFF::emitLinkerDirectives(
1769e8d8bef9SDimitry Andric     MCStreamer &Streamer, Module &M) const {
1770*0b57cec5SDimitry Andric   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
1771*0b57cec5SDimitry Andric     // Emit the linker options to the linker .drectve section.  According to the
1772*0b57cec5SDimitry Andric     // spec, this section is a space-separated string containing flags for
1773*0b57cec5SDimitry Andric     // linker.
1774*0b57cec5SDimitry Andric     MCSection *Sec = getDrectveSection();
1775*0b57cec5SDimitry Andric     Streamer.SwitchSection(Sec);
1776480093f4SDimitry Andric     for (const auto *Option : LinkerOptions->operands()) {
1777*0b57cec5SDimitry Andric       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1778*0b57cec5SDimitry Andric         // Lead with a space for consistency with our dllexport implementation.
1779*0b57cec5SDimitry Andric         std::string Directive(" ");
17805ffd83dbSDimitry Andric         Directive.append(std::string(cast<MDString>(Piece)->getString()));
17815ffd83dbSDimitry Andric         Streamer.emitBytes(Directive);
1782*0b57cec5SDimitry Andric       }
1783*0b57cec5SDimitry Andric     }
1784*0b57cec5SDimitry Andric   }
1785*0b57cec5SDimitry Andric 
1786e8d8bef9SDimitry Andric   // Emit /EXPORT: flags for each exported global as necessary.
1787e8d8bef9SDimitry Andric   std::string Flags;
1788e8d8bef9SDimitry Andric   for (const GlobalValue &GV : M.global_values()) {
1789e8d8bef9SDimitry Andric     raw_string_ostream OS(Flags);
1790fe6060f1SDimitry Andric     emitLinkerFlagsForGlobalCOFF(OS, &GV, getContext().getTargetTriple(),
1791fe6060f1SDimitry Andric                                  getMangler());
1792e8d8bef9SDimitry Andric     OS.flush();
1793e8d8bef9SDimitry Andric     if (!Flags.empty()) {
1794e8d8bef9SDimitry Andric       Streamer.SwitchSection(getDrectveSection());
1795e8d8bef9SDimitry Andric       Streamer.emitBytes(Flags);
1796e8d8bef9SDimitry Andric     }
1797e8d8bef9SDimitry Andric     Flags.clear();
1798e8d8bef9SDimitry Andric   }
1799*0b57cec5SDimitry Andric 
1800e8d8bef9SDimitry Andric   // Emit /INCLUDE: flags for each used global as necessary.
1801e8d8bef9SDimitry Andric   if (const auto *LU = M.getNamedGlobal("llvm.used")) {
1802e8d8bef9SDimitry Andric     assert(LU->hasInitializer() && "expected llvm.used to have an initializer");
1803e8d8bef9SDimitry Andric     assert(isa<ArrayType>(LU->getValueType()) &&
1804e8d8bef9SDimitry Andric            "expected llvm.used to be an array type");
1805e8d8bef9SDimitry Andric     if (const auto *A = cast<ConstantArray>(LU->getInitializer())) {
1806e8d8bef9SDimitry Andric       for (const Value *Op : A->operands()) {
1807e8d8bef9SDimitry Andric         const auto *GV = cast<GlobalValue>(Op->stripPointerCasts());
1808e8d8bef9SDimitry Andric         // Global symbols with internal or private linkage are not visible to
1809e8d8bef9SDimitry Andric         // the linker, and thus would cause an error when the linker tried to
1810e8d8bef9SDimitry Andric         // preserve the symbol due to the `/include:` directive.
1811e8d8bef9SDimitry Andric         if (GV->hasLocalLinkage())
1812e8d8bef9SDimitry Andric           continue;
1813*0b57cec5SDimitry Andric 
1814e8d8bef9SDimitry Andric         raw_string_ostream OS(Flags);
1815fe6060f1SDimitry Andric         emitLinkerFlagsForUsedCOFF(OS, GV, getContext().getTargetTriple(),
1816fe6060f1SDimitry Andric                                    getMangler());
1817e8d8bef9SDimitry Andric         OS.flush();
1818e8d8bef9SDimitry Andric 
1819e8d8bef9SDimitry Andric         if (!Flags.empty()) {
1820e8d8bef9SDimitry Andric           Streamer.SwitchSection(getDrectveSection());
1821e8d8bef9SDimitry Andric           Streamer.emitBytes(Flags);
1822e8d8bef9SDimitry Andric         }
1823e8d8bef9SDimitry Andric         Flags.clear();
1824e8d8bef9SDimitry Andric       }
1825e8d8bef9SDimitry Andric     }
1826e8d8bef9SDimitry Andric   }
1827*0b57cec5SDimitry Andric }
1828*0b57cec5SDimitry Andric 
1829*0b57cec5SDimitry Andric void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1830*0b57cec5SDimitry Andric                                               const TargetMachine &TM) {
1831*0b57cec5SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TM);
1832e8d8bef9SDimitry Andric   this->TM = &TM;
1833*0b57cec5SDimitry Andric   const Triple &T = TM.getTargetTriple();
1834*0b57cec5SDimitry Andric   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1835*0b57cec5SDimitry Andric     StaticCtorSection =
1836*0b57cec5SDimitry Andric         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1837*0b57cec5SDimitry Andric                                            COFF::IMAGE_SCN_MEM_READ,
1838*0b57cec5SDimitry Andric                            SectionKind::getReadOnly());
1839*0b57cec5SDimitry Andric     StaticDtorSection =
1840*0b57cec5SDimitry Andric         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1841*0b57cec5SDimitry Andric                                            COFF::IMAGE_SCN_MEM_READ,
1842*0b57cec5SDimitry Andric                            SectionKind::getReadOnly());
1843*0b57cec5SDimitry Andric   } else {
1844*0b57cec5SDimitry Andric     StaticCtorSection = Ctx.getCOFFSection(
1845*0b57cec5SDimitry Andric         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1846*0b57cec5SDimitry Andric                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1847*0b57cec5SDimitry Andric         SectionKind::getData());
1848*0b57cec5SDimitry Andric     StaticDtorSection = Ctx.getCOFFSection(
1849*0b57cec5SDimitry Andric         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1850*0b57cec5SDimitry Andric                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1851*0b57cec5SDimitry Andric         SectionKind::getData());
1852*0b57cec5SDimitry Andric   }
1853*0b57cec5SDimitry Andric }
1854*0b57cec5SDimitry Andric 
1855*0b57cec5SDimitry Andric static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
1856*0b57cec5SDimitry Andric                                                    const Triple &T, bool IsCtor,
1857*0b57cec5SDimitry Andric                                                    unsigned Priority,
1858*0b57cec5SDimitry Andric                                                    const MCSymbol *KeySym,
1859*0b57cec5SDimitry Andric                                                    MCSectionCOFF *Default) {
1860*0b57cec5SDimitry Andric   if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1861*0b57cec5SDimitry Andric     // If the priority is the default, use .CRT$XCU, possibly associative.
1862*0b57cec5SDimitry Andric     if (Priority == 65535)
1863*0b57cec5SDimitry Andric       return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
1864*0b57cec5SDimitry Andric 
1865*0b57cec5SDimitry Andric     // Otherwise, we need to compute a new section name. Low priorities should
1866*0b57cec5SDimitry Andric     // run earlier. The linker will sort sections ASCII-betically, and we need a
1867*0b57cec5SDimitry Andric     // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1868*0b57cec5SDimitry Andric     // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1869*0b57cec5SDimitry Andric     // low priorities need to sort before 'L', since the CRT uses that
1870*0b57cec5SDimitry Andric     // internally, so we use ".CRT$XCA00001" for them.
1871*0b57cec5SDimitry Andric     SmallString<24> Name;
1872*0b57cec5SDimitry Andric     raw_svector_ostream OS(Name);
18738bcb0991SDimitry Andric     OS << ".CRT$X" << (IsCtor ? "C" : "T") <<
18748bcb0991SDimitry Andric         (Priority < 200 ? 'A' : 'T') << format("%05u", Priority);
1875*0b57cec5SDimitry Andric     MCSectionCOFF *Sec = Ctx.getCOFFSection(
1876*0b57cec5SDimitry Andric         Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1877*0b57cec5SDimitry Andric         SectionKind::getReadOnly());
1878*0b57cec5SDimitry Andric     return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0);
1879*0b57cec5SDimitry Andric   }
1880*0b57cec5SDimitry Andric 
1881*0b57cec5SDimitry Andric   std::string Name = IsCtor ? ".ctors" : ".dtors";
1882*0b57cec5SDimitry Andric   if (Priority != 65535)
1883*0b57cec5SDimitry Andric     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
1884*0b57cec5SDimitry Andric 
1885*0b57cec5SDimitry Andric   return Ctx.getAssociativeCOFFSection(
1886*0b57cec5SDimitry Andric       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1887*0b57cec5SDimitry Andric                                    COFF::IMAGE_SCN_MEM_READ |
1888*0b57cec5SDimitry Andric                                    COFF::IMAGE_SCN_MEM_WRITE,
1889*0b57cec5SDimitry Andric                          SectionKind::getData()),
1890*0b57cec5SDimitry Andric       KeySym, 0);
1891*0b57cec5SDimitry Andric }
1892*0b57cec5SDimitry Andric 
1893*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
1894*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1895fe6060f1SDimitry Andric   return getCOFFStaticStructorSection(
1896fe6060f1SDimitry Andric       getContext(), getContext().getTargetTriple(), true, Priority, KeySym,
1897*0b57cec5SDimitry Andric       cast<MCSectionCOFF>(StaticCtorSection));
1898*0b57cec5SDimitry Andric }
1899*0b57cec5SDimitry Andric 
1900*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
1901*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
1902fe6060f1SDimitry Andric   return getCOFFStaticStructorSection(
1903fe6060f1SDimitry Andric       getContext(), getContext().getTargetTriple(), false, Priority, KeySym,
1904*0b57cec5SDimitry Andric       cast<MCSectionCOFF>(StaticDtorSection));
1905*0b57cec5SDimitry Andric }
1906*0b57cec5SDimitry Andric 
1907*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
1908*0b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
1909*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
1910*0b57cec5SDimitry Andric   const Triple &T = TM.getTargetTriple();
1911*0b57cec5SDimitry Andric   if (T.isOSCygMing())
1912*0b57cec5SDimitry Andric     return nullptr;
1913*0b57cec5SDimitry Andric 
1914*0b57cec5SDimitry Andric   // Our symbols should exist in address space zero, cowardly no-op if
1915*0b57cec5SDimitry Andric   // otherwise.
1916*0b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
1917*0b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0)
1918*0b57cec5SDimitry Andric     return nullptr;
1919*0b57cec5SDimitry Andric 
1920*0b57cec5SDimitry Andric   // Both ptrtoint instructions must wrap global objects:
1921*0b57cec5SDimitry Andric   // - Only global variables are eligible for image relative relocations.
1922*0b57cec5SDimitry Andric   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1923*0b57cec5SDimitry Andric   // We expect __ImageBase to be a global variable without a section, externally
1924*0b57cec5SDimitry Andric   // defined.
1925*0b57cec5SDimitry Andric   //
1926*0b57cec5SDimitry Andric   // It should look something like this: @__ImageBase = external constant i8
1927*0b57cec5SDimitry Andric   if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
1928*0b57cec5SDimitry Andric       LHS->isThreadLocal() || RHS->isThreadLocal() ||
1929*0b57cec5SDimitry Andric       RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
1930*0b57cec5SDimitry Andric       cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
1931*0b57cec5SDimitry Andric     return nullptr;
1932*0b57cec5SDimitry Andric 
1933*0b57cec5SDimitry Andric   return MCSymbolRefExpr::create(TM.getSymbol(LHS),
1934*0b57cec5SDimitry Andric                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
1935*0b57cec5SDimitry Andric                                  getContext());
1936*0b57cec5SDimitry Andric }
1937*0b57cec5SDimitry Andric 
1938*0b57cec5SDimitry Andric static std::string APIntToHexString(const APInt &AI) {
1939*0b57cec5SDimitry Andric   unsigned Width = (AI.getBitWidth() / 8) * 2;
1940fe6060f1SDimitry Andric   std::string HexString = toString(AI, 16, /*Signed=*/false);
19415ffd83dbSDimitry Andric   llvm::transform(HexString, HexString.begin(), tolower);
1942*0b57cec5SDimitry Andric   unsigned Size = HexString.size();
1943*0b57cec5SDimitry Andric   assert(Width >= Size && "hex string is too large!");
1944*0b57cec5SDimitry Andric   HexString.insert(HexString.begin(), Width - Size, '0');
1945*0b57cec5SDimitry Andric 
1946*0b57cec5SDimitry Andric   return HexString;
1947*0b57cec5SDimitry Andric }
1948*0b57cec5SDimitry Andric 
1949*0b57cec5SDimitry Andric static std::string scalarConstantToHexString(const Constant *C) {
1950*0b57cec5SDimitry Andric   Type *Ty = C->getType();
1951*0b57cec5SDimitry Andric   if (isa<UndefValue>(C)) {
1952349cc55cSDimitry Andric     return APIntToHexString(APInt::getZero(Ty->getPrimitiveSizeInBits()));
1953*0b57cec5SDimitry Andric   } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
1954*0b57cec5SDimitry Andric     return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
1955*0b57cec5SDimitry Andric   } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
1956*0b57cec5SDimitry Andric     return APIntToHexString(CI->getValue());
1957*0b57cec5SDimitry Andric   } else {
1958*0b57cec5SDimitry Andric     unsigned NumElements;
19595ffd83dbSDimitry Andric     if (auto *VTy = dyn_cast<VectorType>(Ty))
19605ffd83dbSDimitry Andric       NumElements = cast<FixedVectorType>(VTy)->getNumElements();
1961*0b57cec5SDimitry Andric     else
1962*0b57cec5SDimitry Andric       NumElements = Ty->getArrayNumElements();
1963*0b57cec5SDimitry Andric     std::string HexString;
1964*0b57cec5SDimitry Andric     for (int I = NumElements - 1, E = -1; I != E; --I)
1965*0b57cec5SDimitry Andric       HexString += scalarConstantToHexString(C->getAggregateElement(I));
1966*0b57cec5SDimitry Andric     return HexString;
1967*0b57cec5SDimitry Andric   }
1968*0b57cec5SDimitry Andric }
1969*0b57cec5SDimitry Andric 
1970*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
1971*0b57cec5SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
19725ffd83dbSDimitry Andric     Align &Alignment) const {
1973*0b57cec5SDimitry Andric   if (Kind.isMergeableConst() && C &&
1974*0b57cec5SDimitry Andric       getContext().getAsmInfo()->hasCOFFComdatConstants()) {
1975*0b57cec5SDimitry Andric     // This creates comdat sections with the given symbol name, but unless
1976*0b57cec5SDimitry Andric     // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1977*0b57cec5SDimitry Andric     // will be created with a null storage class, which makes GNU binutils
1978*0b57cec5SDimitry Andric     // error out.
1979*0b57cec5SDimitry Andric     const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1980*0b57cec5SDimitry Andric                                      COFF::IMAGE_SCN_MEM_READ |
1981*0b57cec5SDimitry Andric                                      COFF::IMAGE_SCN_LNK_COMDAT;
1982*0b57cec5SDimitry Andric     std::string COMDATSymName;
1983*0b57cec5SDimitry Andric     if (Kind.isMergeableConst4()) {
19845ffd83dbSDimitry Andric       if (Alignment <= 4) {
1985*0b57cec5SDimitry Andric         COMDATSymName = "__real@" + scalarConstantToHexString(C);
19865ffd83dbSDimitry Andric         Alignment = Align(4);
1987*0b57cec5SDimitry Andric       }
1988*0b57cec5SDimitry Andric     } else if (Kind.isMergeableConst8()) {
19895ffd83dbSDimitry Andric       if (Alignment <= 8) {
1990*0b57cec5SDimitry Andric         COMDATSymName = "__real@" + scalarConstantToHexString(C);
19915ffd83dbSDimitry Andric         Alignment = Align(8);
1992*0b57cec5SDimitry Andric       }
1993*0b57cec5SDimitry Andric     } else if (Kind.isMergeableConst16()) {
1994*0b57cec5SDimitry Andric       // FIXME: These may not be appropriate for non-x86 architectures.
19955ffd83dbSDimitry Andric       if (Alignment <= 16) {
1996*0b57cec5SDimitry Andric         COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
19975ffd83dbSDimitry Andric         Alignment = Align(16);
1998*0b57cec5SDimitry Andric       }
1999*0b57cec5SDimitry Andric     } else if (Kind.isMergeableConst32()) {
20005ffd83dbSDimitry Andric       if (Alignment <= 32) {
2001*0b57cec5SDimitry Andric         COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
20025ffd83dbSDimitry Andric         Alignment = Align(32);
2003*0b57cec5SDimitry Andric       }
2004*0b57cec5SDimitry Andric     }
2005*0b57cec5SDimitry Andric 
2006*0b57cec5SDimitry Andric     if (!COMDATSymName.empty())
2007*0b57cec5SDimitry Andric       return getContext().getCOFFSection(".rdata", Characteristics, Kind,
2008*0b57cec5SDimitry Andric                                          COMDATSymName,
2009*0b57cec5SDimitry Andric                                          COFF::IMAGE_COMDAT_SELECT_ANY);
2010*0b57cec5SDimitry Andric   }
2011*0b57cec5SDimitry Andric 
20125ffd83dbSDimitry Andric   return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C,
20135ffd83dbSDimitry Andric                                                          Alignment);
2014*0b57cec5SDimitry Andric }
2015*0b57cec5SDimitry Andric 
2016*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2017*0b57cec5SDimitry Andric //                                  Wasm
2018*0b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
2019*0b57cec5SDimitry Andric 
2020*0b57cec5SDimitry Andric static const Comdat *getWasmComdat(const GlobalValue *GV) {
2021*0b57cec5SDimitry Andric   const Comdat *C = GV->getComdat();
2022*0b57cec5SDimitry Andric   if (!C)
2023*0b57cec5SDimitry Andric     return nullptr;
2024*0b57cec5SDimitry Andric 
2025*0b57cec5SDimitry Andric   if (C->getSelectionKind() != Comdat::Any)
2026*0b57cec5SDimitry Andric     report_fatal_error("WebAssembly COMDATs only support "
2027*0b57cec5SDimitry Andric                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
2028*0b57cec5SDimitry Andric                        "lowered.");
2029*0b57cec5SDimitry Andric 
2030*0b57cec5SDimitry Andric   return C;
2031*0b57cec5SDimitry Andric }
2032*0b57cec5SDimitry Andric 
2033fe6060f1SDimitry Andric static unsigned getWasmSectionFlags(SectionKind K) {
2034fe6060f1SDimitry Andric   unsigned Flags = 0;
2035fe6060f1SDimitry Andric 
2036fe6060f1SDimitry Andric   if (K.isThreadLocal())
2037fe6060f1SDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_TLS;
2038fe6060f1SDimitry Andric 
2039fe6060f1SDimitry Andric   if (K.isMergeableCString())
2040fe6060f1SDimitry Andric     Flags |= wasm::WASM_SEG_FLAG_STRINGS;
2041fe6060f1SDimitry Andric 
2042fe6060f1SDimitry Andric   // TODO(sbc): Add suport for K.isMergeableConst()
2043fe6060f1SDimitry Andric 
2044fe6060f1SDimitry Andric   return Flags;
2045fe6060f1SDimitry Andric }
2046fe6060f1SDimitry Andric 
2047*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
2048*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2049*0b57cec5SDimitry Andric   // We don't support explict section names for functions in the wasm object
2050*0b57cec5SDimitry Andric   // format.  Each function has to be in its own unique section.
2051*0b57cec5SDimitry Andric   if (isa<Function>(GO)) {
2052*0b57cec5SDimitry Andric     return SelectSectionForGlobal(GO, Kind, TM);
2053*0b57cec5SDimitry Andric   }
2054*0b57cec5SDimitry Andric 
2055*0b57cec5SDimitry Andric   StringRef Name = GO->getSection();
2056*0b57cec5SDimitry Andric 
20575ffd83dbSDimitry Andric   // Certain data sections we treat as named custom sections rather than
20585ffd83dbSDimitry Andric   // segments within the data section.
20595ffd83dbSDimitry Andric   // This could be avoided if all data segements (the wasm sense) were
20605ffd83dbSDimitry Andric   // represented as their own sections (in the llvm sense).
20615ffd83dbSDimitry Andric   // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138
20625ffd83dbSDimitry Andric   if (Name == ".llvmcmd" || Name == ".llvmbc")
20635ffd83dbSDimitry Andric     Kind = SectionKind::getMetadata();
2064*0b57cec5SDimitry Andric 
2065*0b57cec5SDimitry Andric   StringRef Group = "";
2066*0b57cec5SDimitry Andric   if (const Comdat *C = getWasmComdat(GO)) {
2067*0b57cec5SDimitry Andric     Group = C->getName();
2068*0b57cec5SDimitry Andric   }
2069*0b57cec5SDimitry Andric 
2070fe6060f1SDimitry Andric   unsigned Flags = getWasmSectionFlags(Kind);
2071fe6060f1SDimitry Andric   MCSectionWasm *Section = getContext().getWasmSection(
2072fe6060f1SDimitry Andric       Name, Kind, Flags, Group, MCContext::GenericSectionID);
2073*0b57cec5SDimitry Andric 
2074*0b57cec5SDimitry Andric   return Section;
2075*0b57cec5SDimitry Andric }
2076*0b57cec5SDimitry Andric 
2077*0b57cec5SDimitry Andric static MCSectionWasm *selectWasmSectionForGlobal(
2078*0b57cec5SDimitry Andric     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
2079*0b57cec5SDimitry Andric     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
2080*0b57cec5SDimitry Andric   StringRef Group = "";
2081*0b57cec5SDimitry Andric   if (const Comdat *C = getWasmComdat(GO)) {
2082*0b57cec5SDimitry Andric     Group = C->getName();
2083*0b57cec5SDimitry Andric   }
2084*0b57cec5SDimitry Andric 
2085*0b57cec5SDimitry Andric   bool UniqueSectionNames = TM.getUniqueSectionNames();
2086*0b57cec5SDimitry Andric   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
2087*0b57cec5SDimitry Andric 
2088*0b57cec5SDimitry Andric   if (const auto *F = dyn_cast<Function>(GO)) {
2089*0b57cec5SDimitry Andric     const auto &OptionalPrefix = F->getSectionPrefix();
2090*0b57cec5SDimitry Andric     if (OptionalPrefix)
2091e8d8bef9SDimitry Andric       raw_svector_ostream(Name) << '.' << *OptionalPrefix;
2092*0b57cec5SDimitry Andric   }
2093*0b57cec5SDimitry Andric 
2094*0b57cec5SDimitry Andric   if (EmitUniqueSection && UniqueSectionNames) {
2095*0b57cec5SDimitry Andric     Name.push_back('.');
2096*0b57cec5SDimitry Andric     TM.getNameWithPrefix(Name, GO, Mang, true);
2097*0b57cec5SDimitry Andric   }
2098*0b57cec5SDimitry Andric   unsigned UniqueID = MCContext::GenericSectionID;
2099*0b57cec5SDimitry Andric   if (EmitUniqueSection && !UniqueSectionNames) {
2100*0b57cec5SDimitry Andric     UniqueID = *NextUniqueID;
2101*0b57cec5SDimitry Andric     (*NextUniqueID)++;
2102*0b57cec5SDimitry Andric   }
2103*0b57cec5SDimitry Andric 
2104fe6060f1SDimitry Andric   unsigned Flags = getWasmSectionFlags(Kind);
2105fe6060f1SDimitry Andric   return Ctx.getWasmSection(Name, Kind, Flags, Group, UniqueID);
2106*0b57cec5SDimitry Andric }
2107*0b57cec5SDimitry Andric 
2108*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
2109*0b57cec5SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2110*0b57cec5SDimitry Andric 
2111*0b57cec5SDimitry Andric   if (Kind.isCommon())
2112*0b57cec5SDimitry Andric     report_fatal_error("mergable sections not supported yet on wasm");
2113*0b57cec5SDimitry Andric 
2114*0b57cec5SDimitry Andric   // If we have -ffunction-section or -fdata-section then we should emit the
2115*0b57cec5SDimitry Andric   // global value to a uniqued section specifically for it.
2116*0b57cec5SDimitry Andric   bool EmitUniqueSection = false;
2117*0b57cec5SDimitry Andric   if (Kind.isText())
2118*0b57cec5SDimitry Andric     EmitUniqueSection = TM.getFunctionSections();
2119*0b57cec5SDimitry Andric   else
2120*0b57cec5SDimitry Andric     EmitUniqueSection = TM.getDataSections();
2121*0b57cec5SDimitry Andric   EmitUniqueSection |= GO->hasComdat();
2122*0b57cec5SDimitry Andric 
2123*0b57cec5SDimitry Andric   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
2124*0b57cec5SDimitry Andric                                     EmitUniqueSection, &NextUniqueID);
2125*0b57cec5SDimitry Andric }
2126*0b57cec5SDimitry Andric 
2127*0b57cec5SDimitry Andric bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
2128*0b57cec5SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
2129*0b57cec5SDimitry Andric   // We can always create relative relocations, so use another section
2130*0b57cec5SDimitry Andric   // that can be marked non-executable.
2131*0b57cec5SDimitry Andric   return false;
2132*0b57cec5SDimitry Andric }
2133*0b57cec5SDimitry Andric 
2134*0b57cec5SDimitry Andric const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
2135*0b57cec5SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
2136*0b57cec5SDimitry Andric     const TargetMachine &TM) const {
2137*0b57cec5SDimitry Andric   // We may only use a PLT-relative relocation to refer to unnamed_addr
2138*0b57cec5SDimitry Andric   // functions.
2139*0b57cec5SDimitry Andric   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
2140*0b57cec5SDimitry Andric     return nullptr;
2141*0b57cec5SDimitry Andric 
21424824e7fdSDimitry Andric   // Basic correctness checks.
2143*0b57cec5SDimitry Andric   if (LHS->getType()->getPointerAddressSpace() != 0 ||
2144*0b57cec5SDimitry Andric       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
2145*0b57cec5SDimitry Andric       RHS->isThreadLocal())
2146*0b57cec5SDimitry Andric     return nullptr;
2147*0b57cec5SDimitry Andric 
2148*0b57cec5SDimitry Andric   return MCBinaryExpr::createSub(
2149*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
2150*0b57cec5SDimitry Andric                               getContext()),
2151*0b57cec5SDimitry Andric       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
2152*0b57cec5SDimitry Andric }
2153*0b57cec5SDimitry Andric 
2154*0b57cec5SDimitry Andric void TargetLoweringObjectFileWasm::InitializeWasm() {
2155*0b57cec5SDimitry Andric   StaticCtorSection =
2156*0b57cec5SDimitry Andric       getContext().getWasmSection(".init_array", SectionKind::getData());
2157*0b57cec5SDimitry Andric 
2158*0b57cec5SDimitry Andric   // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
2159*0b57cec5SDimitry Andric   // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
2160*0b57cec5SDimitry Andric   TTypeEncoding = dwarf::DW_EH_PE_absptr;
2161*0b57cec5SDimitry Andric }
2162*0b57cec5SDimitry Andric 
2163*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
2164*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
2165*0b57cec5SDimitry Andric   return Priority == UINT16_MAX ?
2166*0b57cec5SDimitry Andric          StaticCtorSection :
2167*0b57cec5SDimitry Andric          getContext().getWasmSection(".init_array." + utostr(Priority),
2168*0b57cec5SDimitry Andric                                      SectionKind::getData());
2169*0b57cec5SDimitry Andric }
2170*0b57cec5SDimitry Andric 
2171*0b57cec5SDimitry Andric MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
2172*0b57cec5SDimitry Andric     unsigned Priority, const MCSymbol *KeySym) const {
2173*0b57cec5SDimitry Andric   llvm_unreachable("@llvm.global_dtors should have been lowered already");
2174*0b57cec5SDimitry Andric   return nullptr;
2175*0b57cec5SDimitry Andric }
21768bcb0991SDimitry Andric 
21778bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
21788bcb0991SDimitry Andric //                                  XCOFF
21798bcb0991SDimitry Andric //===----------------------------------------------------------------------===//
2180e8d8bef9SDimitry Andric bool TargetLoweringObjectFileXCOFF::ShouldEmitEHBlock(
2181e8d8bef9SDimitry Andric     const MachineFunction *MF) {
2182e8d8bef9SDimitry Andric   if (!MF->getLandingPads().empty())
2183e8d8bef9SDimitry Andric     return true;
2184e8d8bef9SDimitry Andric 
2185e8d8bef9SDimitry Andric   const Function &F = MF->getFunction();
2186e8d8bef9SDimitry Andric   if (!F.hasPersonalityFn() || !F.needsUnwindTableEntry())
2187e8d8bef9SDimitry Andric     return false;
2188e8d8bef9SDimitry Andric 
2189fe6060f1SDimitry Andric   const GlobalValue *Per =
2190fe6060f1SDimitry Andric       dyn_cast<GlobalValue>(F.getPersonalityFn()->stripPointerCasts());
2191fe6060f1SDimitry Andric   assert(Per && "Personality routine is not a GlobalValue type.");
2192e8d8bef9SDimitry Andric   if (isNoOpWithoutInvoke(classifyEHPersonality(Per)))
2193e8d8bef9SDimitry Andric     return false;
2194e8d8bef9SDimitry Andric 
2195e8d8bef9SDimitry Andric   return true;
2196e8d8bef9SDimitry Andric }
2197e8d8bef9SDimitry Andric 
2198fe6060f1SDimitry Andric bool TargetLoweringObjectFileXCOFF::ShouldSetSSPCanaryBitInTB(
2199fe6060f1SDimitry Andric     const MachineFunction *MF) {
2200fe6060f1SDimitry Andric   const Function &F = MF->getFunction();
2201fe6060f1SDimitry Andric   if (!F.hasStackProtectorFnAttr())
2202fe6060f1SDimitry Andric     return false;
2203fe6060f1SDimitry Andric   // FIXME: check presence of canary word
2204fe6060f1SDimitry Andric   // There are cases that the stack protectors are not really inserted even if
2205fe6060f1SDimitry Andric   // the attributes are on.
2206fe6060f1SDimitry Andric   return true;
2207fe6060f1SDimitry Andric }
2208fe6060f1SDimitry Andric 
2209e8d8bef9SDimitry Andric MCSymbol *
2210e8d8bef9SDimitry Andric TargetLoweringObjectFileXCOFF::getEHInfoTableSymbol(const MachineFunction *MF) {
2211e8d8bef9SDimitry Andric   return MF->getMMI().getContext().getOrCreateSymbol(
2212e8d8bef9SDimitry Andric       "__ehinfo." + Twine(MF->getFunctionNumber()));
2213e8d8bef9SDimitry Andric }
2214e8d8bef9SDimitry Andric 
22155ffd83dbSDimitry Andric MCSymbol *
22165ffd83dbSDimitry Andric TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV,
22175ffd83dbSDimitry Andric                                                const TargetMachine &TM) const {
22185ffd83dbSDimitry Andric   // We always use a qualname symbol for a GV that represents
22195ffd83dbSDimitry Andric   // a declaration, a function descriptor, or a common symbol.
2220e8d8bef9SDimitry Andric   // If a GV represents a GlobalVariable and -fdata-sections is enabled, we
2221e8d8bef9SDimitry Andric   // also return a qualname so that a label symbol could be avoided.
22225ffd83dbSDimitry Andric   // It is inherently ambiguous when the GO represents the address of a
22235ffd83dbSDimitry Andric   // function, as the GO could either represent a function descriptor or a
22245ffd83dbSDimitry Andric   // function entry point. We choose to always return a function descriptor
22255ffd83dbSDimitry Andric   // here.
22265ffd83dbSDimitry Andric   if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) {
2227fe6060f1SDimitry Andric     if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV))
2228fe6060f1SDimitry Andric       if (GVar->hasAttribute("toc-data"))
2229fe6060f1SDimitry Andric         return cast<MCSectionXCOFF>(
2230fe6060f1SDimitry Andric                    SectionForGlobal(GVar, SectionKind::getData(), TM))
2231fe6060f1SDimitry Andric             ->getQualNameSymbol();
2232fe6060f1SDimitry Andric 
22335ffd83dbSDimitry Andric     if (GO->isDeclarationForLinker())
22345ffd83dbSDimitry Andric       return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM))
22355ffd83dbSDimitry Andric           ->getQualNameSymbol();
22365ffd83dbSDimitry Andric 
22375ffd83dbSDimitry Andric     SectionKind GOKind = getKindForGlobal(GO, TM);
22385ffd83dbSDimitry Andric     if (GOKind.isText())
22395ffd83dbSDimitry Andric       return cast<MCSectionXCOFF>(
22405ffd83dbSDimitry Andric                  getSectionForFunctionDescriptor(cast<Function>(GO), TM))
22415ffd83dbSDimitry Andric           ->getQualNameSymbol();
2242fe6060f1SDimitry Andric     if ((TM.getDataSections() && !GO->hasSection()) || GO->hasCommonLinkage() ||
2243fe6060f1SDimitry Andric         GOKind.isBSSLocal() || GOKind.isThreadBSSLocal())
22445ffd83dbSDimitry Andric       return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM))
22455ffd83dbSDimitry Andric           ->getQualNameSymbol();
22465ffd83dbSDimitry Andric   }
22475ffd83dbSDimitry Andric 
22485ffd83dbSDimitry Andric   // For all other cases, fall back to getSymbol to return the unqualified name.
22495ffd83dbSDimitry Andric   return nullptr;
22505ffd83dbSDimitry Andric }
22515ffd83dbSDimitry Andric 
22528bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal(
22538bcb0991SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2254e8d8bef9SDimitry Andric   if (!GO->hasSection())
2255e8d8bef9SDimitry Andric     report_fatal_error("#pragma clang section is not yet supported");
2256e8d8bef9SDimitry Andric 
2257e8d8bef9SDimitry Andric   StringRef SectionName = GO->getSection();
2258fe6060f1SDimitry Andric 
2259fe6060f1SDimitry Andric   // Handle the XCOFF::TD case first, then deal with the rest.
2260fe6060f1SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2261fe6060f1SDimitry Andric     if (GVar->hasAttribute("toc-data"))
2262fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2263fe6060f1SDimitry Andric           SectionName, Kind,
2264fe6060f1SDimitry Andric           XCOFF::CsectProperties(/*MappingClass*/ XCOFF::XMC_TD, XCOFF::XTY_SD),
2265fe6060f1SDimitry Andric           /* MultiSymbolsAllowed*/ true);
2266fe6060f1SDimitry Andric 
2267e8d8bef9SDimitry Andric   XCOFF::StorageMappingClass MappingClass;
2268e8d8bef9SDimitry Andric   if (Kind.isText())
2269e8d8bef9SDimitry Andric     MappingClass = XCOFF::XMC_PR;
2270e8d8bef9SDimitry Andric   else if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS())
2271e8d8bef9SDimitry Andric     MappingClass = XCOFF::XMC_RW;
2272e8d8bef9SDimitry Andric   else if (Kind.isReadOnly())
2273e8d8bef9SDimitry Andric     MappingClass = XCOFF::XMC_RO;
2274e8d8bef9SDimitry Andric   else
2275e8d8bef9SDimitry Andric     report_fatal_error("XCOFF other section types not yet implemented.");
2276e8d8bef9SDimitry Andric 
2277fe6060f1SDimitry Andric   return getContext().getXCOFFSection(
2278fe6060f1SDimitry Andric       SectionName, Kind, XCOFF::CsectProperties(MappingClass, XCOFF::XTY_SD),
2279fe6060f1SDimitry Andric       /* MultiSymbolsAllowed*/ true);
22808bcb0991SDimitry Andric }
22818bcb0991SDimitry Andric 
22825ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference(
22835ffd83dbSDimitry Andric     const GlobalObject *GO, const TargetMachine &TM) const {
22845ffd83dbSDimitry Andric   assert(GO->isDeclarationForLinker() &&
22855ffd83dbSDimitry Andric          "Tried to get ER section for a defined global.");
22865ffd83dbSDimitry Andric 
22875ffd83dbSDimitry Andric   SmallString<128> Name;
22885ffd83dbSDimitry Andric   getNameWithPrefix(Name, GO, TM);
22895ffd83dbSDimitry Andric 
2290fe6060f1SDimitry Andric   XCOFF::StorageMappingClass SMC =
2291fe6060f1SDimitry Andric       isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA;
2292fe6060f1SDimitry Andric   if (GO->isThreadLocal())
2293fe6060f1SDimitry Andric     SMC = XCOFF::XMC_UL;
2294fe6060f1SDimitry Andric 
22955ffd83dbSDimitry Andric   // Externals go into a csect of type ER.
22965ffd83dbSDimitry Andric   return getContext().getXCOFFSection(
2297fe6060f1SDimitry Andric       Name, SectionKind::getMetadata(),
2298fe6060f1SDimitry Andric       XCOFF::CsectProperties(SMC, XCOFF::XTY_ER));
22995ffd83dbSDimitry Andric }
23005ffd83dbSDimitry Andric 
23018bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal(
23028bcb0991SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2303fe6060f1SDimitry Andric   // Handle the XCOFF::TD case first, then deal with the rest.
2304fe6060f1SDimitry Andric   if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GO))
2305fe6060f1SDimitry Andric     if (GVar->hasAttribute("toc-data")) {
23068bcb0991SDimitry Andric       SmallString<128> Name;
23078bcb0991SDimitry Andric       getNameWithPrefix(Name, GO, TM);
23088bcb0991SDimitry Andric       return getContext().getXCOFFSection(
2309fe6060f1SDimitry Andric           Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TD, XCOFF::XTY_SD),
2310fe6060f1SDimitry Andric           /* MultiSymbolsAllowed*/ true);
2311fe6060f1SDimitry Andric     }
2312fe6060f1SDimitry Andric 
2313fe6060f1SDimitry Andric   // Common symbols go into a csect with matching name which will get mapped
2314fe6060f1SDimitry Andric   // into the .bss section.
2315fe6060f1SDimitry Andric   // Zero-initialized local TLS symbols go into a csect with matching name which
2316fe6060f1SDimitry Andric   // will get mapped into the .tbss section.
2317fe6060f1SDimitry Andric   if (Kind.isBSSLocal() || GO->hasCommonLinkage() || Kind.isThreadBSSLocal()) {
2318fe6060f1SDimitry Andric     SmallString<128> Name;
2319fe6060f1SDimitry Andric     getNameWithPrefix(Name, GO, TM);
2320fe6060f1SDimitry Andric     XCOFF::StorageMappingClass SMC = Kind.isBSSLocal() ? XCOFF::XMC_BS
2321fe6060f1SDimitry Andric                                      : Kind.isCommon() ? XCOFF::XMC_RW
2322fe6060f1SDimitry Andric                                                        : XCOFF::XMC_UL;
2323fe6060f1SDimitry Andric     return getContext().getXCOFFSection(
2324fe6060f1SDimitry Andric         Name, Kind, XCOFF::CsectProperties(SMC, XCOFF::XTY_CM));
23258bcb0991SDimitry Andric   }
23268bcb0991SDimitry Andric 
2327480093f4SDimitry Andric   if (Kind.isMergeableCString()) {
23285ffd83dbSDimitry Andric     Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
2329480093f4SDimitry Andric         cast<GlobalVariable>(GO));
2330480093f4SDimitry Andric 
2331480093f4SDimitry Andric     unsigned EntrySize = getEntrySizeForKind(Kind);
2332480093f4SDimitry Andric     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
2333480093f4SDimitry Andric     SmallString<128> Name;
23345ffd83dbSDimitry Andric     Name = SizeSpec + utostr(Alignment.value());
2335480093f4SDimitry Andric 
2336e8d8bef9SDimitry Andric     if (TM.getDataSections())
2337e8d8bef9SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2338e8d8bef9SDimitry Andric 
2339480093f4SDimitry Andric     return getContext().getXCOFFSection(
2340fe6060f1SDimitry Andric         Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD),
2341e8d8bef9SDimitry Andric         /* MultiSymbolsAllowed*/ !TM.getDataSections());
2342480093f4SDimitry Andric   }
2343480093f4SDimitry Andric 
2344e8d8bef9SDimitry Andric   if (Kind.isText()) {
2345e8d8bef9SDimitry Andric     if (TM.getFunctionSections()) {
2346e8d8bef9SDimitry Andric       return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM))
2347e8d8bef9SDimitry Andric           ->getRepresentedCsect();
2348e8d8bef9SDimitry Andric     }
23498bcb0991SDimitry Andric     return TextSection;
2350e8d8bef9SDimitry Andric   }
23518bcb0991SDimitry Andric 
2352e8d8bef9SDimitry Andric   // TODO: We may put Kind.isReadOnlyWithRel() under option control, because
2353e8d8bef9SDimitry Andric   // user may want to have read-only data with relocations placed into a
2354e8d8bef9SDimitry Andric   // read-only section by the compiler.
2355e8d8bef9SDimitry Andric   // For BSS kind, zero initialized data must be emitted to the .data section
2356e8d8bef9SDimitry Andric   // because external linkage control sections that get mapped to the .bss
2357e8d8bef9SDimitry Andric   // section will be linked as tentative defintions, which is only appropriate
2358e8d8bef9SDimitry Andric   // for SectionKind::Common.
2359e8d8bef9SDimitry Andric   if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) {
2360e8d8bef9SDimitry Andric     if (TM.getDataSections()) {
2361e8d8bef9SDimitry Andric       SmallString<128> Name;
2362e8d8bef9SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2363fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2364fe6060f1SDimitry Andric           Name, SectionKind::getData(),
2365fe6060f1SDimitry Andric           XCOFF::CsectProperties(XCOFF::XMC_RW, XCOFF::XTY_SD));
2366e8d8bef9SDimitry Andric     }
23678bcb0991SDimitry Andric     return DataSection;
2368e8d8bef9SDimitry Andric   }
23698bcb0991SDimitry Andric 
2370e8d8bef9SDimitry Andric   if (Kind.isReadOnly()) {
2371e8d8bef9SDimitry Andric     if (TM.getDataSections()) {
2372e8d8bef9SDimitry Andric       SmallString<128> Name;
2373e8d8bef9SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2374fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2375fe6060f1SDimitry Andric           Name, SectionKind::getReadOnly(),
2376fe6060f1SDimitry Andric           XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
2377e8d8bef9SDimitry Andric     }
2378480093f4SDimitry Andric     return ReadOnlySection;
2379e8d8bef9SDimitry Andric   }
2380480093f4SDimitry Andric 
2381fe6060f1SDimitry Andric   // External/weak TLS data and initialized local TLS data are not eligible
2382fe6060f1SDimitry Andric   // to be put into common csect. If data sections are enabled, thread
2383fe6060f1SDimitry Andric   // data are emitted into separate sections. Otherwise, thread data
2384fe6060f1SDimitry Andric   // are emitted into the .tdata section.
2385fe6060f1SDimitry Andric   if (Kind.isThreadLocal()) {
2386fe6060f1SDimitry Andric     if (TM.getDataSections()) {
2387fe6060f1SDimitry Andric       SmallString<128> Name;
2388fe6060f1SDimitry Andric       getNameWithPrefix(Name, GO, TM);
2389fe6060f1SDimitry Andric       return getContext().getXCOFFSection(
2390fe6060f1SDimitry Andric           Name, Kind, XCOFF::CsectProperties(XCOFF::XMC_TL, XCOFF::XTY_SD));
2391fe6060f1SDimitry Andric     }
2392fe6060f1SDimitry Andric     return TLSDataSection;
2393fe6060f1SDimitry Andric   }
2394fe6060f1SDimitry Andric 
23958bcb0991SDimitry Andric   report_fatal_error("XCOFF other section types not yet implemented.");
23968bcb0991SDimitry Andric }
23978bcb0991SDimitry Andric 
2398480093f4SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable(
2399480093f4SDimitry Andric     const Function &F, const TargetMachine &TM) const {
2400480093f4SDimitry Andric   assert (!F.getComdat() && "Comdat not supported on XCOFF.");
2401e8d8bef9SDimitry Andric 
2402e8d8bef9SDimitry Andric   if (!TM.getFunctionSections())
2403480093f4SDimitry Andric     return ReadOnlySection;
2404e8d8bef9SDimitry Andric 
2405e8d8bef9SDimitry Andric   // If the function can be removed, produce a unique section so that
2406e8d8bef9SDimitry Andric   // the table doesn't prevent the removal.
2407e8d8bef9SDimitry Andric   SmallString<128> NameStr(".rodata.jmp..");
2408e8d8bef9SDimitry Andric   getNameWithPrefix(NameStr, &F, TM);
2409fe6060f1SDimitry Andric   return getContext().getXCOFFSection(
2410fe6060f1SDimitry Andric       NameStr, SectionKind::getReadOnly(),
2411fe6060f1SDimitry Andric       XCOFF::CsectProperties(XCOFF::XMC_RO, XCOFF::XTY_SD));
2412480093f4SDimitry Andric }
2413480093f4SDimitry Andric 
24148bcb0991SDimitry Andric bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection(
24158bcb0991SDimitry Andric     bool UsesLabelDifference, const Function &F) const {
2416480093f4SDimitry Andric   return false;
2417480093f4SDimitry Andric }
2418480093f4SDimitry Andric 
2419480093f4SDimitry Andric /// Given a mergeable constant with the specified size and relocation
2420480093f4SDimitry Andric /// information, return a section that it should be placed in.
2421480093f4SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant(
2422480093f4SDimitry Andric     const DataLayout &DL, SectionKind Kind, const Constant *C,
24235ffd83dbSDimitry Andric     Align &Alignment) const {
2424480093f4SDimitry Andric   // TODO: Enable emiting constant pool to unique sections when we support it.
2425349cc55cSDimitry Andric   if (Alignment > Align(16))
2426349cc55cSDimitry Andric     report_fatal_error("Alignments greater than 16 not yet supported.");
2427349cc55cSDimitry Andric 
2428349cc55cSDimitry Andric   if (Alignment == Align(8)) {
2429349cc55cSDimitry Andric     assert(ReadOnly8Section && "Section should always be initialized.");
2430349cc55cSDimitry Andric     return ReadOnly8Section;
2431349cc55cSDimitry Andric   }
2432349cc55cSDimitry Andric 
2433349cc55cSDimitry Andric   if (Alignment == Align(16)) {
2434349cc55cSDimitry Andric     assert(ReadOnly16Section && "Section should always be initialized.");
2435349cc55cSDimitry Andric     return ReadOnly16Section;
2436349cc55cSDimitry Andric   }
2437349cc55cSDimitry Andric 
2438480093f4SDimitry Andric   return ReadOnlySection;
24398bcb0991SDimitry Andric }
24408bcb0991SDimitry Andric 
24418bcb0991SDimitry Andric void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx,
24428bcb0991SDimitry Andric                                                const TargetMachine &TgtM) {
24438bcb0991SDimitry Andric   TargetLoweringObjectFile::Initialize(Ctx, TgtM);
2444e8d8bef9SDimitry Andric   TTypeEncoding =
2445e8d8bef9SDimitry Andric       dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_datarel |
2446e8d8bef9SDimitry Andric       (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4
2447e8d8bef9SDimitry Andric                                             : dwarf::DW_EH_PE_sdata8);
24488bcb0991SDimitry Andric   PersonalityEncoding = 0;
24498bcb0991SDimitry Andric   LSDAEncoding = 0;
2450e8d8bef9SDimitry Andric   CallSiteEncoding = dwarf::DW_EH_PE_udata4;
24518bcb0991SDimitry Andric }
24528bcb0991SDimitry Andric 
24538bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection(
24548bcb0991SDimitry Andric 	unsigned Priority, const MCSymbol *KeySym) const {
2455e8d8bef9SDimitry Andric   report_fatal_error("no static constructor section on AIX");
24568bcb0991SDimitry Andric }
24578bcb0991SDimitry Andric 
24588bcb0991SDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection(
24598bcb0991SDimitry Andric 	unsigned Priority, const MCSymbol *KeySym) const {
2460e8d8bef9SDimitry Andric   report_fatal_error("no static destructor section on AIX");
24618bcb0991SDimitry Andric }
24628bcb0991SDimitry Andric 
24638bcb0991SDimitry Andric const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference(
24648bcb0991SDimitry Andric     const GlobalValue *LHS, const GlobalValue *RHS,
24658bcb0991SDimitry Andric     const TargetMachine &TM) const {
2466349cc55cSDimitry Andric   /* Not implemented yet, but don't crash, return nullptr. */
2467349cc55cSDimitry Andric   return nullptr;
24688bcb0991SDimitry Andric }
24698bcb0991SDimitry Andric 
2470e8d8bef9SDimitry Andric XCOFF::StorageClass
2471e8d8bef9SDimitry Andric TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) {
2472e8d8bef9SDimitry Andric   assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX.");
2473e8d8bef9SDimitry Andric 
2474e8d8bef9SDimitry Andric   switch (GV->getLinkage()) {
24758bcb0991SDimitry Andric   case GlobalValue::InternalLinkage:
2476480093f4SDimitry Andric   case GlobalValue::PrivateLinkage:
24778bcb0991SDimitry Andric     return XCOFF::C_HIDEXT;
24788bcb0991SDimitry Andric   case GlobalValue::ExternalLinkage:
24798bcb0991SDimitry Andric   case GlobalValue::CommonLinkage:
24805ffd83dbSDimitry Andric   case GlobalValue::AvailableExternallyLinkage:
24818bcb0991SDimitry Andric     return XCOFF::C_EXT;
24828bcb0991SDimitry Andric   case GlobalValue::ExternalWeakLinkage:
24835ffd83dbSDimitry Andric   case GlobalValue::LinkOnceAnyLinkage:
24845ffd83dbSDimitry Andric   case GlobalValue::LinkOnceODRLinkage:
24855ffd83dbSDimitry Andric   case GlobalValue::WeakAnyLinkage:
24865ffd83dbSDimitry Andric   case GlobalValue::WeakODRLinkage:
24878bcb0991SDimitry Andric     return XCOFF::C_WEAKEXT;
24885ffd83dbSDimitry Andric   case GlobalValue::AppendingLinkage:
24898bcb0991SDimitry Andric     report_fatal_error(
24905ffd83dbSDimitry Andric         "There is no mapping that implements AppendingLinkage for XCOFF.");
24918bcb0991SDimitry Andric   }
24925ffd83dbSDimitry Andric   llvm_unreachable("Unknown linkage type!");
24935ffd83dbSDimitry Andric }
24945ffd83dbSDimitry Andric 
24955ffd83dbSDimitry Andric MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol(
2496e8d8bef9SDimitry Andric     const GlobalValue *Func, const TargetMachine &TM) const {
2497349cc55cSDimitry Andric   assert((isa<Function>(Func) ||
2498e8d8bef9SDimitry Andric           (isa<GlobalAlias>(Func) &&
2499349cc55cSDimitry Andric            isa_and_nonnull<Function>(
2500349cc55cSDimitry Andric                cast<GlobalAlias>(Func)->getAliaseeObject()))) &&
2501e8d8bef9SDimitry Andric          "Func must be a function or an alias which has a function as base "
2502e8d8bef9SDimitry Andric          "object.");
2503e8d8bef9SDimitry Andric 
25045ffd83dbSDimitry Andric   SmallString<128> NameStr;
25055ffd83dbSDimitry Andric   NameStr.push_back('.');
2506e8d8bef9SDimitry Andric   getNameWithPrefix(NameStr, Func, TM);
2507e8d8bef9SDimitry Andric 
2508e8d8bef9SDimitry Andric   // When -function-sections is enabled and explicit section is not specified,
2509e8d8bef9SDimitry Andric   // it's not necessary to emit function entry point label any more. We will use
2510e8d8bef9SDimitry Andric   // function entry point csect instead. And for function delcarations, the
2511e8d8bef9SDimitry Andric   // undefined symbols gets treated as csect with XTY_ER property.
2512e8d8bef9SDimitry Andric   if (((TM.getFunctionSections() && !Func->hasSection()) ||
2513e8d8bef9SDimitry Andric        Func->isDeclaration()) &&
2514e8d8bef9SDimitry Andric       isa<Function>(Func)) {
2515e8d8bef9SDimitry Andric     return getContext()
2516fe6060f1SDimitry Andric         .getXCOFFSection(
2517fe6060f1SDimitry Andric             NameStr, SectionKind::getText(),
2518fe6060f1SDimitry Andric             XCOFF::CsectProperties(XCOFF::XMC_PR, Func->isDeclaration()
2519fe6060f1SDimitry Andric                                                       ? XCOFF::XTY_ER
2520fe6060f1SDimitry Andric                                                       : XCOFF::XTY_SD))
2521e8d8bef9SDimitry Andric         ->getQualNameSymbol();
2522e8d8bef9SDimitry Andric   }
2523e8d8bef9SDimitry Andric 
25245ffd83dbSDimitry Andric   return getContext().getOrCreateSymbol(NameStr);
25255ffd83dbSDimitry Andric }
25265ffd83dbSDimitry Andric 
25275ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor(
25285ffd83dbSDimitry Andric     const Function *F, const TargetMachine &TM) const {
25295ffd83dbSDimitry Andric   SmallString<128> NameStr;
25305ffd83dbSDimitry Andric   getNameWithPrefix(NameStr, F, TM);
2531fe6060f1SDimitry Andric   return getContext().getXCOFFSection(
2532fe6060f1SDimitry Andric       NameStr, SectionKind::getData(),
2533fe6060f1SDimitry Andric       XCOFF::CsectProperties(XCOFF::XMC_DS, XCOFF::XTY_SD));
25345ffd83dbSDimitry Andric }
25355ffd83dbSDimitry Andric 
25365ffd83dbSDimitry Andric MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry(
2537e8d8bef9SDimitry Andric     const MCSymbol *Sym, const TargetMachine &TM) const {
2538e8d8bef9SDimitry Andric   // Use TE storage-mapping class when large code model is enabled so that
2539e8d8bef9SDimitry Andric   // the chance of needing -bbigtoc is decreased.
25405ffd83dbSDimitry Andric   return getContext().getXCOFFSection(
2541fe6060f1SDimitry Andric       cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), SectionKind::getData(),
2542fe6060f1SDimitry Andric       XCOFF::CsectProperties(
2543e8d8bef9SDimitry Andric           TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE : XCOFF::XMC_TC,
2544fe6060f1SDimitry Andric           XCOFF::XTY_SD));
2545fe6060f1SDimitry Andric }
2546fe6060f1SDimitry Andric 
2547fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
2548fe6060f1SDimitry Andric //                                  GOFF
2549fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
255004eeddc0SDimitry Andric TargetLoweringObjectFileGOFF::TargetLoweringObjectFileGOFF() {}
2551fe6060f1SDimitry Andric 
2552fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::getExplicitSectionGlobal(
2553fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2554fe6060f1SDimitry Andric   return SelectSectionForGlobal(GO, Kind, TM);
2555fe6060f1SDimitry Andric }
2556fe6060f1SDimitry Andric 
2557fe6060f1SDimitry Andric MCSection *TargetLoweringObjectFileGOFF::SelectSectionForGlobal(
2558fe6060f1SDimitry Andric     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
2559fe6060f1SDimitry Andric   auto *Symbol = TM.getSymbol(GO);
2560fe6060f1SDimitry Andric   if (Kind.isBSS())
2561fe6060f1SDimitry Andric     return getContext().getGOFFSection(Symbol->getName(),
2562fe6060f1SDimitry Andric                                        SectionKind::getBSS());
2563fe6060f1SDimitry Andric 
2564fe6060f1SDimitry Andric   return getContext().getObjectFileInfo()->getTextSection();
25658bcb0991SDimitry Andric }
2566