blob: 58ae9cc53bda3c1968ff43b72f69de0e7e29b46d [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"
Peter Collingbourne94d77862015-11-03 23:40:03 +000027#include "llvm/MC/MCAsmInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000028#include "llvm/MC/MCContext.h"
29#include "llvm/MC/MCExpr.h"
Chris Lattner87cffa92010-05-07 17:17:41 +000030#include "llvm/MC/MCSectionCOFF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000031#include "llvm/MC/MCSectionELF.h"
32#include "llvm/MC/MCSectionMachO.h"
Rafael Espindolaa83b1772011-04-16 03:51:21 +000033#include "llvm/MC/MCStreamer.h"
Rafael Espindolaa8695762015-06-02 00:25:12 +000034#include "llvm/MC/MCSymbolELF.h"
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +000035#include "llvm/MC/MCValue.h"
Reid Kleckner1f13d472015-09-03 16:41:50 +000036#include "llvm/Support/COFF.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000037#include "llvm/Support/Dwarf.h"
Rafael Espindolaaea49582011-01-23 04:28:49 +000038#include "llvm/Support/ELF.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000039#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/raw_ostream.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000041#include "llvm/Target/TargetLowering.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000042#include "llvm/Target/TargetMachine.h"
Eric Christopherd9134482014-08-04 21:25:23 +000043#include "llvm/Target/TargetSubtargetInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000044using namespace llvm;
Anton Korobeynikov31a92122010-02-21 20:28:15 +000045using namespace dwarf;
Anton Korobeynikovab663a02010-02-15 22:37:53 +000046
47//===----------------------------------------------------------------------===//
48// ELF
49//===----------------------------------------------------------------------===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +000050
Rafael Espindoladaeafb42014-02-19 17:23:20 +000051MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
52 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
53 MachineModuleInfo *MMI) const {
Rafael Espindolace83fc32011-04-27 23:17:57 +000054 unsigned Encoding = getPersonalityEncoding();
Logan Chienc0029812014-05-30 16:48:56 +000055 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
Jim Grosbach6f482002015-05-18 18:43:14 +000056 return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +000057 TM.getSymbol(GV, Mang)->getName());
Logan Chienc0029812014-05-30 16:48:56 +000058 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
59 return TM.getSymbol(GV, Mang);
60 report_fatal_error("We do not support this DWARF encoding yet!");
Rafael Espindolaa83b1772011-04-16 03:51:21 +000061}
62
Mehdi Amini5c0fa582015-07-16 06:04:17 +000063void TargetLoweringObjectFileELF::emitPersonalityValue(
64 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000065 SmallString<64> NameData("DW.ref.");
66 NameData += Sym->getName();
Rafael Espindolaa8695762015-06-02 00:25:12 +000067 MCSymbolELF *Label =
68 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
Rafael Espindola39897762011-04-27 21:29:52 +000069 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
70 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000071 StringRef Prefix = ".data.";
72 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
Rafael Espindola39897762011-04-27 21:29:52 +000073 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
Rafael Espindola0709a7b2015-05-21 19:20:38 +000074 MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
75 Flags, 0, Label->getName());
Mehdi Amini5c0fa582015-07-16 06:04:17 +000076 unsigned Size = DL.getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +000077 Streamer.SwitchSection(Sec);
Mehdi Amini5c0fa582015-07-16 06:04:17 +000078 Streamer.EmitValueToAlignment(DL.getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +000079 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
Jim Grosbach13760bd2015-05-30 01:25:56 +000080 const MCExpr *E = MCConstantExpr::create(Size, getContext());
Rafael Espindolaa8695762015-06-02 00:25:12 +000081 Streamer.emitELFSize(Label, E);
Rafael Espindola39897762011-04-27 21:29:52 +000082 Streamer.EmitLabel(Label);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000083
Rafael Espindola39897762011-04-27 21:29:52 +000084 Streamer.EmitSymbolValue(Sym, Size);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000085}
86
Rafael Espindola15b26692014-02-09 14:50:44 +000087const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
88 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +000089 const TargetMachine &TM, MachineModuleInfo *MMI,
90 MCStreamer &Streamer) const {
Anton Korobeynikove42af362012-11-14 01:47:00 +000091
92 if (Encoding & dwarf::DW_EH_PE_indirect) {
93 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
94
Rafael Espindoladaeafb42014-02-19 17:23:20 +000095 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
Anton Korobeynikove42af362012-11-14 01:47:00 +000096
97 // Add information about the stub reference to ELFMMI so that the stub
98 // gets emitted by the asmprinter.
Anton Korobeynikove42af362012-11-14 01:47:00 +000099 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000100 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000101 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000102 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
103 }
104
105 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000106 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Anton Korobeynikove42af362012-11-14 01:47:00 +0000107 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
108 }
109
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000110 return TargetLoweringObjectFile::
111 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000112}
113
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000114static SectionKind
115getELFKindForNamedSection(StringRef Name, SectionKind K) {
Rafael Espindola0d018b12011-05-24 03:10:31 +0000116 // N.B.: The defaults used in here are no the same ones used in MC.
117 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
118 // both gas and MC will produce a section with no flags. Given
Bill Wendlingd1634052012-07-19 00:04:14 +0000119 // section(".eh_frame") gcc will produce:
120 //
121 // .section .eh_frame,"a",@progbits
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000122 if (Name.empty() || Name[0] != '.') return K;
123
124 // Some lame default implementation based on some magic section names.
125 if (Name == ".bss" ||
126 Name.startswith(".bss.") ||
127 Name.startswith(".gnu.linkonce.b.") ||
128 Name.startswith(".llvm.linkonce.b.") ||
129 Name == ".sbss" ||
130 Name.startswith(".sbss.") ||
131 Name.startswith(".gnu.linkonce.sb.") ||
132 Name.startswith(".llvm.linkonce.sb."))
133 return SectionKind::getBSS();
134
135 if (Name == ".tdata" ||
136 Name.startswith(".tdata.") ||
137 Name.startswith(".gnu.linkonce.td.") ||
138 Name.startswith(".llvm.linkonce.td."))
139 return SectionKind::getThreadData();
140
141 if (Name == ".tbss" ||
142 Name.startswith(".tbss.") ||
143 Name.startswith(".gnu.linkonce.tb.") ||
144 Name.startswith(".llvm.linkonce.tb."))
145 return SectionKind::getThreadBSS();
146
147 return K;
148}
149
150
151static unsigned getELFSectionType(StringRef Name, SectionKind K) {
152
153 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000154 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000155
156 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000157 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000158
159 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000160 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000161
162 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000163 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000164
Rafael Espindolaaea49582011-01-23 04:28:49 +0000165 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000166}
167
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000168static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000169 unsigned Flags = 0;
170
171 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000172 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000173
174 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000175 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000176
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000177 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000178 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000179
180 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000181 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000182
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000183 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000184 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000185
186 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000187 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000188
189 return Flags;
190}
191
David Majnemerdad0a642014-06-27 18:19:56 +0000192static const Comdat *getELFComdat(const GlobalValue *GV) {
193 const Comdat *C = GV->getComdat();
194 if (!C)
195 return nullptr;
196
197 if (C->getSelectionKind() != Comdat::Any)
198 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
199 C->getName() + "' cannot be lowered.");
200
201 return C;
202}
203
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000204MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000205 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
206 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000207 StringRef SectionName = GV->getSection();
208
209 // Infer section flags from the section name if we can.
210 Kind = getELFKindForNamedSection(SectionName, Kind);
211
David Majnemerdad0a642014-06-27 18:19:56 +0000212 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000213 unsigned Flags = getELFSectionFlags(Kind);
David Majnemerdad0a642014-06-27 18:19:56 +0000214 if (const Comdat *C = getELFComdat(GV)) {
215 Group = C->getName();
216 Flags |= ELF::SHF_GROUP;
217 }
Chris Lattner80c34592010-04-08 21:34:17 +0000218 return getContext().getELFSection(SectionName,
David Majnemerdad0a642014-06-27 18:19:56 +0000219 getELFSectionType(SectionName, Kind), Flags,
Rafael Espindolaba31e272015-01-29 17:33:21 +0000220 /*EntrySize=*/0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000221}
222
Rafael Espindola25d2c202015-02-11 14:44:17 +0000223/// Return the section prefix name used by options FunctionsSections and
224/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000225static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000226 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000227 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000228 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000229 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000230 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000231 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000232 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000233 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000234 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000235 return ".tbss";
Rafael Espindola449711c2015-11-18 06:02:15 +0000236 if (Kind.isData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000237 return ".data";
Chris Lattner5b212a32010-04-13 00:36:43 +0000238 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000239 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000240}
241
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000242static MCSectionELF *
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000243selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
244 SectionKind Kind, Mangler &Mang,
245 const TargetMachine &TM, bool EmitUniqueSection,
246 unsigned Flags, unsigned *NextUniqueID) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000247 unsigned EntrySize = 0;
248 if (Kind.isMergeableCString()) {
249 if (Kind.isMergeable2ByteCString()) {
250 EntrySize = 2;
251 } else if (Kind.isMergeable4ByteCString()) {
252 EntrySize = 4;
253 } else {
254 EntrySize = 1;
255 assert(Kind.isMergeable1ByteCString() && "unknown string width");
256 }
257 } else if (Kind.isMergeableConst()) {
258 if (Kind.isMergeableConst4()) {
259 EntrySize = 4;
260 } else if (Kind.isMergeableConst8()) {
261 EntrySize = 8;
262 } else {
263 assert(Kind.isMergeableConst16() && "unknown data width");
264 EntrySize = 16;
265 }
266 }
267
Rafael Espindola9075f772015-02-20 23:28:28 +0000268 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000269 if (const Comdat *C = getELFComdat(GV)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000270 Flags |= ELF::SHF_GROUP;
271 Group = C->getName();
272 }
273
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000274 bool UniqueSectionNames = TM.getUniqueSectionNames();
275 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000276 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000277 // We also need alignment here.
278 // FIXME: this is getting the alignment of the character, not the
279 // alignment of the global!
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000280 unsigned Align = GV->getParent()->getDataLayout().getPreferredAlignment(
281 cast<GlobalVariable>(GV));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000282
Rafael Espindolaba31e272015-01-29 17:33:21 +0000283 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000284 Name = SizeSpec + utostr(Align);
285 } else if (Kind.isMergeableConst()) {
286 Name = ".rodata.cst";
287 Name += utostr(EntrySize);
288 } else {
289 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000290 }
291
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000292 if (EmitUniqueSection && UniqueSectionNames) {
293 Name.push_back('.');
294 TM.getNameWithPrefix(Name, GV, Mang, true);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000295 }
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000296 unsigned UniqueID = ~0;
297 if (EmitUniqueSection && !UniqueSectionNames) {
298 UniqueID = *NextUniqueID;
299 (*NextUniqueID)++;
300 }
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000301 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000302 EntrySize, Group, UniqueID);
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000303}
304
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000305MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000306 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
307 const TargetMachine &TM) const {
308 unsigned Flags = getELFSectionFlags(Kind);
309
310 // If we have -ffunction-section or -fdata-section then we should emit the
311 // global value to a uniqued section specifically for it.
312 bool EmitUniqueSection = false;
313 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
314 if (Kind.isText())
315 EmitUniqueSection = TM.getFunctionSections();
316 else
317 EmitUniqueSection = TM.getDataSections();
318 }
319 EmitUniqueSection |= GV->hasComdat();
320
321 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000322 EmitUniqueSection, Flags, &NextUniqueID);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000323}
324
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000325MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
Rafael Espindola29786d42015-02-12 17:16:46 +0000326 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
327 // If the function can be removed, produce a unique section so that
328 // the table doesn't prevent the removal.
329 const Comdat *C = F.getComdat();
330 bool EmitUniqueSection = TM.getFunctionSections() || C;
331 if (!EmitUniqueSection)
332 return ReadOnlySection;
333
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000334 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000335 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
336 &NextUniqueID);
Rafael Espindola29786d42015-02-12 17:16:46 +0000337}
338
Rafael Espindoladf195192015-02-17 23:34:51 +0000339bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
340 bool UsesLabelDifference, const Function &F) const {
341 // We can always create relative relocations, so use another section
342 // that can be marked non-executable.
343 return false;
344}
345
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000346/// Given a mergeable constant with the specified size and relocation
347/// information, return a section that it should be placed in.
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000348MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
349 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000350 if (Kind.isMergeableConst4() && MergeableConst4Section)
351 return MergeableConst4Section;
352 if (Kind.isMergeableConst8() && MergeableConst8Section)
353 return MergeableConst8Section;
354 if (Kind.isMergeableConst16() && MergeableConst16Section)
355 return MergeableConst16Section;
356 if (Kind.isReadOnly())
357 return ReadOnlySection;
358
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000359 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
360 return DataRelROSection;
361}
362
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000363static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
364 bool IsCtor, unsigned Priority,
365 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000366 std::string Name;
367 unsigned Type;
368 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000369 StringRef COMDAT = KeySym ? KeySym->getName() : "";
370
371 if (KeySym)
372 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000373
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000374 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000375 if (IsCtor) {
376 Type = ELF::SHT_INIT_ARRAY;
377 Name = ".init_array";
378 } else {
379 Type = ELF::SHT_FINI_ARRAY;
380 Name = ".fini_array";
381 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000382 if (Priority != 65535) {
383 Name += '.';
384 Name += utostr(Priority);
385 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000386 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000387 // The default scheme is .ctor / .dtor, so we have to invert the priority
388 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000389 if (IsCtor)
390 Name = ".ctors";
391 else
392 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000393 if (Priority != 65535) {
394 Name += '.';
395 Name += utostr(65535 - Priority);
396 }
397 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000398 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000399
Rafael Espindolaba31e272015-01-29 17:33:21 +0000400 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000401}
402
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000403MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000404 unsigned Priority, const MCSymbol *KeySym) const {
405 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
406 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000407}
408
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000409MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000410 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000411 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
412 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000413}
414
415void
416TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
417 UseInitArray = UseInitArray_;
418 if (!UseInitArray)
419 return;
420
Rafael Espindolaba31e272015-01-29 17:33:21 +0000421 StaticCtorSection = getContext().getELFSection(
422 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
423 StaticDtorSection = getContext().getELFSection(
424 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000425}
426
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000427//===----------------------------------------------------------------------===//
428// MachO
429//===----------------------------------------------------------------------===//
430
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000431TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
432 : TargetLoweringObjectFile() {
433 SupportIndirectSymViaGOTPCRel = true;
434}
435
Daniel Dunbar95856122013-01-18 19:37:00 +0000436/// emitModuleFlags - Perform code emission for module flags.
Bill Wendling06df7722012-02-14 21:28:13 +0000437void TargetLoweringObjectFileMachO::
Bill Wendling734909a2012-02-15 22:36:15 +0000438emitModuleFlags(MCStreamer &Streamer,
439 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000440 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000441 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000442 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000443 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000444 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000445
Bill Wendling734909a2012-02-15 22:36:15 +0000446 for (ArrayRef<Module::ModuleFlagEntry>::iterator
447 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
448 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendling06df7722012-02-14 21:28:13 +0000449
450 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000451 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000452 continue;
453
Bill Wendling734909a2012-02-15 22:36:15 +0000454 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000455 Metadata *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000456
Daniel Dunbar95856122013-01-18 19:37:00 +0000457 if (Key == "Objective-C Image Info Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000458 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000459 } else if (Key == "Objective-C Garbage Collection" ||
460 Key == "Objective-C GC Only" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000461 Key == "Objective-C Is Simulated" ||
462 Key == "Objective-C Image Swift Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000463 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000464 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000465 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000466 } else if (Key == "Linker Options") {
467 LinkerOptions = cast<MDNode>(Val);
468 }
469 }
470
471 // Emit the linker options if present.
472 if (LinkerOptions) {
473 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
474 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
475 SmallVector<std::string, 4> StrOptions;
476
477 // Convert to strings.
478 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
479 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
480 StrOptions.push_back(MDOption->getString());
481 }
482
483 Streamer.EmitLinkerOptions(StrOptions);
484 }
Bill Wendling06df7722012-02-14 21:28:13 +0000485 }
486
Bill Wendling734909a2012-02-15 22:36:15 +0000487 // The section is mandatory. If we don't have it, then we don't have GC info.
488 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000489
Bill Wendling734909a2012-02-15 22:36:15 +0000490 StringRef Segment, Section;
491 unsigned TAA = 0, StubSize = 0;
492 bool TAAParsed;
493 std::string ErrorCode =
494 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
495 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000496 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000497 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000498 report_fatal_error("Invalid section specifier '" + Section + "': " +
499 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000500
Bill Wendling734909a2012-02-15 22:36:15 +0000501 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000502 MCSectionMachO *S = getContext().getMachOSection(
Rafael Espindola449711c2015-11-18 06:02:15 +0000503 Segment, Section, TAA, StubSize, SectionKind::getData());
Bill Wendling734909a2012-02-15 22:36:15 +0000504 Streamer.SwitchSection(S);
505 Streamer.EmitLabel(getContext().
Jim Grosbach6f482002015-05-18 18:43:14 +0000506 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000507 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000508 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000509 Streamer.AddBlankLine();
510}
511
David Majnemerdad0a642014-06-27 18:19:56 +0000512static void checkMachOComdat(const GlobalValue *GV) {
513 const Comdat *C = GV->getComdat();
514 if (!C)
515 return;
516
517 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
518 "' cannot be lowered.");
519}
520
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000521MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000522 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
523 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000524 // Parse the section specifier and create it if valid.
525 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000526 unsigned TAA = 0, StubSize = 0;
527 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000528
529 checkMachOComdat(GV);
530
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000531 std::string ErrorCode =
532 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000533 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000534 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000535 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000536 report_fatal_error("Global variable '" + GV->getName() +
537 "' has an invalid section specifier '" +
538 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000539 }
540
541 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000542 MCSectionMachO *S =
543 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000544
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000545 // If TAA wasn't set by ParseSectionSpecifier() above,
546 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000547 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000548 TAA = S->getTypeAndAttributes();
549
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000550 // Okay, now that we got the section, verify that the TAA & StubSize agree.
551 // If the user declared multiple globals with different section flags, we need
552 // to reject it here.
553 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000554 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000555 report_fatal_error("Global variable '" + GV->getName() +
556 "' section type or attributes does not match previous"
557 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000558 }
559
560 return S;
561}
562
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000563MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
564 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
565 const TargetMachine &TM) const {
David Majnemerdad0a642014-06-27 18:19:56 +0000566 checkMachOComdat(GV);
Bill Wendling25b61db2013-11-17 10:53:13 +0000567
568 // Handle thread local data.
569 if (Kind.isThreadBSS()) return TLSBSSSection;
570 if (Kind.isThreadData()) return TLSDataSection;
571
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000572 if (Kind.isText())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000573 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
574
575 // If this is weak/linkonce, put this in a coalescable section, either in text
576 // or data depending on if it is writable.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000577 if (GV->isWeakForLinker()) {
578 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000579 return ConstTextCoalSection;
580 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000581 }
582
583 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000584 if (Kind.isMergeable1ByteCString() &&
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000585 GV->getParent()->getDataLayout().getPreferredAlignment(
586 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000587 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000588
Chris Lattneref2f8042010-03-07 04:28:09 +0000589 // Do not put 16-bit arrays in the UString section if they have an
590 // externally visible label, this runs into issues with certain linker
591 // versions.
592 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000593 GV->getParent()->getDataLayout().getPreferredAlignment(
594 cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000595 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000596
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000597 // With MachO only variables whose corresponding symbol starts with 'l' or
598 // 'L' can be merged, so we only try merging GVs with private linkage.
599 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000600 if (Kind.isMergeableConst4())
601 return FourByteConstantSection;
602 if (Kind.isMergeableConst8())
603 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000604 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000605 return SixteenByteConstantSection;
606 }
607
608 // Otherwise, if it is readonly, but not something we can specially optimize,
609 // just drop it in .const.
610 if (Kind.isReadOnly())
611 return ReadOnlySection;
612
613 // If this is marked const, put it into a const section. But if the dynamic
614 // linker needs to write to it, put it in the data segment.
615 if (Kind.isReadOnlyWithRel())
616 return ConstDataSection;
617
618 // Put zero initialized globals with strong external linkage in the
619 // DATA, __common section with the .zerofill directive.
620 if (Kind.isBSSExtern())
621 return DataCommonSection;
622
623 // Put zero initialized globals with local linkage in __DATA,__bss directive
624 // with the .zerofill directive (aka .lcomm).
625 if (Kind.isBSSLocal())
626 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000627
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000628 // Otherwise, just drop the variable in the normal data section.
629 return DataSection;
630}
631
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000632MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
633 const DataLayout &DL, SectionKind Kind, const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000634 // If this constant requires a relocation, we have to put it in the data
635 // segment, not in the text segment.
Rafael Espindola449711c2015-11-18 06:02:15 +0000636 if (Kind.isData() || Kind.isReadOnlyWithRel())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000637 return ConstDataSection;
638
639 if (Kind.isMergeableConst4())
640 return FourByteConstantSection;
641 if (Kind.isMergeableConst8())
642 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000643 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000644 return SixteenByteConstantSection;
645 return ReadOnlySection; // .const
646}
647
Rafael Espindola15b26692014-02-09 14:50:44 +0000648const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
649 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000650 const TargetMachine &TM, MachineModuleInfo *MMI,
651 MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000652 // The mach-o version of this method defaults to returning a stub reference.
653
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000654 if (Encoding & DW_EH_PE_indirect) {
655 MachineModuleInfoMachO &MachOMMI =
656 MMI->getObjFileInfo<MachineModuleInfoMachO>();
657
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000658 MCSymbol *SSym =
659 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000660
661 // Add information about the stub reference to MachOMMI so that the stub
662 // gets emitted by the asmprinter.
Bill Wendling57e3aaa2011-10-24 23:05:43 +0000663 MachineModuleInfoImpl::StubValueTy &StubSym =
664 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
665 MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000666 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000667 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000668 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000669 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000670
671 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000672 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Anton Korobeynikove42af362012-11-14 01:47:00 +0000673 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000674 }
675
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000676 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
677 TM, MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000678}
679
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000680MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
681 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
682 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000683 // The mach-o version of this method defaults to returning a stub reference.
684 MachineModuleInfoMachO &MachOMMI =
685 MMI->getObjFileInfo<MachineModuleInfoMachO>();
686
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000687 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000688
689 // Add information about the stub reference to MachOMMI so that the stub
690 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000691 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000692 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000693 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola08704342011-04-27 23:08:15 +0000694 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
695 }
696
697 return SSym;
698}
699
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000700const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
701 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
702 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
Benjamin Kramerdf005cb2015-08-08 18:27:36 +0000703 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000704 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
705 // through a non_lazy_ptr stub instead. One advantage is that it allows the
706 // computation of deltas to final external symbols. Example:
707 //
708 // _extgotequiv:
709 // .long _extfoo
710 //
711 // _delta:
712 // .long _extgotequiv-_delta
713 //
714 // is transformed to:
715 //
716 // _delta:
717 // .long L_extfoo$non_lazy_ptr-(_delta+0)
718 //
719 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
720 // L_extfoo$non_lazy_ptr:
721 // .indirect_symbol _extfoo
722 // .long 0
723 //
724 MachineModuleInfoMachO &MachOMMI =
725 MMI->getObjFileInfo<MachineModuleInfoMachO>();
726 MCContext &Ctx = getContext();
727
728 // The offset must consider the original displacement from the base symbol
729 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
730 Offset = -MV.getConstant();
731 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
732
733 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
734 // non_lazy_ptr stubs.
735 SmallString<128> Name;
736 StringRef Suffix = "$non_lazy_ptr";
Mehdi Amini5c0fa582015-07-16 06:04:17 +0000737 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000738 Name += Sym->getName();
739 Name += Suffix;
Jim Grosbach6f482002015-05-18 18:43:14 +0000740 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000741
742 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
743 if (!StubSym.getPointer())
744 StubSym = MachineModuleInfoImpl::
745 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
746
747 const MCExpr *BSymExpr =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000748 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000749 const MCExpr *LHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000750 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000751
752 if (!Offset)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000753 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000754
755 const MCExpr *RHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000756 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
757 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000758}
759
Peter Collingbourne94d77862015-11-03 23:40:03 +0000760static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
761 const MCSection &Section) {
762 if (!AsmInfo.isSectionAtomizableBySymbols(Section))
763 return true;
764
765 // If it is not dead stripped, it is safe to use private labels.
766 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
767 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
768 return true;
769
770 return false;
771}
772
773void TargetLoweringObjectFileMachO::getNameWithPrefix(
774 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
775 const TargetMachine &TM) const {
776 SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GV, TM);
777 const MCSection *TheSection = SectionForGlobal(GV, GVKind, Mang, TM);
778 bool CannotUsePrivateLabel =
779 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
780 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
781}
782
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000783//===----------------------------------------------------------------------===//
784// COFF
785//===----------------------------------------------------------------------===//
786
Chris Lattner87cffa92010-05-07 17:17:41 +0000787static unsigned
788getCOFFSectionFlags(SectionKind K) {
789 unsigned Flags = 0;
790
Anton Korobeynikove4152302010-07-06 15:24:56 +0000791 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000792 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000793 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000794 else if (K.isText())
795 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000796 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000797 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar329d2022010-07-01 20:07:24 +0000798 COFF::IMAGE_SCN_CNT_CODE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000799 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000800 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000801 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
802 COFF::IMAGE_SCN_MEM_READ |
803 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000804 else if (K.isThreadLocal())
805 Flags |=
806 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
807 COFF::IMAGE_SCN_MEM_READ |
808 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000809 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000810 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000811 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
812 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000813 else if (K.isWriteable())
814 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000815 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
816 COFF::IMAGE_SCN_MEM_READ |
817 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000818
819 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000820}
821
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000822static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000823 const Comdat *C = GV->getComdat();
824 assert(C && "expected GV to have a Comdat!");
825
826 StringRef ComdatGVName = C->getName();
827 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
828 if (!ComdatGV)
829 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
830 "' does not exist.");
831
832 if (ComdatGV->getComdat() != C)
833 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000834 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000835
836 return ComdatGV;
837}
838
839static int getSelectionForCOFF(const GlobalValue *GV) {
840 if (const Comdat *C = GV->getComdat()) {
841 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
842 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
843 ComdatKey = GA->getBaseObject();
844 if (ComdatKey == GV) {
845 switch (C->getSelectionKind()) {
846 case Comdat::Any:
847 return COFF::IMAGE_COMDAT_SELECT_ANY;
848 case Comdat::ExactMatch:
849 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
850 case Comdat::Largest:
851 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
852 case Comdat::NoDuplicates:
853 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
854 case Comdat::SameSize:
855 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
856 }
857 } else {
858 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
859 }
David Majnemerdad0a642014-06-27 18:19:56 +0000860 }
861 return 0;
862}
863
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000864MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000865 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
866 const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000867 int Selection = 0;
868 unsigned Characteristics = getCOFFSectionFlags(Kind);
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000869 StringRef Name = GV->getSection();
870 StringRef COMDATSymName = "";
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000871 if (GV->hasComdat()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000872 Selection = getSelectionForCOFF(GV);
873 const GlobalValue *ComdatGV;
874 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
875 ComdatGV = getComdatGVForCOFF(GV);
876 else
877 ComdatGV = GV;
878
879 if (!ComdatGV->hasPrivateLinkage()) {
880 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
881 COMDATSymName = Sym->getName();
882 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
883 } else {
884 Selection = 0;
885 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000886 }
887 return getContext().getCOFFSection(Name,
888 Characteristics,
Nico Riecka37acf72013-07-06 12:13:10 +0000889 Kind,
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000890 COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000891 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000892}
893
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000894static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000895 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000896 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +0000897 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000898 return ".bss";
899 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +0000900 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +0000901 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
902 return ".rdata";
903 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000904}
905
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000906MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
907 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
908 const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +0000909 // If we have -ffunction-sections then we should emit the global value to a
910 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +0000911 bool EmitUniquedSection;
912 if (Kind.isText())
913 EmitUniquedSection = TM.getFunctionSections();
914 else
915 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000916
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000917 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000918 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner02844932010-05-07 21:49:09 +0000919 unsigned Characteristics = getCOFFSectionFlags(Kind);
920
Daniel Dunbar329d2022010-07-01 20:07:24 +0000921 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
David Majnemerdad0a642014-06-27 18:19:56 +0000922 int Selection = getSelectionForCOFF(GV);
923 if (!Selection)
924 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
925 const GlobalValue *ComdatGV;
926 if (GV->hasComdat())
927 ComdatGV = getComdatGVForCOFF(GV);
928 else
929 ComdatGV = GV;
930
931 if (!ComdatGV->hasPrivateLinkage()) {
932 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
933 StringRef COMDATSymName = Sym->getName();
934 return getContext().getCOFFSection(Name, Characteristics, Kind,
935 COMDATSymName, Selection);
David Majnemer7db449a2015-03-17 23:54:51 +0000936 } else {
937 SmallString<256> TmpData;
Peter Collingbourne94d77862015-11-03 23:40:03 +0000938 Mang.getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true);
David Majnemer7db449a2015-03-17 23:54:51 +0000939 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
940 Selection);
David Majnemerdad0a642014-06-27 18:19:56 +0000941 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000942 }
943
944 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +0000945 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000946
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000947 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +0000948 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000949
David Majnemer597be2d2014-09-22 20:39:23 +0000950 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +0000951 return ReadOnlySection;
952
David Majnemera9bdb322014-04-08 22:33:40 +0000953 // Note: we claim that common symbols are put in BSSSection, but they are
954 // really emitted with the magic .comm directive, which creates a symbol table
955 // entry but not a section.
956 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +0000957 return BSSSection;
958
959 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000960}
961
David Majnemer7db449a2015-03-17 23:54:51 +0000962void TargetLoweringObjectFileCOFF::getNameWithPrefix(
Peter Collingbourne94d77862015-11-03 23:40:03 +0000963 SmallVectorImpl<char> &OutName, const GlobalValue *GV, Mangler &Mang,
964 const TargetMachine &TM) const {
965 bool CannotUsePrivateLabel = false;
David Majnemer7db449a2015-03-17 23:54:51 +0000966 if (GV->hasPrivateLinkage() &&
967 ((isa<Function>(GV) && TM.getFunctionSections()) ||
968 (isa<GlobalVariable>(GV) && TM.getDataSections())))
969 CannotUsePrivateLabel = true;
970
971 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
972}
973
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000974MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
Rafael Espindolaab447e42015-03-11 19:58:37 +0000975 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
976 // If the function can be removed, produce a unique section so that
977 // the table doesn't prevent the removal.
978 const Comdat *C = F.getComdat();
979 bool EmitUniqueSection = TM.getFunctionSections() || C;
980 if (!EmitUniqueSection)
981 return ReadOnlySection;
982
983 // FIXME: we should produce a symbol for F instead.
984 if (F.hasPrivateLinkage())
985 return ReadOnlySection;
986
987 MCSymbol *Sym = TM.getSymbol(&F, Mang);
988 StringRef COMDATSymName = Sym->getName();
989
990 SectionKind Kind = SectionKind::getReadOnly();
991 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
992 unsigned Characteristics = getCOFFSectionFlags(Kind);
993 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
994
995 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
996 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
997}
998
Reid Klecknerd973ca32013-04-25 19:34:41 +0000999void TargetLoweringObjectFileCOFF::
1000emitModuleFlags(MCStreamer &Streamer,
1001 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +00001002 Mangler &Mang, const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +00001003 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001004
1005 // Look for the "Linker Options" flag, since it's the only one we support.
1006 for (ArrayRef<Module::ModuleFlagEntry>::iterator
1007 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1008 const Module::ModuleFlagEntry &MFE = *i;
1009 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001010 Metadata *Val = MFE.Val;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001011 if (Key == "Linker Options") {
1012 LinkerOptions = cast<MDNode>(Val);
1013 break;
1014 }
1015 }
1016 if (!LinkerOptions)
1017 return;
1018
1019 // Emit the linker options to the linker .drectve section. According to the
1020 // spec, this section is a space-separated string containing flags for linker.
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001021 MCSection *Sec = getDrectveSection();
Reid Klecknerd973ca32013-04-25 19:34:41 +00001022 Streamer.SwitchSection(Sec);
1023 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1024 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1025 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1026 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
Reid Klecknerd973ca32013-04-25 19:34:41 +00001027 // Lead with a space for consistency with our dllexport implementation.
Michael Kupersteinfc3e6262015-02-16 11:57:17 +00001028 std::string Directive(" ");
1029 Directive.append(MDOption->getString());
1030 Streamer.EmitBytes(Directive);
Reid Klecknerd973ca32013-04-25 19:34:41 +00001031 }
1032 }
1033}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001034
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001035MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001036 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001037 return getContext().getAssociativeCOFFSection(
1038 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001039}
1040
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001041MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001042 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001043 return getContext().getAssociativeCOFFSection(
1044 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001045}
Peter Collingbourneaef36592015-06-29 22:04:09 +00001046
1047void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
1048 raw_ostream &OS, const GlobalValue *GV, const Mangler &Mang) const {
1049 if (!GV->hasDLLExportStorageClass() || GV->isDeclaration())
1050 return;
1051
1052 const Triple &TT = getTargetTriple();
1053
1054 if (TT.isKnownWindowsMSVCEnvironment())
1055 OS << " /EXPORT:";
1056 else
1057 OS << " -export:";
1058
1059 if (TT.isWindowsGNUEnvironment() || TT.isWindowsCygwinEnvironment()) {
1060 std::string Flag;
1061 raw_string_ostream FlagOS(Flag);
1062 Mang.getNameWithPrefix(FlagOS, GV, false);
1063 FlagOS.flush();
Mehdi Amini5c0fa582015-07-16 06:04:17 +00001064 if (Flag[0] == GV->getParent()->getDataLayout().getGlobalPrefix())
Peter Collingbourneaef36592015-06-29 22:04:09 +00001065 OS << Flag.substr(1);
1066 else
1067 OS << Flag;
1068 } else {
1069 Mang.getNameWithPrefix(OS, GV, false);
1070 }
1071
1072 if (!GV->getValueType()->isFunctionTy()) {
1073 if (TT.isKnownWindowsMSVCEnvironment())
1074 OS << ",DATA";
1075 else
1076 OS << ",data";
1077 }
1078}