blob: 6922e33c8d6cba2d3021426c4998f7fa8b9efb3c [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
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000171static SectionKind
172getELFKindForNamedSection(StringRef Name, SectionKind K) {
Rafael Espindola0d018b12011-05-24 03:10:31 +0000173 // N.B.: The defaults used in here are no the same ones used in MC.
174 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
175 // both gas and MC will produce a section with no flags. Given
Bill Wendlingd1634052012-07-19 00:04:14 +0000176 // section(".eh_frame") gcc will produce:
177 //
178 // .section .eh_frame,"a",@progbits
Xinliang David Li4a5ddf82017-04-14 17:48:40 +0000179
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000180 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
181 /*AddSegmentInfo=*/false))
Xinliang David Li5f04f922016-01-14 18:09:45 +0000182 return SectionKind::getMetadata();
183
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000184 if (Name.empty() || Name[0] != '.') return K;
185
186 // Some lame default implementation based on some magic section names.
187 if (Name == ".bss" ||
188 Name.startswith(".bss.") ||
189 Name.startswith(".gnu.linkonce.b.") ||
190 Name.startswith(".llvm.linkonce.b.") ||
191 Name == ".sbss" ||
192 Name.startswith(".sbss.") ||
193 Name.startswith(".gnu.linkonce.sb.") ||
194 Name.startswith(".llvm.linkonce.sb."))
195 return SectionKind::getBSS();
196
197 if (Name == ".tdata" ||
198 Name.startswith(".tdata.") ||
199 Name.startswith(".gnu.linkonce.td.") ||
200 Name.startswith(".llvm.linkonce.td."))
201 return SectionKind::getThreadData();
202
203 if (Name == ".tbss" ||
204 Name.startswith(".tbss.") ||
205 Name.startswith(".gnu.linkonce.tb.") ||
206 Name.startswith(".llvm.linkonce.tb."))
207 return SectionKind::getThreadBSS();
208
209 return K;
210}
211
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000212static unsigned getELFSectionType(StringRef Name, SectionKind K) {
Petr Hosek12903552016-09-20 20:21:13 +0000213 // Use SHT_NOTE for section whose name starts with ".note" to allow
214 // emitting ELF notes from C variable declaration.
215 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
216 if (Name.startswith(".note"))
217 return ELF::SHT_NOTE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000218
219 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000220 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000221
222 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000223 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000224
225 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000226 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000227
228 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000229 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000230
Rafael Espindolaaea49582011-01-23 04:28:49 +0000231 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000232}
233
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000234static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000235 unsigned Flags = 0;
236
237 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000238 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000239
240 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000241 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000242
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000243 if (K.isExecuteOnly())
244 Flags |= ELF::SHF_ARM_PURECODE;
245
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000246 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000247 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000248
249 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000250 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000251
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000252 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000253 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000254
255 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000256 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000257
258 return Flags;
259}
260
David Majnemerdad0a642014-06-27 18:19:56 +0000261static const Comdat *getELFComdat(const GlobalValue *GV) {
262 const Comdat *C = GV->getComdat();
263 if (!C)
264 return nullptr;
265
266 if (C->getSelectionKind() != Comdat::Any)
267 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
268 C->getName() + "' cannot be lowered.");
269
270 return C;
271}
272
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000273static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
274 const TargetMachine &TM) {
275 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
276 if (!MD)
277 return nullptr;
278
Evgeniy Stepanovf7e8acf2017-05-08 23:46:20 +0000279 const MDOperand &Op = MD->getOperand(0);
280 if (!Op.get())
281 return nullptr;
282
283 auto *VM = dyn_cast<ValueAsMetadata>(Op);
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000284 if (!VM)
285 report_fatal_error("MD_associated operand is not ValueAsMetadata");
286
287 GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
288 return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
289}
290
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000291MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000292 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
293 StringRef SectionName = GO->getSection();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000294
Javed Absarb16d1462017-06-05 10:09:13 +0000295 // Check if '#pragma clang section' name is applicable.
296 // Note that pragma directive overrides -ffunction-section, -fdata-section
297 // and so section name is exactly as user specified and not uniqued.
298 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
299 if (GV && GV->hasImplicitSection()) {
300 auto Attrs = GV->getAttributes();
301 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
302 SectionName = Attrs.getAttribute("bss-section").getValueAsString();
303 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
304 SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
305 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
306 SectionName = Attrs.getAttribute("data-section").getValueAsString();
307 }
308 }
309 const Function *F = dyn_cast<Function>(GO);
310 if (F && F->hasFnAttribute("implicit-section-name")) {
311 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
312 }
313
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000314 // Infer section flags from the section name if we can.
315 Kind = getELFKindForNamedSection(SectionName, Kind);
316
David Majnemerdad0a642014-06-27 18:19:56 +0000317 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000318 unsigned Flags = getELFSectionFlags(Kind);
Peter Collingbourne67335642016-10-24 19:23:39 +0000319 if (const Comdat *C = getELFComdat(GO)) {
David Majnemerdad0a642014-06-27 18:19:56 +0000320 Group = C->getName();
321 Flags |= ELF::SHF_GROUP;
322 }
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000323
324 // A section can have at most one associated section. Put each global with
325 // MD_associated in a unique section.
326 unsigned UniqueID = MCContext::GenericSectionID;
327 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
328 if (AssociatedSymbol) {
329 UniqueID = NextUniqueID++;
330 Flags |= ELF::SHF_LINK_ORDER;
331 }
332
333 MCSectionELF *Section = getContext().getELFSection(
334 SectionName, getELFSectionType(SectionName, Kind), Flags,
335 /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
336 // Make sure that we did not get some other section with incompatible sh_link.
337 // This should not be possible due to UniqueID code above.
338 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
339 return Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000340}
341
Rafael Espindola25d2c202015-02-11 14:44:17 +0000342/// Return the section prefix name used by options FunctionsSections and
343/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000344static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000345 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000346 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000347 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000348 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000349 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000350 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000351 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000352 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000353 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000354 return ".tbss";
Rafael Espindola449711c2015-11-18 06:02:15 +0000355 if (Kind.isData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000356 return ".data";
Chris Lattner5b212a32010-04-13 00:36:43 +0000357 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000358 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000359}
360
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000361static MCSectionELF *selectELFSectionForGlobal(
362 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
363 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
364 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000365 unsigned EntrySize = 0;
366 if (Kind.isMergeableCString()) {
367 if (Kind.isMergeable2ByteCString()) {
368 EntrySize = 2;
369 } else if (Kind.isMergeable4ByteCString()) {
370 EntrySize = 4;
371 } else {
372 EntrySize = 1;
373 assert(Kind.isMergeable1ByteCString() && "unknown string width");
374 }
375 } else if (Kind.isMergeableConst()) {
376 if (Kind.isMergeableConst4()) {
377 EntrySize = 4;
378 } else if (Kind.isMergeableConst8()) {
379 EntrySize = 8;
David Majnemer964b70d2016-02-22 22:23:11 +0000380 } else if (Kind.isMergeableConst16()) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000381 EntrySize = 16;
David Majnemer964b70d2016-02-22 22:23:11 +0000382 } else {
383 assert(Kind.isMergeableConst32() && "unknown data width");
384 EntrySize = 32;
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000385 }
386 }
387
Rafael Espindola9075f772015-02-20 23:28:28 +0000388 StringRef Group = "";
Peter Collingbourne67335642016-10-24 19:23:39 +0000389 if (const Comdat *C = getELFComdat(GO)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000390 Flags |= ELF::SHF_GROUP;
391 Group = C->getName();
392 }
393
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000394 bool UniqueSectionNames = TM.getUniqueSectionNames();
395 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000396 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000397 // We also need alignment here.
398 // FIXME: this is getting the alignment of the character, not the
399 // alignment of the global!
Peter Collingbourne67335642016-10-24 19:23:39 +0000400 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
401 cast<GlobalVariable>(GO));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000402
Rafael Espindolaba31e272015-01-29 17:33:21 +0000403 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000404 Name = SizeSpec + utostr(Align);
405 } else if (Kind.isMergeableConst()) {
406 Name = ".rodata.cst";
407 Name += utostr(EntrySize);
408 } else {
409 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000410 }
Dehao Chen302b69c2016-10-18 20:42:47 +0000411
Peter Collingbourne67335642016-10-24 19:23:39 +0000412 if (const auto *F = dyn_cast<Function>(GO)) {
Dehao Chen302b69c2016-10-18 20:42:47 +0000413 const auto &OptionalPrefix = F->getSectionPrefix();
414 if (OptionalPrefix)
415 Name += *OptionalPrefix;
416 }
Dehao Chenf84b6302016-02-23 03:39:24 +0000417
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000418 if (EmitUniqueSection && UniqueSectionNames) {
419 Name.push_back('.');
Peter Collingbourne67335642016-10-24 19:23:39 +0000420 TM.getNameWithPrefix(Name, GO, Mang, true);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000421 }
Reid Kleckner97837b72016-05-02 23:22:18 +0000422 unsigned UniqueID = MCContext::GenericSectionID;
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000423 if (EmitUniqueSection && !UniqueSectionNames) {
424 UniqueID = *NextUniqueID;
425 (*NextUniqueID)++;
426 }
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000427 // Use 0 as the unique ID for execute-only text
428 if (Kind.isExecuteOnly())
429 UniqueID = 0;
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000430 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000431 EntrySize, Group, UniqueID, AssociatedSymbol);
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000432}
433
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000434MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000435 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000436 unsigned Flags = getELFSectionFlags(Kind);
437
438 // If we have -ffunction-section or -fdata-section then we should emit the
439 // global value to a uniqued section specifically for it.
440 bool EmitUniqueSection = false;
441 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
442 if (Kind.isText())
443 EmitUniqueSection = TM.getFunctionSections();
444 else
445 EmitUniqueSection = TM.getDataSections();
446 }
Peter Collingbourne67335642016-10-24 19:23:39 +0000447 EmitUniqueSection |= GO->hasComdat();
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000448
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000449 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
450 if (AssociatedSymbol) {
451 EmitUniqueSection = true;
452 Flags |= ELF::SHF_LINK_ORDER;
453 }
454
455 MCSectionELF *Section = selectELFSectionForGlobal(
456 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
457 &NextUniqueID, AssociatedSymbol);
458 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
459 return Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000460}
461
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000462MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000463 const Function &F, const TargetMachine &TM) const {
Rafael Espindola29786d42015-02-12 17:16:46 +0000464 // If the function can be removed, produce a unique section so that
465 // the table doesn't prevent the removal.
466 const Comdat *C = F.getComdat();
467 bool EmitUniqueSection = TM.getFunctionSections() || C;
468 if (!EmitUniqueSection)
469 return ReadOnlySection;
470
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000471 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000472 getMangler(), TM, EmitUniqueSection,
473 ELF::SHF_ALLOC, &NextUniqueID,
474 /* AssociatedSymbol */ nullptr);
Rafael Espindola29786d42015-02-12 17:16:46 +0000475}
476
Rafael Espindoladf195192015-02-17 23:34:51 +0000477bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
478 bool UsesLabelDifference, const Function &F) const {
479 // We can always create relative relocations, so use another section
480 // that can be marked non-executable.
481 return false;
482}
483
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000484/// Given a mergeable constant with the specified size and relocation
485/// information, return a section that it should be placed in.
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000486MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000487 const DataLayout &DL, SectionKind Kind, const Constant *C,
488 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000489 if (Kind.isMergeableConst4() && MergeableConst4Section)
490 return MergeableConst4Section;
491 if (Kind.isMergeableConst8() && MergeableConst8Section)
492 return MergeableConst8Section;
493 if (Kind.isMergeableConst16() && MergeableConst16Section)
494 return MergeableConst16Section;
David Majnemer964b70d2016-02-22 22:23:11 +0000495 if (Kind.isMergeableConst32() && MergeableConst32Section)
496 return MergeableConst32Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000497 if (Kind.isReadOnly())
498 return ReadOnlySection;
499
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000500 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
501 return DataRelROSection;
502}
503
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000504static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
505 bool IsCtor, unsigned Priority,
506 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000507 std::string Name;
508 unsigned Type;
509 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000510 StringRef COMDAT = KeySym ? KeySym->getName() : "";
511
512 if (KeySym)
513 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000514
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000515 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000516 if (IsCtor) {
517 Type = ELF::SHT_INIT_ARRAY;
518 Name = ".init_array";
519 } else {
520 Type = ELF::SHT_FINI_ARRAY;
521 Name = ".fini_array";
522 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000523 if (Priority != 65535) {
524 Name += '.';
525 Name += utostr(Priority);
526 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000527 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000528 // The default scheme is .ctor / .dtor, so we have to invert the priority
529 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000530 if (IsCtor)
531 Name = ".ctors";
532 else
533 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000534 if (Priority != 65535) {
535 Name += '.';
536 Name += utostr(65535 - Priority);
537 }
538 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000539 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000540
Rafael Espindolaba31e272015-01-29 17:33:21 +0000541 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000542}
543
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000544MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000545 unsigned Priority, const MCSymbol *KeySym) const {
546 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
547 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000548}
549
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000550MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000551 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000552 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
553 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000554}
555
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000556const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000557 const GlobalValue *LHS, const GlobalValue *RHS,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000558 const TargetMachine &TM) const {
559 // We may only use a PLT-relative relocation to refer to unnamed_addr
560 // functions.
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000561 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000562 return nullptr;
563
564 // Basic sanity checks.
565 if (LHS->getType()->getPointerAddressSpace() != 0 ||
566 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
567 RHS->isThreadLocal())
568 return nullptr;
569
570 return MCBinaryExpr::createSub(
Tim Northoverb64fb452016-11-22 16:17:20 +0000571 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000572 getContext()),
Tim Northoverb64fb452016-11-22 16:17:20 +0000573 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000574}
575
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000576void
577TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
578 UseInitArray = UseInitArray_;
Rafael Espindola46fa2312016-08-29 12:33:42 +0000579 MCContext &Ctx = getContext();
580 if (!UseInitArray) {
581 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
582 ELF::SHF_ALLOC | ELF::SHF_WRITE);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000583
Rafael Espindola46fa2312016-08-29 12:33:42 +0000584 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
585 ELF::SHF_ALLOC | ELF::SHF_WRITE);
586 return;
587 }
588
589 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
590 ELF::SHF_WRITE | ELF::SHF_ALLOC);
591 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
592 ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000593}
594
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000595//===----------------------------------------------------------------------===//
596// MachO
597//===----------------------------------------------------------------------===//
598
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000599TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
600 : TargetLoweringObjectFile() {
601 SupportIndirectSymViaGOTPCRel = true;
602}
603
Rafael Espindola46fa2312016-08-29 12:33:42 +0000604void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
605 const TargetMachine &TM) {
606 TargetLoweringObjectFile::Initialize(Ctx, TM);
Rafael Espindola412a5292016-08-29 12:47:22 +0000607 if (TM.getRelocationModel() == Reloc::Static) {
Rafael Espindola46fa2312016-08-29 12:33:42 +0000608 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
609 SectionKind::getData());
610 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
611 SectionKind::getData());
612 } else {
613 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
614 MachO::S_MOD_INIT_FUNC_POINTERS,
615 SectionKind::getData());
616 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
617 MachO::S_MOD_TERM_FUNC_POINTERS,
618 SectionKind::getData());
619 }
620}
621
Peter Collingbourne89061b22017-06-12 20:10:48 +0000622void TargetLoweringObjectFileMachO::emitModuleMetadata(
623 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
Daniel Dunbar95856122013-01-18 19:37:00 +0000624 // Emit the linker options if present.
Peter Collingbourne89061b22017-06-12 20:10:48 +0000625 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000626 for (const auto &Option : LinkerOptions->operands()) {
Daniel Dunbar95856122013-01-18 19:37:00 +0000627 SmallVector<std::string, 4> StrOptions;
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000628 for (const auto &Piece : cast<MDNode>(Option)->operands())
629 StrOptions.push_back(cast<MDString>(Piece)->getString());
Daniel Dunbar95856122013-01-18 19:37:00 +0000630 Streamer.EmitLinkerOptions(StrOptions);
631 }
Bill Wendling06df7722012-02-14 21:28:13 +0000632 }
633
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000634 unsigned VersionVal = 0;
635 unsigned ImageInfoFlags = 0;
636 StringRef SectionVal;
Peter Collingbourne89061b22017-06-12 20:10:48 +0000637
638 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000639
Bill Wendling734909a2012-02-15 22:36:15 +0000640 // The section is mandatory. If we don't have it, then we don't have GC info.
Saleem Abdulrasool4c474342017-06-05 21:26:39 +0000641 if (SectionVal.empty())
642 return;
Bill Wendling06df7722012-02-14 21:28:13 +0000643
Bill Wendling734909a2012-02-15 22:36:15 +0000644 StringRef Segment, Section;
645 unsigned TAA = 0, StubSize = 0;
646 bool TAAParsed;
647 std::string ErrorCode =
648 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
649 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000650 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000651 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000652 report_fatal_error("Invalid section specifier '" + Section + "': " +
653 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000654
Bill Wendling734909a2012-02-15 22:36:15 +0000655 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000656 MCSectionMachO *S = getContext().getMachOSection(
Rafael Espindola449711c2015-11-18 06:02:15 +0000657 Segment, Section, TAA, StubSize, SectionKind::getData());
Bill Wendling734909a2012-02-15 22:36:15 +0000658 Streamer.SwitchSection(S);
659 Streamer.EmitLabel(getContext().
Jim Grosbach6f482002015-05-18 18:43:14 +0000660 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000661 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000662 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000663 Streamer.AddBlankLine();
664}
665
David Majnemerdad0a642014-06-27 18:19:56 +0000666static void checkMachOComdat(const GlobalValue *GV) {
667 const Comdat *C = GV->getComdat();
668 if (!C)
669 return;
670
671 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
672 "' cannot be lowered.");
673}
674
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000675MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000676 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000677 // Parse the section specifier and create it if valid.
678 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000679 unsigned TAA = 0, StubSize = 0;
680 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000681
Peter Collingbourne67335642016-10-24 19:23:39 +0000682 checkMachOComdat(GO);
David Majnemerdad0a642014-06-27 18:19:56 +0000683
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000684 std::string ErrorCode =
Peter Collingbourne67335642016-10-24 19:23:39 +0000685 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000686 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000687 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000688 // If invalid, report the error with report_fatal_error.
Peter Collingbourne67335642016-10-24 19:23:39 +0000689 report_fatal_error("Global variable '" + GO->getName() +
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000690 "' has an invalid section specifier '" +
Peter Collingbourne67335642016-10-24 19:23:39 +0000691 GO->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000692 }
693
694 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000695 MCSectionMachO *S =
696 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000697
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000698 // If TAA wasn't set by ParseSectionSpecifier() above,
699 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000700 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000701 TAA = S->getTypeAndAttributes();
702
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000703 // Okay, now that we got the section, verify that the TAA & StubSize agree.
704 // If the user declared multiple globals with different section flags, we need
705 // to reject it here.
706 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000707 // If invalid, report the error with report_fatal_error.
Peter Collingbourne67335642016-10-24 19:23:39 +0000708 report_fatal_error("Global variable '" + GO->getName() +
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000709 "' section type or attributes does not match previous"
710 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000711 }
712
713 return S;
714}
715
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000716MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000717 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
718 checkMachOComdat(GO);
Bill Wendling25b61db2013-11-17 10:53:13 +0000719
720 // Handle thread local data.
721 if (Kind.isThreadBSS()) return TLSBSSSection;
722 if (Kind.isThreadData()) return TLSDataSection;
723
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000724 if (Kind.isText())
Peter Collingbourne67335642016-10-24 19:23:39 +0000725 return GO->isWeakForLinker() ? TextCoalSection : TextSection;
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000726
727 // If this is weak/linkonce, put this in a coalescable section, either in text
728 // or data depending on if it is writable.
Peter Collingbourne67335642016-10-24 19:23:39 +0000729 if (GO->isWeakForLinker()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000730 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000731 return ConstTextCoalSection;
732 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000733 }
734
735 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000736 if (Kind.isMergeable1ByteCString() &&
Peter Collingbourne67335642016-10-24 19:23:39 +0000737 GO->getParent()->getDataLayout().getPreferredAlignment(
738 cast<GlobalVariable>(GO)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000739 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000740
Chris Lattneref2f8042010-03-07 04:28:09 +0000741 // Do not put 16-bit arrays in the UString section if they have an
742 // externally visible label, this runs into issues with certain linker
743 // versions.
Peter Collingbourne67335642016-10-24 19:23:39 +0000744 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
745 GO->getParent()->getDataLayout().getPreferredAlignment(
746 cast<GlobalVariable>(GO)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000747 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000748
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000749 // With MachO only variables whose corresponding symbol starts with 'l' or
750 // 'L' can be merged, so we only try merging GVs with private linkage.
Peter Collingbourne67335642016-10-24 19:23:39 +0000751 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000752 if (Kind.isMergeableConst4())
753 return FourByteConstantSection;
754 if (Kind.isMergeableConst8())
755 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000756 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000757 return SixteenByteConstantSection;
758 }
759
760 // Otherwise, if it is readonly, but not something we can specially optimize,
761 // just drop it in .const.
762 if (Kind.isReadOnly())
763 return ReadOnlySection;
764
765 // If this is marked const, put it into a const section. But if the dynamic
766 // linker needs to write to it, put it in the data segment.
767 if (Kind.isReadOnlyWithRel())
768 return ConstDataSection;
769
770 // Put zero initialized globals with strong external linkage in the
771 // DATA, __common section with the .zerofill directive.
772 if (Kind.isBSSExtern())
773 return DataCommonSection;
774
775 // Put zero initialized globals with local linkage in __DATA,__bss directive
776 // with the .zerofill directive (aka .lcomm).
777 if (Kind.isBSSLocal())
778 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000779
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000780 // Otherwise, just drop the variable in the normal data section.
781 return DataSection;
782}
783
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000784MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000785 const DataLayout &DL, SectionKind Kind, const Constant *C,
786 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000787 // If this constant requires a relocation, we have to put it in the data
788 // segment, not in the text segment.
Rafael Espindola449711c2015-11-18 06:02:15 +0000789 if (Kind.isData() || Kind.isReadOnlyWithRel())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000790 return ConstDataSection;
791
792 if (Kind.isMergeableConst4())
793 return FourByteConstantSection;
794 if (Kind.isMergeableConst8())
795 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000796 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000797 return SixteenByteConstantSection;
798 return ReadOnlySection; // .const
799}
800
Rafael Espindola15b26692014-02-09 14:50:44 +0000801const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000802 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
803 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000804 // The mach-o version of this method defaults to returning a stub reference.
805
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000806 if (Encoding & DW_EH_PE_indirect) {
807 MachineModuleInfoMachO &MachOMMI =
808 MMI->getObjFileInfo<MachineModuleInfoMachO>();
809
Eric Christopher4367c7f2016-09-16 07:33:15 +0000810 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000811
812 // Add information about the stub reference to MachOMMI so that the stub
813 // gets emitted by the asmprinter.
Rafael Espindola712f9572016-05-17 16:01:32 +0000814 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000815 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000816 MCSymbol *Sym = TM.getSymbol(GV);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000817 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000818 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000819
820 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000821 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000822 Encoding & ~DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000823 }
824
Eric Christopher4367c7f2016-09-16 07:33:15 +0000825 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
826 MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000827}
828
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000829MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000830 const GlobalValue *GV, const TargetMachine &TM,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000831 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000832 // The mach-o version of this method defaults to returning a stub reference.
833 MachineModuleInfoMachO &MachOMMI =
834 MMI->getObjFileInfo<MachineModuleInfoMachO>();
835
Eric Christopher4367c7f2016-09-16 07:33:15 +0000836 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000837
838 // Add information about the stub reference to MachOMMI so that the stub
839 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000840 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000841 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000842 MCSymbol *Sym = TM.getSymbol(GV);
Rafael Espindola08704342011-04-27 23:08:15 +0000843 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
844 }
845
846 return SSym;
847}
848
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000849const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
850 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
851 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000852 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000853 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
854 // through a non_lazy_ptr stub instead. One advantage is that it allows the
855 // computation of deltas to final external symbols. Example:
856 //
857 // _extgotequiv:
858 // .long _extfoo
859 //
860 // _delta:
861 // .long _extgotequiv-_delta
862 //
863 // is transformed to:
864 //
865 // _delta:
866 // .long L_extfoo$non_lazy_ptr-(_delta+0)
867 //
868 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
869 // L_extfoo$non_lazy_ptr:
870 // .indirect_symbol _extfoo
871 // .long 0
872 //
873 MachineModuleInfoMachO &MachOMMI =
874 MMI->getObjFileInfo<MachineModuleInfoMachO>();
875 MCContext &Ctx = getContext();
876
877 // The offset must consider the original displacement from the base symbol
878 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
879 Offset = -MV.getConstant();
880 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
881
882 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
883 // non_lazy_ptr stubs.
884 SmallString<128> Name;
885 StringRef Suffix = "$non_lazy_ptr";
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000886 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000887 Name += Sym->getName();
888 Name += Suffix;
Jim Grosbach6f482002015-05-18 18:43:14 +0000889 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000890
891 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
892 if (!StubSym.getPointer())
893 StubSym = MachineModuleInfoImpl::
894 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
895
896 const MCExpr *BSymExpr =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000897 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000898 const MCExpr *LHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000899 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000900
901 if (!Offset)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000902 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000903
904 const MCExpr *RHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000905 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
906 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000907}
908
Peter Collingbourne94d77862015-11-03 23:40:03 +0000909static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
910 const MCSection &Section) {
911 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
912 return true;
913
914 // If it is not dead stripped, it is safe to use private labels.
915 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
916 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
917 return true;
918
919 return false;
920}
921
922void TargetLoweringObjectFileMachO::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000923 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +0000924 const TargetMachine &TM) const {
Peter Collingbourne67335642016-10-24 19:23:39 +0000925 bool CannotUsePrivateLabel = true;
926 if (auto *GO = GV->getBaseObject()) {
927 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
928 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
929 CannotUsePrivateLabel =
930 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
931 }
Eric Christopher4367c7f2016-09-16 07:33:15 +0000932 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
Peter Collingbourne94d77862015-11-03 23:40:03 +0000933}
934
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000935//===----------------------------------------------------------------------===//
936// COFF
937//===----------------------------------------------------------------------===//
938
Chris Lattner87cffa92010-05-07 17:17:41 +0000939static unsigned
Renato Golinef3eb062016-06-27 14:42:20 +0000940getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
Chris Lattner87cffa92010-05-07 17:17:41 +0000941 unsigned Flags = 0;
Renato Golinef3eb062016-06-27 14:42:20 +0000942 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
Chris Lattner87cffa92010-05-07 17:17:41 +0000943
Anton Korobeynikove4152302010-07-06 15:24:56 +0000944 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000945 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000946 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000947 else if (K.isText())
948 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000949 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000950 COFF::IMAGE_SCN_MEM_READ |
Renato Golinef3eb062016-06-27 14:42:20 +0000951 COFF::IMAGE_SCN_CNT_CODE |
952 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
David Majnemerb8dbebb2014-09-20 07:31:46 +0000953 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000954 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000955 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
956 COFF::IMAGE_SCN_MEM_READ |
957 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000958 else if (K.isThreadLocal())
959 Flags |=
960 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
961 COFF::IMAGE_SCN_MEM_READ |
962 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000963 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000964 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000965 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
966 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000967 else if (K.isWriteable())
968 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000969 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
970 COFF::IMAGE_SCN_MEM_READ |
971 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000972
973 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000974}
975
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000976static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000977 const Comdat *C = GV->getComdat();
978 assert(C && "expected GV to have a Comdat!");
979
980 StringRef ComdatGVName = C->getName();
981 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
982 if (!ComdatGV)
983 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
984 "' does not exist.");
985
986 if (ComdatGV->getComdat() != C)
987 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000988 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000989
990 return ComdatGV;
991}
992
993static int getSelectionForCOFF(const GlobalValue *GV) {
994 if (const Comdat *C = GV->getComdat()) {
995 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
996 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
997 ComdatKey = GA->getBaseObject();
998 if (ComdatKey == GV) {
999 switch (C->getSelectionKind()) {
1000 case Comdat::Any:
1001 return COFF::IMAGE_COMDAT_SELECT_ANY;
1002 case Comdat::ExactMatch:
1003 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
1004 case Comdat::Largest:
1005 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
1006 case Comdat::NoDuplicates:
1007 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1008 case Comdat::SameSize:
1009 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
1010 }
1011 } else {
1012 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
1013 }
David Majnemerdad0a642014-06-27 18:19:56 +00001014 }
1015 return 0;
1016}
1017
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001018MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +00001019 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +00001020 int Selection = 0;
Renato Golinef3eb062016-06-27 14:42:20 +00001021 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Peter Collingbourne67335642016-10-24 19:23:39 +00001022 StringRef Name = GO->getSection();
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001023 StringRef COMDATSymName = "";
Peter Collingbourne67335642016-10-24 19:23:39 +00001024 if (GO->hasComdat()) {
1025 Selection = getSelectionForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001026 const GlobalValue *ComdatGV;
1027 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
Peter Collingbourne67335642016-10-24 19:23:39 +00001028 ComdatGV = getComdatGVForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001029 else
Peter Collingbourne67335642016-10-24 19:23:39 +00001030 ComdatGV = GO;
David Majnemerdad0a642014-06-27 18:19:56 +00001031
1032 if (!ComdatGV->hasPrivateLinkage()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001033 MCSymbol *Sym = TM.getSymbol(ComdatGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001034 COMDATSymName = Sym->getName();
1035 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1036 } else {
1037 Selection = 0;
1038 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +00001039 }
Reid Kleckner97837b72016-05-02 23:22:18 +00001040
1041 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +00001042 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001043}
1044
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001045static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001046 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001047 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +00001048 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001049 return ".bss";
1050 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +00001051 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +00001052 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1053 return ".rdata";
1054 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001055}
1056
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001057MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +00001058 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +00001059 // If we have -ffunction-sections then we should emit the global value to a
1060 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +00001061 bool EmitUniquedSection;
1062 if (Kind.isText())
1063 EmitUniquedSection = TM.getFunctionSections();
1064 else
1065 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001066
Peter Collingbourne67335642016-10-24 19:23:39 +00001067 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001068 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +00001069 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Chris Lattner02844932010-05-07 21:49:09 +00001070
Daniel Dunbar329d2022010-07-01 20:07:24 +00001071 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Peter Collingbourne67335642016-10-24 19:23:39 +00001072 int Selection = getSelectionForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001073 if (!Selection)
1074 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1075 const GlobalValue *ComdatGV;
Peter Collingbourne67335642016-10-24 19:23:39 +00001076 if (GO->hasComdat())
1077 ComdatGV = getComdatGVForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001078 else
Peter Collingbourne67335642016-10-24 19:23:39 +00001079 ComdatGV = GO;
David Majnemerdad0a642014-06-27 18:19:56 +00001080
Reid Kleckner97837b72016-05-02 23:22:18 +00001081 unsigned UniqueID = MCContext::GenericSectionID;
1082 if (EmitUniquedSection)
1083 UniqueID = NextUniqueID++;
1084
David Majnemerdad0a642014-06-27 18:19:56 +00001085 if (!ComdatGV->hasPrivateLinkage()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001086 MCSymbol *Sym = TM.getSymbol(ComdatGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001087 StringRef COMDATSymName = Sym->getName();
1088 return getContext().getCOFFSection(Name, Characteristics, Kind,
Reid Kleckner97837b72016-05-02 23:22:18 +00001089 COMDATSymName, Selection, UniqueID);
David Majnemer7db449a2015-03-17 23:54:51 +00001090 } else {
1091 SmallString<256> TmpData;
Peter Collingbourne67335642016-10-24 19:23:39 +00001092 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
David Majnemer7db449a2015-03-17 23:54:51 +00001093 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
Reid Kleckner97837b72016-05-02 23:22:18 +00001094 Selection, UniqueID);
David Majnemerdad0a642014-06-27 18:19:56 +00001095 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001096 }
1097
1098 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +00001099 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001100
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001101 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +00001102 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001103
David Majnemer597be2d2014-09-22 20:39:23 +00001104 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +00001105 return ReadOnlySection;
1106
David Majnemera9bdb322014-04-08 22:33:40 +00001107 // Note: we claim that common symbols are put in BSSSection, but they are
1108 // really emitted with the magic .comm directive, which creates a symbol table
1109 // entry but not a section.
1110 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +00001111 return BSSSection;
1112
1113 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001114}
1115
David Majnemer7db449a2015-03-17 23:54:51 +00001116void TargetLoweringObjectFileCOFF::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001117 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +00001118 const TargetMachine &TM) const {
1119 bool CannotUsePrivateLabel = false;
David Majnemer7db449a2015-03-17 23:54:51 +00001120 if (GV->hasPrivateLinkage() &&
1121 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1122 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1123 CannotUsePrivateLabel = true;
1124
Eric Christopher4367c7f2016-09-16 07:33:15 +00001125 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
David Majnemer7db449a2015-03-17 23:54:51 +00001126}
1127
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001128MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001129 const Function &F, const TargetMachine &TM) const {
Rafael Espindolaab447e42015-03-11 19:58:37 +00001130 // If the function can be removed, produce a unique section so that
1131 // the table doesn't prevent the removal.
1132 const Comdat *C = F.getComdat();
1133 bool EmitUniqueSection = TM.getFunctionSections() || C;
1134 if (!EmitUniqueSection)
1135 return ReadOnlySection;
1136
1137 // FIXME: we should produce a symbol for F instead.
1138 if (F.hasPrivateLinkage())
1139 return ReadOnlySection;
1140
Tim Northoverb64fb452016-11-22 16:17:20 +00001141 MCSymbol *Sym = TM.getSymbol(&F);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001142 StringRef COMDATSymName = Sym->getName();
1143
1144 SectionKind Kind = SectionKind::getReadOnly();
1145 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +00001146 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001147 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Reid Kleckner97837b72016-05-02 23:22:18 +00001148 unsigned UniqueID = NextUniqueID++;
Rafael Espindolaab447e42015-03-11 19:58:37 +00001149
1150 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Reid Kleckner97837b72016-05-02 23:22:18 +00001151 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001152}
1153
Peter Collingbourne89061b22017-06-12 20:10:48 +00001154void TargetLoweringObjectFileCOFF::emitModuleMetadata(
1155 MCStreamer &Streamer, Module &M, const TargetMachine &TM) const {
1156 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001157 // Emit the linker options to the linker .drectve section. According to the
1158 // spec, this section is a space-separated string containing flags for
1159 // linker.
1160 MCSection *Sec = getDrectveSection();
1161 Streamer.SwitchSection(Sec);
1162 for (const auto &Option : LinkerOptions->operands()) {
1163 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1164 // Lead with a space for consistency with our dllexport implementation.
1165 std::string Directive(" ");
1166 Directive.append(cast<MDString>(Piece)->getString());
1167 Streamer.EmitBytes(Directive);
1168 }
Reid Klecknerd973ca32013-04-25 19:34:41 +00001169 }
1170 }
Saleem Abdulrasool4c474342017-06-05 21:26:39 +00001171
1172 unsigned Version = 0;
1173 unsigned Flags = 0;
1174 StringRef Section;
1175
Peter Collingbourne89061b22017-06-12 20:10:48 +00001176 GetObjCImageInfo(M, Version, Flags, Section);
Saleem Abdulrasool4c474342017-06-05 21:26:39 +00001177 if (Section.empty())
1178 return;
1179
1180 auto &C = getContext();
1181 auto *S = C.getCOFFSection(
1182 Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
1183 SectionKind::getReadOnly());
1184 Streamer.SwitchSection(S);
1185 Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
1186 Streamer.EmitIntValue(Version, 4);
1187 Streamer.EmitIntValue(Flags, 4);
1188 Streamer.AddBlankLine();
Reid Klecknerd973ca32013-04-25 19:34:41 +00001189}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001190
Rafael Espindola46fa2312016-08-29 12:33:42 +00001191void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1192 const TargetMachine &TM) {
1193 TargetLoweringObjectFile::Initialize(Ctx, TM);
1194 const Triple &T = TM.getTargetTriple();
1195 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1196 StaticCtorSection =
1197 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1198 COFF::IMAGE_SCN_MEM_READ,
1199 SectionKind::getReadOnly());
1200 StaticDtorSection =
1201 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1202 COFF::IMAGE_SCN_MEM_READ,
1203 SectionKind::getReadOnly());
1204 } else {
1205 StaticCtorSection = Ctx.getCOFFSection(
1206 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1207 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1208 SectionKind::getData());
1209 StaticDtorSection = Ctx.getCOFFSection(
1210 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1211 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1212 SectionKind::getData());
1213 }
1214}
1215
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001216MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001217 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001218 return getContext().getAssociativeCOFFSection(
Reid Kleckner97837b72016-05-02 23:22:18 +00001219 cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001220}
1221
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001222MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001223 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001224 return getContext().getAssociativeCOFFSection(
Reid Kleckner97837b72016-05-02 23:22:18 +00001225 cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001226}
Peter Collingbourneaef36592015-06-29 22:04:09 +00001227
1228void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001229 raw_ostream &OS, const GlobalValue *GV) const {
Bob Haarmandd4ebc12017-02-02 23:00:49 +00001230 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
Peter Collingbourneaef36592015-06-29 22:04:09 +00001231}
Dan Gohman18eafb62017-02-22 01:23:18 +00001232
1233//===----------------------------------------------------------------------===//
1234// Wasm
1235//===----------------------------------------------------------------------===//
1236
Dan Gohmand934cb82017-02-24 23:18:00 +00001237static const Comdat *getWasmComdat(const GlobalValue *GV) {
1238 const Comdat *C = GV->getComdat();
1239 if (!C)
1240 return nullptr;
1241
1242 if (C->getSelectionKind() != Comdat::Any)
1243 report_fatal_error("Wasm COMDATs only support SelectionKind::Any, '" +
1244 C->getName() + "' cannot be lowered.");
1245
1246 return C;
1247}
1248
Dan Gohman18eafb62017-02-22 01:23:18 +00001249MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1250 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1251 llvm_unreachable("getExplicitSectionGlobal not yet implemented");
1252 return nullptr;
1253}
1254
Dan Gohmand934cb82017-02-24 23:18:00 +00001255static MCSectionWasm *
1256selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO,
1257 SectionKind Kind, Mangler &Mang,
1258 const TargetMachine &TM, bool EmitUniqueSection,
1259 unsigned Flags, unsigned *NextUniqueID) {
1260 StringRef Group = "";
1261 if (getWasmComdat(GO))
1262 llvm_unreachable("comdat not yet supported for wasm");
1263
1264 bool UniqueSectionNames = TM.getUniqueSectionNames();
1265 SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1266
1267 if (const auto *F = dyn_cast<Function>(GO)) {
1268 const auto &OptionalPrefix = F->getSectionPrefix();
1269 if (OptionalPrefix)
1270 Name += *OptionalPrefix;
1271 }
1272
1273 if (EmitUniqueSection && UniqueSectionNames) {
1274 Name.push_back('.');
1275 TM.getNameWithPrefix(Name, GO, Mang, true);
1276 }
1277 unsigned UniqueID = MCContext::GenericSectionID;
1278 if (EmitUniqueSection && !UniqueSectionNames) {
1279 UniqueID = *NextUniqueID;
1280 (*NextUniqueID)++;
1281 }
1282 return Ctx.getWasmSection(Name, /*Type=*/0, Flags,
1283 Group, UniqueID);
1284}
1285
Dan Gohman18eafb62017-02-22 01:23:18 +00001286MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1287 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Dan Gohmand934cb82017-02-24 23:18:00 +00001288
1289 if (Kind.isCommon())
1290 report_fatal_error("mergable sections not supported yet on wasm");
1291
1292 // If we have -ffunction-section or -fdata-section then we should emit the
1293 // global value to a uniqued section specifically for it.
1294 bool EmitUniqueSection = false;
Dan Gohman18eafb62017-02-22 01:23:18 +00001295 if (Kind.isText())
Dan Gohmand934cb82017-02-24 23:18:00 +00001296 EmitUniqueSection = TM.getFunctionSections();
1297 else
1298 EmitUniqueSection = TM.getDataSections();
1299 EmitUniqueSection |= GO->hasComdat();
1300
1301 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1302 EmitUniqueSection, /*Flags=*/0,
1303 &NextUniqueID);
Dan Gohman18eafb62017-02-22 01:23:18 +00001304}
1305
1306bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1307 bool UsesLabelDifference, const Function &F) const {
1308 // We can always create relative relocations, so use another section
1309 // that can be marked non-executable.
1310 return false;
1311}
1312
1313const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1314 const GlobalValue *LHS, const GlobalValue *RHS,
1315 const TargetMachine &TM) const {
1316 // We may only use a PLT-relative relocation to refer to unnamed_addr
1317 // functions.
1318 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1319 return nullptr;
1320
1321 // Basic sanity checks.
1322 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1323 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1324 RHS->isThreadLocal())
1325 return nullptr;
1326
1327 return MCBinaryExpr::createSub(
1328 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1329 getContext()),
1330 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1331}
1332
1333void
1334TargetLoweringObjectFileWasm::InitializeWasm() {
1335 // TODO: Initialize StaticCtorSection and StaticDtorSection.
1336}