blob: 3b205d0760eba20307d46cc1c0020eebb8a7a65b [file] [log] [blame]
Anton Korobeynikovab663a02010-02-15 22:37:53 +00001//===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
2//
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
15#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/SmallString.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/ADT/Triple.h"
19#include "llvm/CodeGen/MachineModuleInfoImpls.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/Constants.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/DerivedTypes.h"
23#include "llvm/IR/Function.h"
24#include "llvm/IR/GlobalVariable.h"
Rafael Espindola894843c2014-01-07 21:19:40 +000025#include "llvm/IR/Mangler.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000027#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCExpr.h"
Chris Lattner87cffa92010-05-07 17:17:41 +000029#include "llvm/MC/MCSectionCOFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000030#include "llvm/MC/MCSectionELF.h"
31#include "llvm/MC/MCSectionMachO.h"
Rafael Espindolaa83b1772011-04-16 03:51:21 +000032#include "llvm/MC/MCStreamer.h"
Rafael Espindolaa8695762015-06-02 00:25:12 +000033#include "llvm/MC/MCSymbolELF.h"
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +000034#include "llvm/MC/MCValue.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000035#include "llvm/Support/Dwarf.h"
Rafael Espindolaaea49582011-01-23 04:28:49 +000036#include "llvm/Support/ELF.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000037#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/raw_ostream.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000039#include "llvm/Target/TargetLowering.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000040#include "llvm/Target/TargetMachine.h"
Eric Christopherd9134482014-08-04 21:25:23 +000041#include "llvm/Target/TargetSubtargetInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000042using namespace llvm;
Anton Korobeynikov31a92122010-02-21 20:28:15 +000043using namespace dwarf;
Anton Korobeynikovab663a02010-02-15 22:37:53 +000044
45//===----------------------------------------------------------------------===//
46// ELF
47//===----------------------------------------------------------------------===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +000048
Rafael Espindoladaeafb42014-02-19 17:23:20 +000049MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
50 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
51 MachineModuleInfo *MMI) const {
Rafael Espindolace83fc32011-04-27 23:17:57 +000052 unsigned Encoding = getPersonalityEncoding();
Logan Chienc0029812014-05-30 16:48:56 +000053 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
Jim Grosbach6f482002015-05-18 18:43:14 +000054 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +000055 TM.getSymbol(GV, Mang)->getName());
Logan Chienc0029812014-05-30 16:48:56 +000056 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
57 return TM.getSymbol(GV, Mang);
58 report_fatal_error("We do not support this DWARF encoding yet!");
Rafael Espindolaa83b1772011-04-16 03:51:21 +000059}
60
Mehdi Amini5c0fa582015-07-16 06:04:17 +000061void TargetLoweringObjectFileELF::emitPersonalityValue(
62 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000063 SmallString<64> NameData("DW.ref.");
64 NameData += Sym->getName();
Rafael Espindolaa8695762015-06-02 00:25:12 +000065 MCSymbolELF *Label =
66 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
Rafael Espindola39897762011-04-27 21:29:52 +000067 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
68 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000069 StringRef Prefix = ".data.";
70 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
Rafael Espindola39897762011-04-27 21:29:52 +000071 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
Rafael Espindola0709a7b2015-05-21 19:20:38 +000072 MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
73 Flags, 0, Label->getName());
Mehdi Amini5c0fa582015-07-16 06:04:17 +000074 unsigned Size = DL.getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +000075 Streamer.SwitchSection(Sec);
Mehdi Amini5c0fa582015-07-16 06:04:17 +000076 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +000077 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
Jim Grosbach13760bd2015-05-30 01:25:56 +000078 const MCExpr *E = MCConstantExpr::create(Size, getContext());
Rafael Espindolaa8695762015-06-02 00:25:12 +000079 Streamer.emitELFSize(Label, E);
Rafael Espindola39897762011-04-27 21:29:52 +000080 Streamer.EmitLabel(Label);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000081
Rafael Espindola39897762011-04-27 21:29:52 +000082 Streamer.EmitSymbolValue(Sym, Size);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000083}
84
Rafael Espindola15b26692014-02-09 14:50:44 +000085const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
86 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +000087 const TargetMachine &TM, MachineModuleInfo *MMI,
88 MCStreamer &Streamer) const {
Anton Korobeynikove42af362012-11-14 01:47:00 +000089
90 if (Encoding & dwarf::DW_EH_PE_indirect) {
91 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
92
Rafael Espindoladaeafb42014-02-19 17:23:20 +000093 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
Anton Korobeynikove42af362012-11-14 01:47:00 +000094
95 // Add information about the stub reference to ELFMMI so that the stub
96 // gets emitted by the asmprinter.
Anton Korobeynikove42af362012-11-14 01:47:00 +000097 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +000098 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +000099 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000100 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
101 }
102
103 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000104 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Anton Korobeynikove42af362012-11-14 01:47:00 +0000105 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
106 }
107
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000108 return TargetLoweringObjectFile::
109 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000110}
111
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000112static SectionKind
113getELFKindForNamedSection(StringRef Name, SectionKind K) {
Rafael Espindola0d018b12011-05-24 03:10:31 +0000114 // N.B.: The defaults used in here are no the same ones used in MC.
115 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
116 // both gas and MC will produce a section with no flags. Given
Bill Wendlingd1634052012-07-19 00:04:14 +0000117 // section(".eh_frame") gcc will produce:
118 //
119 // .section .eh_frame,"a",@progbits
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000120 if (Name.empty() || Name[0] != '.') return K;
121
122 // Some lame default implementation based on some magic section names.
123 if (Name == ".bss" ||
124 Name.startswith(".bss.") ||
125 Name.startswith(".gnu.linkonce.b.") ||
126 Name.startswith(".llvm.linkonce.b.") ||
127 Name == ".sbss" ||
128 Name.startswith(".sbss.") ||
129 Name.startswith(".gnu.linkonce.sb.") ||
130 Name.startswith(".llvm.linkonce.sb."))
131 return SectionKind::getBSS();
132
133 if (Name == ".tdata" ||
134 Name.startswith(".tdata.") ||
135 Name.startswith(".gnu.linkonce.td.") ||
136 Name.startswith(".llvm.linkonce.td."))
137 return SectionKind::getThreadData();
138
139 if (Name == ".tbss" ||
140 Name.startswith(".tbss.") ||
141 Name.startswith(".gnu.linkonce.tb.") ||
142 Name.startswith(".llvm.linkonce.tb."))
143 return SectionKind::getThreadBSS();
144
145 return K;
146}
147
148
149static unsigned getELFSectionType(StringRef Name, SectionKind K) {
150
151 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000152 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000153
154 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000155 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000156
157 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000158 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000159
160 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000161 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000162
Rafael Espindolaaea49582011-01-23 04:28:49 +0000163 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000164}
165
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000166static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000167 unsigned Flags = 0;
168
169 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000170 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000171
172 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000173 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000174
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000175 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000176 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000177
178 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000179 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000180
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000181 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000182 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000183
184 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000185 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000186
187 return Flags;
188}
189
David Majnemerdad0a642014-06-27 18:19:56 +0000190static const Comdat *getELFComdat(const GlobalValue *GV) {
191 const Comdat *C = GV->getComdat();
192 if (!C)
193 return nullptr;
194
195 if (C->getSelectionKind() != Comdat::Any)
196 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
197 C->getName() + "' cannot be lowered.");
198
199 return C;
200}
201
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000202MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000203 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
204 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000205 StringRef SectionName = GV->getSection();
206
207 // Infer section flags from the section name if we can.
208 Kind = getELFKindForNamedSection(SectionName, Kind);
209
David Majnemerdad0a642014-06-27 18:19:56 +0000210 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000211 unsigned Flags = getELFSectionFlags(Kind);
David Majnemerdad0a642014-06-27 18:19:56 +0000212 if (const Comdat *C = getELFComdat(GV)) {
213 Group = C->getName();
214 Flags |= ELF::SHF_GROUP;
215 }
Chris Lattner80c34592010-04-08 21:34:17 +0000216 return getContext().getELFSection(SectionName,
David Majnemerdad0a642014-06-27 18:19:56 +0000217 getELFSectionType(SectionName, Kind), Flags,
Rafael Espindolaba31e272015-01-29 17:33:21 +0000218 /*EntrySize=*/0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000219}
220
Rafael Espindola25d2c202015-02-11 14:44:17 +0000221/// Return the section prefix name used by options FunctionsSections and
222/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000223static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000224 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000225 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000226 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000227 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000228 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000229 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000230 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000231 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000232 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000233 return ".tbss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000234 if (Kind.isDataNoRel())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000235 return ".data";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000236 if (Kind.isDataRelLocal())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000237 return ".data.rel.local";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000238 if (Kind.isDataRel())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000239 return ".data.rel";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000240 if (Kind.isReadOnlyWithRelLocal())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000241 return ".data.rel.ro.local";
Chris Lattner5b212a32010-04-13 00:36:43 +0000242 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000243 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000244}
245
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000246static MCSectionELF *
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000247selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
248 SectionKind Kind, Mangler &Mang,
249 const TargetMachine &TM, bool EmitUniqueSection,
250 unsigned Flags, unsigned *NextUniqueID) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000251 unsigned EntrySize = 0;
252 if (Kind.isMergeableCString()) {
253 if (Kind.isMergeable2ByteCString()) {
254 EntrySize = 2;
255 } else if (Kind.isMergeable4ByteCString()) {
256 EntrySize = 4;
257 } else {
258 EntrySize = 1;
259 assert(Kind.isMergeable1ByteCString() && "unknown string width");
260 }
261 } else if (Kind.isMergeableConst()) {
262 if (Kind.isMergeableConst4()) {
263 EntrySize = 4;
264 } else if (Kind.isMergeableConst8()) {
265 EntrySize = 8;
266 } else {
267 assert(Kind.isMergeableConst16() && "unknown data width");
268 EntrySize = 16;
269 }
270 }
271
Rafael Espindola9075f772015-02-20 23:28:28 +0000272 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000273 if (const Comdat *C = getELFComdat(GV)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000274 Flags |= ELF::SHF_GROUP;
275 Group = C->getName();
276 }
277
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000278 bool UniqueSectionNames = TM.getUniqueSectionNames();
279 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000280 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000281 // We also need alignment here.
282 // FIXME: this is getting the alignment of the character, not the
283 // alignment of the global!
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000284 unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
285 cast<GlobalVariable>(GV));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000286
Rafael Espindolaba31e272015-01-29 17:33:21 +0000287 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000288 Name = SizeSpec + utostr(Align);
289 } else if (Kind.isMergeableConst()) {
290 Name = ".rodata.cst";
291 Name += utostr(EntrySize);
292 } else {
293 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000294 }
295
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000296 if (EmitUniqueSection && UniqueSectionNames) {
297 Name.push_back('.');
298 TM.getNameWithPrefix(Name, GV, Mang, true);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000299 }
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000300 unsigned UniqueID = ~0;
301 if (EmitUniqueSection && !UniqueSectionNames) {
302 UniqueID = *NextUniqueID;
303 (*NextUniqueID)++;
304 }
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000305 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000306 EntrySize, Group, UniqueID);
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000307}
308
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000309MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000310 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
311 const TargetMachine &TM) const {
312 unsigned Flags = getELFSectionFlags(Kind);
313
314 // If we have -ffunction-section or -fdata-section then we should emit the
315 // global value to a uniqued section specifically for it.
316 bool EmitUniqueSection = false;
317 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
318 if (Kind.isText())
319 EmitUniqueSection = TM.getFunctionSections();
320 else
321 EmitUniqueSection = TM.getDataSections();
322 }
323 EmitUniqueSection |= GV->hasComdat();
324
325 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000326 EmitUniqueSection, Flags, &NextUniqueID);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000327}
328
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000329MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
Rafael Espindola29786d42015-02-12 17:16:46 +0000330 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
331 // If the function can be removed, produce a unique section so that
332 // the table doesn't prevent the removal.
333 const Comdat *C = F.getComdat();
334 bool EmitUniqueSection = TM.getFunctionSections() || C;
335 if (!EmitUniqueSection)
336 return ReadOnlySection;
337
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000338 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000339 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
340 &NextUniqueID);
Rafael Espindola29786d42015-02-12 17:16:46 +0000341}
342
Rafael Espindoladf195192015-02-17 23:34:51 +0000343bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
344 bool UsesLabelDifference, const Function &F) const {
345 // We can always create relative relocations, so use another section
346 // that can be marked non-executable.
347 return false;
348}
349
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000350/// Given a mergeable constant with the specified size and relocation
351/// information, return a section that it should be placed in.
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000352MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
353 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000354 if (Kind.isMergeableConst4() && MergeableConst4Section)
355 return MergeableConst4Section;
356 if (Kind.isMergeableConst8() && MergeableConst8Section)
357 return MergeableConst8Section;
358 if (Kind.isMergeableConst16() && MergeableConst16Section)
359 return MergeableConst16Section;
360 if (Kind.isReadOnly())
361 return ReadOnlySection;
362
363 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
364 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
365 return DataRelROSection;
366}
367
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000368static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
369 bool IsCtor, unsigned Priority,
370 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000371 std::string Name;
372 unsigned Type;
373 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000374 StringRef COMDAT = KeySym ? KeySym->getName() : "";
375
376 if (KeySym)
377 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000378
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000379 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000380 if (IsCtor) {
381 Type = ELF::SHT_INIT_ARRAY;
382 Name = ".init_array";
383 } else {
384 Type = ELF::SHT_FINI_ARRAY;
385 Name = ".fini_array";
386 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000387 if (Priority != 65535) {
388 Name += '.';
389 Name += utostr(Priority);
390 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000391 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000392 // The default scheme is .ctor / .dtor, so we have to invert the priority
393 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000394 if (IsCtor)
395 Name = ".ctors";
396 else
397 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000398 if (Priority != 65535) {
399 Name += '.';
400 Name += utostr(65535 - Priority);
401 }
402 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000403 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000404
Rafael Espindolaba31e272015-01-29 17:33:21 +0000405 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000406}
407
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000408MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000409 unsigned Priority, const MCSymbol *KeySym) const {
410 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
411 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000412}
413
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000414MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000415 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000416 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
417 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000418}
419
420void
421TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
422 UseInitArray = UseInitArray_;
423 if (!UseInitArray)
424 return;
425
Rafael Espindolaba31e272015-01-29 17:33:21 +0000426 StaticCtorSection = getContext().getELFSection(
427 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
428 StaticDtorSection = getContext().getELFSection(
429 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000430}
431
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000432//===----------------------------------------------------------------------===//
433// MachO
434//===----------------------------------------------------------------------===//
435
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000436TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
437 : TargetLoweringObjectFile() {
438 SupportIndirectSymViaGOTPCRel = true;
439}
440
Daniel Dunbar95856122013-01-18 19:37:00 +0000441/// emitModuleFlags - Perform code emission for module flags.
Bill Wendling06df7722012-02-14 21:28:13 +0000442void TargetLoweringObjectFileMachO::
Bill Wendling734909a2012-02-15 22:36:15 +0000443emitModuleFlags(MCStreamer &Streamer,
444 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000445 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000446 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000447 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000448 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000449 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000450
Bill Wendling734909a2012-02-15 22:36:15 +0000451 for (ArrayRef<Module::ModuleFlagEntry>::iterator
452 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
453 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendling06df7722012-02-14 21:28:13 +0000454
455 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000456 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000457 continue;
458
Bill Wendling734909a2012-02-15 22:36:15 +0000459 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000460 Metadata *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000461
Daniel Dunbar95856122013-01-18 19:37:00 +0000462 if (Key == "Objective-C Image Info Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000463 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000464 } else if (Key == "Objective-C Garbage Collection" ||
465 Key == "Objective-C GC Only" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000466 Key == "Objective-C Is Simulated" ||
467 Key == "Objective-C Image Swift Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000468 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000469 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000470 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000471 } else if (Key == "Linker Options") {
472 LinkerOptions = cast<MDNode>(Val);
473 }
474 }
475
476 // Emit the linker options if present.
477 if (LinkerOptions) {
478 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
479 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
480 SmallVector<std::string, 4> StrOptions;
481
482 // Convert to strings.
483 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
484 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
485 StrOptions.push_back(MDOption->getString());
486 }
487
488 Streamer.EmitLinkerOptions(StrOptions);
489 }
Bill Wendling06df7722012-02-14 21:28:13 +0000490 }
491
Bill Wendling734909a2012-02-15 22:36:15 +0000492 // The section is mandatory. If we don't have it, then we don't have GC info.
493 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000494
Bill Wendling734909a2012-02-15 22:36:15 +0000495 StringRef Segment, Section;
496 unsigned TAA = 0, StubSize = 0;
497 bool TAAParsed;
498 std::string ErrorCode =
499 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
500 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000501 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000502 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000503 report_fatal_error("Invalid section specifier '" + Section + "': " +
504 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000505
Bill Wendling734909a2012-02-15 22:36:15 +0000506 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000507 MCSectionMachO *S = getContext().getMachOSection(
508 Segment, Section, TAA, StubSize, SectionKind::getDataNoRel());
Bill Wendling734909a2012-02-15 22:36:15 +0000509 Streamer.SwitchSection(S);
510 Streamer.EmitLabel(getContext().
Jim Grosbach6f482002015-05-18 18:43:14 +0000511 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000512 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000513 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000514 Streamer.AddBlankLine();
515}
516
David Majnemerdad0a642014-06-27 18:19:56 +0000517static void checkMachOComdat(const GlobalValue *GV) {
518 const Comdat *C = GV->getComdat();
519 if (!C)
520 return;
521
522 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
523 "' cannot be lowered.");
524}
525
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000526MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000527 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
528 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000529 // Parse the section specifier and create it if valid.
530 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000531 unsigned TAA = 0, StubSize = 0;
532 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000533
534 checkMachOComdat(GV);
535
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000536 std::string ErrorCode =
537 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000538 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000539 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000540 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000541 report_fatal_error("Global variable '" + GV->getName() +
542 "' has an invalid section specifier '" +
543 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000544 }
545
546 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000547 MCSectionMachO *S =
548 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000549
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000550 // If TAA wasn't set by ParseSectionSpecifier() above,
551 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000552 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000553 TAA = S->getTypeAndAttributes();
554
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000555 // Okay, now that we got the section, verify that the TAA & StubSize agree.
556 // If the user declared multiple globals with different section flags, we need
557 // to reject it here.
558 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000559 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000560 report_fatal_error("Global variable '" + GV->getName() +
561 "' section type or attributes does not match previous"
562 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000563 }
564
565 return S;
566}
567
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000568MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
569 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
570 const TargetMachine &TM) const {
David Majnemerdad0a642014-06-27 18:19:56 +0000571 checkMachOComdat(GV);
Bill Wendling25b61db2013-11-17 10:53:13 +0000572
573 // Handle thread local data.
574 if (Kind.isThreadBSS()) return TLSBSSSection;
575 if (Kind.isThreadData()) return TLSDataSection;
576
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000577 if (Kind.isText())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000578 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
579
580 // If this is weak/linkonce, put this in a coalescable section, either in text
581 // or data depending on if it is writable.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000582 if (GV->isWeakForLinker()) {
583 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000584 return ConstTextCoalSection;
585 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000586 }
587
588 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000589 if (Kind.isMergeable1ByteCString() &&
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000590 GV->getParent()->getDataLayout().getPreferredAlignment(
591 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000592 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000593
Chris Lattneref2f8042010-03-07 04:28:09 +0000594 // Do not put 16-bit arrays in the UString section if they have an
595 // externally visible label, this runs into issues with certain linker
596 // versions.
597 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000598 GV->getParent()->getDataLayout().getPreferredAlignment(
599 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000600 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000601
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000602 // With MachO only variables whose corresponding symbol starts with 'l' or
603 // 'L' can be merged, so we only try merging GVs with private linkage.
604 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000605 if (Kind.isMergeableConst4())
606 return FourByteConstantSection;
607 if (Kind.isMergeableConst8())
608 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000609 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000610 return SixteenByteConstantSection;
611 }
612
613 // Otherwise, if it is readonly, but not something we can specially optimize,
614 // just drop it in .const.
615 if (Kind.isReadOnly())
616 return ReadOnlySection;
617
618 // If this is marked const, put it into a const section. But if the dynamic
619 // linker needs to write to it, put it in the data segment.
620 if (Kind.isReadOnlyWithRel())
621 return ConstDataSection;
622
623 // Put zero initialized globals with strong external linkage in the
624 // DATA, __common section with the .zerofill directive.
625 if (Kind.isBSSExtern())
626 return DataCommonSection;
627
628 // Put zero initialized globals with local linkage in __DATA,__bss directive
629 // with the .zerofill directive (aka .lcomm).
630 if (Kind.isBSSLocal())
631 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000632
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000633 // Otherwise, just drop the variable in the normal data section.
634 return DataSection;
635}
636
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000637MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
638 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000639 // If this constant requires a relocation, we have to put it in the data
640 // segment, not in the text segment.
641 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
642 return ConstDataSection;
643
644 if (Kind.isMergeableConst4())
645 return FourByteConstantSection;
646 if (Kind.isMergeableConst8())
647 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000648 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000649 return SixteenByteConstantSection;
650 return ReadOnlySection; // .const
651}
652
Rafael Espindola15b26692014-02-09 14:50:44 +0000653const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
654 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000655 const TargetMachine &TM, MachineModuleInfo *MMI,
656 MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000657 // The mach-o version of this method defaults to returning a stub reference.
658
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000659 if (Encoding & DW_EH_PE_indirect) {
660 MachineModuleInfoMachO &MachOMMI =
661 MMI->getObjFileInfo<MachineModuleInfoMachO>();
662
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000663 MCSymbol *SSym =
664 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000665
666 // Add information about the stub reference to MachOMMI so that the stub
667 // gets emitted by the asmprinter.
Bill Wendling57e3aaa2011-10-24 23:05:43 +0000668 MachineModuleInfoImpl::StubValueTy &StubSym =
669 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
670 MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000671 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000672 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000673 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000674 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000675
676 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000677 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Anton Korobeynikove42af362012-11-14 01:47:00 +0000678 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000679 }
680
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000681 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
682 TM, MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000683}
684
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000685MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
686 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
687 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000688 // The mach-o version of this method defaults to returning a stub reference.
689 MachineModuleInfoMachO &MachOMMI =
690 MMI->getObjFileInfo<MachineModuleInfoMachO>();
691
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000692 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000693
694 // Add information about the stub reference to MachOMMI so that the stub
695 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000696 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000697 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000698 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola08704342011-04-27 23:08:15 +0000699 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
700 }
701
702 return SSym;
703}
704
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000705const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
706 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
707 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000708 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000709 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
710 // through a non_lazy_ptr stub instead. One advantage is that it allows the
711 // computation of deltas to final external symbols. Example:
712 //
713 // _extgotequiv:
714 // .long _extfoo
715 //
716 // _delta:
717 // .long _extgotequiv-_delta
718 //
719 // is transformed to:
720 //
721 // _delta:
722 // .long L_extfoo$non_lazy_ptr-(_delta+0)
723 //
724 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
725 // L_extfoo$non_lazy_ptr:
726 // .indirect_symbol _extfoo
727 // .long 0
728 //
729 MachineModuleInfoMachO &MachOMMI =
730 MMI->getObjFileInfo<MachineModuleInfoMachO>();
731 MCContext &Ctx = getContext();
732
733 // The offset must consider the original displacement from the base symbol
734 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
735 Offset = -MV.getConstant();
736 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
737
738 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
739 // non_lazy_ptr stubs.
740 SmallString<128> Name;
741 StringRef Suffix = "$non_lazy_ptr";
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000742 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000743 Name += Sym->getName();
744 Name += Suffix;
Jim Grosbach6f482002015-05-18 18:43:14 +0000745 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000746
747 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
748 if (!StubSym.getPointer())
749 StubSym = MachineModuleInfoImpl::
750 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
751
752 const MCExpr *BSymExpr =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000753 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000754 const MCExpr *LHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000755 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000756
757 if (!Offset)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000758 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000759
760 const MCExpr *RHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000761 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
762 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000763}
764
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000765//===----------------------------------------------------------------------===//
766// COFF
767//===----------------------------------------------------------------------===//
768
Chris Lattner87cffa92010-05-07 17:17:41 +0000769static unsigned
770getCOFFSectionFlags(SectionKind K) {
771 unsigned Flags = 0;
772
Anton Korobeynikove4152302010-07-06 15:24:56 +0000773 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000774 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000775 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000776 else if (K.isText())
777 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000778 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000779 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar329d2022010-07-01 20:07:24 +0000780 COFF::IMAGE_SCN_CNT_CODE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000781 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000782 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000783 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
784 COFF::IMAGE_SCN_MEM_READ |
785 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000786 else if (K.isThreadLocal())
787 Flags |=
788 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
789 COFF::IMAGE_SCN_MEM_READ |
790 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000791 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000792 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000793 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
794 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000795 else if (K.isWriteable())
796 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000797 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
798 COFF::IMAGE_SCN_MEM_READ |
799 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000800
801 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000802}
803
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000804static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000805 const Comdat *C = GV->getComdat();
806 assert(C && "expected GV to have a Comdat!");
807
808 StringRef ComdatGVName = C->getName();
809 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
810 if (!ComdatGV)
811 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
812 "' does not exist.");
813
814 if (ComdatGV->getComdat() != C)
815 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000816 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000817
818 return ComdatGV;
819}
820
821static int getSelectionForCOFF(const GlobalValue *GV) {
822 if (const Comdat *C = GV->getComdat()) {
823 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
824 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
825 ComdatKey = GA->getBaseObject();
826 if (ComdatKey == GV) {
827 switch (C->getSelectionKind()) {
828 case Comdat::Any:
829 return COFF::IMAGE_COMDAT_SELECT_ANY;
830 case Comdat::ExactMatch:
831 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
832 case Comdat::Largest:
833 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
834 case Comdat::NoDuplicates:
835 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
836 case Comdat::SameSize:
837 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
838 }
839 } else {
840 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
841 }
David Majnemerdad0a642014-06-27 18:19:56 +0000842 }
843 return 0;
844}
845
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000846MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000847 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
848 const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000849 int Selection = 0;
850 unsigned Characteristics = getCOFFSectionFlags(Kind);
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000851 StringRef Name = GV->getSection();
852 StringRef COMDATSymName = "";
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000853 if (GV->hasComdat()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000854 Selection = getSelectionForCOFF(GV);
855 const GlobalValue *ComdatGV;
856 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
857 ComdatGV = getComdatGVForCOFF(GV);
858 else
859 ComdatGV = GV;
860
861 if (!ComdatGV->hasPrivateLinkage()) {
862 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
863 COMDATSymName = Sym->getName();
864 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
865 } else {
866 Selection = 0;
867 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000868 }
869 return getContext().getCOFFSection(Name,
870 Characteristics,
Nico Riecka37acf72013-07-06 12:13:10 +0000871 Kind,
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000872 COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000873 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000874}
875
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000876static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000877 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000878 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +0000879 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000880 return ".bss";
881 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +0000882 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +0000883 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
884 return ".rdata";
885 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000886}
887
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000888MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
889 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
890 const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +0000891 // If we have -ffunction-sections then we should emit the global value to a
892 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +0000893 bool EmitUniquedSection;
894 if (Kind.isText())
895 EmitUniquedSection = TM.getFunctionSections();
896 else
897 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000898
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000899 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000900 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner02844932010-05-07 21:49:09 +0000901 unsigned Characteristics = getCOFFSectionFlags(Kind);
902
Daniel Dunbar329d2022010-07-01 20:07:24 +0000903 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
David Majnemerdad0a642014-06-27 18:19:56 +0000904 int Selection = getSelectionForCOFF(GV);
905 if (!Selection)
906 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
907 const GlobalValue *ComdatGV;
908 if (GV->hasComdat())
909 ComdatGV = getComdatGVForCOFF(GV);
910 else
911 ComdatGV = GV;
912
913 if (!ComdatGV->hasPrivateLinkage()) {
914 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
915 StringRef COMDATSymName = Sym->getName();
916 return getContext().getCOFFSection(Name, Characteristics, Kind,
917 COMDATSymName, Selection);
David Majnemer7db449a2015-03-17 23:54:51 +0000918 } else {
919 SmallString<256> TmpData;
920 getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true, Mang, TM);
921 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
922 Selection);
David Majnemerdad0a642014-06-27 18:19:56 +0000923 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000924 }
925
926 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +0000927 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000928
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000929 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +0000930 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000931
David Majnemer597be2d2014-09-22 20:39:23 +0000932 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +0000933 return ReadOnlySection;
934
David Majnemera9bdb322014-04-08 22:33:40 +0000935 // Note: we claim that common symbols are put in BSSSection, but they are
936 // really emitted with the magic .comm directive, which creates a symbol table
937 // entry but not a section.
938 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +0000939 return BSSSection;
940
941 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000942}
943
David Majnemer7db449a2015-03-17 23:54:51 +0000944void TargetLoweringObjectFileCOFF::getNameWithPrefix(
945 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
946 bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
947 if (GV->hasPrivateLinkage() &&
948 ((isa<Function>(GV) && TM.getFunctionSections()) ||
949 (isa<GlobalVariable>(GV) && TM.getDataSections())))
950 CannotUsePrivateLabel = true;
951
952 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
953}
954
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000955MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
Rafael Espindolaab447e42015-03-11 19:58:37 +0000956 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
957 // If the function can be removed, produce a unique section so that
958 // the table doesn't prevent the removal.
959 const Comdat *C = F.getComdat();
960 bool EmitUniqueSection = TM.getFunctionSections() || C;
961 if (!EmitUniqueSection)
962 return ReadOnlySection;
963
964 // FIXME: we should produce a symbol for F instead.
965 if (F.hasPrivateLinkage())
966 return ReadOnlySection;
967
968 MCSymbol *Sym = TM.getSymbol(&F, Mang);
969 StringRef COMDATSymName = Sym->getName();
970
971 SectionKind Kind = SectionKind::getReadOnly();
972 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
973 unsigned Characteristics = getCOFFSectionFlags(Kind);
974 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
975
976 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
977 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
978}
979
Reid Klecknerd973ca32013-04-25 19:34:41 +0000980void TargetLoweringObjectFileCOFF::
981emitModuleFlags(MCStreamer &Streamer,
982 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000983 Mangler &Mang, const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000984 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +0000985
986 // Look for the "Linker Options" flag, since it's the only one we support.
987 for (ArrayRef<Module::ModuleFlagEntry>::iterator
988 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
989 const Module::ModuleFlagEntry &MFE = *i;
990 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000991 Metadata *Val = MFE.Val;
Reid Klecknerd973ca32013-04-25 19:34:41 +0000992 if (Key == "Linker Options") {
993 LinkerOptions = cast<MDNode>(Val);
994 break;
995 }
996 }
997 if (!LinkerOptions)
998 return;
999
1000 // Emit the linker options to the linker .drectve section. According to the
1001 // spec, this section is a space-separated string containing flags for linker.
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001002 MCSection *Sec = getDrectveSection();
Reid Klecknerd973ca32013-04-25 19:34:41 +00001003 Streamer.SwitchSection(Sec);
1004 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1005 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1006 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1007 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
Reid Klecknerd973ca32013-04-25 19:34:41 +00001008 // Lead with a space for consistency with our dllexport implementation.
Michael Kupersteinfc3e6262015-02-16 11:57:17 +00001009 std::string Directive(" ");
1010 Directive.append(MDOption->getString());
1011 Streamer.EmitBytes(Directive);
Reid Klecknerd973ca32013-04-25 19:34:41 +00001012 }
1013 }
1014}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001015
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001016MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001017 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001018 return getContext().getAssociativeCOFFSection(
1019 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001020}
1021
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001022MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001023 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001024 return getContext().getAssociativeCOFFSection(
1025 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001026}
Peter Collingbourneaef36592015-06-29 22:04:09 +00001027
1028void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1029 raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
1030 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1031 return;
1032
1033 const Triple &TT = getTargetTriple();
1034
1035 if (TT.isKnownWindowsMSVCEnvironment())
1036 OS << " /EXPORT:";
1037 else
1038 OS << " -export:";
1039
1040 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1041 std::string Flag;
1042 raw_string_ostream FlagOS(Flag);
1043 Mang.getNameWithPrefix(FlagOS, GV, false);
1044 FlagOS.flush();
Mehdi Amini5c0fa582015-07-16 06:04:17 +00001045 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
Peter Collingbourneaef36592015-06-29 22:04:09 +00001046 OS << Flag.substr(1);
1047 else
1048 OS << Flag;
1049 } else {
1050 Mang.getNameWithPrefix(OS, GV, false);
1051 }
1052
1053 if (!GV->getValueType()->isFunctionTy()) {
1054 if (TT.isKnownWindowsMSVCEnvironment())
1055 OS << ",DATA";
1056 else
1057 OS << ",data";
1058 }
1059}