blob: e45cdee43680a3e91a8a2526d62c47de3e82f463 [file] [log] [blame]
Eugene Zelenkofa912a72017-02-27 22:45:06 +00001//===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements classes used to handle lowerings specific to common
11// object file formats.
12//
13//===----------------------------------------------------------------------===//
14
Chandler Carruth6bda14b2017-06-06 11:49:48 +000015#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SmallString.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000017#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000018#include "llvm/ADT/StringExtras.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000019#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000020#include "llvm/ADT/Triple.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/COFF.h"
22#include "llvm/BinaryFormat/Dwarf.h"
23#include "llvm/BinaryFormat/ELF.h"
24#include "llvm/BinaryFormat/MachO.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000025#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/CodeGen/MachineModuleInfoImpls.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000027#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000032#include "llvm/IR/GlobalAlias.h"
33#include "llvm/IR/GlobalObject.h"
34#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000035#include "llvm/IR/GlobalVariable.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000036#include "llvm/IR/Mangler.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000037#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000038#include "llvm/IR/Module.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000039#include "llvm/IR/Type.h"
Peter Collingbourne94d77862015-11-03 23:40:03 +000040#include "llvm/MC/MCAsmInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000041#include "llvm/MC/MCContext.h"
42#include "llvm/MC/MCExpr.h"
Chris Lattner87cffa92010-05-07 17:17:41 +000043#include "llvm/MC/MCSectionCOFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000044#include "llvm/MC/MCSectionELF.h"
45#include "llvm/MC/MCSectionMachO.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000046#include "llvm/MC/MCSectionWasm.h"
Rafael Espindolaa83b1772011-04-16 03:51:21 +000047#include "llvm/MC/MCStreamer.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000048#include "llvm/MC/MCSymbol.h"
Rafael Espindolaa8695762015-06-02 00:25:12 +000049#include "llvm/MC/MCSymbolELF.h"
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +000050#include "llvm/MC/MCValue.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000051#include "llvm/MC/SectionKind.h"
Xinliang David Li5f04f922016-01-14 18:09:45 +000052#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000053#include "llvm/Support/Casting.h"
54#include "llvm/Support/CodeGen.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000055#include "llvm/Support/ErrorHandling.h"
56#include "llvm/Support/raw_ostream.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000057#include "llvm/Target/TargetMachine.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000058#include <cassert>
59#include <string>
60
Anton Korobeynikovab663a02010-02-15 22:37:53 +000061using namespace llvm;
Anton Korobeynikov31a92122010-02-21 20:28:15 +000062using namespace dwarf;
Anton Korobeynikovab663a02010-02-15 22:37:53 +000063
Peter Collingbourne89061b22017-06-12 20:10:48 +000064static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
Saleem Abdulrasool4c474342017-06-05 21:26:39 +000065 StringRef &Section) {
Peter Collingbourne89061b22017-06-12 20:10:48 +000066 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
67 M.getModuleFlagsMetadata(ModuleFlags);
68
Saleem Abdulrasool4c474342017-06-05 21:26:39 +000069 for (const auto &MFE: ModuleFlags) {
70 // Ignore flags with 'Require' behaviour.
71 if (MFE.Behavior == Module::Require)
72 continue;
73
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();
85 }
86 }
87}
88
Anton Korobeynikovab663a02010-02-15 22:37:53 +000089//===----------------------------------------------------------------------===//
90// ELF
91//===----------------------------------------------------------------------===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +000092
Peter Collingbourne89061b22017-06-12 20:10:48 +000093void TargetLoweringObjectFileELF::emitModuleMetadata(
94 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
Saleem Abdulrasool4c474342017-06-05 21:26:39 +000095 unsigned Version = 0;
96 unsigned Flags = 0;
97 StringRef Section;
98
Peter Collingbourne89061b22017-06-12 20:10:48 +000099 GetObjCImageInfo(M, Version, Flags, Section);
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000100 if (Section.empty())
101 return;
102
103 auto &C = getContext();
104 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
105 Streamer.SwitchSection(S);
106 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
107 Streamer.EmitIntValue(Version, 4);
108 Streamer.EmitIntValue(Flags, 4);
109 Streamer.AddBlankLine();
110}
111
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000112MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000113 const GlobalValue *GV, const TargetMachine &TM,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000114 MachineModuleInfo *MMI) const {
Rafael Espindolace83fc32011-04-27 23:17:57 +0000115 unsigned Encoding = getPersonalityEncoding();
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000116 if ((Encoding & 0x80) == DW_EH_PE_indirect)
Jim Grosbach6f482002015-05-18 18:43:14 +0000117 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
Tim Northoverb64fb452016-11-22 16:17:20 +0000118 TM.getSymbol(GV)->getName());
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000119 if ((Encoding & 0x70) == DW_EH_PE_absptr)
Tim Northoverb64fb452016-11-22 16:17:20 +0000120 return TM.getSymbol(GV);
Logan Chienc0029812014-05-30 16:48:56 +0000121 report_fatal_error("We do not support this DWARF encoding yet!");
Rafael Espindolaa83b1772011-04-16 03:51:21 +0000122}
123
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000124void TargetLoweringObjectFileELF::emitPersonalityValue(
125 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +0000126 SmallString<64> NameData("DW.ref.");
127 NameData += Sym->getName();
Rafael Espindolaa8695762015-06-02 00:25:12 +0000128 MCSymbolELF *Label =
129 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
Rafael Espindola39897762011-04-27 21:29:52 +0000130 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
131 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola39897762011-04-27 21:29:52 +0000132 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
Eric Christopher36e601c2016-07-01 06:07:38 +0000133 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
134 ELF::SHT_PROGBITS, Flags, 0);
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000135 unsigned Size = DL.getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +0000136 Streamer.SwitchSection(Sec);
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000137 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +0000138 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
Jim Grosbach13760bd2015-05-30 01:25:56 +0000139 const MCExpr *E = MCConstantExpr::create(Size, getContext());
Rafael Espindolaa8695762015-06-02 00:25:12 +0000140 Streamer.emitELFSize(Label, E);
Rafael Espindola39897762011-04-27 21:29:52 +0000141 Streamer.EmitLabel(Label);
Rafael Espindolaa83b1772011-04-16 03:51:21 +0000142
Rafael Espindola39897762011-04-27 21:29:52 +0000143 Streamer.EmitSymbolValue(Sym, Size);
Rafael Espindolaa83b1772011-04-16 03:51:21 +0000144}
145
Rafael Espindola15b26692014-02-09 14:50:44 +0000146const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000147 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
148 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000149 if (Encoding & DW_EH_PE_indirect) {
Anton Korobeynikove42af362012-11-14 01:47:00 +0000150 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
151
Eric Christopher4367c7f2016-09-16 07:33:15 +0000152 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000153
154 // Add information about the stub reference to ELFMMI so that the stub
155 // gets emitted by the asmprinter.
Anton Korobeynikove42af362012-11-14 01:47:00 +0000156 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000157 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000158 MCSymbol *Sym = TM.getSymbol(GV);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000159 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
160 }
161
162 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000163 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000164 Encoding & ~DW_EH_PE_indirect, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000165 }
166
Eric Christopher4367c7f2016-09-16 07:33:15 +0000167 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
168 MMI, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000169}
170
Sam Clegg12fd3da2017-10-20 21:28:38 +0000171static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
Rafael Espindola0d018b12011-05-24 03:10:31 +0000172 // N.B.: The defaults used in here are no the same ones used in MC.
173 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
174 // both gas and MC will produce a section with no flags. Given
Bill Wendlingd1634052012-07-19 00:04:14 +0000175 // section(".eh_frame") gcc will produce:
176 //
177 // .section .eh_frame,"a",@progbits
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000178
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000179 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
180 /*AddSegmentInfo=*/false))
Xinliang David Li5f04f922016-01-14 18:09:45 +0000181 return SectionKind::getMetadata();
182
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000183 if (Name.empty() || Name[0] != '.') return K;
184
185 // Some lame default implementation based on some magic section names.
186 if (Name == ".bss" ||
187 Name.startswith(".bss.") ||
188 Name.startswith(".gnu.linkonce.b.") ||
189 Name.startswith(".llvm.linkonce.b.") ||
190 Name == ".sbss" ||
191 Name.startswith(".sbss.") ||
192 Name.startswith(".gnu.linkonce.sb.") ||
193 Name.startswith(".llvm.linkonce.sb."))
194 return SectionKind::getBSS();
195
196 if (Name == ".tdata" ||
197 Name.startswith(".tdata.") ||
198 Name.startswith(".gnu.linkonce.td.") ||
199 Name.startswith(".llvm.linkonce.td."))
200 return SectionKind::getThreadData();
201
202 if (Name == ".tbss" ||
203 Name.startswith(".tbss.") ||
204 Name.startswith(".gnu.linkonce.tb.") ||
205 Name.startswith(".llvm.linkonce.tb."))
206 return SectionKind::getThreadBSS();
207
208 return K;
209}
210
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000211static unsigned getELFSectionType(StringRef Name, SectionKind K) {
Petr Hosek12903552016-09-20 20:21:13 +0000212 // Use SHT_NOTE for section whose name starts with ".note" to allow
213 // emitting ELF notes from C variable declaration.
214 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
215 if (Name.startswith(".note"))
216 return ELF::SHT_NOTE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000217
218 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000219 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000220
221 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000222 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000223
224 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000225 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000226
227 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000228 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000229
Rafael Espindolaaea49582011-01-23 04:28:49 +0000230 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000231}
232
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000233static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000234 unsigned Flags = 0;
235
236 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000237 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000238
239 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000240 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000241
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000242 if (K.isExecuteOnly())
243 Flags |= ELF::SHF_ARM_PURECODE;
244
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000245 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000246 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000247
248 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000249 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000250
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000251 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000252 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000253
254 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000255 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000256
257 return Flags;
258}
259
David Majnemerdad0a642014-06-27 18:19:56 +0000260static const Comdat *getELFComdat(const GlobalValue *GV) {
261 const Comdat *C = GV->getComdat();
262 if (!C)
263 return nullptr;
264
265 if (C->getSelectionKind() != Comdat::Any)
266 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
267 C->getName() + "' cannot be lowered.");
268
269 return C;
270}
271
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000272static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
273 const TargetMachine &TM) {
274 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
275 if (!MD)
276 return nullptr;
277
Evgeniy Stepanovf7e8acf2017-05-08 23:46:20 +0000278 const MDOperand &Op = MD->getOperand(0);
279 if (!Op.get())
280 return nullptr;
281
282 auto *VM = dyn_cast<ValueAsMetadata>(Op);
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000283 if (!VM)
284 report_fatal_error("MD_associated operand is not ValueAsMetadata");
285
286 GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
287 return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
288}
289
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000290MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000291 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
292 StringRef SectionName = GO->getSection();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000293
Javed Absarb16d1462017-06-05 10:09:13 +0000294 // Check if '#pragma clang section' name is applicable.
295 // Note that pragma directive overrides -ffunction-section, -fdata-section
296 // and so section name is exactly as user specified and not uniqued.
297 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
298 if (GV && GV->hasImplicitSection()) {
299 auto Attrs = GV->getAttributes();
300 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
301 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
302 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
303 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
304 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
305 SectionName = Attrs.getAttribute("data-section").getValueAsString();
306 }
307 }
308 const Function *F = dyn_cast<Function>(GO);
309 if (F && F->hasFnAttribute("implicit-section-name")) {
310 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
311 }
312
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000313 // Infer section flags from the section name if we can.
314 Kind = getELFKindForNamedSection(SectionName, Kind);
315
David Majnemerdad0a642014-06-27 18:19:56 +0000316 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000317 unsigned Flags = getELFSectionFlags(Kind);
Peter Collingbourne67335642016-10-24 19:23:39 +0000318 if (const Comdat *C = getELFComdat(GO)) {
David Majnemerdad0a642014-06-27 18:19:56 +0000319 Group = C->getName();
320 Flags |= ELF::SHF_GROUP;
321 }
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000322
323 // A section can have at most one associated section. Put each global with
324 // MD_associated in a unique section.
325 unsigned UniqueID = MCContext::GenericSectionID;
326 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
327 if (AssociatedSymbol) {
328 UniqueID = NextUniqueID++;
329 Flags |= ELF::SHF_LINK_ORDER;
330 }
331
332 MCSectionELF *Section = getContext().getELFSection(
333 SectionName, getELFSectionType(SectionName, Kind), Flags,
334 /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
335 // Make sure that we did not get some other section with incompatible sh_link.
336 // This should not be possible due to UniqueID code above.
337 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
338 return Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000339}
340
Rafael Espindola25d2c202015-02-11 14:44:17 +0000341/// Return the section prefix name used by options FunctionsSections and
342/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000343static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000344 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000345 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000346 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000347 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000348 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000349 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000350 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000351 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000352 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000353 return ".tbss";
Rafael Espindola449711c2015-11-18 06:02:15 +0000354 if (Kind.isData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000355 return ".data";
Chris Lattner5b212a32010-04-13 00:36:43 +0000356 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000357 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000358}
359
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000360static MCSectionELF *selectELFSectionForGlobal(
361 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
362 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
363 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000364 unsigned EntrySize = 0;
365 if (Kind.isMergeableCString()) {
366 if (Kind.isMergeable2ByteCString()) {
367 EntrySize = 2;
368 } else if (Kind.isMergeable4ByteCString()) {
369 EntrySize = 4;
370 } else {
371 EntrySize = 1;
372 assert(Kind.isMergeable1ByteCString() && "unknown string width");
373 }
374 } else if (Kind.isMergeableConst()) {
375 if (Kind.isMergeableConst4()) {
376 EntrySize = 4;
377 } else if (Kind.isMergeableConst8()) {
378 EntrySize = 8;
David Majnemer964b70d2016-02-22 22:23:11 +0000379 } else if (Kind.isMergeableConst16()) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000380 EntrySize = 16;
David Majnemer964b70d2016-02-22 22:23:11 +0000381 } else {
382 assert(Kind.isMergeableConst32() && "unknown data width");
383 EntrySize = 32;
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000384 }
385 }
386
Rafael Espindola9075f772015-02-20 23:28:28 +0000387 StringRef Group = "";
Peter Collingbourne67335642016-10-24 19:23:39 +0000388 if (const Comdat *C = getELFComdat(GO)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000389 Flags |= ELF::SHF_GROUP;
390 Group = C->getName();
391 }
392
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000393 bool UniqueSectionNames = TM.getUniqueSectionNames();
394 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000395 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000396 // We also need alignment here.
397 // FIXME: this is getting the alignment of the character, not the
398 // alignment of the global!
Peter Collingbourne67335642016-10-24 19:23:39 +0000399 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
400 cast<GlobalVariable>(GO));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000401
Rafael Espindolaba31e272015-01-29 17:33:21 +0000402 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000403 Name = SizeSpec + utostr(Align);
404 } else if (Kind.isMergeableConst()) {
405 Name = ".rodata.cst";
406 Name += utostr(EntrySize);
407 } else {
408 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000409 }
Dehao Chen302b69c2016-10-18 20:42:47 +0000410
Peter Collingbourne67335642016-10-24 19:23:39 +0000411 if (const auto *F = dyn_cast<Function>(GO)) {
Dehao Chen302b69c2016-10-18 20:42:47 +0000412 const auto &OptionalPrefix = F->getSectionPrefix();
413 if (OptionalPrefix)
414 Name += *OptionalPrefix;
415 }
Dehao Chenf84b6302016-02-23 03:39:24 +0000416
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000417 if (EmitUniqueSection && UniqueSectionNames) {
418 Name.push_back('.');
Peter Collingbourne67335642016-10-24 19:23:39 +0000419 TM.getNameWithPrefix(Name, GO, Mang, true);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000420 }
Reid Kleckner97837b72016-05-02 23:22:18 +0000421 unsigned UniqueID = MCContext::GenericSectionID;
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000422 if (EmitUniqueSection && !UniqueSectionNames) {
423 UniqueID = *NextUniqueID;
424 (*NextUniqueID)++;
425 }
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000426 // Use 0 as the unique ID for execute-only text
427 if (Kind.isExecuteOnly())
428 UniqueID = 0;
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000429 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000430 EntrySize, Group, UniqueID, AssociatedSymbol);
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000431}
432
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000433MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000434 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000435 unsigned Flags = getELFSectionFlags(Kind);
436
437 // If we have -ffunction-section or -fdata-section then we should emit the
438 // global value to a uniqued section specifically for it.
439 bool EmitUniqueSection = false;
440 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
441 if (Kind.isText())
442 EmitUniqueSection = TM.getFunctionSections();
443 else
444 EmitUniqueSection = TM.getDataSections();
445 }
Peter Collingbourne67335642016-10-24 19:23:39 +0000446 EmitUniqueSection |= GO->hasComdat();
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000447
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000448 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
449 if (AssociatedSymbol) {
450 EmitUniqueSection = true;
451 Flags |= ELF::SHF_LINK_ORDER;
452 }
453
454 MCSectionELF *Section = selectELFSectionForGlobal(
455 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
456 &NextUniqueID, AssociatedSymbol);
457 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
458 return Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000459}
460
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000461MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000462 const Function &F, const TargetMachine &TM) const {
Rafael Espindola29786d42015-02-12 17:16:46 +0000463 // If the function can be removed, produce a unique section so that
464 // the table doesn't prevent the removal.
465 const Comdat *C = F.getComdat();
466 bool EmitUniqueSection = TM.getFunctionSections() || C;
467 if (!EmitUniqueSection)
468 return ReadOnlySection;
469
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000470 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000471 getMangler(), TM, EmitUniqueSection,
472 ELF::SHF_ALLOC, &NextUniqueID,
473 /* AssociatedSymbol */ nullptr);
Rafael Espindola29786d42015-02-12 17:16:46 +0000474}
475
Rafael Espindoladf195192015-02-17 23:34:51 +0000476bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
477 bool UsesLabelDifference, const Function &F) const {
478 // We can always create relative relocations, so use another section
479 // that can be marked non-executable.
480 return false;
481}
482
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000483/// Given a mergeable constant with the specified size and relocation
484/// information, return a section that it should be placed in.
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000485MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000486 const DataLayout &DL, SectionKind Kind, const Constant *C,
487 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000488 if (Kind.isMergeableConst4() && MergeableConst4Section)
489 return MergeableConst4Section;
490 if (Kind.isMergeableConst8() && MergeableConst8Section)
491 return MergeableConst8Section;
492 if (Kind.isMergeableConst16() && MergeableConst16Section)
493 return MergeableConst16Section;
David Majnemer964b70d2016-02-22 22:23:11 +0000494 if (Kind.isMergeableConst32() && MergeableConst32Section)
495 return MergeableConst32Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000496 if (Kind.isReadOnly())
497 return ReadOnlySection;
498
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000499 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
500 return DataRelROSection;
501}
502
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000503static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
504 bool IsCtor, unsigned Priority,
505 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000506 std::string Name;
507 unsigned Type;
508 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000509 StringRef COMDAT = KeySym ? KeySym->getName() : "";
510
511 if (KeySym)
512 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000513
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000514 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000515 if (IsCtor) {
516 Type = ELF::SHT_INIT_ARRAY;
517 Name = ".init_array";
518 } else {
519 Type = ELF::SHT_FINI_ARRAY;
520 Name = ".fini_array";
521 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000522 if (Priority != 65535) {
523 Name += '.';
524 Name += utostr(Priority);
525 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000526 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000527 // The default scheme is .ctor / .dtor, so we have to invert the priority
528 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000529 if (IsCtor)
530 Name = ".ctors";
531 else
532 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000533 if (Priority != 65535) {
534 Name += '.';
535 Name += utostr(65535 - Priority);
536 }
537 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000538 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000539
Rafael Espindolaba31e272015-01-29 17:33:21 +0000540 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000541}
542
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000543MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000544 unsigned Priority, const MCSymbol *KeySym) const {
545 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
546 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000547}
548
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000549MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000550 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000551 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
552 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000553}
554
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000555const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000556 const GlobalValue *LHS, const GlobalValue *RHS,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000557 const TargetMachine &TM) const {
558 // We may only use a PLT-relative relocation to refer to unnamed_addr
559 // functions.
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000560 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000561 return nullptr;
562
563 // Basic sanity checks.
564 if (LHS->getType()->getPointerAddressSpace() != 0 ||
565 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
566 RHS->isThreadLocal())
567 return nullptr;
568
569 return MCBinaryExpr::createSub(
Tim Northoverb64fb452016-11-22 16:17:20 +0000570 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000571 getContext()),
Tim Northoverb64fb452016-11-22 16:17:20 +0000572 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000573}
574
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000575void
576TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
577 UseInitArray = UseInitArray_;
Rafael Espindola46fa2312016-08-29 12:33:42 +0000578 MCContext &Ctx = getContext();
579 if (!UseInitArray) {
580 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
581 ELF::SHF_ALLOC | ELF::SHF_WRITE);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000582
Rafael Espindola46fa2312016-08-29 12:33:42 +0000583 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
584 ELF::SHF_ALLOC | ELF::SHF_WRITE);
585 return;
586 }
587
588 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
589 ELF::SHF_WRITE | ELF::SHF_ALLOC);
590 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
591 ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000592}
593
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000594//===----------------------------------------------------------------------===//
595// MachO
596//===----------------------------------------------------------------------===//
597
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000598TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
599 : TargetLoweringObjectFile() {
600 SupportIndirectSymViaGOTPCRel = true;
601}
602
Rafael Espindola46fa2312016-08-29 12:33:42 +0000603void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
604 const TargetMachine &TM) {
605 TargetLoweringObjectFile::Initialize(Ctx, TM);
Rafael Espindola412a5292016-08-29 12:47:22 +0000606 if (TM.getRelocationModel() == Reloc::Static) {
Rafael Espindola46fa2312016-08-29 12:33:42 +0000607 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
608 SectionKind::getData());
609 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
610 SectionKind::getData());
611 } else {
612 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
613 MachO::S_MOD_INIT_FUNC_POINTERS,
614 SectionKind::getData());
615 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
616 MachO::S_MOD_TERM_FUNC_POINTERS,
617 SectionKind::getData());
618 }
619}
620
Peter Collingbourne89061b22017-06-12 20:10:48 +0000621void TargetLoweringObjectFileMachO::emitModuleMetadata(
622 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
Daniel Dunbar95856122013-01-18 19:37:00 +0000623 // Emit the linker options if present.
Peter Collingbourne89061b22017-06-12 20:10:48 +0000624 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000625 for (const auto &Option : LinkerOptions->operands()) {
Daniel Dunbar95856122013-01-18 19:37:00 +0000626 SmallVector<std::string, 4> StrOptions;
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000627 for (const auto &Piece : cast<MDNode>(Option)->operands())
628 StrOptions.push_back(cast<MDString>(Piece)->getString());
Daniel Dunbar95856122013-01-18 19:37:00 +0000629 Streamer.EmitLinkerOptions(StrOptions);
630 }
Bill Wendling06df7722012-02-14 21:28:13 +0000631 }
632
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000633 unsigned VersionVal = 0;
634 unsigned ImageInfoFlags = 0;
635 StringRef SectionVal;
Peter Collingbourne89061b22017-06-12 20:10:48 +0000636
637 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000638
Bill Wendling734909a2012-02-15 22:36:15 +0000639 // The section is mandatory. If we don't have it, then we don't have GC info.
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000640 if (SectionVal.empty())
641 return;
Bill Wendling06df7722012-02-14 21:28:13 +0000642
Bill Wendling734909a2012-02-15 22:36:15 +0000643 StringRef Segment, Section;
644 unsigned TAA = 0, StubSize = 0;
645 bool TAAParsed;
646 std::string ErrorCode =
647 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
648 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000649 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000650 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000651 report_fatal_error("Invalid section specifier '" + Section + "': " +
652 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000653
Bill Wendling734909a2012-02-15 22:36:15 +0000654 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000655 MCSectionMachO *S = getContext().getMachOSection(
Rafael Espindola449711c2015-11-18 06:02:15 +0000656 Segment, Section, TAA, StubSize, SectionKind::getData());
Bill Wendling734909a2012-02-15 22:36:15 +0000657 Streamer.SwitchSection(S);
658 Streamer.EmitLabel(getContext().
Jim Grosbach6f482002015-05-18 18:43:14 +0000659 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000660 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000661 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000662 Streamer.AddBlankLine();
663}
664
David Majnemerdad0a642014-06-27 18:19:56 +0000665static void checkMachOComdat(const GlobalValue *GV) {
666 const Comdat *C = GV->getComdat();
667 if (!C)
668 return;
669
670 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
671 "' cannot be lowered.");
672}
673
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000674MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000675 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000676 // Parse the section specifier and create it if valid.
677 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000678 unsigned TAA = 0, StubSize = 0;
679 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000680
Peter Collingbourne67335642016-10-24 19:23:39 +0000681 checkMachOComdat(GO);
David Majnemerdad0a642014-06-27 18:19:56 +0000682
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000683 std::string ErrorCode =
Peter Collingbourne67335642016-10-24 19:23:39 +0000684 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000685 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000686 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000687 // If invalid, report the error with report_fatal_error.
Peter Collingbourne67335642016-10-24 19:23:39 +0000688 report_fatal_error("Global variable '" + GO->getName() +
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000689 "' has an invalid section specifier '" +
Peter Collingbourne67335642016-10-24 19:23:39 +0000690 GO->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000691 }
692
693 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000694 MCSectionMachO *S =
695 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000696
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000697 // If TAA wasn't set by ParseSectionSpecifier() above,
698 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000699 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000700 TAA = S->getTypeAndAttributes();
701
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000702 // Okay, now that we got the section, verify that the TAA & StubSize agree.
703 // If the user declared multiple globals with different section flags, we need
704 // to reject it here.
705 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000706 // If invalid, report the error with report_fatal_error.
Peter Collingbourne67335642016-10-24 19:23:39 +0000707 report_fatal_error("Global variable '" + GO->getName() +
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000708 "' section type or attributes does not match previous"
709 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000710 }
711
712 return S;
713}
714
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000715MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000716 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
717 checkMachOComdat(GO);
Bill Wendling25b61db2013-11-17 10:53:13 +0000718
719 // Handle thread local data.
720 if (Kind.isThreadBSS()) return TLSBSSSection;
721 if (Kind.isThreadData()) return TLSDataSection;
722
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000723 if (Kind.isText())
Peter Collingbourne67335642016-10-24 19:23:39 +0000724 return GO->isWeakForLinker() ? TextCoalSection : TextSection;
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000725
726 // If this is weak/linkonce, put this in a coalescable section, either in text
727 // or data depending on if it is writable.
Peter Collingbourne67335642016-10-24 19:23:39 +0000728 if (GO->isWeakForLinker()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000729 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000730 return ConstTextCoalSection;
731 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000732 }
733
734 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000735 if (Kind.isMergeable1ByteCString() &&
Peter Collingbourne67335642016-10-24 19:23:39 +0000736 GO->getParent()->getDataLayout().getPreferredAlignment(
737 cast<GlobalVariable>(GO)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000738 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000739
Chris Lattneref2f8042010-03-07 04:28:09 +0000740 // Do not put 16-bit arrays in the UString section if they have an
741 // externally visible label, this runs into issues with certain linker
742 // versions.
Peter Collingbourne67335642016-10-24 19:23:39 +0000743 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
744 GO->getParent()->getDataLayout().getPreferredAlignment(
745 cast<GlobalVariable>(GO)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000746 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000747
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000748 // With MachO only variables whose corresponding symbol starts with 'l' or
749 // 'L' can be merged, so we only try merging GVs with private linkage.
Peter Collingbourne67335642016-10-24 19:23:39 +0000750 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000751 if (Kind.isMergeableConst4())
752 return FourByteConstantSection;
753 if (Kind.isMergeableConst8())
754 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000755 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000756 return SixteenByteConstantSection;
757 }
758
759 // Otherwise, if it is readonly, but not something we can specially optimize,
760 // just drop it in .const.
761 if (Kind.isReadOnly())
762 return ReadOnlySection;
763
764 // If this is marked const, put it into a const section. But if the dynamic
765 // linker needs to write to it, put it in the data segment.
766 if (Kind.isReadOnlyWithRel())
767 return ConstDataSection;
768
769 // Put zero initialized globals with strong external linkage in the
770 // DATA, __common section with the .zerofill directive.
771 if (Kind.isBSSExtern())
772 return DataCommonSection;
773
774 // Put zero initialized globals with local linkage in __DATA,__bss directive
775 // with the .zerofill directive (aka .lcomm).
776 if (Kind.isBSSLocal())
777 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000778
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000779 // Otherwise, just drop the variable in the normal data section.
780 return DataSection;
781}
782
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000783MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000784 const DataLayout &DL, SectionKind Kind, const Constant *C,
785 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000786 // If this constant requires a relocation, we have to put it in the data
787 // segment, not in the text segment.
Rafael Espindola449711c2015-11-18 06:02:15 +0000788 if (Kind.isData() || Kind.isReadOnlyWithRel())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000789 return ConstDataSection;
790
791 if (Kind.isMergeableConst4())
792 return FourByteConstantSection;
793 if (Kind.isMergeableConst8())
794 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000795 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000796 return SixteenByteConstantSection;
797 return ReadOnlySection; // .const
798}
799
Rafael Espindola15b26692014-02-09 14:50:44 +0000800const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000801 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
802 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000803 // The mach-o version of this method defaults to returning a stub reference.
804
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000805 if (Encoding & DW_EH_PE_indirect) {
806 MachineModuleInfoMachO &MachOMMI =
807 MMI->getObjFileInfo<MachineModuleInfoMachO>();
808
Eric Christopher4367c7f2016-09-16 07:33:15 +0000809 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000810
811 // Add information about the stub reference to MachOMMI so that the stub
812 // gets emitted by the asmprinter.
Rafael Espindola712f9572016-05-17 16:01:32 +0000813 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000814 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000815 MCSymbol *Sym = TM.getSymbol(GV);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000816 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000817 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000818
819 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000820 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000821 Encoding & ~DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000822 }
823
Eric Christopher4367c7f2016-09-16 07:33:15 +0000824 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
825 MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000826}
827
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000828MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000829 const GlobalValue *GV, const TargetMachine &TM,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000830 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000831 // The mach-o version of this method defaults to returning a stub reference.
832 MachineModuleInfoMachO &MachOMMI =
833 MMI->getObjFileInfo<MachineModuleInfoMachO>();
834
Eric Christopher4367c7f2016-09-16 07:33:15 +0000835 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000836
837 // Add information about the stub reference to MachOMMI so that the stub
838 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000839 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000840 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000841 MCSymbol *Sym = TM.getSymbol(GV);
Rafael Espindola08704342011-04-27 23:08:15 +0000842 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
843 }
844
845 return SSym;
846}
847
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000848const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
849 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
850 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000851 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000852 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
853 // through a non_lazy_ptr stub instead. One advantage is that it allows the
854 // computation of deltas to final external symbols. Example:
855 //
856 // _extgotequiv:
857 // .long _extfoo
858 //
859 // _delta:
860 // .long _extgotequiv-_delta
861 //
862 // is transformed to:
863 //
864 // _delta:
865 // .long L_extfoo$non_lazy_ptr-(_delta+0)
866 //
867 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
868 // L_extfoo$non_lazy_ptr:
869 // .indirect_symbol _extfoo
870 // .long 0
871 //
872 MachineModuleInfoMachO &MachOMMI =
873 MMI->getObjFileInfo<MachineModuleInfoMachO>();
874 MCContext &Ctx = getContext();
875
876 // The offset must consider the original displacement from the base symbol
877 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
878 Offset = -MV.getConstant();
879 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
880
881 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
882 // non_lazy_ptr stubs.
883 SmallString<128> Name;
884 StringRef Suffix = "$non_lazy_ptr";
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000885 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000886 Name += Sym->getName();
887 Name += Suffix;
Jim Grosbach6f482002015-05-18 18:43:14 +0000888 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000889
890 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
891 if (!StubSym.getPointer())
892 StubSym = MachineModuleInfoImpl::
893 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
894
895 const MCExpr *BSymExpr =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000896 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000897 const MCExpr *LHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000898 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000899
900 if (!Offset)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000901 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000902
903 const MCExpr *RHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000904 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
905 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000906}
907
Peter Collingbourne94d77862015-11-03 23:40:03 +0000908static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
909 const MCSection &Section) {
910 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
911 return true;
912
913 // If it is not dead stripped, it is safe to use private labels.
914 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
915 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
916 return true;
917
918 return false;
919}
920
921void TargetLoweringObjectFileMachO::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000922 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +0000923 const TargetMachine &TM) const {
Peter Collingbourne67335642016-10-24 19:23:39 +0000924 bool CannotUsePrivateLabel = true;
925 if (auto *GO = GV->getBaseObject()) {
926 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
927 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
928 CannotUsePrivateLabel =
929 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
930 }
Eric Christopher4367c7f2016-09-16 07:33:15 +0000931 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
Peter Collingbourne94d77862015-11-03 23:40:03 +0000932}
933
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000934//===----------------------------------------------------------------------===//
935// COFF
936//===----------------------------------------------------------------------===//
937
Chris Lattner87cffa92010-05-07 17:17:41 +0000938static unsigned
Renato Golinef3eb062016-06-27 14:42:20 +0000939getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
Chris Lattner87cffa92010-05-07 17:17:41 +0000940 unsigned Flags = 0;
Renato Golinef3eb062016-06-27 14:42:20 +0000941 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
Chris Lattner87cffa92010-05-07 17:17:41 +0000942
Anton Korobeynikove4152302010-07-06 15:24:56 +0000943 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000944 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000945 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000946 else if (K.isText())
947 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000948 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000949 COFF::IMAGE_SCN_MEM_READ |
Renato Golinef3eb062016-06-27 14:42:20 +0000950 COFF::IMAGE_SCN_CNT_CODE |
951 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
David Majnemerb8dbebb2014-09-20 07:31:46 +0000952 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000953 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000954 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
955 COFF::IMAGE_SCN_MEM_READ |
956 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000957 else if (K.isThreadLocal())
958 Flags |=
959 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
960 COFF::IMAGE_SCN_MEM_READ |
961 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000962 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000963 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000964 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
965 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000966 else if (K.isWriteable())
967 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000968 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
969 COFF::IMAGE_SCN_MEM_READ |
970 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000971
972 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000973}
974
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000975static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000976 const Comdat *C = GV->getComdat();
977 assert(C && "expected GV to have a Comdat!");
978
979 StringRef ComdatGVName = C->getName();
980 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
981 if (!ComdatGV)
982 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
983 "' does not exist.");
984
985 if (ComdatGV->getComdat() != C)
986 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000987 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000988
989 return ComdatGV;
990}
991
992static int getSelectionForCOFF(const GlobalValue *GV) {
993 if (const Comdat *C = GV->getComdat()) {
994 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
995 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
996 ComdatKey = GA->getBaseObject();
997 if (ComdatKey == GV) {
998 switch (C->getSelectionKind()) {
999 case Comdat::Any:
1000 return COFF::IMAGE_COMDAT_SELECT_ANY;
1001 case Comdat::ExactMatch:
1002 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1003 case Comdat::Largest:
1004 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1005 case Comdat::NoDuplicates:
1006 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1007 case Comdat::SameSize:
1008 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1009 }
1010 } else {
1011 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1012 }
David Majnemerdad0a642014-06-27 18:19:56 +00001013 }
1014 return 0;
1015}
1016
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001017MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +00001018 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +00001019 int Selection = 0;
Renato Golinef3eb062016-06-27 14:42:20 +00001020 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Peter Collingbourne67335642016-10-24 19:23:39 +00001021 StringRef Name = GO->getSection();
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001022 StringRef COMDATSymName = "";
Peter Collingbourne67335642016-10-24 19:23:39 +00001023 if (GO->hasComdat()) {
1024 Selection = getSelectionForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001025 const GlobalValue *ComdatGV;
1026 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
Peter Collingbourne67335642016-10-24 19:23:39 +00001027 ComdatGV = getComdatGVForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001028 else
Peter Collingbourne67335642016-10-24 19:23:39 +00001029 ComdatGV = GO;
David Majnemerdad0a642014-06-27 18:19:56 +00001030
1031 if (!ComdatGV->hasPrivateLinkage()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001032 MCSymbol *Sym = TM.getSymbol(ComdatGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001033 COMDATSymName = Sym->getName();
1034 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1035 } else {
1036 Selection = 0;
1037 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +00001038 }
Reid Kleckner97837b72016-05-02 23:22:18 +00001039
1040 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +00001041 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001042}
1043
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001044static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001045 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001046 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +00001047 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001048 return ".bss";
1049 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +00001050 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +00001051 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1052 return ".rdata";
1053 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001054}
1055
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001056MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +00001057 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +00001058 // If we have -ffunction-sections then we should emit the global value to a
1059 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +00001060 bool EmitUniquedSection;
1061 if (Kind.isText())
1062 EmitUniquedSection = TM.getFunctionSections();
1063 else
1064 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001065
Peter Collingbourne67335642016-10-24 19:23:39 +00001066 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001067 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +00001068 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Chris Lattner02844932010-05-07 21:49:09 +00001069
Daniel Dunbar329d2022010-07-01 20:07:24 +00001070 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Peter Collingbourne67335642016-10-24 19:23:39 +00001071 int Selection = getSelectionForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001072 if (!Selection)
1073 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1074 const GlobalValue *ComdatGV;
Peter Collingbourne67335642016-10-24 19:23:39 +00001075 if (GO->hasComdat())
1076 ComdatGV = getComdatGVForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001077 else
Peter Collingbourne67335642016-10-24 19:23:39 +00001078 ComdatGV = GO;
David Majnemerdad0a642014-06-27 18:19:56 +00001079
Reid Kleckner97837b72016-05-02 23:22:18 +00001080 unsigned UniqueID = MCContext::GenericSectionID;
1081 if (EmitUniquedSection)
1082 UniqueID = NextUniqueID++;
1083
David Majnemerdad0a642014-06-27 18:19:56 +00001084 if (!ComdatGV->hasPrivateLinkage()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001085 MCSymbol *Sym = TM.getSymbol(ComdatGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001086 StringRef COMDATSymName = Sym->getName();
1087 return getContext().getCOFFSection(Name, Characteristics, Kind,
Reid Kleckner97837b72016-05-02 23:22:18 +00001088 COMDATSymName, Selection, UniqueID);
David Majnemer7db449a2015-03-17 23:54:51 +00001089 } else {
1090 SmallString<256> TmpData;
Peter Collingbourne67335642016-10-24 19:23:39 +00001091 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
David Majnemer7db449a2015-03-17 23:54:51 +00001092 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
Reid Kleckner97837b72016-05-02 23:22:18 +00001093 Selection, UniqueID);
David Majnemerdad0a642014-06-27 18:19:56 +00001094 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001095 }
1096
1097 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +00001098 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001099
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001100 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +00001101 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001102
David Majnemer597be2d2014-09-22 20:39:23 +00001103 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +00001104 return ReadOnlySection;
1105
David Majnemera9bdb322014-04-08 22:33:40 +00001106 // Note: we claim that common symbols are put in BSSSection, but they are
1107 // really emitted with the magic .comm directive, which creates a symbol table
1108 // entry but not a section.
1109 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +00001110 return BSSSection;
1111
1112 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001113}
1114
David Majnemer7db449a2015-03-17 23:54:51 +00001115void TargetLoweringObjectFileCOFF::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001116 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +00001117 const TargetMachine &TM) const {
1118 bool CannotUsePrivateLabel = false;
David Majnemer7db449a2015-03-17 23:54:51 +00001119 if (GV->hasPrivateLinkage() &&
1120 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1121 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1122 CannotUsePrivateLabel = true;
1123
Eric Christopher4367c7f2016-09-16 07:33:15 +00001124 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
David Majnemer7db449a2015-03-17 23:54:51 +00001125}
1126
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001127MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001128 const Function &F, const TargetMachine &TM) const {
Rafael Espindolaab447e42015-03-11 19:58:37 +00001129 // If the function can be removed, produce a unique section so that
1130 // the table doesn't prevent the removal.
1131 const Comdat *C = F.getComdat();
1132 bool EmitUniqueSection = TM.getFunctionSections() || C;
1133 if (!EmitUniqueSection)
1134 return ReadOnlySection;
1135
1136 // FIXME: we should produce a symbol for F instead.
1137 if (F.hasPrivateLinkage())
1138 return ReadOnlySection;
1139
Tim Northoverb64fb452016-11-22 16:17:20 +00001140 MCSymbol *Sym = TM.getSymbol(&F);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001141 StringRef COMDATSymName = Sym->getName();
1142
1143 SectionKind Kind = SectionKind::getReadOnly();
1144 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +00001145 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001146 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Reid Kleckner97837b72016-05-02 23:22:18 +00001147 unsigned UniqueID = NextUniqueID++;
Rafael Espindolaab447e42015-03-11 19:58:37 +00001148
1149 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Reid Kleckner97837b72016-05-02 23:22:18 +00001150 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001151}
1152
Peter Collingbourne89061b22017-06-12 20:10:48 +00001153void TargetLoweringObjectFileCOFF::emitModuleMetadata(
1154 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
1155 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001156 // Emit the linker options to the linker .drectve section. According to the
1157 // spec, this section is a space-separated string containing flags for
1158 // linker.
1159 MCSection *Sec = getDrectveSection();
1160 Streamer.SwitchSection(Sec);
1161 for (const auto &Option : LinkerOptions->operands()) {
1162 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1163 // Lead with a space for consistency with our dllexport implementation.
1164 std::string Directive(" ");
1165 Directive.append(cast<MDString>(Piece)->getString());
1166 Streamer.EmitBytes(Directive);
1167 }
Reid Klecknerd973ca32013-04-25 19:34:41 +00001168 }
1169 }
Saleem Abdulrasool4c474342017-06-05 21:26:39 +00001170
1171 unsigned Version = 0;
1172 unsigned Flags = 0;
1173 StringRef Section;
1174
Peter Collingbourne89061b22017-06-12 20:10:48 +00001175 GetObjCImageInfo(M, Version, Flags, Section);
Saleem Abdulrasool4c474342017-06-05 21:26:39 +00001176 if (Section.empty())
1177 return;
1178
1179 auto &C = getContext();
1180 auto *S = C.getCOFFSection(
1181 Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1182 SectionKind::getReadOnly());
1183 Streamer.SwitchSection(S);
1184 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1185 Streamer.EmitIntValue(Version, 4);
1186 Streamer.EmitIntValue(Flags, 4);
1187 Streamer.AddBlankLine();
Reid Klecknerd973ca32013-04-25 19:34:41 +00001188}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001189
Rafael Espindola46fa2312016-08-29 12:33:42 +00001190void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1191 const TargetMachine &TM) {
1192 TargetLoweringObjectFile::Initialize(Ctx, TM);
1193 const Triple &T = TM.getTargetTriple();
1194 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1195 StaticCtorSection =
1196 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1197 COFF::IMAGE_SCN_MEM_READ,
1198 SectionKind::getReadOnly());
1199 StaticDtorSection =
1200 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1201 COFF::IMAGE_SCN_MEM_READ,
1202 SectionKind::getReadOnly());
1203 } else {
1204 StaticCtorSection = Ctx.getCOFFSection(
1205 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1206 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1207 SectionKind::getData());
1208 StaticDtorSection = Ctx.getCOFFSection(
1209 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1210 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1211 SectionKind::getData());
1212 }
1213}
1214
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001215MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001216 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001217 return getContext().getAssociativeCOFFSection(
Reid Kleckner97837b72016-05-02 23:22:18 +00001218 cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001219}
1220
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001221MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001222 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001223 return getContext().getAssociativeCOFFSection(
Reid Kleckner97837b72016-05-02 23:22:18 +00001224 cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001225}
Peter Collingbourneaef36592015-06-29 22:04:09 +00001226
1227void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001228 raw_ostream &OS, const GlobalValue *GV) const {
Bob Haarmandd4ebc12017-02-02 23:00:49 +00001229 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
Peter Collingbourneaef36592015-06-29 22:04:09 +00001230}
Dan Gohman18eafb62017-02-22 01:23:18 +00001231
1232//===----------------------------------------------------------------------===//
1233// Wasm
1234//===----------------------------------------------------------------------===//
1235
Dan Gohmand934cb82017-02-24 23:18:00 +00001236static const Comdat *getWasmComdat(const GlobalValue *GV) {
1237 const Comdat *C = GV->getComdat();
1238 if (!C)
1239 return nullptr;
1240
1241 if (C->getSelectionKind() != Comdat::Any)
1242 report_fatal_error("Wasm COMDATs only support SelectionKind::Any, '" +
1243 C->getName() + "' cannot be lowered.");
1244
1245 return C;
1246}
1247
Dan Gohman18eafb62017-02-22 01:23:18 +00001248MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1249 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Sam Clegg759631c2017-09-15 20:54:59 +00001250 StringRef Name = GO->getSection();
Sam Clegg12fd3da2017-10-20 21:28:38 +00001251 return getContext().getWasmSection(Name, SectionKind::getData());
Dan Gohman18eafb62017-02-22 01:23:18 +00001252}
1253
Sam Clegg2176a9f2017-09-12 18:31:24 +00001254static MCSectionWasm *selectWasmSectionForGlobal(
1255 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
1256 const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
Dan Gohmand934cb82017-02-24 23:18:00 +00001257 StringRef Group = "";
1258 if (getWasmComdat(GO))
1259 llvm_unreachable("comdat not yet supported for wasm");
1260
1261 bool UniqueSectionNames = TM.getUniqueSectionNames();
1262 SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1263
1264 if (const auto *F = dyn_cast<Function>(GO)) {
1265 const auto &OptionalPrefix = F->getSectionPrefix();
1266 if (OptionalPrefix)
1267 Name += *OptionalPrefix;
1268 }
1269
1270 if (EmitUniqueSection && UniqueSectionNames) {
1271 Name.push_back('.');
1272 TM.getNameWithPrefix(Name, GO, Mang, true);
1273 }
1274 unsigned UniqueID = MCContext::GenericSectionID;
1275 if (EmitUniqueSection && !UniqueSectionNames) {
1276 UniqueID = *NextUniqueID;
1277 (*NextUniqueID)++;
1278 }
Sam Clegg12fd3da2017-10-20 21:28:38 +00001279 return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
Dan Gohmand934cb82017-02-24 23:18:00 +00001280}
1281
Dan Gohman18eafb62017-02-22 01:23:18 +00001282MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1283 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Dan Gohmand934cb82017-02-24 23:18:00 +00001284
1285 if (Kind.isCommon())
1286 report_fatal_error("mergable sections not supported yet on wasm");
1287
1288 // If we have -ffunction-section or -fdata-section then we should emit the
1289 // global value to a uniqued section specifically for it.
1290 bool EmitUniqueSection = false;
Dan Gohman18eafb62017-02-22 01:23:18 +00001291 if (Kind.isText())
Dan Gohmand934cb82017-02-24 23:18:00 +00001292 EmitUniqueSection = TM.getFunctionSections();
1293 else
1294 EmitUniqueSection = TM.getDataSections();
1295 EmitUniqueSection |= GO->hasComdat();
1296
1297 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
Sam Clegg2176a9f2017-09-12 18:31:24 +00001298 EmitUniqueSection, &NextUniqueID);
Dan Gohman18eafb62017-02-22 01:23:18 +00001299}
1300
1301bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1302 bool UsesLabelDifference, const Function &F) const {
1303 // We can always create relative relocations, so use another section
1304 // that can be marked non-executable.
1305 return false;
1306}
1307
1308const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1309 const GlobalValue *LHS, const GlobalValue *RHS,
1310 const TargetMachine &TM) const {
1311 // We may only use a PLT-relative relocation to refer to unnamed_addr
1312 // functions.
1313 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1314 return nullptr;
1315
1316 // Basic sanity checks.
1317 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1318 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1319 RHS->isThreadLocal())
1320 return nullptr;
1321
1322 return MCBinaryExpr::createSub(
1323 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1324 getContext()),
1325 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1326}
1327
Sam Cleggb2b019f2017-10-03 11:20:28 +00001328void TargetLoweringObjectFileWasm::InitializeWasm() {
1329 StaticCtorSection =
Sam Clegg12fd3da2017-10-20 21:28:38 +00001330 getContext().getWasmSection(".init_array", SectionKind::getData());
Sam Cleggb2b019f2017-10-03 11:20:28 +00001331 StaticDtorSection =
Sam Clegg12fd3da2017-10-20 21:28:38 +00001332 getContext().getWasmSection(".fini_array", SectionKind::getData());
Dan Gohman18eafb62017-02-22 01:23:18 +00001333}