blob: 1439ff2ad1af56dc5f40f7e8021364ae5f5766df [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 Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/SmallString.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000016#include "llvm/ADT/SmallVector.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/StringExtras.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000018#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000019#include "llvm/ADT/Triple.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000020#include "llvm/CodeGen/MachineModuleInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/CodeGen/MachineModuleInfoImpls.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000022#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
23#include "llvm/IR/Comdat.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/Function.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000028#include "llvm/IR/GlobalAlias.h"
29#include "llvm/IR/GlobalObject.h"
30#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/GlobalVariable.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000032#include "llvm/IR/Mangler.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000033#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/Module.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000035#include "llvm/IR/Type.h"
Peter Collingbourne94d77862015-11-03 23:40:03 +000036#include "llvm/MC/MCAsmInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000037#include "llvm/MC/MCContext.h"
38#include "llvm/MC/MCExpr.h"
Chris Lattner87cffa92010-05-07 17:17:41 +000039#include "llvm/MC/MCSectionCOFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000040#include "llvm/MC/MCSectionELF.h"
41#include "llvm/MC/MCSectionMachO.h"
Dan Gohman18eafb62017-02-22 01:23:18 +000042#include "llvm/MC/MCSectionWasm.h"
Rafael Espindolaa83b1772011-04-16 03:51:21 +000043#include "llvm/MC/MCStreamer.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000044#include "llvm/MC/MCSymbol.h"
Rafael Espindolaa8695762015-06-02 00:25:12 +000045#include "llvm/MC/MCSymbolELF.h"
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +000046#include "llvm/MC/MCValue.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000047#include "llvm/MC/SectionKind.h"
Xinliang David Li5f04f922016-01-14 18:09:45 +000048#include "llvm/ProfileData/InstrProf.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000049#include "llvm/Support/Casting.h"
50#include "llvm/Support/CodeGen.h"
Reid Kleckner1f13d472015-09-03 16:41:50 +000051#include "llvm/Support/COFF.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000052#include "llvm/Support/Dwarf.h"
Rafael Espindolaaea49582011-01-23 04:28:49 +000053#include "llvm/Support/ELF.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000054#include "llvm/Support/ErrorHandling.h"
Eugene Zelenkofa912a72017-02-27 22:45:06 +000055#include "llvm/Support/MachO.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000056#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
64//===----------------------------------------------------------------------===//
65// ELF
66//===----------------------------------------------------------------------===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +000067
Rafael Espindoladaeafb42014-02-19 17:23:20 +000068MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
Eric Christopher4367c7f2016-09-16 07:33:15 +000069 const GlobalValue *GV, const TargetMachine &TM,
Rafael Espindoladaeafb42014-02-19 17:23:20 +000070 MachineModuleInfo *MMI) const {
Rafael Espindolace83fc32011-04-27 23:17:57 +000071 unsigned Encoding = getPersonalityEncoding();
Eugene Zelenkofa912a72017-02-27 22:45:06 +000072 if ((Encoding & 0x80) == DW_EH_PE_indirect)
Jim Grosbach6f482002015-05-18 18:43:14 +000073 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
Tim Northoverb64fb452016-11-22 16:17:20 +000074 TM.getSymbol(GV)->getName());
Eugene Zelenkofa912a72017-02-27 22:45:06 +000075 if ((Encoding & 0x70) == DW_EH_PE_absptr)
Tim Northoverb64fb452016-11-22 16:17:20 +000076 return TM.getSymbol(GV);
Logan Chienc0029812014-05-30 16:48:56 +000077 report_fatal_error("We do not support this DWARF encoding yet!");
Rafael Espindolaa83b1772011-04-16 03:51:21 +000078}
79
Mehdi Amini5c0fa582015-07-16 06:04:17 +000080void TargetLoweringObjectFileELF::emitPersonalityValue(
81 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000082 SmallString<64> NameData("DW.ref.");
83 NameData += Sym->getName();
Rafael Espindolaa8695762015-06-02 00:25:12 +000084 MCSymbolELF *Label =
85 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
Rafael Espindola39897762011-04-27 21:29:52 +000086 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
87 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola39897762011-04-27 21:29:52 +000088 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
Eric Christopher36e601c2016-07-01 06:07:38 +000089 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
90 ELF::SHT_PROGBITS, Flags, 0);
Mehdi Amini5c0fa582015-07-16 06:04:17 +000091 unsigned Size = DL.getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +000092 Streamer.SwitchSection(Sec);
Mehdi Amini5c0fa582015-07-16 06:04:17 +000093 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +000094 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
Jim Grosbach13760bd2015-05-30 01:25:56 +000095 const MCExpr *E = MCConstantExpr::create(Size, getContext());
Rafael Espindolaa8695762015-06-02 00:25:12 +000096 Streamer.emitELFSize(Label, E);
Rafael Espindola39897762011-04-27 21:29:52 +000097 Streamer.EmitLabel(Label);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000098
Rafael Espindola39897762011-04-27 21:29:52 +000099 Streamer.EmitSymbolValue(Sym, Size);
Rafael Espindolaa83b1772011-04-16 03:51:21 +0000100}
101
Rafael Espindola15b26692014-02-09 14:50:44 +0000102const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000103 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
104 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000105 if (Encoding & DW_EH_PE_indirect) {
Anton Korobeynikove42af362012-11-14 01:47:00 +0000106 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
107
Eric Christopher4367c7f2016-09-16 07:33:15 +0000108 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000109
110 // Add information about the stub reference to ELFMMI so that the stub
111 // gets emitted by the asmprinter.
Anton Korobeynikove42af362012-11-14 01:47:00 +0000112 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000113 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000114 MCSymbol *Sym = TM.getSymbol(GV);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000115 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
116 }
117
118 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000119 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000120 Encoding & ~DW_EH_PE_indirect, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000121 }
122
Eric Christopher4367c7f2016-09-16 07:33:15 +0000123 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
124 MMI, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000125}
126
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000127static SectionKind
128getELFKindForNamedSection(StringRef Name, SectionKind K) {
Rafael Espindola0d018b12011-05-24 03:10:31 +0000129 // N.B.: The defaults used in here are no the same ones used in MC.
130 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
131 // both gas and MC will produce a section with no flags. Given
Bill Wendlingd1634052012-07-19 00:04:14 +0000132 // section(".eh_frame") gcc will produce:
133 //
134 // .section .eh_frame,"a",@progbits
Xinliang David Li5f04f922016-01-14 18:09:45 +0000135
136 if (Name == getInstrProfCoverageSectionName(false))
137 return SectionKind::getMetadata();
138
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000139 if (Name.empty() || Name[0] != '.') return K;
140
141 // Some lame default implementation based on some magic section names.
142 if (Name == ".bss" ||
143 Name.startswith(".bss.") ||
144 Name.startswith(".gnu.linkonce.b.") ||
145 Name.startswith(".llvm.linkonce.b.") ||
146 Name == ".sbss" ||
147 Name.startswith(".sbss.") ||
148 Name.startswith(".gnu.linkonce.sb.") ||
149 Name.startswith(".llvm.linkonce.sb."))
150 return SectionKind::getBSS();
151
152 if (Name == ".tdata" ||
153 Name.startswith(".tdata.") ||
154 Name.startswith(".gnu.linkonce.td.") ||
155 Name.startswith(".llvm.linkonce.td."))
156 return SectionKind::getThreadData();
157
158 if (Name == ".tbss" ||
159 Name.startswith(".tbss.") ||
160 Name.startswith(".gnu.linkonce.tb.") ||
161 Name.startswith(".llvm.linkonce.tb."))
162 return SectionKind::getThreadBSS();
163
164 return K;
165}
166
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000167static unsigned getELFSectionType(StringRef Name, SectionKind K) {
Petr Hosek12903552016-09-20 20:21:13 +0000168 // Use SHT_NOTE for section whose name starts with ".note" to allow
169 // emitting ELF notes from C variable declaration.
170 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
171 if (Name.startswith(".note"))
172 return ELF::SHT_NOTE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000173
174 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000175 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000176
177 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000178 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000179
180 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000181 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000182
183 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000184 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000185
Rafael Espindolaaea49582011-01-23 04:28:49 +0000186 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000187}
188
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000189static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000190 unsigned Flags = 0;
191
192 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000193 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000194
195 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000196 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000197
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000198 if (K.isExecuteOnly())
199 Flags |= ELF::SHF_ARM_PURECODE;
200
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000201 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000202 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000203
204 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000205 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000206
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000207 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000208 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000209
210 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000211 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000212
213 return Flags;
214}
215
David Majnemerdad0a642014-06-27 18:19:56 +0000216static const Comdat *getELFComdat(const GlobalValue *GV) {
217 const Comdat *C = GV->getComdat();
218 if (!C)
219 return nullptr;
220
221 if (C->getSelectionKind() != Comdat::Any)
222 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
223 C->getName() + "' cannot be lowered.");
224
225 return C;
226}
227
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000228static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
229 const TargetMachine &TM) {
230 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
231 if (!MD)
232 return nullptr;
233
234 auto *VM = dyn_cast<ValueAsMetadata>(MD->getOperand(0));
235 if (!VM)
236 report_fatal_error("MD_associated operand is not ValueAsMetadata");
237
238 GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
239 return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
240}
241
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000242MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000243 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
244 StringRef SectionName = GO->getSection();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000245
246 // Infer section flags from the section name if we can.
247 Kind = getELFKindForNamedSection(SectionName, Kind);
248
David Majnemerdad0a642014-06-27 18:19:56 +0000249 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000250 unsigned Flags = getELFSectionFlags(Kind);
Peter Collingbourne67335642016-10-24 19:23:39 +0000251 if (const Comdat *C = getELFComdat(GO)) {
David Majnemerdad0a642014-06-27 18:19:56 +0000252 Group = C->getName();
253 Flags |= ELF::SHF_GROUP;
254 }
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000255
256 // A section can have at most one associated section. Put each global with
257 // MD_associated in a unique section.
258 unsigned UniqueID = MCContext::GenericSectionID;
259 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
260 if (AssociatedSymbol) {
261 UniqueID = NextUniqueID++;
262 Flags |= ELF::SHF_LINK_ORDER;
263 }
264
265 MCSectionELF *Section = getContext().getELFSection(
266 SectionName, getELFSectionType(SectionName, Kind), Flags,
267 /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
268 // Make sure that we did not get some other section with incompatible sh_link.
269 // This should not be possible due to UniqueID code above.
270 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
271 return Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000272}
273
Rafael Espindola25d2c202015-02-11 14:44:17 +0000274/// Return the section prefix name used by options FunctionsSections and
275/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000276static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000277 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000278 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000279 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000280 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000281 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000282 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000283 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000284 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000285 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000286 return ".tbss";
Rafael Espindola449711c2015-11-18 06:02:15 +0000287 if (Kind.isData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000288 return ".data";
Chris Lattner5b212a32010-04-13 00:36:43 +0000289 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000290 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000291}
292
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000293static MCSectionELF *selectELFSectionForGlobal(
294 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
295 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
296 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000297 unsigned EntrySize = 0;
298 if (Kind.isMergeableCString()) {
299 if (Kind.isMergeable2ByteCString()) {
300 EntrySize = 2;
301 } else if (Kind.isMergeable4ByteCString()) {
302 EntrySize = 4;
303 } else {
304 EntrySize = 1;
305 assert(Kind.isMergeable1ByteCString() && "unknown string width");
306 }
307 } else if (Kind.isMergeableConst()) {
308 if (Kind.isMergeableConst4()) {
309 EntrySize = 4;
310 } else if (Kind.isMergeableConst8()) {
311 EntrySize = 8;
David Majnemer964b70d2016-02-22 22:23:11 +0000312 } else if (Kind.isMergeableConst16()) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000313 EntrySize = 16;
David Majnemer964b70d2016-02-22 22:23:11 +0000314 } else {
315 assert(Kind.isMergeableConst32() && "unknown data width");
316 EntrySize = 32;
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000317 }
318 }
319
Rafael Espindola9075f772015-02-20 23:28:28 +0000320 StringRef Group = "";
Peter Collingbourne67335642016-10-24 19:23:39 +0000321 if (const Comdat *C = getELFComdat(GO)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000322 Flags |= ELF::SHF_GROUP;
323 Group = C->getName();
324 }
325
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000326 bool UniqueSectionNames = TM.getUniqueSectionNames();
327 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000328 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000329 // We also need alignment here.
330 // FIXME: this is getting the alignment of the character, not the
331 // alignment of the global!
Peter Collingbourne67335642016-10-24 19:23:39 +0000332 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
333 cast<GlobalVariable>(GO));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000334
Rafael Espindolaba31e272015-01-29 17:33:21 +0000335 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000336 Name = SizeSpec + utostr(Align);
337 } else if (Kind.isMergeableConst()) {
338 Name = ".rodata.cst";
339 Name += utostr(EntrySize);
340 } else {
341 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000342 }
Dehao Chen302b69c2016-10-18 20:42:47 +0000343
Peter Collingbourne67335642016-10-24 19:23:39 +0000344 if (const auto *F = dyn_cast<Function>(GO)) {
Dehao Chen302b69c2016-10-18 20:42:47 +0000345 const auto &OptionalPrefix = F->getSectionPrefix();
346 if (OptionalPrefix)
347 Name += *OptionalPrefix;
348 }
Dehao Chenf84b6302016-02-23 03:39:24 +0000349
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000350 if (EmitUniqueSection && UniqueSectionNames) {
351 Name.push_back('.');
Peter Collingbourne67335642016-10-24 19:23:39 +0000352 TM.getNameWithPrefix(Name, GO, Mang, true);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000353 }
Reid Kleckner97837b72016-05-02 23:22:18 +0000354 unsigned UniqueID = MCContext::GenericSectionID;
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000355 if (EmitUniqueSection && !UniqueSectionNames) {
356 UniqueID = *NextUniqueID;
357 (*NextUniqueID)++;
358 }
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000359 // Use 0 as the unique ID for execute-only text
360 if (Kind.isExecuteOnly())
361 UniqueID = 0;
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000362 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000363 EntrySize, Group, UniqueID, AssociatedSymbol);
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000364}
365
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000366MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000367 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000368 unsigned Flags = getELFSectionFlags(Kind);
369
370 // If we have -ffunction-section or -fdata-section then we should emit the
371 // global value to a uniqued section specifically for it.
372 bool EmitUniqueSection = false;
373 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
374 if (Kind.isText())
375 EmitUniqueSection = TM.getFunctionSections();
376 else
377 EmitUniqueSection = TM.getDataSections();
378 }
Peter Collingbourne67335642016-10-24 19:23:39 +0000379 EmitUniqueSection |= GO->hasComdat();
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000380
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000381 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
382 if (AssociatedSymbol) {
383 EmitUniqueSection = true;
384 Flags |= ELF::SHF_LINK_ORDER;
385 }
386
387 MCSectionELF *Section = selectELFSectionForGlobal(
388 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
389 &NextUniqueID, AssociatedSymbol);
390 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
391 return Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000392}
393
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000394MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000395 const Function &F, const TargetMachine &TM) const {
Rafael Espindola29786d42015-02-12 17:16:46 +0000396 // If the function can be removed, produce a unique section so that
397 // the table doesn't prevent the removal.
398 const Comdat *C = F.getComdat();
399 bool EmitUniqueSection = TM.getFunctionSections() || C;
400 if (!EmitUniqueSection)
401 return ReadOnlySection;
402
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000403 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000404 getMangler(), TM, EmitUniqueSection,
405 ELF::SHF_ALLOC, &NextUniqueID,
406 /* AssociatedSymbol */ nullptr);
Rafael Espindola29786d42015-02-12 17:16:46 +0000407}
408
Rafael Espindoladf195192015-02-17 23:34:51 +0000409bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
410 bool UsesLabelDifference, const Function &F) const {
411 // We can always create relative relocations, so use another section
412 // that can be marked non-executable.
413 return false;
414}
415
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000416/// Given a mergeable constant with the specified size and relocation
417/// information, return a section that it should be placed in.
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000418MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000419 const DataLayout &DL, SectionKind Kind, const Constant *C,
420 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000421 if (Kind.isMergeableConst4() && MergeableConst4Section)
422 return MergeableConst4Section;
423 if (Kind.isMergeableConst8() && MergeableConst8Section)
424 return MergeableConst8Section;
425 if (Kind.isMergeableConst16() && MergeableConst16Section)
426 return MergeableConst16Section;
David Majnemer964b70d2016-02-22 22:23:11 +0000427 if (Kind.isMergeableConst32() && MergeableConst32Section)
428 return MergeableConst32Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000429 if (Kind.isReadOnly())
430 return ReadOnlySection;
431
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000432 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
433 return DataRelROSection;
434}
435
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000436static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
437 bool IsCtor, unsigned Priority,
438 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000439 std::string Name;
440 unsigned Type;
441 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000442 StringRef COMDAT = KeySym ? KeySym->getName() : "";
443
444 if (KeySym)
445 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000446
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000447 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000448 if (IsCtor) {
449 Type = ELF::SHT_INIT_ARRAY;
450 Name = ".init_array";
451 } else {
452 Type = ELF::SHT_FINI_ARRAY;
453 Name = ".fini_array";
454 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000455 if (Priority != 65535) {
456 Name += '.';
457 Name += utostr(Priority);
458 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000459 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000460 // The default scheme is .ctor / .dtor, so we have to invert the priority
461 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000462 if (IsCtor)
463 Name = ".ctors";
464 else
465 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000466 if (Priority != 65535) {
467 Name += '.';
468 Name += utostr(65535 - Priority);
469 }
470 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000471 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000472
Rafael Espindolaba31e272015-01-29 17:33:21 +0000473 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000474}
475
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000476MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000477 unsigned Priority, const MCSymbol *KeySym) const {
478 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
479 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000480}
481
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000482MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000483 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000484 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
485 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000486}
487
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000488const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000489 const GlobalValue *LHS, const GlobalValue *RHS,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000490 const TargetMachine &TM) const {
491 // We may only use a PLT-relative relocation to refer to unnamed_addr
492 // functions.
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000493 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000494 return nullptr;
495
496 // Basic sanity checks.
497 if (LHS->getType()->getPointerAddressSpace() != 0 ||
498 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
499 RHS->isThreadLocal())
500 return nullptr;
501
502 return MCBinaryExpr::createSub(
Tim Northoverb64fb452016-11-22 16:17:20 +0000503 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000504 getContext()),
Tim Northoverb64fb452016-11-22 16:17:20 +0000505 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000506}
507
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000508void
509TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
510 UseInitArray = UseInitArray_;
Rafael Espindola46fa2312016-08-29 12:33:42 +0000511 MCContext &Ctx = getContext();
512 if (!UseInitArray) {
513 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
514 ELF::SHF_ALLOC | ELF::SHF_WRITE);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000515
Rafael Espindola46fa2312016-08-29 12:33:42 +0000516 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
517 ELF::SHF_ALLOC | ELF::SHF_WRITE);
518 return;
519 }
520
521 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
522 ELF::SHF_WRITE | ELF::SHF_ALLOC);
523 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
524 ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000525}
526
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000527//===----------------------------------------------------------------------===//
528// MachO
529//===----------------------------------------------------------------------===//
530
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000531TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
532 : TargetLoweringObjectFile() {
533 SupportIndirectSymViaGOTPCRel = true;
534}
535
Rafael Espindola46fa2312016-08-29 12:33:42 +0000536void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
537 const TargetMachine &TM) {
538 TargetLoweringObjectFile::Initialize(Ctx, TM);
Rafael Espindola412a5292016-08-29 12:47:22 +0000539 if (TM.getRelocationModel() == Reloc::Static) {
Rafael Espindola46fa2312016-08-29 12:33:42 +0000540 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
541 SectionKind::getData());
542 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
543 SectionKind::getData());
544 } else {
545 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
546 MachO::S_MOD_INIT_FUNC_POINTERS,
547 SectionKind::getData());
548 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
549 MachO::S_MOD_TERM_FUNC_POINTERS,
550 SectionKind::getData());
551 }
552}
553
Daniel Dunbar95856122013-01-18 19:37:00 +0000554/// emitModuleFlags - Perform code emission for module flags.
Eric Christopher4367c7f2016-09-16 07:33:15 +0000555void TargetLoweringObjectFileMachO::emitModuleFlags(
556 MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
557 const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000558 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000559 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000560 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000561 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000562
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000563 for (const auto &MFE : ModuleFlags) {
Bill Wendling06df7722012-02-14 21:28:13 +0000564 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000565 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000566 continue;
567
Bill Wendling734909a2012-02-15 22:36:15 +0000568 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000569 Metadata *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000570
Daniel Dunbar95856122013-01-18 19:37:00 +0000571 if (Key == "Objective-C Image Info Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000572 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000573 } else if (Key == "Objective-C Garbage Collection" ||
574 Key == "Objective-C GC Only" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000575 Key == "Objective-C Is Simulated" ||
Manman Renc77e0ff2016-01-29 23:51:00 +0000576 Key == "Objective-C Class Properties" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000577 Key == "Objective-C Image Swift Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000578 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000579 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000580 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000581 } else if (Key == "Linker Options") {
582 LinkerOptions = cast<MDNode>(Val);
583 }
584 }
585
586 // Emit the linker options if present.
587 if (LinkerOptions) {
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000588 for (const auto &Option : LinkerOptions->operands()) {
Daniel Dunbar95856122013-01-18 19:37:00 +0000589 SmallVector<std::string, 4> StrOptions;
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000590 for (const auto &Piece : cast<MDNode>(Option)->operands())
591 StrOptions.push_back(cast<MDString>(Piece)->getString());
Daniel Dunbar95856122013-01-18 19:37:00 +0000592 Streamer.EmitLinkerOptions(StrOptions);
593 }
Bill Wendling06df7722012-02-14 21:28:13 +0000594 }
595
Bill Wendling734909a2012-02-15 22:36:15 +0000596 // The section is mandatory. If we don't have it, then we don't have GC info.
597 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000598
Bill Wendling734909a2012-02-15 22:36:15 +0000599 StringRef Segment, Section;
600 unsigned TAA = 0, StubSize = 0;
601 bool TAAParsed;
602 std::string ErrorCode =
603 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
604 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000605 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000606 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000607 report_fatal_error("Invalid section specifier '" + Section + "': " +
608 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000609
Bill Wendling734909a2012-02-15 22:36:15 +0000610 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000611 MCSectionMachO *S = getContext().getMachOSection(
Rafael Espindola449711c2015-11-18 06:02:15 +0000612 Segment, Section, TAA, StubSize, SectionKind::getData());
Bill Wendling734909a2012-02-15 22:36:15 +0000613 Streamer.SwitchSection(S);
614 Streamer.EmitLabel(getContext().
Jim Grosbach6f482002015-05-18 18:43:14 +0000615 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000616 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000617 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000618 Streamer.AddBlankLine();
619}
620
David Majnemerdad0a642014-06-27 18:19:56 +0000621static void checkMachOComdat(const GlobalValue *GV) {
622 const Comdat *C = GV->getComdat();
623 if (!C)
624 return;
625
626 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
627 "' cannot be lowered.");
628}
629
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000630MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000631 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000632 // Parse the section specifier and create it if valid.
633 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000634 unsigned TAA = 0, StubSize = 0;
635 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000636
Peter Collingbourne67335642016-10-24 19:23:39 +0000637 checkMachOComdat(GO);
David Majnemerdad0a642014-06-27 18:19:56 +0000638
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000639 std::string ErrorCode =
Peter Collingbourne67335642016-10-24 19:23:39 +0000640 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000641 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000642 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000643 // If invalid, report the error with report_fatal_error.
Peter Collingbourne67335642016-10-24 19:23:39 +0000644 report_fatal_error("Global variable '" + GO->getName() +
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000645 "' has an invalid section specifier '" +
Peter Collingbourne67335642016-10-24 19:23:39 +0000646 GO->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000647 }
648
649 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000650 MCSectionMachO *S =
651 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000652
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000653 // If TAA wasn't set by ParseSectionSpecifier() above,
654 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000655 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000656 TAA = S->getTypeAndAttributes();
657
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000658 // Okay, now that we got the section, verify that the TAA & StubSize agree.
659 // If the user declared multiple globals with different section flags, we need
660 // to reject it here.
661 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000662 // If invalid, report the error with report_fatal_error.
Peter Collingbourne67335642016-10-24 19:23:39 +0000663 report_fatal_error("Global variable '" + GO->getName() +
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000664 "' section type or attributes does not match previous"
665 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000666 }
667
668 return S;
669}
670
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000671MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000672 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
673 checkMachOComdat(GO);
Bill Wendling25b61db2013-11-17 10:53:13 +0000674
675 // Handle thread local data.
676 if (Kind.isThreadBSS()) return TLSBSSSection;
677 if (Kind.isThreadData()) return TLSDataSection;
678
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000679 if (Kind.isText())
Peter Collingbourne67335642016-10-24 19:23:39 +0000680 return GO->isWeakForLinker() ? TextCoalSection : TextSection;
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000681
682 // If this is weak/linkonce, put this in a coalescable section, either in text
683 // or data depending on if it is writable.
Peter Collingbourne67335642016-10-24 19:23:39 +0000684 if (GO->isWeakForLinker()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000685 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000686 return ConstTextCoalSection;
687 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000688 }
689
690 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000691 if (Kind.isMergeable1ByteCString() &&
Peter Collingbourne67335642016-10-24 19:23:39 +0000692 GO->getParent()->getDataLayout().getPreferredAlignment(
693 cast<GlobalVariable>(GO)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000694 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000695
Chris Lattneref2f8042010-03-07 04:28:09 +0000696 // Do not put 16-bit arrays in the UString section if they have an
697 // externally visible label, this runs into issues with certain linker
698 // versions.
Peter Collingbourne67335642016-10-24 19:23:39 +0000699 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
700 GO->getParent()->getDataLayout().getPreferredAlignment(
701 cast<GlobalVariable>(GO)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000702 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000703
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000704 // With MachO only variables whose corresponding symbol starts with 'l' or
705 // 'L' can be merged, so we only try merging GVs with private linkage.
Peter Collingbourne67335642016-10-24 19:23:39 +0000706 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000707 if (Kind.isMergeableConst4())
708 return FourByteConstantSection;
709 if (Kind.isMergeableConst8())
710 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000711 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000712 return SixteenByteConstantSection;
713 }
714
715 // Otherwise, if it is readonly, but not something we can specially optimize,
716 // just drop it in .const.
717 if (Kind.isReadOnly())
718 return ReadOnlySection;
719
720 // If this is marked const, put it into a const section. But if the dynamic
721 // linker needs to write to it, put it in the data segment.
722 if (Kind.isReadOnlyWithRel())
723 return ConstDataSection;
724
725 // Put zero initialized globals with strong external linkage in the
726 // DATA, __common section with the .zerofill directive.
727 if (Kind.isBSSExtern())
728 return DataCommonSection;
729
730 // Put zero initialized globals with local linkage in __DATA,__bss directive
731 // with the .zerofill directive (aka .lcomm).
732 if (Kind.isBSSLocal())
733 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000734
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000735 // Otherwise, just drop the variable in the normal data section.
736 return DataSection;
737}
738
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000739MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000740 const DataLayout &DL, SectionKind Kind, const Constant *C,
741 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000742 // If this constant requires a relocation, we have to put it in the data
743 // segment, not in the text segment.
Rafael Espindola449711c2015-11-18 06:02:15 +0000744 if (Kind.isData() || Kind.isReadOnlyWithRel())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000745 return ConstDataSection;
746
747 if (Kind.isMergeableConst4())
748 return FourByteConstantSection;
749 if (Kind.isMergeableConst8())
750 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000751 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000752 return SixteenByteConstantSection;
753 return ReadOnlySection; // .const
754}
755
Rafael Espindola15b26692014-02-09 14:50:44 +0000756const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000757 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
758 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000759 // The mach-o version of this method defaults to returning a stub reference.
760
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000761 if (Encoding & DW_EH_PE_indirect) {
762 MachineModuleInfoMachO &MachOMMI =
763 MMI->getObjFileInfo<MachineModuleInfoMachO>();
764
Eric Christopher4367c7f2016-09-16 07:33:15 +0000765 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000766
767 // Add information about the stub reference to MachOMMI so that the stub
768 // gets emitted by the asmprinter.
Rafael Espindola712f9572016-05-17 16:01:32 +0000769 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000770 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000771 MCSymbol *Sym = TM.getSymbol(GV);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000772 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000773 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000774
775 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000776 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000777 Encoding & ~DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000778 }
779
Eric Christopher4367c7f2016-09-16 07:33:15 +0000780 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
781 MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000782}
783
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000784MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000785 const GlobalValue *GV, const TargetMachine &TM,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000786 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000787 // The mach-o version of this method defaults to returning a stub reference.
788 MachineModuleInfoMachO &MachOMMI =
789 MMI->getObjFileInfo<MachineModuleInfoMachO>();
790
Eric Christopher4367c7f2016-09-16 07:33:15 +0000791 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000792
793 // Add information about the stub reference to MachOMMI so that the stub
794 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000795 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000796 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000797 MCSymbol *Sym = TM.getSymbol(GV);
Rafael Espindola08704342011-04-27 23:08:15 +0000798 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
799 }
800
801 return SSym;
802}
803
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000804const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
805 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
806 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000807 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000808 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
809 // through a non_lazy_ptr stub instead. One advantage is that it allows the
810 // computation of deltas to final external symbols. Example:
811 //
812 // _extgotequiv:
813 // .long _extfoo
814 //
815 // _delta:
816 // .long _extgotequiv-_delta
817 //
818 // is transformed to:
819 //
820 // _delta:
821 // .long L_extfoo$non_lazy_ptr-(_delta+0)
822 //
823 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
824 // L_extfoo$non_lazy_ptr:
825 // .indirect_symbol _extfoo
826 // .long 0
827 //
828 MachineModuleInfoMachO &MachOMMI =
829 MMI->getObjFileInfo<MachineModuleInfoMachO>();
830 MCContext &Ctx = getContext();
831
832 // The offset must consider the original displacement from the base symbol
833 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
834 Offset = -MV.getConstant();
835 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
836
837 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
838 // non_lazy_ptr stubs.
839 SmallString<128> Name;
840 StringRef Suffix = "$non_lazy_ptr";
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000841 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000842 Name += Sym->getName();
843 Name += Suffix;
Jim Grosbach6f482002015-05-18 18:43:14 +0000844 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000845
846 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
847 if (!StubSym.getPointer())
848 StubSym = MachineModuleInfoImpl::
849 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
850
851 const MCExpr *BSymExpr =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000852 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000853 const MCExpr *LHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000854 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000855
856 if (!Offset)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000857 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000858
859 const MCExpr *RHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000860 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
861 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000862}
863
Peter Collingbourne94d77862015-11-03 23:40:03 +0000864static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
865 const MCSection &Section) {
866 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
867 return true;
868
869 // If it is not dead stripped, it is safe to use private labels.
870 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
871 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
872 return true;
873
874 return false;
875}
876
877void TargetLoweringObjectFileMachO::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000878 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +0000879 const TargetMachine &TM) const {
Peter Collingbourne67335642016-10-24 19:23:39 +0000880 bool CannotUsePrivateLabel = true;
881 if (auto *GO = GV->getBaseObject()) {
882 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
883 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
884 CannotUsePrivateLabel =
885 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
886 }
Eric Christopher4367c7f2016-09-16 07:33:15 +0000887 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
Peter Collingbourne94d77862015-11-03 23:40:03 +0000888}
889
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000890//===----------------------------------------------------------------------===//
891// COFF
892//===----------------------------------------------------------------------===//
893
Chris Lattner87cffa92010-05-07 17:17:41 +0000894static unsigned
Renato Golinef3eb062016-06-27 14:42:20 +0000895getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
Chris Lattner87cffa92010-05-07 17:17:41 +0000896 unsigned Flags = 0;
Renato Golinef3eb062016-06-27 14:42:20 +0000897 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
Chris Lattner87cffa92010-05-07 17:17:41 +0000898
Anton Korobeynikove4152302010-07-06 15:24:56 +0000899 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000900 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000901 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000902 else if (K.isText())
903 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000904 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000905 COFF::IMAGE_SCN_MEM_READ |
Renato Golinef3eb062016-06-27 14:42:20 +0000906 COFF::IMAGE_SCN_CNT_CODE |
907 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
David Majnemerb8dbebb2014-09-20 07:31:46 +0000908 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000909 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000910 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
911 COFF::IMAGE_SCN_MEM_READ |
912 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000913 else if (K.isThreadLocal())
914 Flags |=
915 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
916 COFF::IMAGE_SCN_MEM_READ |
917 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000918 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000919 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000920 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
921 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000922 else if (K.isWriteable())
923 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000924 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
925 COFF::IMAGE_SCN_MEM_READ |
926 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000927
928 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000929}
930
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000931static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000932 const Comdat *C = GV->getComdat();
933 assert(C && "expected GV to have a Comdat!");
934
935 StringRef ComdatGVName = C->getName();
936 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
937 if (!ComdatGV)
938 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
939 "' does not exist.");
940
941 if (ComdatGV->getComdat() != C)
942 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000943 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000944
945 return ComdatGV;
946}
947
948static int getSelectionForCOFF(const GlobalValue *GV) {
949 if (const Comdat *C = GV->getComdat()) {
950 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
951 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
952 ComdatKey = GA->getBaseObject();
953 if (ComdatKey == GV) {
954 switch (C->getSelectionKind()) {
955 case Comdat::Any:
956 return COFF::IMAGE_COMDAT_SELECT_ANY;
957 case Comdat::ExactMatch:
958 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
959 case Comdat::Largest:
960 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
961 case Comdat::NoDuplicates:
962 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
963 case Comdat::SameSize:
964 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
965 }
966 } else {
967 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
968 }
David Majnemerdad0a642014-06-27 18:19:56 +0000969 }
970 return 0;
971}
972
Bob Haarmandd4ebc12017-02-02 23:00:49 +0000973void llvm::emitLinkerFlagsForGlobalCOFF(raw_ostream &OS, const GlobalValue *GV,
974 const Triple &TT, Mangler &Mangler) {
975 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
976 return;
977
978 if (TT.isKnownWindowsMSVCEnvironment())
979 OS << " /EXPORT:";
980 else
981 OS << " -export:";
982
983 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
984 std::string Flag;
985 raw_string_ostream FlagOS(Flag);
986 Mangler.getNameWithPrefix(FlagOS, GV, false);
987 FlagOS.flush();
988 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
989 OS << Flag.substr(1);
990 else
991 OS << Flag;
992 } else {
993 Mangler.getNameWithPrefix(OS, GV, false);
994 }
995
996 if (!GV->getValueType()->isFunctionTy()) {
997 if (TT.isKnownWindowsMSVCEnvironment())
998 OS << ",DATA";
999 else
1000 OS << ",data";
1001 }
1002}
1003
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001004MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +00001005 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +00001006 int Selection = 0;
Renato Golinef3eb062016-06-27 14:42:20 +00001007 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Peter Collingbourne67335642016-10-24 19:23:39 +00001008 StringRef Name = GO->getSection();
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001009 StringRef COMDATSymName = "";
Peter Collingbourne67335642016-10-24 19:23:39 +00001010 if (GO->hasComdat()) {
1011 Selection = getSelectionForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001012 const GlobalValue *ComdatGV;
1013 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
Peter Collingbourne67335642016-10-24 19:23:39 +00001014 ComdatGV = getComdatGVForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001015 else
Peter Collingbourne67335642016-10-24 19:23:39 +00001016 ComdatGV = GO;
David Majnemerdad0a642014-06-27 18:19:56 +00001017
1018 if (!ComdatGV->hasPrivateLinkage()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001019 MCSymbol *Sym = TM.getSymbol(ComdatGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001020 COMDATSymName = Sym->getName();
1021 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
1022 } else {
1023 Selection = 0;
1024 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +00001025 }
Reid Kleckner97837b72016-05-02 23:22:18 +00001026
1027 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +00001028 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001029}
1030
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001031static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001032 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001033 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +00001034 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001035 return ".bss";
1036 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +00001037 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +00001038 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1039 return ".rdata";
1040 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001041}
1042
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001043MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +00001044 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +00001045 // If we have -ffunction-sections then we should emit the global value to a
1046 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +00001047 bool EmitUniquedSection;
1048 if (Kind.isText())
1049 EmitUniquedSection = TM.getFunctionSections();
1050 else
1051 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001052
Peter Collingbourne67335642016-10-24 19:23:39 +00001053 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001054 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +00001055 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Chris Lattner02844932010-05-07 21:49:09 +00001056
Daniel Dunbar329d2022010-07-01 20:07:24 +00001057 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Peter Collingbourne67335642016-10-24 19:23:39 +00001058 int Selection = getSelectionForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001059 if (!Selection)
1060 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1061 const GlobalValue *ComdatGV;
Peter Collingbourne67335642016-10-24 19:23:39 +00001062 if (GO->hasComdat())
1063 ComdatGV = getComdatGVForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001064 else
Peter Collingbourne67335642016-10-24 19:23:39 +00001065 ComdatGV = GO;
David Majnemerdad0a642014-06-27 18:19:56 +00001066
Reid Kleckner97837b72016-05-02 23:22:18 +00001067 unsigned UniqueID = MCContext::GenericSectionID;
1068 if (EmitUniquedSection)
1069 UniqueID = NextUniqueID++;
1070
David Majnemerdad0a642014-06-27 18:19:56 +00001071 if (!ComdatGV->hasPrivateLinkage()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001072 MCSymbol *Sym = TM.getSymbol(ComdatGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001073 StringRef COMDATSymName = Sym->getName();
1074 return getContext().getCOFFSection(Name, Characteristics, Kind,
Reid Kleckner97837b72016-05-02 23:22:18 +00001075 COMDATSymName, Selection, UniqueID);
David Majnemer7db449a2015-03-17 23:54:51 +00001076 } else {
1077 SmallString<256> TmpData;
Peter Collingbourne67335642016-10-24 19:23:39 +00001078 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
David Majnemer7db449a2015-03-17 23:54:51 +00001079 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
Reid Kleckner97837b72016-05-02 23:22:18 +00001080 Selection, UniqueID);
David Majnemerdad0a642014-06-27 18:19:56 +00001081 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001082 }
1083
1084 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +00001085 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001086
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001087 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +00001088 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001089
David Majnemer597be2d2014-09-22 20:39:23 +00001090 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +00001091 return ReadOnlySection;
1092
David Majnemera9bdb322014-04-08 22:33:40 +00001093 // Note: we claim that common symbols are put in BSSSection, but they are
1094 // really emitted with the magic .comm directive, which creates a symbol table
1095 // entry but not a section.
1096 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +00001097 return BSSSection;
1098
1099 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001100}
1101
David Majnemer7db449a2015-03-17 23:54:51 +00001102void TargetLoweringObjectFileCOFF::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001103 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +00001104 const TargetMachine &TM) const {
1105 bool CannotUsePrivateLabel = false;
David Majnemer7db449a2015-03-17 23:54:51 +00001106 if (GV->hasPrivateLinkage() &&
1107 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1108 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1109 CannotUsePrivateLabel = true;
1110
Eric Christopher4367c7f2016-09-16 07:33:15 +00001111 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
David Majnemer7db449a2015-03-17 23:54:51 +00001112}
1113
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001114MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001115 const Function &F, const TargetMachine &TM) const {
Rafael Espindolaab447e42015-03-11 19:58:37 +00001116 // If the function can be removed, produce a unique section so that
1117 // the table doesn't prevent the removal.
1118 const Comdat *C = F.getComdat();
1119 bool EmitUniqueSection = TM.getFunctionSections() || C;
1120 if (!EmitUniqueSection)
1121 return ReadOnlySection;
1122
1123 // FIXME: we should produce a symbol for F instead.
1124 if (F.hasPrivateLinkage())
1125 return ReadOnlySection;
1126
Tim Northoverb64fb452016-11-22 16:17:20 +00001127 MCSymbol *Sym = TM.getSymbol(&F);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001128 StringRef COMDATSymName = Sym->getName();
1129
1130 SectionKind Kind = SectionKind::getReadOnly();
1131 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +00001132 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001133 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Reid Kleckner97837b72016-05-02 23:22:18 +00001134 unsigned UniqueID = NextUniqueID++;
Rafael Espindolaab447e42015-03-11 19:58:37 +00001135
1136 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Reid Kleckner97837b72016-05-02 23:22:18 +00001137 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001138}
1139
Eric Christopher4367c7f2016-09-16 07:33:15 +00001140void TargetLoweringObjectFileCOFF::emitModuleFlags(
1141 MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1142 const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +00001143 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001144
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001145 for (const auto &MFE : ModuleFlags) {
Reid Klecknerd973ca32013-04-25 19:34:41 +00001146 StringRef Key = MFE.Key->getString();
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001147 if (Key == "Linker Options")
1148 LinkerOptions = cast<MDNode>(MFE.Val);
Reid Klecknerd973ca32013-04-25 19:34:41 +00001149 }
Reid Klecknerd973ca32013-04-25 19:34:41 +00001150
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001151 if (LinkerOptions) {
1152 // Emit the linker options to the linker .drectve section. According to the
1153 // spec, this section is a space-separated string containing flags for
1154 // linker.
1155 MCSection *Sec = getDrectveSection();
1156 Streamer.SwitchSection(Sec);
1157 for (const auto &Option : LinkerOptions->operands()) {
1158 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1159 // Lead with a space for consistency with our dllexport implementation.
1160 std::string Directive(" ");
1161 Directive.append(cast<MDString>(Piece)->getString());
1162 Streamer.EmitBytes(Directive);
1163 }
Reid Klecknerd973ca32013-04-25 19:34:41 +00001164 }
1165 }
1166}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001167
Rafael Espindola46fa2312016-08-29 12:33:42 +00001168void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1169 const TargetMachine &TM) {
1170 TargetLoweringObjectFile::Initialize(Ctx, TM);
1171 const Triple &T = TM.getTargetTriple();
1172 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1173 StaticCtorSection =
1174 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1175 COFF::IMAGE_SCN_MEM_READ,
1176 SectionKind::getReadOnly());
1177 StaticDtorSection =
1178 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1179 COFF::IMAGE_SCN_MEM_READ,
1180 SectionKind::getReadOnly());
1181 } else {
1182 StaticCtorSection = Ctx.getCOFFSection(
1183 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1184 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1185 SectionKind::getData());
1186 StaticDtorSection = Ctx.getCOFFSection(
1187 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1188 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1189 SectionKind::getData());
1190 }
1191}
1192
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001193MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001194 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001195 return getContext().getAssociativeCOFFSection(
Reid Kleckner97837b72016-05-02 23:22:18 +00001196 cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001197}
1198
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001199MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001200 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001201 return getContext().getAssociativeCOFFSection(
Reid Kleckner97837b72016-05-02 23:22:18 +00001202 cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001203}
Peter Collingbourneaef36592015-06-29 22:04:09 +00001204
1205void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001206 raw_ostream &OS, const GlobalValue *GV) const {
Bob Haarmandd4ebc12017-02-02 23:00:49 +00001207 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
Peter Collingbourneaef36592015-06-29 22:04:09 +00001208}
Dan Gohman18eafb62017-02-22 01:23:18 +00001209
1210//===----------------------------------------------------------------------===//
1211// Wasm
1212//===----------------------------------------------------------------------===//
1213
Dan Gohmand934cb82017-02-24 23:18:00 +00001214static const Comdat *getWasmComdat(const GlobalValue *GV) {
1215 const Comdat *C = GV->getComdat();
1216 if (!C)
1217 return nullptr;
1218
1219 if (C->getSelectionKind() != Comdat::Any)
1220 report_fatal_error("Wasm COMDATs only support SelectionKind::Any, '" +
1221 C->getName() + "' cannot be lowered.");
1222
1223 return C;
1224}
1225
Dan Gohman18eafb62017-02-22 01:23:18 +00001226MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1227 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1228 llvm_unreachable("getExplicitSectionGlobal not yet implemented");
1229 return nullptr;
1230}
1231
Dan Gohmand934cb82017-02-24 23:18:00 +00001232static MCSectionWasm *
1233selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO,
1234 SectionKind Kind, Mangler &Mang,
1235 const TargetMachine &TM, bool EmitUniqueSection,
1236 unsigned Flags, unsigned *NextUniqueID) {
1237 StringRef Group = "";
1238 if (getWasmComdat(GO))
1239 llvm_unreachable("comdat not yet supported for wasm");
1240
1241 bool UniqueSectionNames = TM.getUniqueSectionNames();
1242 SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1243
1244 if (const auto *F = dyn_cast<Function>(GO)) {
1245 const auto &OptionalPrefix = F->getSectionPrefix();
1246 if (OptionalPrefix)
1247 Name += *OptionalPrefix;
1248 }
1249
1250 if (EmitUniqueSection && UniqueSectionNames) {
1251 Name.push_back('.');
1252 TM.getNameWithPrefix(Name, GO, Mang, true);
1253 }
1254 unsigned UniqueID = MCContext::GenericSectionID;
1255 if (EmitUniqueSection && !UniqueSectionNames) {
1256 UniqueID = *NextUniqueID;
1257 (*NextUniqueID)++;
1258 }
1259 return Ctx.getWasmSection(Name, /*Type=*/0, Flags,
1260 Group, UniqueID);
1261}
1262
Dan Gohman18eafb62017-02-22 01:23:18 +00001263MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1264 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Dan Gohmand934cb82017-02-24 23:18:00 +00001265
1266 if (Kind.isCommon())
1267 report_fatal_error("mergable sections not supported yet on wasm");
1268
1269 // If we have -ffunction-section or -fdata-section then we should emit the
1270 // global value to a uniqued section specifically for it.
1271 bool EmitUniqueSection = false;
Dan Gohman18eafb62017-02-22 01:23:18 +00001272 if (Kind.isText())
Dan Gohmand934cb82017-02-24 23:18:00 +00001273 EmitUniqueSection = TM.getFunctionSections();
1274 else
1275 EmitUniqueSection = TM.getDataSections();
1276 EmitUniqueSection |= GO->hasComdat();
1277
1278 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1279 EmitUniqueSection, /*Flags=*/0,
1280 &NextUniqueID);
Dan Gohman18eafb62017-02-22 01:23:18 +00001281}
1282
1283bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1284 bool UsesLabelDifference, const Function &F) const {
1285 // We can always create relative relocations, so use another section
1286 // that can be marked non-executable.
1287 return false;
1288}
1289
1290const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1291 const GlobalValue *LHS, const GlobalValue *RHS,
1292 const TargetMachine &TM) const {
1293 // We may only use a PLT-relative relocation to refer to unnamed_addr
1294 // functions.
1295 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1296 return nullptr;
1297
1298 // Basic sanity checks.
1299 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1300 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1301 RHS->isThreadLocal())
1302 return nullptr;
1303
1304 return MCBinaryExpr::createSub(
1305 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1306 getContext()),
1307 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1308}
1309
1310void
1311TargetLoweringObjectFileWasm::InitializeWasm() {
1312 // TODO: Initialize StaticCtorSection and StaticDtorSection.
1313}