blob: 34892680aceb3953846cf73c4e7107be05fbeb73 [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 Li4a5ddf82017-04-14 17:48:40 +0000135
Vedant Kumar1a6a2b62017-04-15 00:09:57 +0000136 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
137 /*AddSegmentInfo=*/false))
Xinliang David Li5f04f922016-01-14 18:09:45 +0000138 return SectionKind::getMetadata();
139
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000140 if (Name.empty() || Name[0] != '.') return K;
141
142 // Some lame default implementation based on some magic section names.
143 if (Name == ".bss" ||
144 Name.startswith(".bss.") ||
145 Name.startswith(".gnu.linkonce.b.") ||
146 Name.startswith(".llvm.linkonce.b.") ||
147 Name == ".sbss" ||
148 Name.startswith(".sbss.") ||
149 Name.startswith(".gnu.linkonce.sb.") ||
150 Name.startswith(".llvm.linkonce.sb."))
151 return SectionKind::getBSS();
152
153 if (Name == ".tdata" ||
154 Name.startswith(".tdata.") ||
155 Name.startswith(".gnu.linkonce.td.") ||
156 Name.startswith(".llvm.linkonce.td."))
157 return SectionKind::getThreadData();
158
159 if (Name == ".tbss" ||
160 Name.startswith(".tbss.") ||
161 Name.startswith(".gnu.linkonce.tb.") ||
162 Name.startswith(".llvm.linkonce.tb."))
163 return SectionKind::getThreadBSS();
164
165 return K;
166}
167
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000168static unsigned getELFSectionType(StringRef Name, SectionKind K) {
Petr Hosek12903552016-09-20 20:21:13 +0000169 // Use SHT_NOTE for section whose name starts with ".note" to allow
170 // emitting ELF notes from C variable declaration.
171 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
172 if (Name.startswith(".note"))
173 return ELF::SHT_NOTE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000174
175 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000176 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000177
178 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000179 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000180
181 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000182 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000183
184 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000185 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000186
Rafael Espindolaaea49582011-01-23 04:28:49 +0000187 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000188}
189
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000190static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000191 unsigned Flags = 0;
192
193 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000194 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000195
196 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000197 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000198
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000199 if (K.isExecuteOnly())
200 Flags |= ELF::SHF_ARM_PURECODE;
201
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000202 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000203 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000204
205 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000206 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000207
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000208 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000209 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000210
211 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000212 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000213
214 return Flags;
215}
216
David Majnemerdad0a642014-06-27 18:19:56 +0000217static const Comdat *getELFComdat(const GlobalValue *GV) {
218 const Comdat *C = GV->getComdat();
219 if (!C)
220 return nullptr;
221
222 if (C->getSelectionKind() != Comdat::Any)
223 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
224 C->getName() + "' cannot be lowered.");
225
226 return C;
227}
228
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000229static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
230 const TargetMachine &TM) {
231 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
232 if (!MD)
233 return nullptr;
234
235 auto *VM = dyn_cast<ValueAsMetadata>(MD->getOperand(0));
236 if (!VM)
237 report_fatal_error("MD_associated operand is not ValueAsMetadata");
238
239 GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
240 return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
241}
242
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000243MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000244 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
245 StringRef SectionName = GO->getSection();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000246
247 // Infer section flags from the section name if we can.
248 Kind = getELFKindForNamedSection(SectionName, Kind);
249
David Majnemerdad0a642014-06-27 18:19:56 +0000250 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000251 unsigned Flags = getELFSectionFlags(Kind);
Peter Collingbourne67335642016-10-24 19:23:39 +0000252 if (const Comdat *C = getELFComdat(GO)) {
David Majnemerdad0a642014-06-27 18:19:56 +0000253 Group = C->getName();
254 Flags |= ELF::SHF_GROUP;
255 }
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000256
257 // A section can have at most one associated section. Put each global with
258 // MD_associated in a unique section.
259 unsigned UniqueID = MCContext::GenericSectionID;
260 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
261 if (AssociatedSymbol) {
262 UniqueID = NextUniqueID++;
263 Flags |= ELF::SHF_LINK_ORDER;
264 }
265
266 MCSectionELF *Section = getContext().getELFSection(
267 SectionName, getELFSectionType(SectionName, Kind), Flags,
268 /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
269 // Make sure that we did not get some other section with incompatible sh_link.
270 // This should not be possible due to UniqueID code above.
271 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
272 return Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000273}
274
Rafael Espindola25d2c202015-02-11 14:44:17 +0000275/// Return the section prefix name used by options FunctionsSections and
276/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000277static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000278 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000279 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000280 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000281 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000282 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000283 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000284 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000285 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000286 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000287 return ".tbss";
Rafael Espindola449711c2015-11-18 06:02:15 +0000288 if (Kind.isData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000289 return ".data";
Chris Lattner5b212a32010-04-13 00:36:43 +0000290 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000291 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000292}
293
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000294static MCSectionELF *selectELFSectionForGlobal(
295 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
296 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
297 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000298 unsigned EntrySize = 0;
299 if (Kind.isMergeableCString()) {
300 if (Kind.isMergeable2ByteCString()) {
301 EntrySize = 2;
302 } else if (Kind.isMergeable4ByteCString()) {
303 EntrySize = 4;
304 } else {
305 EntrySize = 1;
306 assert(Kind.isMergeable1ByteCString() && "unknown string width");
307 }
308 } else if (Kind.isMergeableConst()) {
309 if (Kind.isMergeableConst4()) {
310 EntrySize = 4;
311 } else if (Kind.isMergeableConst8()) {
312 EntrySize = 8;
David Majnemer964b70d2016-02-22 22:23:11 +0000313 } else if (Kind.isMergeableConst16()) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000314 EntrySize = 16;
David Majnemer964b70d2016-02-22 22:23:11 +0000315 } else {
316 assert(Kind.isMergeableConst32() && "unknown data width");
317 EntrySize = 32;
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000318 }
319 }
320
Rafael Espindola9075f772015-02-20 23:28:28 +0000321 StringRef Group = "";
Peter Collingbourne67335642016-10-24 19:23:39 +0000322 if (const Comdat *C = getELFComdat(GO)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000323 Flags |= ELF::SHF_GROUP;
324 Group = C->getName();
325 }
326
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000327 bool UniqueSectionNames = TM.getUniqueSectionNames();
328 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000329 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000330 // We also need alignment here.
331 // FIXME: this is getting the alignment of the character, not the
332 // alignment of the global!
Peter Collingbourne67335642016-10-24 19:23:39 +0000333 unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
334 cast<GlobalVariable>(GO));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000335
Rafael Espindolaba31e272015-01-29 17:33:21 +0000336 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000337 Name = SizeSpec + utostr(Align);
338 } else if (Kind.isMergeableConst()) {
339 Name = ".rodata.cst";
340 Name += utostr(EntrySize);
341 } else {
342 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000343 }
Dehao Chen302b69c2016-10-18 20:42:47 +0000344
Peter Collingbourne67335642016-10-24 19:23:39 +0000345 if (const auto *F = dyn_cast<Function>(GO)) {
Dehao Chen302b69c2016-10-18 20:42:47 +0000346 const auto &OptionalPrefix = F->getSectionPrefix();
347 if (OptionalPrefix)
348 Name += *OptionalPrefix;
349 }
Dehao Chenf84b6302016-02-23 03:39:24 +0000350
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000351 if (EmitUniqueSection && UniqueSectionNames) {
352 Name.push_back('.');
Peter Collingbourne67335642016-10-24 19:23:39 +0000353 TM.getNameWithPrefix(Name, GO, Mang, true);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000354 }
Reid Kleckner97837b72016-05-02 23:22:18 +0000355 unsigned UniqueID = MCContext::GenericSectionID;
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000356 if (EmitUniqueSection && !UniqueSectionNames) {
357 UniqueID = *NextUniqueID;
358 (*NextUniqueID)++;
359 }
Prakhar Bahuguna52a7dd72016-12-15 07:59:08 +0000360 // Use 0 as the unique ID for execute-only text
361 if (Kind.isExecuteOnly())
362 UniqueID = 0;
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000363 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000364 EntrySize, Group, UniqueID, AssociatedSymbol);
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000365}
366
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000367MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000368 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000369 unsigned Flags = getELFSectionFlags(Kind);
370
371 // If we have -ffunction-section or -fdata-section then we should emit the
372 // global value to a uniqued section specifically for it.
373 bool EmitUniqueSection = false;
374 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
375 if (Kind.isText())
376 EmitUniqueSection = TM.getFunctionSections();
377 else
378 EmitUniqueSection = TM.getDataSections();
379 }
Peter Collingbourne67335642016-10-24 19:23:39 +0000380 EmitUniqueSection |= GO->hasComdat();
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000381
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000382 const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
383 if (AssociatedSymbol) {
384 EmitUniqueSection = true;
385 Flags |= ELF::SHF_LINK_ORDER;
386 }
387
388 MCSectionELF *Section = selectELFSectionForGlobal(
389 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
390 &NextUniqueID, AssociatedSymbol);
391 assert(Section->getAssociatedSymbol() == AssociatedSymbol);
392 return Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000393}
394
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000395MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000396 const Function &F, const TargetMachine &TM) const {
Rafael Espindola29786d42015-02-12 17:16:46 +0000397 // If the function can be removed, produce a unique section so that
398 // the table doesn't prevent the removal.
399 const Comdat *C = F.getComdat();
400 bool EmitUniqueSection = TM.getFunctionSections() || C;
401 if (!EmitUniqueSection)
402 return ReadOnlySection;
403
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000404 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
Evgeniy Stepanov51c962f722017-03-17 22:17:24 +0000405 getMangler(), TM, EmitUniqueSection,
406 ELF::SHF_ALLOC, &NextUniqueID,
407 /* AssociatedSymbol */ nullptr);
Rafael Espindola29786d42015-02-12 17:16:46 +0000408}
409
Rafael Espindoladf195192015-02-17 23:34:51 +0000410bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
411 bool UsesLabelDifference, const Function &F) const {
412 // We can always create relative relocations, so use another section
413 // that can be marked non-executable.
414 return false;
415}
416
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000417/// Given a mergeable constant with the specified size and relocation
418/// information, return a section that it should be placed in.
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000419MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000420 const DataLayout &DL, SectionKind Kind, const Constant *C,
421 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000422 if (Kind.isMergeableConst4() && MergeableConst4Section)
423 return MergeableConst4Section;
424 if (Kind.isMergeableConst8() && MergeableConst8Section)
425 return MergeableConst8Section;
426 if (Kind.isMergeableConst16() && MergeableConst16Section)
427 return MergeableConst16Section;
David Majnemer964b70d2016-02-22 22:23:11 +0000428 if (Kind.isMergeableConst32() && MergeableConst32Section)
429 return MergeableConst32Section;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000430 if (Kind.isReadOnly())
431 return ReadOnlySection;
432
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000433 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
434 return DataRelROSection;
435}
436
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000437static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
438 bool IsCtor, unsigned Priority,
439 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000440 std::string Name;
441 unsigned Type;
442 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000443 StringRef COMDAT = KeySym ? KeySym->getName() : "";
444
445 if (KeySym)
446 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000447
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000448 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000449 if (IsCtor) {
450 Type = ELF::SHT_INIT_ARRAY;
451 Name = ".init_array";
452 } else {
453 Type = ELF::SHT_FINI_ARRAY;
454 Name = ".fini_array";
455 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000456 if (Priority != 65535) {
457 Name += '.';
458 Name += utostr(Priority);
459 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000460 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000461 // The default scheme is .ctor / .dtor, so we have to invert the priority
462 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000463 if (IsCtor)
464 Name = ".ctors";
465 else
466 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000467 if (Priority != 65535) {
468 Name += '.';
469 Name += utostr(65535 - Priority);
470 }
471 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000472 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000473
Rafael Espindolaba31e272015-01-29 17:33:21 +0000474 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000475}
476
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000477MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000478 unsigned Priority, const MCSymbol *KeySym) const {
479 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
480 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000481}
482
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000483MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000484 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000485 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
486 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000487}
488
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000489const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000490 const GlobalValue *LHS, const GlobalValue *RHS,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000491 const TargetMachine &TM) const {
492 // We may only use a PLT-relative relocation to refer to unnamed_addr
493 // functions.
Peter Collingbourne96efdd62016-06-14 21:01:22 +0000494 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000495 return nullptr;
496
497 // Basic sanity checks.
498 if (LHS->getType()->getPointerAddressSpace() != 0 ||
499 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
500 RHS->isThreadLocal())
501 return nullptr;
502
503 return MCBinaryExpr::createSub(
Tim Northoverb64fb452016-11-22 16:17:20 +0000504 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000505 getContext()),
Tim Northoverb64fb452016-11-22 16:17:20 +0000506 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000507}
508
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000509void
510TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
511 UseInitArray = UseInitArray_;
Rafael Espindola46fa2312016-08-29 12:33:42 +0000512 MCContext &Ctx = getContext();
513 if (!UseInitArray) {
514 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
515 ELF::SHF_ALLOC | ELF::SHF_WRITE);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000516
Rafael Espindola46fa2312016-08-29 12:33:42 +0000517 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
518 ELF::SHF_ALLOC | ELF::SHF_WRITE);
519 return;
520 }
521
522 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
523 ELF::SHF_WRITE | ELF::SHF_ALLOC);
524 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
525 ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000526}
527
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000528//===----------------------------------------------------------------------===//
529// MachO
530//===----------------------------------------------------------------------===//
531
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000532TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
533 : TargetLoweringObjectFile() {
534 SupportIndirectSymViaGOTPCRel = true;
535}
536
Rafael Espindola46fa2312016-08-29 12:33:42 +0000537void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
538 const TargetMachine &TM) {
539 TargetLoweringObjectFile::Initialize(Ctx, TM);
Rafael Espindola412a5292016-08-29 12:47:22 +0000540 if (TM.getRelocationModel() == Reloc::Static) {
Rafael Espindola46fa2312016-08-29 12:33:42 +0000541 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
542 SectionKind::getData());
543 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
544 SectionKind::getData());
545 } else {
546 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
547 MachO::S_MOD_INIT_FUNC_POINTERS,
548 SectionKind::getData());
549 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
550 MachO::S_MOD_TERM_FUNC_POINTERS,
551 SectionKind::getData());
552 }
553}
554
Daniel Dunbar95856122013-01-18 19:37:00 +0000555/// emitModuleFlags - Perform code emission for module flags.
Eric Christopher4367c7f2016-09-16 07:33:15 +0000556void TargetLoweringObjectFileMachO::emitModuleFlags(
557 MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
558 const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000559 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000560 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000561 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000562 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000563
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000564 for (const auto &MFE : ModuleFlags) {
Bill Wendling06df7722012-02-14 21:28:13 +0000565 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000566 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000567 continue;
568
Bill Wendling734909a2012-02-15 22:36:15 +0000569 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000570 Metadata *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000571
Daniel Dunbar95856122013-01-18 19:37:00 +0000572 if (Key == "Objective-C Image Info Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000573 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000574 } else if (Key == "Objective-C Garbage Collection" ||
575 Key == "Objective-C GC Only" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000576 Key == "Objective-C Is Simulated" ||
Manman Renc77e0ff2016-01-29 23:51:00 +0000577 Key == "Objective-C Class Properties" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000578 Key == "Objective-C Image Swift Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000579 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000580 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000581 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000582 } else if (Key == "Linker Options") {
583 LinkerOptions = cast<MDNode>(Val);
584 }
585 }
586
587 // Emit the linker options if present.
588 if (LinkerOptions) {
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000589 for (const auto &Option : LinkerOptions->operands()) {
Daniel Dunbar95856122013-01-18 19:37:00 +0000590 SmallVector<std::string, 4> StrOptions;
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +0000591 for (const auto &Piece : cast<MDNode>(Option)->operands())
592 StrOptions.push_back(cast<MDString>(Piece)->getString());
Daniel Dunbar95856122013-01-18 19:37:00 +0000593 Streamer.EmitLinkerOptions(StrOptions);
594 }
Bill Wendling06df7722012-02-14 21:28:13 +0000595 }
596
Bill Wendling734909a2012-02-15 22:36:15 +0000597 // The section is mandatory. If we don't have it, then we don't have GC info.
598 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000599
Bill Wendling734909a2012-02-15 22:36:15 +0000600 StringRef Segment, Section;
601 unsigned TAA = 0, StubSize = 0;
602 bool TAAParsed;
603 std::string ErrorCode =
604 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
605 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000606 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000607 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000608 report_fatal_error("Invalid section specifier '" + Section + "': " +
609 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000610
Bill Wendling734909a2012-02-15 22:36:15 +0000611 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000612 MCSectionMachO *S = getContext().getMachOSection(
Rafael Espindola449711c2015-11-18 06:02:15 +0000613 Segment, Section, TAA, StubSize, SectionKind::getData());
Bill Wendling734909a2012-02-15 22:36:15 +0000614 Streamer.SwitchSection(S);
615 Streamer.EmitLabel(getContext().
Jim Grosbach6f482002015-05-18 18:43:14 +0000616 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000617 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000618 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000619 Streamer.AddBlankLine();
620}
621
David Majnemerdad0a642014-06-27 18:19:56 +0000622static void checkMachOComdat(const GlobalValue *GV) {
623 const Comdat *C = GV->getComdat();
624 if (!C)
625 return;
626
627 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
628 "' cannot be lowered.");
629}
630
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000631MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000632 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000633 // Parse the section specifier and create it if valid.
634 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000635 unsigned TAA = 0, StubSize = 0;
636 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000637
Peter Collingbourne67335642016-10-24 19:23:39 +0000638 checkMachOComdat(GO);
David Majnemerdad0a642014-06-27 18:19:56 +0000639
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000640 std::string ErrorCode =
Peter Collingbourne67335642016-10-24 19:23:39 +0000641 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000642 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000643 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000644 // If invalid, report the error with report_fatal_error.
Peter Collingbourne67335642016-10-24 19:23:39 +0000645 report_fatal_error("Global variable '" + GO->getName() +
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000646 "' has an invalid section specifier '" +
Peter Collingbourne67335642016-10-24 19:23:39 +0000647 GO->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000648 }
649
650 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000651 MCSectionMachO *S =
652 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000653
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000654 // If TAA wasn't set by ParseSectionSpecifier() above,
655 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000656 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000657 TAA = S->getTypeAndAttributes();
658
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000659 // Okay, now that we got the section, verify that the TAA & StubSize agree.
660 // If the user declared multiple globals with different section flags, we need
661 // to reject it here.
662 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000663 // If invalid, report the error with report_fatal_error.
Peter Collingbourne67335642016-10-24 19:23:39 +0000664 report_fatal_error("Global variable '" + GO->getName() +
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000665 "' section type or attributes does not match previous"
666 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000667 }
668
669 return S;
670}
671
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000672MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000673 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
674 checkMachOComdat(GO);
Bill Wendling25b61db2013-11-17 10:53:13 +0000675
676 // Handle thread local data.
677 if (Kind.isThreadBSS()) return TLSBSSSection;
678 if (Kind.isThreadData()) return TLSDataSection;
679
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000680 if (Kind.isText())
Peter Collingbourne67335642016-10-24 19:23:39 +0000681 return GO->isWeakForLinker() ? TextCoalSection : TextSection;
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000682
683 // If this is weak/linkonce, put this in a coalescable section, either in text
684 // or data depending on if it is writable.
Peter Collingbourne67335642016-10-24 19:23:39 +0000685 if (GO->isWeakForLinker()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000686 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000687 return ConstTextCoalSection;
688 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000689 }
690
691 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000692 if (Kind.isMergeable1ByteCString() &&
Peter Collingbourne67335642016-10-24 19:23:39 +0000693 GO->getParent()->getDataLayout().getPreferredAlignment(
694 cast<GlobalVariable>(GO)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000695 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000696
Chris Lattneref2f8042010-03-07 04:28:09 +0000697 // Do not put 16-bit arrays in the UString section if they have an
698 // externally visible label, this runs into issues with certain linker
699 // versions.
Peter Collingbourne67335642016-10-24 19:23:39 +0000700 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
701 GO->getParent()->getDataLayout().getPreferredAlignment(
702 cast<GlobalVariable>(GO)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000703 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000704
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000705 // With MachO only variables whose corresponding symbol starts with 'l' or
706 // 'L' can be merged, so we only try merging GVs with private linkage.
Peter Collingbourne67335642016-10-24 19:23:39 +0000707 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000708 if (Kind.isMergeableConst4())
709 return FourByteConstantSection;
710 if (Kind.isMergeableConst8())
711 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000712 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000713 return SixteenByteConstantSection;
714 }
715
716 // Otherwise, if it is readonly, but not something we can specially optimize,
717 // just drop it in .const.
718 if (Kind.isReadOnly())
719 return ReadOnlySection;
720
721 // If this is marked const, put it into a const section. But if the dynamic
722 // linker needs to write to it, put it in the data segment.
723 if (Kind.isReadOnlyWithRel())
724 return ConstDataSection;
725
726 // Put zero initialized globals with strong external linkage in the
727 // DATA, __common section with the .zerofill directive.
728 if (Kind.isBSSExtern())
729 return DataCommonSection;
730
731 // Put zero initialized globals with local linkage in __DATA,__bss directive
732 // with the .zerofill directive (aka .lcomm).
733 if (Kind.isBSSLocal())
734 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000735
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000736 // Otherwise, just drop the variable in the normal data section.
737 return DataSection;
738}
739
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000740MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
David Majnemera3ea4072016-02-21 01:30:30 +0000741 const DataLayout &DL, SectionKind Kind, const Constant *C,
742 unsigned &Align) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000743 // If this constant requires a relocation, we have to put it in the data
744 // segment, not in the text segment.
Rafael Espindola449711c2015-11-18 06:02:15 +0000745 if (Kind.isData() || Kind.isReadOnlyWithRel())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000746 return ConstDataSection;
747
748 if (Kind.isMergeableConst4())
749 return FourByteConstantSection;
750 if (Kind.isMergeableConst8())
751 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000752 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000753 return SixteenByteConstantSection;
754 return ReadOnlySection; // .const
755}
756
Rafael Espindola15b26692014-02-09 14:50:44 +0000757const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000758 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
759 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000760 // The mach-o version of this method defaults to returning a stub reference.
761
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000762 if (Encoding & DW_EH_PE_indirect) {
763 MachineModuleInfoMachO &MachOMMI =
764 MMI->getObjFileInfo<MachineModuleInfoMachO>();
765
Eric Christopher4367c7f2016-09-16 07:33:15 +0000766 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000767
768 // Add information about the stub reference to MachOMMI so that the stub
769 // gets emitted by the asmprinter.
Rafael Espindola712f9572016-05-17 16:01:32 +0000770 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000771 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000772 MCSymbol *Sym = TM.getSymbol(GV);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000773 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000774 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000775
776 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000777 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Eugene Zelenkofa912a72017-02-27 22:45:06 +0000778 Encoding & ~DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000779 }
780
Eric Christopher4367c7f2016-09-16 07:33:15 +0000781 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
782 MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000783}
784
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000785MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000786 const GlobalValue *GV, const TargetMachine &TM,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000787 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000788 // The mach-o version of this method defaults to returning a stub reference.
789 MachineModuleInfoMachO &MachOMMI =
790 MMI->getObjFileInfo<MachineModuleInfoMachO>();
791
Eric Christopher4367c7f2016-09-16 07:33:15 +0000792 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000793
794 // Add information about the stub reference to MachOMMI so that the stub
795 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000796 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000797 if (!StubSym.getPointer()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000798 MCSymbol *Sym = TM.getSymbol(GV);
Rafael Espindola08704342011-04-27 23:08:15 +0000799 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
800 }
801
802 return SSym;
803}
804
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000805const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
806 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
807 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000808 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000809 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
810 // through a non_lazy_ptr stub instead. One advantage is that it allows the
811 // computation of deltas to final external symbols. Example:
812 //
813 // _extgotequiv:
814 // .long _extfoo
815 //
816 // _delta:
817 // .long _extgotequiv-_delta
818 //
819 // is transformed to:
820 //
821 // _delta:
822 // .long L_extfoo$non_lazy_ptr-(_delta+0)
823 //
824 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
825 // L_extfoo$non_lazy_ptr:
826 // .indirect_symbol _extfoo
827 // .long 0
828 //
829 MachineModuleInfoMachO &MachOMMI =
830 MMI->getObjFileInfo<MachineModuleInfoMachO>();
831 MCContext &Ctx = getContext();
832
833 // The offset must consider the original displacement from the base symbol
834 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
835 Offset = -MV.getConstant();
836 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
837
838 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
839 // non_lazy_ptr stubs.
840 SmallString<128> Name;
841 StringRef Suffix = "$non_lazy_ptr";
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000842 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000843 Name += Sym->getName();
844 Name += Suffix;
Jim Grosbach6f482002015-05-18 18:43:14 +0000845 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000846
847 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
848 if (!StubSym.getPointer())
849 StubSym = MachineModuleInfoImpl::
850 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
851
852 const MCExpr *BSymExpr =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000853 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000854 const MCExpr *LHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000855 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000856
857 if (!Offset)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000858 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000859
860 const MCExpr *RHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000861 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
862 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000863}
864
Peter Collingbourne94d77862015-11-03 23:40:03 +0000865static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
866 const MCSection &Section) {
867 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
868 return true;
869
870 // If it is not dead stripped, it is safe to use private labels.
871 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
872 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
873 return true;
874
875 return false;
876}
877
878void TargetLoweringObjectFileMachO::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +0000879 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +0000880 const TargetMachine &TM) const {
Peter Collingbourne67335642016-10-24 19:23:39 +0000881 bool CannotUsePrivateLabel = true;
882 if (auto *GO = GV->getBaseObject()) {
883 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
884 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
885 CannotUsePrivateLabel =
886 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
887 }
Eric Christopher4367c7f2016-09-16 07:33:15 +0000888 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
Peter Collingbourne94d77862015-11-03 23:40:03 +0000889}
890
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000891//===----------------------------------------------------------------------===//
892// COFF
893//===----------------------------------------------------------------------===//
894
Chris Lattner87cffa92010-05-07 17:17:41 +0000895static unsigned
Renato Golinef3eb062016-06-27 14:42:20 +0000896getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
Chris Lattner87cffa92010-05-07 17:17:41 +0000897 unsigned Flags = 0;
Renato Golinef3eb062016-06-27 14:42:20 +0000898 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
Chris Lattner87cffa92010-05-07 17:17:41 +0000899
Anton Korobeynikove4152302010-07-06 15:24:56 +0000900 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000901 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000902 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000903 else if (K.isText())
904 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000905 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000906 COFF::IMAGE_SCN_MEM_READ |
Renato Golinef3eb062016-06-27 14:42:20 +0000907 COFF::IMAGE_SCN_CNT_CODE |
908 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
David Majnemerb8dbebb2014-09-20 07:31:46 +0000909 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000910 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000911 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
912 COFF::IMAGE_SCN_MEM_READ |
913 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000914 else if (K.isThreadLocal())
915 Flags |=
916 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
917 COFF::IMAGE_SCN_MEM_READ |
918 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000919 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000920 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000921 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
922 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000923 else if (K.isWriteable())
924 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000925 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
926 COFF::IMAGE_SCN_MEM_READ |
927 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000928
929 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000930}
931
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000932static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000933 const Comdat *C = GV->getComdat();
934 assert(C && "expected GV to have a Comdat!");
935
936 StringRef ComdatGVName = C->getName();
937 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
938 if (!ComdatGV)
939 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
940 "' does not exist.");
941
942 if (ComdatGV->getComdat() != C)
943 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000944 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000945
946 return ComdatGV;
947}
948
949static int getSelectionForCOFF(const GlobalValue *GV) {
950 if (const Comdat *C = GV->getComdat()) {
951 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
952 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
953 ComdatKey = GA->getBaseObject();
954 if (ComdatKey == GV) {
955 switch (C->getSelectionKind()) {
956 case Comdat::Any:
957 return COFF::IMAGE_COMDAT_SELECT_ANY;
958 case Comdat::ExactMatch:
959 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
960 case Comdat::Largest:
961 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
962 case Comdat::NoDuplicates:
963 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
964 case Comdat::SameSize:
965 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
966 }
967 } else {
968 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
969 }
David Majnemerdad0a642014-06-27 18:19:56 +0000970 }
971 return 0;
972}
973
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000974MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +0000975 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000976 int Selection = 0;
Renato Golinef3eb062016-06-27 14:42:20 +0000977 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Peter Collingbourne67335642016-10-24 19:23:39 +0000978 StringRef Name = GO->getSection();
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000979 StringRef COMDATSymName = "";
Peter Collingbourne67335642016-10-24 19:23:39 +0000980 if (GO->hasComdat()) {
981 Selection = getSelectionForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +0000982 const GlobalValue *ComdatGV;
983 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
Peter Collingbourne67335642016-10-24 19:23:39 +0000984 ComdatGV = getComdatGVForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +0000985 else
Peter Collingbourne67335642016-10-24 19:23:39 +0000986 ComdatGV = GO;
David Majnemerdad0a642014-06-27 18:19:56 +0000987
988 if (!ComdatGV->hasPrivateLinkage()) {
Tim Northoverb64fb452016-11-22 16:17:20 +0000989 MCSymbol *Sym = TM.getSymbol(ComdatGV);
David Majnemerdad0a642014-06-27 18:19:56 +0000990 COMDATSymName = Sym->getName();
991 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
992 } else {
993 Selection = 0;
994 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000995 }
Reid Kleckner97837b72016-05-02 23:22:18 +0000996
997 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000998 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000999}
1000
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001001static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001002 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001003 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +00001004 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001005 return ".bss";
1006 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +00001007 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +00001008 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
1009 return ".rdata";
1010 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001011}
1012
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001013MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
Peter Collingbourne67335642016-10-24 19:23:39 +00001014 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +00001015 // If we have -ffunction-sections then we should emit the global value to a
1016 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +00001017 bool EmitUniquedSection;
1018 if (Kind.isText())
1019 EmitUniquedSection = TM.getFunctionSections();
1020 else
1021 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001022
Peter Collingbourne67335642016-10-24 19:23:39 +00001023 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +00001024 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +00001025 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Chris Lattner02844932010-05-07 21:49:09 +00001026
Daniel Dunbar329d2022010-07-01 20:07:24 +00001027 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Peter Collingbourne67335642016-10-24 19:23:39 +00001028 int Selection = getSelectionForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001029 if (!Selection)
1030 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
1031 const GlobalValue *ComdatGV;
Peter Collingbourne67335642016-10-24 19:23:39 +00001032 if (GO->hasComdat())
1033 ComdatGV = getComdatGVForCOFF(GO);
David Majnemerdad0a642014-06-27 18:19:56 +00001034 else
Peter Collingbourne67335642016-10-24 19:23:39 +00001035 ComdatGV = GO;
David Majnemerdad0a642014-06-27 18:19:56 +00001036
Reid Kleckner97837b72016-05-02 23:22:18 +00001037 unsigned UniqueID = MCContext::GenericSectionID;
1038 if (EmitUniquedSection)
1039 UniqueID = NextUniqueID++;
1040
David Majnemerdad0a642014-06-27 18:19:56 +00001041 if (!ComdatGV->hasPrivateLinkage()) {
Tim Northoverb64fb452016-11-22 16:17:20 +00001042 MCSymbol *Sym = TM.getSymbol(ComdatGV);
David Majnemerdad0a642014-06-27 18:19:56 +00001043 StringRef COMDATSymName = Sym->getName();
1044 return getContext().getCOFFSection(Name, Characteristics, Kind,
Reid Kleckner97837b72016-05-02 23:22:18 +00001045 COMDATSymName, Selection, UniqueID);
David Majnemer7db449a2015-03-17 23:54:51 +00001046 } else {
1047 SmallString<256> TmpData;
Peter Collingbourne67335642016-10-24 19:23:39 +00001048 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
David Majnemer7db449a2015-03-17 23:54:51 +00001049 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
Reid Kleckner97837b72016-05-02 23:22:18 +00001050 Selection, UniqueID);
David Majnemerdad0a642014-06-27 18:19:56 +00001051 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001052 }
1053
1054 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +00001055 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001056
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001057 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +00001058 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +00001059
David Majnemer597be2d2014-09-22 20:39:23 +00001060 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +00001061 return ReadOnlySection;
1062
David Majnemera9bdb322014-04-08 22:33:40 +00001063 // Note: we claim that common symbols are put in BSSSection, but they are
1064 // really emitted with the magic .comm directive, which creates a symbol table
1065 // entry but not a section.
1066 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +00001067 return BSSSection;
1068
1069 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001070}
1071
David Majnemer7db449a2015-03-17 23:54:51 +00001072void TargetLoweringObjectFileCOFF::getNameWithPrefix(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001073 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
Peter Collingbourne94d77862015-11-03 23:40:03 +00001074 const TargetMachine &TM) const {
1075 bool CannotUsePrivateLabel = false;
David Majnemer7db449a2015-03-17 23:54:51 +00001076 if (GV->hasPrivateLinkage() &&
1077 ((isa<Function>(GV) && TM.getFunctionSections()) ||
1078 (isa<GlobalVariable>(GV) && TM.getDataSections())))
1079 CannotUsePrivateLabel = true;
1080
Eric Christopher4367c7f2016-09-16 07:33:15 +00001081 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
David Majnemer7db449a2015-03-17 23:54:51 +00001082}
1083
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001084MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001085 const Function &F, const TargetMachine &TM) const {
Rafael Espindolaab447e42015-03-11 19:58:37 +00001086 // If the function can be removed, produce a unique section so that
1087 // the table doesn't prevent the removal.
1088 const Comdat *C = F.getComdat();
1089 bool EmitUniqueSection = TM.getFunctionSections() || C;
1090 if (!EmitUniqueSection)
1091 return ReadOnlySection;
1092
1093 // FIXME: we should produce a symbol for F instead.
1094 if (F.hasPrivateLinkage())
1095 return ReadOnlySection;
1096
Tim Northoverb64fb452016-11-22 16:17:20 +00001097 MCSymbol *Sym = TM.getSymbol(&F);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001098 StringRef COMDATSymName = Sym->getName();
1099
1100 SectionKind Kind = SectionKind::getReadOnly();
1101 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Renato Golinef3eb062016-06-27 14:42:20 +00001102 unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001103 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Reid Kleckner97837b72016-05-02 23:22:18 +00001104 unsigned UniqueID = NextUniqueID++;
Rafael Espindolaab447e42015-03-11 19:58:37 +00001105
1106 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
Reid Kleckner97837b72016-05-02 23:22:18 +00001107 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
Rafael Espindolaab447e42015-03-11 19:58:37 +00001108}
1109
Eric Christopher4367c7f2016-09-16 07:33:15 +00001110void TargetLoweringObjectFileCOFF::emitModuleFlags(
1111 MCStreamer &Streamer, ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
1112 const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +00001113 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001114
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001115 for (const auto &MFE : ModuleFlags) {
Reid Klecknerd973ca32013-04-25 19:34:41 +00001116 StringRef Key = MFE.Key->getString();
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001117 if (Key == "Linker Options")
1118 LinkerOptions = cast<MDNode>(MFE.Val);
Reid Klecknerd973ca32013-04-25 19:34:41 +00001119 }
Reid Klecknerd973ca32013-04-25 19:34:41 +00001120
Saleem Abdulrasoole0f0c0e2016-04-30 18:15:34 +00001121 if (LinkerOptions) {
1122 // Emit the linker options to the linker .drectve section. According to the
1123 // spec, this section is a space-separated string containing flags for
1124 // linker.
1125 MCSection *Sec = getDrectveSection();
1126 Streamer.SwitchSection(Sec);
1127 for (const auto &Option : LinkerOptions->operands()) {
1128 for (const auto &Piece : cast<MDNode>(Option)->operands()) {
1129 // Lead with a space for consistency with our dllexport implementation.
1130 std::string Directive(" ");
1131 Directive.append(cast<MDString>(Piece)->getString());
1132 Streamer.EmitBytes(Directive);
1133 }
Reid Klecknerd973ca32013-04-25 19:34:41 +00001134 }
1135 }
1136}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001137
Rafael Espindola46fa2312016-08-29 12:33:42 +00001138void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
1139 const TargetMachine &TM) {
1140 TargetLoweringObjectFile::Initialize(Ctx, TM);
1141 const Triple &T = TM.getTargetTriple();
1142 if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
1143 StaticCtorSection =
1144 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1145 COFF::IMAGE_SCN_MEM_READ,
1146 SectionKind::getReadOnly());
1147 StaticDtorSection =
1148 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1149 COFF::IMAGE_SCN_MEM_READ,
1150 SectionKind::getReadOnly());
1151 } else {
1152 StaticCtorSection = Ctx.getCOFFSection(
1153 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1154 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1155 SectionKind::getData());
1156 StaticDtorSection = Ctx.getCOFFSection(
1157 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
1158 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
1159 SectionKind::getData());
1160 }
1161}
1162
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001163MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001164 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001165 return getContext().getAssociativeCOFFSection(
Reid Kleckner97837b72016-05-02 23:22:18 +00001166 cast<MCSectionCOFF>(StaticCtorSection), KeySym, 0);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001167}
1168
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001169MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001170 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001171 return getContext().getAssociativeCOFFSection(
Reid Kleckner97837b72016-05-02 23:22:18 +00001172 cast<MCSectionCOFF>(StaticDtorSection), KeySym, 0);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001173}
Peter Collingbourneaef36592015-06-29 22:04:09 +00001174
1175void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
Eric Christopher4367c7f2016-09-16 07:33:15 +00001176 raw_ostream &OS, const GlobalValue *GV) const {
Bob Haarmandd4ebc12017-02-02 23:00:49 +00001177 emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
Peter Collingbourneaef36592015-06-29 22:04:09 +00001178}
Dan Gohman18eafb62017-02-22 01:23:18 +00001179
1180//===----------------------------------------------------------------------===//
1181// Wasm
1182//===----------------------------------------------------------------------===//
1183
Dan Gohmand934cb82017-02-24 23:18:00 +00001184static const Comdat *getWasmComdat(const GlobalValue *GV) {
1185 const Comdat *C = GV->getComdat();
1186 if (!C)
1187 return nullptr;
1188
1189 if (C->getSelectionKind() != Comdat::Any)
1190 report_fatal_error("Wasm COMDATs only support SelectionKind::Any, '" +
1191 C->getName() + "' cannot be lowered.");
1192
1193 return C;
1194}
1195
Dan Gohman18eafb62017-02-22 01:23:18 +00001196MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
1197 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
1198 llvm_unreachable("getExplicitSectionGlobal not yet implemented");
1199 return nullptr;
1200}
1201
Dan Gohmand934cb82017-02-24 23:18:00 +00001202static MCSectionWasm *
1203selectWasmSectionForGlobal(MCContext &Ctx, const GlobalObject *GO,
1204 SectionKind Kind, Mangler &Mang,
1205 const TargetMachine &TM, bool EmitUniqueSection,
1206 unsigned Flags, unsigned *NextUniqueID) {
1207 StringRef Group = "";
1208 if (getWasmComdat(GO))
1209 llvm_unreachable("comdat not yet supported for wasm");
1210
1211 bool UniqueSectionNames = TM.getUniqueSectionNames();
1212 SmallString<128> Name = getSectionPrefixForGlobal(Kind);
1213
1214 if (const auto *F = dyn_cast<Function>(GO)) {
1215 const auto &OptionalPrefix = F->getSectionPrefix();
1216 if (OptionalPrefix)
1217 Name += *OptionalPrefix;
1218 }
1219
1220 if (EmitUniqueSection && UniqueSectionNames) {
1221 Name.push_back('.');
1222 TM.getNameWithPrefix(Name, GO, Mang, true);
1223 }
1224 unsigned UniqueID = MCContext::GenericSectionID;
1225 if (EmitUniqueSection && !UniqueSectionNames) {
1226 UniqueID = *NextUniqueID;
1227 (*NextUniqueID)++;
1228 }
1229 return Ctx.getWasmSection(Name, /*Type=*/0, Flags,
1230 Group, UniqueID);
1231}
1232
Dan Gohman18eafb62017-02-22 01:23:18 +00001233MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
1234 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
Dan Gohmand934cb82017-02-24 23:18:00 +00001235
1236 if (Kind.isCommon())
1237 report_fatal_error("mergable sections not supported yet on wasm");
1238
1239 // If we have -ffunction-section or -fdata-section then we should emit the
1240 // global value to a uniqued section specifically for it.
1241 bool EmitUniqueSection = false;
Dan Gohman18eafb62017-02-22 01:23:18 +00001242 if (Kind.isText())
Dan Gohmand934cb82017-02-24 23:18:00 +00001243 EmitUniqueSection = TM.getFunctionSections();
1244 else
1245 EmitUniqueSection = TM.getDataSections();
1246 EmitUniqueSection |= GO->hasComdat();
1247
1248 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
1249 EmitUniqueSection, /*Flags=*/0,
1250 &NextUniqueID);
Dan Gohman18eafb62017-02-22 01:23:18 +00001251}
1252
1253bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
1254 bool UsesLabelDifference, const Function &F) const {
1255 // We can always create relative relocations, so use another section
1256 // that can be marked non-executable.
1257 return false;
1258}
1259
1260const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
1261 const GlobalValue *LHS, const GlobalValue *RHS,
1262 const TargetMachine &TM) const {
1263 // We may only use a PLT-relative relocation to refer to unnamed_addr
1264 // functions.
1265 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
1266 return nullptr;
1267
1268 // Basic sanity checks.
1269 if (LHS->getType()->getPointerAddressSpace() != 0 ||
1270 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
1271 RHS->isThreadLocal())
1272 return nullptr;
1273
1274 return MCBinaryExpr::createSub(
1275 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
1276 getContext()),
1277 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
1278}
1279
1280void
1281TargetLoweringObjectFileWasm::InitializeWasm() {
1282 // TODO: Initialize StaticCtorSection and StaticDtorSection.
1283}