1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements classes used to handle lowerings specific to common
10 // object file formats.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
15 #include "llvm/ADT/SmallString.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/BinaryFormat/COFF.h"
21 #include "llvm/BinaryFormat/Dwarf.h"
22 #include "llvm/BinaryFormat/ELF.h"
23 #include "llvm/BinaryFormat/MachO.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
26 #include "llvm/IR/Comdat.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DerivedTypes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/GlobalObject.h"
33 #include "llvm/IR/GlobalValue.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Mangler.h"
36 #include "llvm/IR/Metadata.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/MC/MCAsmInfo.h"
40 #include "llvm/MC/MCContext.h"
41 #include "llvm/MC/MCExpr.h"
42 #include "llvm/MC/MCSectionCOFF.h"
43 #include "llvm/MC/MCSectionELF.h"
44 #include "llvm/MC/MCSectionMachO.h"
45 #include "llvm/MC/MCSectionWasm.h"
46 #include "llvm/MC/MCStreamer.h"
47 #include "llvm/MC/MCSymbol.h"
48 #include "llvm/MC/MCSymbolELF.h"
49 #include "llvm/MC/MCValue.h"
50 #include "llvm/MC/SectionKind.h"
51 #include "llvm/ProfileData/InstrProf.h"
52 #include "llvm/Support/Casting.h"
53 #include "llvm/Support/CodeGen.h"
54 #include "llvm/Support/Format.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Target/TargetMachine.h"
62 using namespace dwarf
;
64 static void GetObjCImageInfo(Module
&M
, unsigned &Version
, unsigned &Flags
,
66 SmallVector
<Module::ModuleFlagEntry
, 8> ModuleFlags
;
67 M
.getModuleFlagsMetadata(ModuleFlags
);
69 for (const auto &MFE
: ModuleFlags
) {
70 // Ignore flags with 'Require' behaviour.
71 if (MFE
.Behavior
== Module::Require
)
74 StringRef Key
= MFE
.Key
->getString();
75 if (Key
== "Objective-C Image Info Version") {
76 Version
= mdconst::extract
<ConstantInt
>(MFE
.Val
)->getZExtValue();
77 } else if (Key
== "Objective-C Garbage Collection" ||
78 Key
== "Objective-C GC Only" ||
79 Key
== "Objective-C Is Simulated" ||
80 Key
== "Objective-C Class Properties" ||
81 Key
== "Objective-C Image Swift Version") {
82 Flags
|= mdconst::extract
<ConstantInt
>(MFE
.Val
)->getZExtValue();
83 } else if (Key
== "Objective-C Image Info Section") {
84 Section
= cast
<MDString
>(MFE
.Val
)->getString();
89 //===----------------------------------------------------------------------===//
91 //===----------------------------------------------------------------------===//
93 void TargetLoweringObjectFileELF::Initialize(MCContext
&Ctx
,
94 const TargetMachine
&TgtM
) {
95 TargetLoweringObjectFile::Initialize(Ctx
, TgtM
);
98 CodeModel::Model CM
= TgtM
.getCodeModel();
100 switch (TgtM
.getTargetTriple().getArch()) {
104 case Triple::thumbeb
:
105 if (Ctx
.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM
)
107 // Fallthrough if not using EHABI
111 PersonalityEncoding
= isPositionIndependent()
112 ? dwarf::DW_EH_PE_indirect
|
113 dwarf::DW_EH_PE_pcrel
|
114 dwarf::DW_EH_PE_sdata4
115 : dwarf::DW_EH_PE_absptr
;
116 LSDAEncoding
= isPositionIndependent()
117 ? dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
118 : dwarf::DW_EH_PE_absptr
;
119 TTypeEncoding
= isPositionIndependent()
120 ? dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
121 dwarf::DW_EH_PE_sdata4
122 : dwarf::DW_EH_PE_absptr
;
125 if (isPositionIndependent()) {
126 PersonalityEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
127 ((CM
== CodeModel::Small
|| CM
== CodeModel::Medium
)
128 ? dwarf::DW_EH_PE_sdata4
: dwarf::DW_EH_PE_sdata8
);
129 LSDAEncoding
= dwarf::DW_EH_PE_pcrel
|
130 (CM
== CodeModel::Small
131 ? dwarf::DW_EH_PE_sdata4
: dwarf::DW_EH_PE_sdata8
);
132 TTypeEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
133 ((CM
== CodeModel::Small
|| CM
== CodeModel::Medium
)
134 ? dwarf::DW_EH_PE_sdata8
: dwarf::DW_EH_PE_sdata4
);
136 PersonalityEncoding
=
137 (CM
== CodeModel::Small
|| CM
== CodeModel::Medium
)
138 ? dwarf::DW_EH_PE_udata4
: dwarf::DW_EH_PE_absptr
;
139 LSDAEncoding
= (CM
== CodeModel::Small
)
140 ? dwarf::DW_EH_PE_udata4
: dwarf::DW_EH_PE_absptr
;
141 TTypeEncoding
= (CM
== CodeModel::Small
)
142 ? dwarf::DW_EH_PE_udata4
: dwarf::DW_EH_PE_absptr
;
145 case Triple::hexagon
:
146 PersonalityEncoding
= dwarf::DW_EH_PE_absptr
;
147 LSDAEncoding
= dwarf::DW_EH_PE_absptr
;
148 TTypeEncoding
= dwarf::DW_EH_PE_absptr
;
149 if (isPositionIndependent()) {
150 PersonalityEncoding
|= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
;
151 LSDAEncoding
|= dwarf::DW_EH_PE_pcrel
;
152 TTypeEncoding
|= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
;
155 case Triple::aarch64
:
156 case Triple::aarch64_be
:
157 // The small model guarantees static code/data size < 4GB, but not where it
158 // will be in memory. Most of these could end up >2GB away so even a signed
159 // pc-relative 32-bit address is insufficient, theoretically.
160 if (isPositionIndependent()) {
161 PersonalityEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
162 dwarf::DW_EH_PE_sdata8
;
163 LSDAEncoding
= dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata8
;
164 TTypeEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
165 dwarf::DW_EH_PE_sdata8
;
167 PersonalityEncoding
= dwarf::DW_EH_PE_absptr
;
168 LSDAEncoding
= dwarf::DW_EH_PE_absptr
;
169 TTypeEncoding
= dwarf::DW_EH_PE_absptr
;
173 LSDAEncoding
= dwarf::DW_EH_PE_absptr
;
174 PersonalityEncoding
= dwarf::DW_EH_PE_absptr
;
175 TTypeEncoding
= dwarf::DW_EH_PE_absptr
;
180 case Triple::mips64el
:
181 // MIPS uses indirect pointer to refer personality functions and types, so
182 // that the eh_frame section can be read-only. DW.ref.personality will be
183 // generated for relocation.
184 PersonalityEncoding
= dwarf::DW_EH_PE_indirect
;
185 // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
186 // identify N64 from just a triple.
187 TTypeEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
188 dwarf::DW_EH_PE_sdata4
;
189 // We don't support PC-relative LSDA references in GAS so we use the default
190 // DW_EH_PE_absptr for those.
192 // FreeBSD must be explicit about the data size and using pcrel since it's
193 // assembler/linker won't do the automatic conversion that the Linux tools
195 if (TgtM
.getTargetTriple().isOSFreeBSD()) {
196 PersonalityEncoding
|= dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
;
197 LSDAEncoding
= dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
;
201 case Triple::ppc64le
:
202 PersonalityEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
203 dwarf::DW_EH_PE_udata8
;
204 LSDAEncoding
= dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_udata8
;
205 TTypeEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
206 dwarf::DW_EH_PE_udata8
;
208 case Triple::sparcel
:
210 if (isPositionIndependent()) {
211 LSDAEncoding
= dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
;
212 PersonalityEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
213 dwarf::DW_EH_PE_sdata4
;
214 TTypeEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
215 dwarf::DW_EH_PE_sdata4
;
217 LSDAEncoding
= dwarf::DW_EH_PE_absptr
;
218 PersonalityEncoding
= dwarf::DW_EH_PE_absptr
;
219 TTypeEncoding
= dwarf::DW_EH_PE_absptr
;
222 case Triple::sparcv9
:
223 LSDAEncoding
= dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
;
224 if (isPositionIndependent()) {
225 PersonalityEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
226 dwarf::DW_EH_PE_sdata4
;
227 TTypeEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
228 dwarf::DW_EH_PE_sdata4
;
230 PersonalityEncoding
= dwarf::DW_EH_PE_absptr
;
231 TTypeEncoding
= dwarf::DW_EH_PE_absptr
;
234 case Triple::systemz
:
235 // All currently-defined code models guarantee that 4-byte PC-relative
236 // values will be in range.
237 if (isPositionIndependent()) {
238 PersonalityEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
239 dwarf::DW_EH_PE_sdata4
;
240 LSDAEncoding
= dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
;
241 TTypeEncoding
= dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
|
242 dwarf::DW_EH_PE_sdata4
;
244 PersonalityEncoding
= dwarf::DW_EH_PE_absptr
;
245 LSDAEncoding
= dwarf::DW_EH_PE_absptr
;
246 TTypeEncoding
= dwarf::DW_EH_PE_absptr
;
254 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer
&Streamer
,
256 auto &C
= getContext();
258 if (NamedMDNode
*LinkerOptions
= M
.getNamedMetadata("llvm.linker.options")) {
259 auto *S
= C
.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS
,
262 Streamer
.SwitchSection(S
);
264 for (const auto &Operand
: LinkerOptions
->operands()) {
265 if (cast
<MDNode
>(Operand
)->getNumOperands() != 2)
266 report_fatal_error("invalid llvm.linker.options");
267 for (const auto &Option
: cast
<MDNode
>(Operand
)->operands()) {
268 Streamer
.EmitBytes(cast
<MDString
>(Option
)->getString());
269 Streamer
.EmitIntValue(0, 1);
274 unsigned Version
= 0;
278 GetObjCImageInfo(M
, Version
, Flags
, Section
);
279 if (!Section
.empty()) {
280 auto *S
= C
.getELFSection(Section
, ELF::SHT_PROGBITS
, ELF::SHF_ALLOC
);
281 Streamer
.SwitchSection(S
);
282 Streamer
.EmitLabel(C
.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
283 Streamer
.EmitIntValue(Version
, 4);
284 Streamer
.EmitIntValue(Flags
, 4);
285 Streamer
.AddBlankLine();
288 SmallVector
<Module::ModuleFlagEntry
, 8> ModuleFlags
;
289 M
.getModuleFlagsMetadata(ModuleFlags
);
291 MDNode
*CFGProfile
= nullptr;
293 for (const auto &MFE
: ModuleFlags
) {
294 StringRef Key
= MFE
.Key
->getString();
295 if (Key
== "CG Profile") {
296 CFGProfile
= cast
<MDNode
>(MFE
.Val
);
304 auto GetSym
= [this](const MDOperand
&MDO
) -> MCSymbol
* {
307 auto V
= cast
<ValueAsMetadata
>(MDO
);
308 const Function
*F
= cast
<Function
>(V
->getValue());
309 return TM
->getSymbol(F
);
312 for (const auto &Edge
: CFGProfile
->operands()) {
313 MDNode
*E
= cast
<MDNode
>(Edge
);
314 const MCSymbol
*From
= GetSym(E
->getOperand(0));
315 const MCSymbol
*To
= GetSym(E
->getOperand(1));
316 // Skip null functions. This can happen if functions are dead stripped after
317 // the CGProfile pass has been run.
320 uint64_t Count
= cast
<ConstantAsMetadata
>(E
->getOperand(2))
324 Streamer
.emitCGProfileEntry(
325 MCSymbolRefExpr::create(From
, MCSymbolRefExpr::VK_None
, C
),
326 MCSymbolRefExpr::create(To
, MCSymbolRefExpr::VK_None
, C
), Count
);
330 MCSymbol
*TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
331 const GlobalValue
*GV
, const TargetMachine
&TM
,
332 MachineModuleInfo
*MMI
) const {
333 unsigned Encoding
= getPersonalityEncoding();
334 if ((Encoding
& 0x80) == DW_EH_PE_indirect
)
335 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
336 TM
.getSymbol(GV
)->getName());
337 if ((Encoding
& 0x70) == DW_EH_PE_absptr
)
338 return TM
.getSymbol(GV
);
339 report_fatal_error("We do not support this DWARF encoding yet!");
342 void TargetLoweringObjectFileELF::emitPersonalityValue(
343 MCStreamer
&Streamer
, const DataLayout
&DL
, const MCSymbol
*Sym
) const {
344 SmallString
<64> NameData("DW.ref.");
345 NameData
+= Sym
->getName();
347 cast
<MCSymbolELF
>(getContext().getOrCreateSymbol(NameData
));
348 Streamer
.EmitSymbolAttribute(Label
, MCSA_Hidden
);
349 Streamer
.EmitSymbolAttribute(Label
, MCSA_Weak
);
350 unsigned Flags
= ELF::SHF_ALLOC
| ELF::SHF_WRITE
| ELF::SHF_GROUP
;
351 MCSection
*Sec
= getContext().getELFNamedSection(".data", Label
->getName(),
352 ELF::SHT_PROGBITS
, Flags
, 0);
353 unsigned Size
= DL
.getPointerSize();
354 Streamer
.SwitchSection(Sec
);
355 Streamer
.EmitValueToAlignment(DL
.getPointerABIAlignment(0));
356 Streamer
.EmitSymbolAttribute(Label
, MCSA_ELF_TypeObject
);
357 const MCExpr
*E
= MCConstantExpr::create(Size
, getContext());
358 Streamer
.emitELFSize(Label
, E
);
359 Streamer
.EmitLabel(Label
);
361 Streamer
.EmitSymbolValue(Sym
, Size
);
364 const MCExpr
*TargetLoweringObjectFileELF::getTTypeGlobalReference(
365 const GlobalValue
*GV
, unsigned Encoding
, const TargetMachine
&TM
,
366 MachineModuleInfo
*MMI
, MCStreamer
&Streamer
) const {
367 if (Encoding
& DW_EH_PE_indirect
) {
368 MachineModuleInfoELF
&ELFMMI
= MMI
->getObjFileInfo
<MachineModuleInfoELF
>();
370 MCSymbol
*SSym
= getSymbolWithGlobalValueBase(GV
, ".DW.stub", TM
);
372 // Add information about the stub reference to ELFMMI so that the stub
373 // gets emitted by the asmprinter.
374 MachineModuleInfoImpl::StubValueTy
&StubSym
= ELFMMI
.getGVStubEntry(SSym
);
375 if (!StubSym
.getPointer()) {
376 MCSymbol
*Sym
= TM
.getSymbol(GV
);
377 StubSym
= MachineModuleInfoImpl::StubValueTy(Sym
, !GV
->hasLocalLinkage());
380 return TargetLoweringObjectFile::
381 getTTypeReference(MCSymbolRefExpr::create(SSym
, getContext()),
382 Encoding
& ~DW_EH_PE_indirect
, Streamer
);
385 return TargetLoweringObjectFile::getTTypeGlobalReference(GV
, Encoding
, TM
,
389 static SectionKind
getELFKindForNamedSection(StringRef Name
, SectionKind K
) {
390 // N.B.: The defaults used in here are not the same ones used in MC.
391 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
392 // both gas and MC will produce a section with no flags. Given
393 // section(".eh_frame") gcc will produce:
395 // .section .eh_frame,"a",@progbits
397 if (Name
== getInstrProfSectionName(IPSK_covmap
, Triple::ELF
,
398 /*AddSegmentInfo=*/false))
399 return SectionKind::getMetadata();
401 if (Name
.empty() || Name
[0] != '.') return K
;
403 // Default implementation based on some magic section names.
404 if (Name
== ".bss" ||
405 Name
.startswith(".bss.") ||
406 Name
.startswith(".gnu.linkonce.b.") ||
407 Name
.startswith(".llvm.linkonce.b.") ||
409 Name
.startswith(".sbss.") ||
410 Name
.startswith(".gnu.linkonce.sb.") ||
411 Name
.startswith(".llvm.linkonce.sb."))
412 return SectionKind::getBSS();
414 if (Name
== ".tdata" ||
415 Name
.startswith(".tdata.") ||
416 Name
.startswith(".gnu.linkonce.td.") ||
417 Name
.startswith(".llvm.linkonce.td."))
418 return SectionKind::getThreadData();
420 if (Name
== ".tbss" ||
421 Name
.startswith(".tbss.") ||
422 Name
.startswith(".gnu.linkonce.tb.") ||
423 Name
.startswith(".llvm.linkonce.tb."))
424 return SectionKind::getThreadBSS();
429 static unsigned getELFSectionType(StringRef Name
, SectionKind K
) {
430 // Use SHT_NOTE for section whose name starts with ".note" to allow
431 // emitting ELF notes from C variable declaration.
432 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
433 if (Name
.startswith(".note"))
434 return ELF::SHT_NOTE
;
436 if (Name
== ".init_array")
437 return ELF::SHT_INIT_ARRAY
;
439 if (Name
== ".fini_array")
440 return ELF::SHT_FINI_ARRAY
;
442 if (Name
== ".preinit_array")
443 return ELF::SHT_PREINIT_ARRAY
;
445 if (K
.isBSS() || K
.isThreadBSS())
446 return ELF::SHT_NOBITS
;
448 return ELF::SHT_PROGBITS
;
451 static unsigned getELFSectionFlags(SectionKind K
) {
455 Flags
|= ELF::SHF_ALLOC
;
458 Flags
|= ELF::SHF_EXECINSTR
;
460 if (K
.isExecuteOnly())
461 Flags
|= ELF::SHF_ARM_PURECODE
;
464 Flags
|= ELF::SHF_WRITE
;
466 if (K
.isThreadLocal())
467 Flags
|= ELF::SHF_TLS
;
469 if (K
.isMergeableCString() || K
.isMergeableConst())
470 Flags
|= ELF::SHF_MERGE
;
472 if (K
.isMergeableCString())
473 Flags
|= ELF::SHF_STRINGS
;
478 static const Comdat
*getELFComdat(const GlobalValue
*GV
) {
479 const Comdat
*C
= GV
->getComdat();
483 if (C
->getSelectionKind() != Comdat::Any
)
484 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
485 C
->getName() + "' cannot be lowered.");
490 static const MCSymbolELF
*getAssociatedSymbol(const GlobalObject
*GO
,
491 const TargetMachine
&TM
) {
492 MDNode
*MD
= GO
->getMetadata(LLVMContext::MD_associated
);
496 const MDOperand
&Op
= MD
->getOperand(0);
500 auto *VM
= dyn_cast
<ValueAsMetadata
>(Op
);
502 report_fatal_error("MD_associated operand is not ValueAsMetadata");
504 GlobalObject
*OtherGO
= dyn_cast
<GlobalObject
>(VM
->getValue());
505 return OtherGO
? dyn_cast
<MCSymbolELF
>(TM
.getSymbol(OtherGO
)) : nullptr;
508 static unsigned getEntrySizeForKind(SectionKind Kind
) {
509 if (Kind
.isMergeable1ByteCString())
511 else if (Kind
.isMergeable2ByteCString())
513 else if (Kind
.isMergeable4ByteCString())
515 else if (Kind
.isMergeableConst4())
517 else if (Kind
.isMergeableConst8())
519 else if (Kind
.isMergeableConst16())
521 else if (Kind
.isMergeableConst32())
524 // We shouldn't have mergeable C strings or mergeable constants that we
525 // didn't handle above.
526 assert(!Kind
.isMergeableCString() && "unknown string width");
527 assert(!Kind
.isMergeableConst() && "unknown data width");
532 MCSection
*TargetLoweringObjectFileELF::getExplicitSectionGlobal(
533 const GlobalObject
*GO
, SectionKind Kind
, const TargetMachine
&TM
) const {
534 StringRef SectionName
= GO
->getSection();
536 // Check if '#pragma clang section' name is applicable.
537 // Note that pragma directive overrides -ffunction-section, -fdata-section
538 // and so section name is exactly as user specified and not uniqued.
539 const GlobalVariable
*GV
= dyn_cast
<GlobalVariable
>(GO
);
540 if (GV
&& GV
->hasImplicitSection()) {
541 auto Attrs
= GV
->getAttributes();
542 if (Attrs
.hasAttribute("bss-section") && Kind
.isBSS()) {
543 SectionName
= Attrs
.getAttribute("bss-section").getValueAsString();
544 } else if (Attrs
.hasAttribute("rodata-section") && Kind
.isReadOnly()) {
545 SectionName
= Attrs
.getAttribute("rodata-section").getValueAsString();
546 } else if (Attrs
.hasAttribute("data-section") && Kind
.isData()) {
547 SectionName
= Attrs
.getAttribute("data-section").getValueAsString();
550 const Function
*F
= dyn_cast
<Function
>(GO
);
551 if (F
&& F
->hasFnAttribute("implicit-section-name")) {
552 SectionName
= F
->getFnAttribute("implicit-section-name").getValueAsString();
555 // Infer section flags from the section name if we can.
556 Kind
= getELFKindForNamedSection(SectionName
, Kind
);
558 StringRef Group
= "";
559 unsigned Flags
= getELFSectionFlags(Kind
);
560 if (const Comdat
*C
= getELFComdat(GO
)) {
561 Group
= C
->getName();
562 Flags
|= ELF::SHF_GROUP
;
565 // A section can have at most one associated section. Put each global with
566 // MD_associated in a unique section.
567 unsigned UniqueID
= MCContext::GenericSectionID
;
568 const MCSymbolELF
*AssociatedSymbol
= getAssociatedSymbol(GO
, TM
);
569 if (AssociatedSymbol
) {
570 UniqueID
= NextUniqueID
++;
571 Flags
|= ELF::SHF_LINK_ORDER
;
574 MCSectionELF
*Section
= getContext().getELFSection(
575 SectionName
, getELFSectionType(SectionName
, Kind
), Flags
,
576 getEntrySizeForKind(Kind
), Group
, UniqueID
, AssociatedSymbol
);
577 // Make sure that we did not get some other section with incompatible sh_link.
578 // This should not be possible due to UniqueID code above.
579 assert(Section
->getAssociatedSymbol() == AssociatedSymbol
&&
580 "Associated symbol mismatch between sections");
584 /// Return the section prefix name used by options FunctionsSections and
586 static StringRef
getSectionPrefixForGlobal(SectionKind Kind
) {
589 if (Kind
.isReadOnly())
593 if (Kind
.isThreadData())
595 if (Kind
.isThreadBSS())
599 assert(Kind
.isReadOnlyWithRel() && "Unknown section kind");
600 return ".data.rel.ro";
603 static MCSectionELF
*selectELFSectionForGlobal(
604 MCContext
&Ctx
, const GlobalObject
*GO
, SectionKind Kind
, Mangler
&Mang
,
605 const TargetMachine
&TM
, bool EmitUniqueSection
, unsigned Flags
,
606 unsigned *NextUniqueID
, const MCSymbolELF
*AssociatedSymbol
) {
608 StringRef Group
= "";
609 if (const Comdat
*C
= getELFComdat(GO
)) {
610 Flags
|= ELF::SHF_GROUP
;
611 Group
= C
->getName();
614 // Get the section entry size based on the kind.
615 unsigned EntrySize
= getEntrySizeForKind(Kind
);
617 SmallString
<128> Name
;
618 if (Kind
.isMergeableCString()) {
619 // We also need alignment here.
620 // FIXME: this is getting the alignment of the character, not the
621 // alignment of the global!
622 unsigned Align
= GO
->getParent()->getDataLayout().getPreferredAlignment(
623 cast
<GlobalVariable
>(GO
));
625 std::string SizeSpec
= ".rodata.str" + utostr(EntrySize
) + ".";
626 Name
= SizeSpec
+ utostr(Align
);
627 } else if (Kind
.isMergeableConst()) {
628 Name
= ".rodata.cst";
629 Name
+= utostr(EntrySize
);
631 Name
= getSectionPrefixForGlobal(Kind
);
634 if (const auto *F
= dyn_cast
<Function
>(GO
)) {
635 const auto &OptionalPrefix
= F
->getSectionPrefix();
637 Name
+= *OptionalPrefix
;
640 unsigned UniqueID
= MCContext::GenericSectionID
;
641 if (EmitUniqueSection
) {
642 if (TM
.getUniqueSectionNames()) {
644 TM
.getNameWithPrefix(Name
, GO
, Mang
, true /*MayAlwaysUsePrivate*/);
646 UniqueID
= *NextUniqueID
;
650 // Use 0 as the unique ID for execute-only text.
651 if (Kind
.isExecuteOnly())
653 return Ctx
.getELFSection(Name
, getELFSectionType(Name
, Kind
), Flags
,
654 EntrySize
, Group
, UniqueID
, AssociatedSymbol
);
657 MCSection
*TargetLoweringObjectFileELF::SelectSectionForGlobal(
658 const GlobalObject
*GO
, SectionKind Kind
, const TargetMachine
&TM
) const {
659 unsigned Flags
= getELFSectionFlags(Kind
);
661 // If we have -ffunction-section or -fdata-section then we should emit the
662 // global value to a uniqued section specifically for it.
663 bool EmitUniqueSection
= false;
664 if (!(Flags
& ELF::SHF_MERGE
) && !Kind
.isCommon()) {
666 EmitUniqueSection
= TM
.getFunctionSections();
668 EmitUniqueSection
= TM
.getDataSections();
670 EmitUniqueSection
|= GO
->hasComdat();
672 const MCSymbolELF
*AssociatedSymbol
= getAssociatedSymbol(GO
, TM
);
673 if (AssociatedSymbol
) {
674 EmitUniqueSection
= true;
675 Flags
|= ELF::SHF_LINK_ORDER
;
678 MCSectionELF
*Section
= selectELFSectionForGlobal(
679 getContext(), GO
, Kind
, getMangler(), TM
, EmitUniqueSection
, Flags
,
680 &NextUniqueID
, AssociatedSymbol
);
681 assert(Section
->getAssociatedSymbol() == AssociatedSymbol
);
685 MCSection
*TargetLoweringObjectFileELF::getSectionForJumpTable(
686 const Function
&F
, const TargetMachine
&TM
) const {
687 // If the function can be removed, produce a unique section so that
688 // the table doesn't prevent the removal.
689 const Comdat
*C
= F
.getComdat();
690 bool EmitUniqueSection
= TM
.getFunctionSections() || C
;
691 if (!EmitUniqueSection
)
692 return ReadOnlySection
;
694 return selectELFSectionForGlobal(getContext(), &F
, SectionKind::getReadOnly(),
695 getMangler(), TM
, EmitUniqueSection
,
696 ELF::SHF_ALLOC
, &NextUniqueID
,
697 /* AssociatedSymbol */ nullptr);
700 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
701 bool UsesLabelDifference
, const Function
&F
) const {
702 // We can always create relative relocations, so use another section
703 // that can be marked non-executable.
707 /// Given a mergeable constant with the specified size and relocation
708 /// information, return a section that it should be placed in.
709 MCSection
*TargetLoweringObjectFileELF::getSectionForConstant(
710 const DataLayout
&DL
, SectionKind Kind
, const Constant
*C
,
711 unsigned &Align
) const {
712 if (Kind
.isMergeableConst4() && MergeableConst4Section
)
713 return MergeableConst4Section
;
714 if (Kind
.isMergeableConst8() && MergeableConst8Section
)
715 return MergeableConst8Section
;
716 if (Kind
.isMergeableConst16() && MergeableConst16Section
)
717 return MergeableConst16Section
;
718 if (Kind
.isMergeableConst32() && MergeableConst32Section
)
719 return MergeableConst32Section
;
720 if (Kind
.isReadOnly())
721 return ReadOnlySection
;
723 assert(Kind
.isReadOnlyWithRel() && "Unknown section kind");
724 return DataRelROSection
;
727 static MCSectionELF
*getStaticStructorSection(MCContext
&Ctx
, bool UseInitArray
,
728 bool IsCtor
, unsigned Priority
,
729 const MCSymbol
*KeySym
) {
732 unsigned Flags
= ELF::SHF_ALLOC
| ELF::SHF_WRITE
;
733 StringRef COMDAT
= KeySym
? KeySym
->getName() : "";
736 Flags
|= ELF::SHF_GROUP
;
740 Type
= ELF::SHT_INIT_ARRAY
;
741 Name
= ".init_array";
743 Type
= ELF::SHT_FINI_ARRAY
;
744 Name
= ".fini_array";
746 if (Priority
!= 65535) {
748 Name
+= utostr(Priority
);
751 // The default scheme is .ctor / .dtor, so we have to invert the priority
757 if (Priority
!= 65535)
758 raw_string_ostream(Name
) << format(".%05u", 65535 - Priority
);
759 Type
= ELF::SHT_PROGBITS
;
762 return Ctx
.getELFSection(Name
, Type
, Flags
, 0, COMDAT
);
765 MCSection
*TargetLoweringObjectFileELF::getStaticCtorSection(
766 unsigned Priority
, const MCSymbol
*KeySym
) const {
767 return getStaticStructorSection(getContext(), UseInitArray
, true, Priority
,
771 MCSection
*TargetLoweringObjectFileELF::getStaticDtorSection(
772 unsigned Priority
, const MCSymbol
*KeySym
) const {
773 return getStaticStructorSection(getContext(), UseInitArray
, false, Priority
,
777 const MCExpr
*TargetLoweringObjectFileELF::lowerRelativeReference(
778 const GlobalValue
*LHS
, const GlobalValue
*RHS
,
779 const TargetMachine
&TM
) const {
780 // We may only use a PLT-relative relocation to refer to unnamed_addr
782 if (!LHS
->hasGlobalUnnamedAddr() || !LHS
->getValueType()->isFunctionTy())
785 // Basic sanity checks.
786 if (LHS
->getType()->getPointerAddressSpace() != 0 ||
787 RHS
->getType()->getPointerAddressSpace() != 0 || LHS
->isThreadLocal() ||
788 RHS
->isThreadLocal())
791 return MCBinaryExpr::createSub(
792 MCSymbolRefExpr::create(TM
.getSymbol(LHS
), PLTRelativeVariantKind
,
794 MCSymbolRefExpr::create(TM
.getSymbol(RHS
), getContext()), getContext());
797 MCSection
*TargetLoweringObjectFileELF::getSectionForCommandLines() const {
798 // Use ".GCC.command.line" since this feature is to support clang's
799 // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the
801 return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS
,
802 ELF::SHF_MERGE
| ELF::SHF_STRINGS
, 1, "");
806 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_
) {
807 UseInitArray
= UseInitArray_
;
808 MCContext
&Ctx
= getContext();
810 StaticCtorSection
= Ctx
.getELFSection(".ctors", ELF::SHT_PROGBITS
,
811 ELF::SHF_ALLOC
| ELF::SHF_WRITE
);
813 StaticDtorSection
= Ctx
.getELFSection(".dtors", ELF::SHT_PROGBITS
,
814 ELF::SHF_ALLOC
| ELF::SHF_WRITE
);
818 StaticCtorSection
= Ctx
.getELFSection(".init_array", ELF::SHT_INIT_ARRAY
,
819 ELF::SHF_WRITE
| ELF::SHF_ALLOC
);
820 StaticDtorSection
= Ctx
.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY
,
821 ELF::SHF_WRITE
| ELF::SHF_ALLOC
);
824 //===----------------------------------------------------------------------===//
826 //===----------------------------------------------------------------------===//
828 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
829 : TargetLoweringObjectFile() {
830 SupportIndirectSymViaGOTPCRel
= true;
833 void TargetLoweringObjectFileMachO::Initialize(MCContext
&Ctx
,
834 const TargetMachine
&TM
) {
835 TargetLoweringObjectFile::Initialize(Ctx
, TM
);
836 if (TM
.getRelocationModel() == Reloc::Static
) {
837 StaticCtorSection
= Ctx
.getMachOSection("__TEXT", "__constructor", 0,
838 SectionKind::getData());
839 StaticDtorSection
= Ctx
.getMachOSection("__TEXT", "__destructor", 0,
840 SectionKind::getData());
842 StaticCtorSection
= Ctx
.getMachOSection("__DATA", "__mod_init_func",
843 MachO::S_MOD_INIT_FUNC_POINTERS
,
844 SectionKind::getData());
845 StaticDtorSection
= Ctx
.getMachOSection("__DATA", "__mod_term_func",
846 MachO::S_MOD_TERM_FUNC_POINTERS
,
847 SectionKind::getData());
850 PersonalityEncoding
=
851 dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
;
852 LSDAEncoding
= dwarf::DW_EH_PE_pcrel
;
854 dwarf::DW_EH_PE_indirect
| dwarf::DW_EH_PE_pcrel
| dwarf::DW_EH_PE_sdata4
;
857 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer
&Streamer
,
859 // Emit the linker options if present.
860 if (auto *LinkerOptions
= M
.getNamedMetadata("llvm.linker.options")) {
861 for (const auto &Option
: LinkerOptions
->operands()) {
862 SmallVector
<std::string
, 4> StrOptions
;
863 for (const auto &Piece
: cast
<MDNode
>(Option
)->operands())
864 StrOptions
.push_back(cast
<MDString
>(Piece
)->getString());
865 Streamer
.EmitLinkerOptions(StrOptions
);
869 unsigned VersionVal
= 0;
870 unsigned ImageInfoFlags
= 0;
871 StringRef SectionVal
;
873 GetObjCImageInfo(M
, VersionVal
, ImageInfoFlags
, SectionVal
);
875 // The section is mandatory. If we don't have it, then we don't have GC info.
876 if (SectionVal
.empty())
879 StringRef Segment
, Section
;
880 unsigned TAA
= 0, StubSize
= 0;
882 std::string ErrorCode
=
883 MCSectionMachO::ParseSectionSpecifier(SectionVal
, Segment
, Section
,
884 TAA
, TAAParsed
, StubSize
);
885 if (!ErrorCode
.empty())
886 // If invalid, report the error with report_fatal_error.
887 report_fatal_error("Invalid section specifier '" + Section
+ "': " +
891 MCSectionMachO
*S
= getContext().getMachOSection(
892 Segment
, Section
, TAA
, StubSize
, SectionKind::getData());
893 Streamer
.SwitchSection(S
);
894 Streamer
.EmitLabel(getContext().
895 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
896 Streamer
.EmitIntValue(VersionVal
, 4);
897 Streamer
.EmitIntValue(ImageInfoFlags
, 4);
898 Streamer
.AddBlankLine();
901 static void checkMachOComdat(const GlobalValue
*GV
) {
902 const Comdat
*C
= GV
->getComdat();
906 report_fatal_error("MachO doesn't support COMDATs, '" + C
->getName() +
907 "' cannot be lowered.");
910 MCSection
*TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
911 const GlobalObject
*GO
, SectionKind Kind
, const TargetMachine
&TM
) const {
912 // Parse the section specifier and create it if valid.
913 StringRef Segment
, Section
;
914 unsigned TAA
= 0, StubSize
= 0;
917 checkMachOComdat(GO
);
919 std::string ErrorCode
=
920 MCSectionMachO::ParseSectionSpecifier(GO
->getSection(), Segment
, Section
,
921 TAA
, TAAParsed
, StubSize
);
922 if (!ErrorCode
.empty()) {
923 // If invalid, report the error with report_fatal_error.
924 report_fatal_error("Global variable '" + GO
->getName() +
925 "' has an invalid section specifier '" +
926 GO
->getSection() + "': " + ErrorCode
+ ".");
931 getContext().getMachOSection(Segment
, Section
, TAA
, StubSize
, Kind
);
933 // If TAA wasn't set by ParseSectionSpecifier() above,
934 // use the value returned by getMachOSection() as a default.
936 TAA
= S
->getTypeAndAttributes();
938 // Okay, now that we got the section, verify that the TAA & StubSize agree.
939 // If the user declared multiple globals with different section flags, we need
940 // to reject it here.
941 if (S
->getTypeAndAttributes() != TAA
|| S
->getStubSize() != StubSize
) {
942 // If invalid, report the error with report_fatal_error.
943 report_fatal_error("Global variable '" + GO
->getName() +
944 "' section type or attributes does not match previous"
945 " section specifier");
951 MCSection
*TargetLoweringObjectFileMachO::SelectSectionForGlobal(
952 const GlobalObject
*GO
, SectionKind Kind
, const TargetMachine
&TM
) const {
953 checkMachOComdat(GO
);
955 // Handle thread local data.
956 if (Kind
.isThreadBSS()) return TLSBSSSection
;
957 if (Kind
.isThreadData()) return TLSDataSection
;
960 return GO
->isWeakForLinker() ? TextCoalSection
: TextSection
;
962 // If this is weak/linkonce, put this in a coalescable section, either in text
963 // or data depending on if it is writable.
964 if (GO
->isWeakForLinker()) {
965 if (Kind
.isReadOnly())
966 return ConstTextCoalSection
;
967 if (Kind
.isReadOnlyWithRel())
968 return ConstDataCoalSection
;
969 return DataCoalSection
;
972 // FIXME: Alignment check should be handled by section classifier.
973 if (Kind
.isMergeable1ByteCString() &&
974 GO
->getParent()->getDataLayout().getPreferredAlignment(
975 cast
<GlobalVariable
>(GO
)) < 32)
976 return CStringSection
;
978 // Do not put 16-bit arrays in the UString section if they have an
979 // externally visible label, this runs into issues with certain linker
981 if (Kind
.isMergeable2ByteCString() && !GO
->hasExternalLinkage() &&
982 GO
->getParent()->getDataLayout().getPreferredAlignment(
983 cast
<GlobalVariable
>(GO
)) < 32)
984 return UStringSection
;
986 // With MachO only variables whose corresponding symbol starts with 'l' or
987 // 'L' can be merged, so we only try merging GVs with private linkage.
988 if (GO
->hasPrivateLinkage() && Kind
.isMergeableConst()) {
989 if (Kind
.isMergeableConst4())
990 return FourByteConstantSection
;
991 if (Kind
.isMergeableConst8())
992 return EightByteConstantSection
;
993 if (Kind
.isMergeableConst16())
994 return SixteenByteConstantSection
;
997 // Otherwise, if it is readonly, but not something we can specially optimize,
998 // just drop it in .const.
999 if (Kind
.isReadOnly())
1000 return ReadOnlySection
;
1002 // If this is marked const, put it into a const section. But if the dynamic
1003 // linker needs to write to it, put it in the data segment.
1004 if (Kind
.isReadOnlyWithRel())
1005 return ConstDataSection
;
1007 // Put zero initialized globals with strong external linkage in the
1008 // DATA, __common section with the .zerofill directive.
1009 if (Kind
.isBSSExtern())
1010 return DataCommonSection
;
1012 // Put zero initialized globals with local linkage in __DATA,__bss directive
1013 // with the .zerofill directive (aka .lcomm).
1014 if (Kind
.isBSSLocal())
1015 return DataBSSSection
;
1017 // Otherwise, just drop the variable in the normal data section.
1021 MCSection
*TargetLoweringObjectFileMachO::getSectionForConstant(
1022 const DataLayout
&DL
, SectionKind Kind
, const Constant
*C
,
1023 unsigned &Align
) const {
1024 // If this constant requires a relocation, we have to put it in the data
1025 // segment, not in the text segment.
1026 if (Kind
.isData() || Kind
.isReadOnlyWithRel())
1027 return ConstDataSection
;
1029 if (Kind
.isMergeableConst4())
1030 return FourByteConstantSection
;
1031 if (Kind
.isMergeableConst8())
1032 return EightByteConstantSection
;
1033 if (Kind
.isMergeableConst16())
1034 return SixteenByteConstantSection
;
1035 return ReadOnlySection
; // .const
1038 const MCExpr
*TargetLoweringObjectFileMachO::getTTypeGlobalReference(
1039 const GlobalValue
*GV
, unsigned Encoding
, const TargetMachine
&TM
,
1040 MachineModuleInfo
*MMI
, MCStreamer
&Streamer
) const {
1041 // The mach-o version of this method defaults to returning a stub reference.
1043 if (Encoding
& DW_EH_PE_indirect
) {
1044 MachineModuleInfoMachO
&MachOMMI
=
1045 MMI
->getObjFileInfo
<MachineModuleInfoMachO
>();
1047 MCSymbol
*SSym
= getSymbolWithGlobalValueBase(GV
, "$non_lazy_ptr", TM
);
1049 // Add information about the stub reference to MachOMMI so that the stub
1050 // gets emitted by the asmprinter.
1051 MachineModuleInfoImpl::StubValueTy
&StubSym
= MachOMMI
.getGVStubEntry(SSym
);
1052 if (!StubSym
.getPointer()) {
1053 MCSymbol
*Sym
= TM
.getSymbol(GV
);
1054 StubSym
= MachineModuleInfoImpl::StubValueTy(Sym
, !GV
->hasLocalLinkage());
1057 return TargetLoweringObjectFile::
1058 getTTypeReference(MCSymbolRefExpr::create(SSym
, getContext()),
1059 Encoding
& ~DW_EH_PE_indirect
, Streamer
);
1062 return TargetLoweringObjectFile::getTTypeGlobalReference(GV
, Encoding
, TM
,
1066 MCSymbol
*TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
1067 const GlobalValue
*GV
, const TargetMachine
&TM
,
1068 MachineModuleInfo
*MMI
) const {
1069 // The mach-o version of this method defaults to returning a stub reference.
1070 MachineModuleInfoMachO
&MachOMMI
=
1071 MMI
->getObjFileInfo
<MachineModuleInfoMachO
>();
1073 MCSymbol
*SSym
= getSymbolWithGlobalValueBase(GV
, "$non_lazy_ptr", TM
);
1075 // Add information about the stub reference to MachOMMI so that the stub
1076 // gets emitted by the asmprinter.
1077 MachineModuleInfoImpl::StubValueTy
&StubSym
= MachOMMI
.getGVStubEntry(SSym
);
1078 if (!StubSym
.getPointer()) {
1079 MCSymbol
*Sym
= TM
.getSymbol(GV
);
1080 StubSym
= MachineModuleInfoImpl::StubValueTy(Sym
, !GV
->hasLocalLinkage());
1086 const MCExpr
*TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
1087 const MCSymbol
*Sym
, const MCValue
&MV
, int64_t Offset
,
1088 MachineModuleInfo
*MMI
, MCStreamer
&Streamer
) const {
1089 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
1090 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
1091 // through a non_lazy_ptr stub instead. One advantage is that it allows the
1092 // computation of deltas to final external symbols. Example:
1098 // .long _extgotequiv-_delta
1100 // is transformed to:
1103 // .long L_extfoo$non_lazy_ptr-(_delta+0)
1105 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
1106 // L_extfoo$non_lazy_ptr:
1107 // .indirect_symbol _extfoo
1110 // The indirect symbol table (and sections of non_lazy_symbol_pointers type)
1111 // may point to both local (same translation unit) and global (other
1112 // translation units) symbols. Example:
1114 // .section __DATA,__pointers,non_lazy_symbol_pointers
1116 // .indirect_symbol _myGlobal
1119 // .indirect_symbol _myLocal
1122 // If the symbol is local, instead of the symbol's index, the assembler
1123 // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table.
1124 // Then the linker will notice the constant in the table and will look at the
1125 // content of the symbol.
1126 MachineModuleInfoMachO
&MachOMMI
=
1127 MMI
->getObjFileInfo
<MachineModuleInfoMachO
>();
1128 MCContext
&Ctx
= getContext();
1130 // The offset must consider the original displacement from the base symbol
1131 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
1132 Offset
= -MV
.getConstant();
1133 const MCSymbol
*BaseSym
= &MV
.getSymB()->getSymbol();
1135 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
1136 // non_lazy_ptr stubs.
1137 SmallString
<128> Name
;
1138 StringRef Suffix
= "$non_lazy_ptr";
1139 Name
+= MMI
->getModule()->getDataLayout().getPrivateGlobalPrefix();
1140 Name
+= Sym
->getName();
1142 MCSymbol
*Stub
= Ctx
.getOrCreateSymbol(Name
);
1144 MachineModuleInfoImpl::StubValueTy
&StubSym
= MachOMMI
.getGVStubEntry(Stub
);
1145 if (!StubSym
.getPointer()) {
1146 bool IsIndirectLocal
= Sym
->isDefined() && !Sym
->isExternal();
1147 // With the assumption that IsIndirectLocal == GV->hasLocalLinkage().
1148 StubSym
= MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol
*>(Sym
),
1152 const MCExpr
*BSymExpr
=
1153 MCSymbolRefExpr::create(BaseSym
, MCSymbolRefExpr::VK_None
, Ctx
);
1155 MCSymbolRefExpr::create(Stub
, MCSymbolRefExpr::VK_None
, Ctx
);
1158 return MCBinaryExpr::createSub(LHS
, BSymExpr
, Ctx
);
1161 MCBinaryExpr::createAdd(BSymExpr
, MCConstantExpr::create(Offset
, Ctx
), Ctx
);
1162 return MCBinaryExpr::createSub(LHS
, RHS
, Ctx
);
1165 static bool canUsePrivateLabel(const MCAsmInfo
&AsmInfo
,
1166 const MCSection
&Section
) {
1167 if (!AsmInfo
.isSectionAtomizableBySymbols(Section
))
1170 // If it is not dead stripped, it is safe to use private labels.
1171 const MCSectionMachO
&SMO
= cast
<MCSectionMachO
>(Section
);
1172 if (SMO
.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP
))
1178 void TargetLoweringObjectFileMachO::getNameWithPrefix(
1179 SmallVectorImpl
<char> &OutName
, const GlobalValue
*GV
,
1180 const TargetMachine
&TM
) const {
1181 bool CannotUsePrivateLabel
= true;
1182 if (auto *GO
= GV
->getBaseObject()) {
1183 SectionKind GOKind
= TargetLoweringObjectFile::getKindForGlobal(GO
, TM
);
1184 const MCSection
*TheSection
= SectionForGlobal(GO
, GOKind
, TM
);
1185 CannotUsePrivateLabel
=
1186 !canUsePrivateLabel(*TM
.getMCAsmInfo(), *TheSection
);
1188 getMangler().getNameWithPrefix(OutName
, GV
, CannotUsePrivateLabel
);
1191 //===----------------------------------------------------------------------===//
1193 //===----------------------------------------------------------------------===//
1196 getCOFFSectionFlags(SectionKind K
, const TargetMachine
&TM
) {
1198 bool isThumb
= TM
.getTargetTriple().getArch() == Triple::thumb
;
1202 COFF::IMAGE_SCN_MEM_DISCARDABLE
;
1203 else if (K
.isText())
1205 COFF::IMAGE_SCN_MEM_EXECUTE
|
1206 COFF::IMAGE_SCN_MEM_READ
|
1207 COFF::IMAGE_SCN_CNT_CODE
|
1208 (isThumb
? COFF::IMAGE_SCN_MEM_16BIT
: (COFF::SectionCharacteristics
)0);
1211 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA
|
1212 COFF::IMAGE_SCN_MEM_READ
|
1213 COFF::IMAGE_SCN_MEM_WRITE
;
1214 else if (K
.isThreadLocal())
1216 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
|
1217 COFF::IMAGE_SCN_MEM_READ
|
1218 COFF::IMAGE_SCN_MEM_WRITE
;
1219 else if (K
.isReadOnly() || K
.isReadOnlyWithRel())
1221 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
|
1222 COFF::IMAGE_SCN_MEM_READ
;
1223 else if (K
.isWriteable())
1225 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
|
1226 COFF::IMAGE_SCN_MEM_READ
|
1227 COFF::IMAGE_SCN_MEM_WRITE
;
1232 static const GlobalValue
*getComdatGVForCOFF(const GlobalValue
*GV
) {
1233 const Comdat
*C
= GV
->getComdat();
1234 assert(C
&& "expected GV to have a Comdat!");
1236 StringRef ComdatGVName
= C
->getName();
1237 const GlobalValue
*ComdatGV
= GV
->getParent()->getNamedValue(ComdatGVName
);
1239 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName
+
1240 "' does not exist.");
1242 if (ComdatGV
->getComdat() != C
)
1243 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName
+
1244 "' is not a key for its COMDAT.");
1249 static int getSelectionForCOFF(const GlobalValue
*GV
) {
1250 if (const Comdat
*C
= GV
->getComdat()) {
1251 const GlobalValue
*ComdatKey
= getComdatGVForCOFF(GV
);
1252 if (const auto *GA
= dyn_cast
<GlobalAlias
>(ComdatKey
))
1253 ComdatKey
= GA
->getBaseObject();
1254 if (ComdatKey
== GV
) {
1255 switch (C
->getSelectionKind()) {
1257 return COFF::IMAGE_COMDAT_SELECT_ANY
;
1258 case Comdat::ExactMatch
:
1259 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH
;
1260 case Comdat::Largest
:
1261 return COFF::IMAGE_COMDAT_SELECT_LARGEST
;
1262 case Comdat::NoDuplicates
:
1263 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES
;
1264 case Comdat::SameSize
:
1265 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE
;
1268 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE
;
1274 MCSection
*TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
1275 const GlobalObject
*GO
, SectionKind Kind
, const TargetMachine
&TM
) const {
1277 unsigned Characteristics
= getCOFFSectionFlags(Kind
, TM
);
1278 StringRef Name
= GO
->getSection();
1279 StringRef COMDATSymName
= "";
1280 if (GO
->hasComdat()) {
1281 Selection
= getSelectionForCOFF(GO
);
1282 const GlobalValue
*ComdatGV
;
1283 if (Selection
== COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE
)
1284 ComdatGV
= getComdatGVForCOFF(GO
);
1288 if (!ComdatGV
->hasPrivateLinkage()) {
1289 MCSymbol
*Sym
= TM
.getSymbol(ComdatGV
);
1290 COMDATSymName
= Sym
->getName();
1291 Characteristics
|= COFF::IMAGE_SCN_LNK_COMDAT
;
1297 return getContext().getCOFFSection(Name
, Characteristics
, Kind
, COMDATSymName
,
1301 static StringRef
getCOFFSectionNameForUniqueGlobal(SectionKind Kind
) {
1306 if (Kind
.isThreadLocal())
1308 if (Kind
.isReadOnly() || Kind
.isReadOnlyWithRel())
1313 MCSection
*TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
1314 const GlobalObject
*GO
, SectionKind Kind
, const TargetMachine
&TM
) const {
1315 // If we have -ffunction-sections then we should emit the global value to a
1316 // uniqued section specifically for it.
1317 bool EmitUniquedSection
;
1319 EmitUniquedSection
= TM
.getFunctionSections();
1321 EmitUniquedSection
= TM
.getDataSections();
1323 if ((EmitUniquedSection
&& !Kind
.isCommon()) || GO
->hasComdat()) {
1324 SmallString
<256> Name
= getCOFFSectionNameForUniqueGlobal(Kind
);
1326 unsigned Characteristics
= getCOFFSectionFlags(Kind
, TM
);
1328 Characteristics
|= COFF::IMAGE_SCN_LNK_COMDAT
;
1329 int Selection
= getSelectionForCOFF(GO
);
1331 Selection
= COFF::IMAGE_COMDAT_SELECT_NODUPLICATES
;
1332 const GlobalValue
*ComdatGV
;
1333 if (GO
->hasComdat())
1334 ComdatGV
= getComdatGVForCOFF(GO
);
1338 unsigned UniqueID
= MCContext::GenericSectionID
;
1339 if (EmitUniquedSection
)
1340 UniqueID
= NextUniqueID
++;
1342 if (!ComdatGV
->hasPrivateLinkage()) {
1343 MCSymbol
*Sym
= TM
.getSymbol(ComdatGV
);
1344 StringRef COMDATSymName
= Sym
->getName();
1346 // Append "$symbol" to the section name *before* IR-level mangling is
1347 // applied when targetting mingw. This is what GCC does, and the ld.bfd
1348 // COFF linker will not properly handle comdats otherwise.
1349 if (getTargetTriple().isWindowsGNUEnvironment())
1350 raw_svector_ostream(Name
) << '$' << ComdatGV
->getName();
1352 return getContext().getCOFFSection(Name
, Characteristics
, Kind
,
1353 COMDATSymName
, Selection
, UniqueID
);
1355 SmallString
<256> TmpData
;
1356 getMangler().getNameWithPrefix(TmpData
, GO
, /*CannotUsePrivateLabel=*/true);
1357 return getContext().getCOFFSection(Name
, Characteristics
, Kind
, TmpData
,
1358 Selection
, UniqueID
);
1365 if (Kind
.isThreadLocal())
1366 return TLSDataSection
;
1368 if (Kind
.isReadOnly() || Kind
.isReadOnlyWithRel())
1369 return ReadOnlySection
;
1371 // Note: we claim that common symbols are put in BSSSection, but they are
1372 // really emitted with the magic .comm directive, which creates a symbol table
1373 // entry but not a section.
1374 if (Kind
.isBSS() || Kind
.isCommon())
1380 void TargetLoweringObjectFileCOFF::getNameWithPrefix(
1381 SmallVectorImpl
<char> &OutName
, const GlobalValue
*GV
,
1382 const TargetMachine
&TM
) const {
1383 bool CannotUsePrivateLabel
= false;
1384 if (GV
->hasPrivateLinkage() &&
1385 ((isa
<Function
>(GV
) && TM
.getFunctionSections()) ||
1386 (isa
<GlobalVariable
>(GV
) && TM
.getDataSections())))
1387 CannotUsePrivateLabel
= true;
1389 getMangler().getNameWithPrefix(OutName
, GV
, CannotUsePrivateLabel
);
1392 MCSection
*TargetLoweringObjectFileCOFF::getSectionForJumpTable(
1393 const Function
&F
, const TargetMachine
&TM
) const {
1394 // If the function can be removed, produce a unique section so that
1395 // the table doesn't prevent the removal.
1396 const Comdat
*C
= F
.getComdat();
1397 bool EmitUniqueSection
= TM
.getFunctionSections() || C
;
1398 if (!EmitUniqueSection
)
1399 return ReadOnlySection
;
1401 // FIXME: we should produce a symbol for F instead.
1402 if (F
.hasPrivateLinkage())
1403 return ReadOnlySection
;
1405 MCSymbol
*Sym
= TM
.getSymbol(&F
);
1406 StringRef COMDATSymName
= Sym
->getName();
1408 SectionKind Kind
= SectionKind::getReadOnly();
1409 StringRef SecName
= getCOFFSectionNameForUniqueGlobal(Kind
);
1410 unsigned Characteristics
= getCOFFSectionFlags(Kind
, TM
);
1411 Characteristics
|= COFF::IMAGE_SCN_LNK_COMDAT
;
1412 unsigned UniqueID
= NextUniqueID
++;
1414 return getContext().getCOFFSection(
1415 SecName
, Characteristics
, Kind
, COMDATSymName
,
1416 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE
, UniqueID
);
1419 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer
&Streamer
,
1421 if (NamedMDNode
*LinkerOptions
= M
.getNamedMetadata("llvm.linker.options")) {
1422 // Emit the linker options to the linker .drectve section. According to the
1423 // spec, this section is a space-separated string containing flags for
1425 MCSection
*Sec
= getDrectveSection();
1426 Streamer
.SwitchSection(Sec
);
1427 for (const auto &Option
: LinkerOptions
->operands()) {
1428 for (const auto &Piece
: cast
<MDNode
>(Option
)->operands()) {
1429 // Lead with a space for consistency with our dllexport implementation.
1430 std::string
Directive(" ");
1431 Directive
.append(cast
<MDString
>(Piece
)->getString());
1432 Streamer
.EmitBytes(Directive
);
1437 unsigned Version
= 0;
1441 GetObjCImageInfo(M
, Version
, Flags
, Section
);
1442 if (Section
.empty())
1445 auto &C
= getContext();
1446 auto *S
= C
.getCOFFSection(
1447 Section
, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
| COFF::IMAGE_SCN_MEM_READ
,
1448 SectionKind::getReadOnly());
1449 Streamer
.SwitchSection(S
);
1450 Streamer
.EmitLabel(C
.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1451 Streamer
.EmitIntValue(Version
, 4);
1452 Streamer
.EmitIntValue(Flags
, 4);
1453 Streamer
.AddBlankLine();
1456 void TargetLoweringObjectFileCOFF::Initialize(MCContext
&Ctx
,
1457 const TargetMachine
&TM
) {
1458 TargetLoweringObjectFile::Initialize(Ctx
, TM
);
1459 const Triple
&T
= TM
.getTargetTriple();
1460 if (T
.isKnownWindowsMSVCEnvironment() || T
.isWindowsItaniumEnvironment()) {
1462 Ctx
.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
|
1463 COFF::IMAGE_SCN_MEM_READ
,
1464 SectionKind::getReadOnly());
1466 Ctx
.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
|
1467 COFF::IMAGE_SCN_MEM_READ
,
1468 SectionKind::getReadOnly());
1470 StaticCtorSection
= Ctx
.getCOFFSection(
1471 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
|
1472 COFF::IMAGE_SCN_MEM_READ
| COFF::IMAGE_SCN_MEM_WRITE
,
1473 SectionKind::getData());
1474 StaticDtorSection
= Ctx
.getCOFFSection(
1475 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
|
1476 COFF::IMAGE_SCN_MEM_READ
| COFF::IMAGE_SCN_MEM_WRITE
,
1477 SectionKind::getData());
1481 static MCSectionCOFF
*getCOFFStaticStructorSection(MCContext
&Ctx
,
1482 const Triple
&T
, bool IsCtor
,
1484 const MCSymbol
*KeySym
,
1485 MCSectionCOFF
*Default
) {
1486 if (T
.isKnownWindowsMSVCEnvironment() || T
.isWindowsItaniumEnvironment()) {
1487 // If the priority is the default, use .CRT$XCU, possibly associative.
1488 if (Priority
== 65535)
1489 return Ctx
.getAssociativeCOFFSection(Default
, KeySym
, 0);
1491 // Otherwise, we need to compute a new section name. Low priorities should
1492 // run earlier. The linker will sort sections ASCII-betically, and we need a
1493 // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we
1494 // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really
1495 // low priorities need to sort before 'L', since the CRT uses that
1496 // internally, so we use ".CRT$XCA00001" for them.
1497 SmallString
<24> Name
;
1498 raw_svector_ostream
OS(Name
);
1499 OS
<< ".CRT$XC" << (Priority
< 200 ? 'A' : 'T') << format("%05u", Priority
);
1500 MCSectionCOFF
*Sec
= Ctx
.getCOFFSection(
1501 Name
, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
| COFF::IMAGE_SCN_MEM_READ
,
1502 SectionKind::getReadOnly());
1503 return Ctx
.getAssociativeCOFFSection(Sec
, KeySym
, 0);
1506 std::string Name
= IsCtor
? ".ctors" : ".dtors";
1507 if (Priority
!= 65535)
1508 raw_string_ostream(Name
) << format(".%05u", 65535 - Priority
);
1510 return Ctx
.getAssociativeCOFFSection(
1511 Ctx
.getCOFFSection(Name
, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
|
1512 COFF::IMAGE_SCN_MEM_READ
|
1513 COFF::IMAGE_SCN_MEM_WRITE
,
1514 SectionKind::getData()),
1518 MCSection
*TargetLoweringObjectFileCOFF::getStaticCtorSection(
1519 unsigned Priority
, const MCSymbol
*KeySym
) const {
1520 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
1522 cast
<MCSectionCOFF
>(StaticCtorSection
));
1525 MCSection
*TargetLoweringObjectFileCOFF::getStaticDtorSection(
1526 unsigned Priority
, const MCSymbol
*KeySym
) const {
1527 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
1529 cast
<MCSectionCOFF
>(StaticDtorSection
));
1532 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1533 raw_ostream
&OS
, const GlobalValue
*GV
) const {
1534 emitLinkerFlagsForGlobalCOFF(OS
, GV
, getTargetTriple(), getMangler());
1537 void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
1538 raw_ostream
&OS
, const GlobalValue
*GV
) const {
1539 emitLinkerFlagsForUsedCOFF(OS
, GV
, getTargetTriple(), getMangler());
1542 const MCExpr
*TargetLoweringObjectFileCOFF::lowerRelativeReference(
1543 const GlobalValue
*LHS
, const GlobalValue
*RHS
,
1544 const TargetMachine
&TM
) const {
1545 const Triple
&T
= TM
.getTargetTriple();
1546 if (!T
.isKnownWindowsMSVCEnvironment() &&
1547 !T
.isWindowsItaniumEnvironment() &&
1548 !T
.isWindowsCoreCLREnvironment())
1551 // Our symbols should exist in address space zero, cowardly no-op if
1553 if (LHS
->getType()->getPointerAddressSpace() != 0 ||
1554 RHS
->getType()->getPointerAddressSpace() != 0)
1557 // Both ptrtoint instructions must wrap global objects:
1558 // - Only global variables are eligible for image relative relocations.
1559 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
1560 // We expect __ImageBase to be a global variable without a section, externally
1563 // It should look something like this: @__ImageBase = external constant i8
1564 if (!isa
<GlobalObject
>(LHS
) || !isa
<GlobalVariable
>(RHS
) ||
1565 LHS
->isThreadLocal() || RHS
->isThreadLocal() ||
1566 RHS
->getName() != "__ImageBase" || !RHS
->hasExternalLinkage() ||
1567 cast
<GlobalVariable
>(RHS
)->hasInitializer() || RHS
->hasSection())
1570 return MCSymbolRefExpr::create(TM
.getSymbol(LHS
),
1571 MCSymbolRefExpr::VK_COFF_IMGREL32
,
1575 static std::string
APIntToHexString(const APInt
&AI
) {
1576 unsigned Width
= (AI
.getBitWidth() / 8) * 2;
1577 std::string HexString
= utohexstr(AI
.getLimitedValue(), /*LowerCase=*/true);
1578 unsigned Size
= HexString
.size();
1579 assert(Width
>= Size
&& "hex string is too large!");
1580 HexString
.insert(HexString
.begin(), Width
- Size
, '0');
1585 static std::string
scalarConstantToHexString(const Constant
*C
) {
1586 Type
*Ty
= C
->getType();
1587 if (isa
<UndefValue
>(C
)) {
1588 return APIntToHexString(APInt::getNullValue(Ty
->getPrimitiveSizeInBits()));
1589 } else if (const auto *CFP
= dyn_cast
<ConstantFP
>(C
)) {
1590 return APIntToHexString(CFP
->getValueAPF().bitcastToAPInt());
1591 } else if (const auto *CI
= dyn_cast
<ConstantInt
>(C
)) {
1592 return APIntToHexString(CI
->getValue());
1594 unsigned NumElements
;
1595 if (isa
<VectorType
>(Ty
))
1596 NumElements
= Ty
->getVectorNumElements();
1598 NumElements
= Ty
->getArrayNumElements();
1599 std::string HexString
;
1600 for (int I
= NumElements
- 1, E
= -1; I
!= E
; --I
)
1601 HexString
+= scalarConstantToHexString(C
->getAggregateElement(I
));
1606 MCSection
*TargetLoweringObjectFileCOFF::getSectionForConstant(
1607 const DataLayout
&DL
, SectionKind Kind
, const Constant
*C
,
1608 unsigned &Align
) const {
1609 if (Kind
.isMergeableConst() && C
&&
1610 getContext().getAsmInfo()->hasCOFFComdatConstants()) {
1611 // This creates comdat sections with the given symbol name, but unless
1612 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol
1613 // will be created with a null storage class, which makes GNU binutils
1615 const unsigned Characteristics
= COFF::IMAGE_SCN_CNT_INITIALIZED_DATA
|
1616 COFF::IMAGE_SCN_MEM_READ
|
1617 COFF::IMAGE_SCN_LNK_COMDAT
;
1618 std::string COMDATSymName
;
1619 if (Kind
.isMergeableConst4()) {
1621 COMDATSymName
= "__real@" + scalarConstantToHexString(C
);
1624 } else if (Kind
.isMergeableConst8()) {
1626 COMDATSymName
= "__real@" + scalarConstantToHexString(C
);
1629 } else if (Kind
.isMergeableConst16()) {
1630 // FIXME: These may not be appropriate for non-x86 architectures.
1632 COMDATSymName
= "__xmm@" + scalarConstantToHexString(C
);
1635 } else if (Kind
.isMergeableConst32()) {
1637 COMDATSymName
= "__ymm@" + scalarConstantToHexString(C
);
1642 if (!COMDATSymName
.empty())
1643 return getContext().getCOFFSection(".rdata", Characteristics
, Kind
,
1645 COFF::IMAGE_COMDAT_SELECT_ANY
);
1648 return TargetLoweringObjectFile::getSectionForConstant(DL
, Kind
, C
, Align
);
1652 //===----------------------------------------------------------------------===//
1654 //===----------------------------------------------------------------------===//
1656 static const Comdat
*getWasmComdat(const GlobalValue
*GV
) {
1657 const Comdat
*C
= GV
->getComdat();
1661 if (C
->getSelectionKind() != Comdat::Any
)
1662 report_fatal_error("WebAssembly COMDATs only support "
1663 "SelectionKind::Any, '" + C
->getName() + "' cannot be "
1669 static SectionKind
getWasmKindForNamedSection(StringRef Name
, SectionKind K
) {
1670 // If we're told we have function data, then use that.
1672 return SectionKind::getText();
1674 // Otherwise, ignore whatever section type the generic impl detected and use
1675 // a plain data section.
1676 return SectionKind::getData();
1679 MCSection
*TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1680 const GlobalObject
*GO
, SectionKind Kind
, const TargetMachine
&TM
) const {
1681 // We don't support explict section names for functions in the wasm object
1682 // format. Each function has to be in its own unique section.
1683 if (isa
<Function
>(GO
)) {
1684 return SelectSectionForGlobal(GO
, Kind
, TM
);
1687 StringRef Name
= GO
->getSection();
1689 Kind
= getWasmKindForNamedSection(Name
, Kind
);
1691 StringRef Group
= "";
1692 if (const Comdat
*C
= getWasmComdat(GO
)) {
1693 Group
= C
->getName();
1696 return getContext().getWasmSection(Name
, Kind
, Group
,
1697 MCContext::GenericSectionID
);
1700 static MCSectionWasm
*selectWasmSectionForGlobal(
1701 MCContext
&Ctx
, const GlobalObject
*GO
, SectionKind Kind
, Mangler
&Mang
,
1702 const TargetMachine
&TM
, bool EmitUniqueSection
, unsigned *NextUniqueID
) {
1703 StringRef Group
= "";
1704 if (const Comdat
*C
= getWasmComdat(GO
)) {
1705 Group
= C
->getName();
1708 bool UniqueSectionNames
= TM
.getUniqueSectionNames();
1709 SmallString
<128> Name
= getSectionPrefixForGlobal(Kind
);
1711 if (const auto *F
= dyn_cast
<Function
>(GO
)) {
1712 const auto &OptionalPrefix
= F
->getSectionPrefix();
1714 Name
+= *OptionalPrefix
;
1717 if (EmitUniqueSection
&& UniqueSectionNames
) {
1718 Name
.push_back('.');
1719 TM
.getNameWithPrefix(Name
, GO
, Mang
, true);
1721 unsigned UniqueID
= MCContext::GenericSectionID
;
1722 if (EmitUniqueSection
&& !UniqueSectionNames
) {
1723 UniqueID
= *NextUniqueID
;
1726 return Ctx
.getWasmSection(Name
, Kind
, Group
, UniqueID
);
1729 MCSection
*TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1730 const GlobalObject
*GO
, SectionKind Kind
, const TargetMachine
&TM
) const {
1732 if (Kind
.isCommon())
1733 report_fatal_error("mergable sections not supported yet on wasm");
1735 // If we have -ffunction-section or -fdata-section then we should emit the
1736 // global value to a uniqued section specifically for it.
1737 bool EmitUniqueSection
= false;
1739 EmitUniqueSection
= TM
.getFunctionSections();
1741 EmitUniqueSection
= TM
.getDataSections();
1742 EmitUniqueSection
|= GO
->hasComdat();
1744 return selectWasmSectionForGlobal(getContext(), GO
, Kind
, getMangler(), TM
,
1745 EmitUniqueSection
, &NextUniqueID
);
1748 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1749 bool UsesLabelDifference
, const Function
&F
) const {
1750 // We can always create relative relocations, so use another section
1751 // that can be marked non-executable.
1755 const MCExpr
*TargetLoweringObjectFileWasm::lowerRelativeReference(
1756 const GlobalValue
*LHS
, const GlobalValue
*RHS
,
1757 const TargetMachine
&TM
) const {
1758 // We may only use a PLT-relative relocation to refer to unnamed_addr
1760 if (!LHS
->hasGlobalUnnamedAddr() || !LHS
->getValueType()->isFunctionTy())
1763 // Basic sanity checks.
1764 if (LHS
->getType()->getPointerAddressSpace() != 0 ||
1765 RHS
->getType()->getPointerAddressSpace() != 0 || LHS
->isThreadLocal() ||
1766 RHS
->isThreadLocal())
1769 return MCBinaryExpr::createSub(
1770 MCSymbolRefExpr::create(TM
.getSymbol(LHS
), MCSymbolRefExpr::VK_None
,
1772 MCSymbolRefExpr::create(TM
.getSymbol(RHS
), getContext()), getContext());
1775 void TargetLoweringObjectFileWasm::InitializeWasm() {
1777 getContext().getWasmSection(".init_array", SectionKind::getData());
1779 // We don't use PersonalityEncoding and LSDAEncoding because we don't emit
1780 // .cfi directives. We use TTypeEncoding to encode typeinfo global variables.
1781 TTypeEncoding
= dwarf::DW_EH_PE_absptr
;
1784 MCSection
*TargetLoweringObjectFileWasm::getStaticCtorSection(
1785 unsigned Priority
, const MCSymbol
*KeySym
) const {
1786 return Priority
== UINT16_MAX
?
1788 getContext().getWasmSection(".init_array." + utostr(Priority
),
1789 SectionKind::getData());
1792 MCSection
*TargetLoweringObjectFileWasm::getStaticDtorSection(
1793 unsigned Priority
, const MCSymbol
*KeySym
) const {
1794 llvm_unreachable("@llvm.global_dtors should have been lowered already");