blob: d7b043dac0132adf5c15e5c8f1102f7729a2363f [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
61void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
62 const TargetMachine &TM,
Rafael Espindola08704342011-04-27 23:08:15 +000063 const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000064 SmallString<64> NameData("DW.ref.");
65 NameData += Sym->getName();
Rafael Espindolaa8695762015-06-02 00:25:12 +000066 MCSymbolELF *Label =
67 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
Rafael Espindola39897762011-04-27 21:29:52 +000068 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
69 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000070 StringRef Prefix = ".data.";
71 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
Rafael Espindola39897762011-04-27 21:29:52 +000072 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
Rafael Espindola0709a7b2015-05-21 19:20:38 +000073 MCSection *Sec = getContext().getELFSection(NameData, ELF::SHT_PROGBITS,
74 Flags, 0, Label->getName());
Eric Christopher8b770652015-01-26 19:03:15 +000075 unsigned Size = TM.getDataLayout()->getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +000076 Streamer.SwitchSection(Sec);
Eric Christopher8b770652015-01-26 19:03:15 +000077 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +000078 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
Jim Grosbach13760bd2015-05-30 01:25:56 +000079 const MCExpr *E = MCConstantExpr::create(Size, getContext());
Rafael Espindolaa8695762015-06-02 00:25:12 +000080 Streamer.emitELFSize(Label, E);
Rafael Espindola39897762011-04-27 21:29:52 +000081 Streamer.EmitLabel(Label);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000082
Rafael Espindola39897762011-04-27 21:29:52 +000083 Streamer.EmitSymbolValue(Sym, Size);
Rafael Espindolaa83b1772011-04-16 03:51:21 +000084}
85
Rafael Espindola15b26692014-02-09 14:50:44 +000086const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
87 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +000088 const TargetMachine &TM, MachineModuleInfo *MMI,
89 MCStreamer &Streamer) const {
Anton Korobeynikove42af362012-11-14 01:47:00 +000090
91 if (Encoding & dwarf::DW_EH_PE_indirect) {
92 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
93
Rafael Espindoladaeafb42014-02-19 17:23:20 +000094 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
Anton Korobeynikove42af362012-11-14 01:47:00 +000095
96 // Add information about the stub reference to ELFMMI so that the stub
97 // gets emitted by the asmprinter.
Anton Korobeynikove42af362012-11-14 01:47:00 +000098 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +000099 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000100 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000101 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
102 }
103
104 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000105 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Anton Korobeynikove42af362012-11-14 01:47:00 +0000106 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
107 }
108
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000109 return TargetLoweringObjectFile::
110 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
Anton Korobeynikove42af362012-11-14 01:47:00 +0000111}
112
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000113static SectionKind
114getELFKindForNamedSection(StringRef Name, SectionKind K) {
Rafael Espindola0d018b12011-05-24 03:10:31 +0000115 // N.B.: The defaults used in here are no the same ones used in MC.
116 // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
117 // both gas and MC will produce a section with no flags. Given
Bill Wendlingd1634052012-07-19 00:04:14 +0000118 // section(".eh_frame") gcc will produce:
119 //
120 // .section .eh_frame,"a",@progbits
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000121 if (Name.empty() || Name[0] != '.') return K;
122
123 // Some lame default implementation based on some magic section names.
124 if (Name == ".bss" ||
125 Name.startswith(".bss.") ||
126 Name.startswith(".gnu.linkonce.b.") ||
127 Name.startswith(".llvm.linkonce.b.") ||
128 Name == ".sbss" ||
129 Name.startswith(".sbss.") ||
130 Name.startswith(".gnu.linkonce.sb.") ||
131 Name.startswith(".llvm.linkonce.sb."))
132 return SectionKind::getBSS();
133
134 if (Name == ".tdata" ||
135 Name.startswith(".tdata.") ||
136 Name.startswith(".gnu.linkonce.td.") ||
137 Name.startswith(".llvm.linkonce.td."))
138 return SectionKind::getThreadData();
139
140 if (Name == ".tbss" ||
141 Name.startswith(".tbss.") ||
142 Name.startswith(".gnu.linkonce.tb.") ||
143 Name.startswith(".llvm.linkonce.tb."))
144 return SectionKind::getThreadBSS();
145
146 return K;
147}
148
149
150static unsigned getELFSectionType(StringRef Name, SectionKind K) {
151
152 if (Name == ".init_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000153 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000154
155 if (Name == ".fini_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000156 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000157
158 if (Name == ".preinit_array")
Rafael Espindolaaea49582011-01-23 04:28:49 +0000159 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000160
161 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolaaea49582011-01-23 04:28:49 +0000162 return ELF::SHT_NOBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000163
Rafael Espindolaaea49582011-01-23 04:28:49 +0000164 return ELF::SHT_PROGBITS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000165}
166
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000167static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000168 unsigned Flags = 0;
169
170 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000171 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000172
173 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000174 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000175
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000176 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000177 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000178
179 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000180 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000181
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000182 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000183 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000184
185 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000186 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000187
188 return Flags;
189}
190
David Majnemerdad0a642014-06-27 18:19:56 +0000191static const Comdat *getELFComdat(const GlobalValue *GV) {
192 const Comdat *C = GV->getComdat();
193 if (!C)
194 return nullptr;
195
196 if (C->getSelectionKind() != Comdat::Any)
197 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
198 C->getName() + "' cannot be lowered.");
199
200 return C;
201}
202
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000203MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000204 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
205 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000206 StringRef SectionName = GV->getSection();
207
208 // Infer section flags from the section name if we can.
209 Kind = getELFKindForNamedSection(SectionName, Kind);
210
David Majnemerdad0a642014-06-27 18:19:56 +0000211 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000212 unsigned Flags = getELFSectionFlags(Kind);
David Majnemerdad0a642014-06-27 18:19:56 +0000213 if (const Comdat *C = getELFComdat(GV)) {
214 Group = C->getName();
215 Flags |= ELF::SHF_GROUP;
216 }
Chris Lattner80c34592010-04-08 21:34:17 +0000217 return getContext().getELFSection(SectionName,
David Majnemerdad0a642014-06-27 18:19:56 +0000218 getELFSectionType(SectionName, Kind), Flags,
Rafael Espindolaba31e272015-01-29 17:33:21 +0000219 /*EntrySize=*/0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000220}
221
Rafael Espindola25d2c202015-02-11 14:44:17 +0000222/// Return the section prefix name used by options FunctionsSections and
223/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000224static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000225 if (Kind.isText())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000226 return ".text";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000227 if (Kind.isReadOnly())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000228 return ".rodata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000229 if (Kind.isBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000230 return ".bss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000231 if (Kind.isThreadData())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000232 return ".tdata";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000233 if (Kind.isThreadBSS())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000234 return ".tbss";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000235 if (Kind.isDataNoRel())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000236 return ".data";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000237 if (Kind.isDataRelLocal())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000238 return ".data.rel.local";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000239 if (Kind.isDataRel())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000240 return ".data.rel";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000241 if (Kind.isReadOnlyWithRelLocal())
Rafael Espindola68fa2492015-02-17 20:48:01 +0000242 return ".data.rel.ro.local";
Chris Lattner5b212a32010-04-13 00:36:43 +0000243 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Rafael Espindola68fa2492015-02-17 20:48:01 +0000244 return ".data.rel.ro";
Chris Lattner5b212a32010-04-13 00:36:43 +0000245}
246
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000247static MCSectionELF *
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000248selectELFSectionForGlobal(MCContext &Ctx, const GlobalValue *GV,
249 SectionKind Kind, Mangler &Mang,
250 const TargetMachine &TM, bool EmitUniqueSection,
251 unsigned Flags, unsigned *NextUniqueID) {
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000252 unsigned EntrySize = 0;
253 if (Kind.isMergeableCString()) {
254 if (Kind.isMergeable2ByteCString()) {
255 EntrySize = 2;
256 } else if (Kind.isMergeable4ByteCString()) {
257 EntrySize = 4;
258 } else {
259 EntrySize = 1;
260 assert(Kind.isMergeable1ByteCString() && "unknown string width");
261 }
262 } else if (Kind.isMergeableConst()) {
263 if (Kind.isMergeableConst4()) {
264 EntrySize = 4;
265 } else if (Kind.isMergeableConst8()) {
266 EntrySize = 8;
267 } else {
268 assert(Kind.isMergeableConst16() && "unknown data width");
269 EntrySize = 16;
270 }
271 }
272
Rafael Espindola9075f772015-02-20 23:28:28 +0000273 StringRef Group = "";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000274 if (const Comdat *C = getELFComdat(GV)) {
Rafael Espindola9075f772015-02-20 23:28:28 +0000275 Flags |= ELF::SHF_GROUP;
276 Group = C->getName();
277 }
278
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000279 bool UniqueSectionNames = TM.getUniqueSectionNames();
280 SmallString<128> Name;
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000281 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000282 // We also need alignment here.
283 // FIXME: this is getting the alignment of the character, not the
284 // alignment of the global!
285 unsigned Align =
Eric Christopher8b770652015-01-26 19:03:15 +0000286 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000287
Rafael Espindolaba31e272015-01-29 17:33:21 +0000288 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000289 Name = SizeSpec + utostr(Align);
290 } else if (Kind.isMergeableConst()) {
291 Name = ".rodata.cst";
292 Name += utostr(EntrySize);
293 } else {
294 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000295 }
296
Rafael Espindola8bc9ccc2015-02-25 00:52:15 +0000297 if (EmitUniqueSection && UniqueSectionNames) {
298 Name.push_back('.');
299 TM.getNameWithPrefix(Name, GV, Mang, true);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000300 }
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000301 unsigned UniqueID = ~0;
302 if (EmitUniqueSection && !UniqueSectionNames) {
303 UniqueID = *NextUniqueID;
304 (*NextUniqueID)++;
305 }
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000306 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000307 EntrySize, Group, UniqueID);
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000308}
309
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000310MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000311 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
312 const TargetMachine &TM) const {
313 unsigned Flags = getELFSectionFlags(Kind);
314
315 // If we have -ffunction-section or -fdata-section then we should emit the
316 // global value to a uniqued section specifically for it.
317 bool EmitUniqueSection = false;
318 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
319 if (Kind.isText())
320 EmitUniqueSection = TM.getFunctionSections();
321 else
322 EmitUniqueSection = TM.getDataSections();
323 }
324 EmitUniqueSection |= GV->hasComdat();
325
326 return selectELFSectionForGlobal(getContext(), GV, Kind, Mang, TM,
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000327 EmitUniqueSection, Flags, &NextUniqueID);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000328}
329
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000330MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
Rafael Espindola29786d42015-02-12 17:16:46 +0000331 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
332 // If the function can be removed, produce a unique section so that
333 // the table doesn't prevent the removal.
334 const Comdat *C = F.getComdat();
335 bool EmitUniqueSection = TM.getFunctionSections() || C;
336 if (!EmitUniqueSection)
337 return ReadOnlySection;
338
Rafael Espindola4491d0d2015-02-26 23:55:11 +0000339 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
Rafael Espindola8ca44f02015-04-04 18:02:01 +0000340 Mang, TM, EmitUniqueSection, ELF::SHF_ALLOC,
341 &NextUniqueID);
Rafael Espindola29786d42015-02-12 17:16:46 +0000342}
343
Rafael Espindoladf195192015-02-17 23:34:51 +0000344bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
345 bool UsesLabelDifference, const Function &F) const {
346 // We can always create relative relocations, so use another section
347 // that can be marked non-executable.
348 return false;
349}
350
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000351/// Given a mergeable constant with the specified size and relocation
352/// information, return a section that it should be placed in.
353MCSection *
David Majnemer8bce66b2014-07-14 22:57:27 +0000354TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
355 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000356 if (Kind.isMergeableConst4() && MergeableConst4Section)
357 return MergeableConst4Section;
358 if (Kind.isMergeableConst8() && MergeableConst8Section)
359 return MergeableConst8Section;
360 if (Kind.isMergeableConst16() && MergeableConst16Section)
361 return MergeableConst16Section;
362 if (Kind.isReadOnly())
363 return ReadOnlySection;
364
365 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
366 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
367 return DataRelROSection;
368}
369
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000370static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
371 bool IsCtor, unsigned Priority,
372 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000373 std::string Name;
374 unsigned Type;
375 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000376 StringRef COMDAT = KeySym ? KeySym->getName() : "";
377
378 if (KeySym)
379 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000380
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000381 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000382 if (IsCtor) {
383 Type = ELF::SHT_INIT_ARRAY;
384 Name = ".init_array";
385 } else {
386 Type = ELF::SHT_FINI_ARRAY;
387 Name = ".fini_array";
388 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000389 if (Priority != 65535) {
390 Name += '.';
391 Name += utostr(Priority);
392 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000393 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000394 // The default scheme is .ctor / .dtor, so we have to invert the priority
395 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000396 if (IsCtor)
397 Name = ".ctors";
398 else
399 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000400 if (Priority != 65535) {
401 Name += '.';
402 Name += utostr(65535 - Priority);
403 }
404 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000405 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000406
Rafael Espindolaba31e272015-01-29 17:33:21 +0000407 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000408}
409
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000410MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000411 unsigned Priority, const MCSymbol *KeySym) const {
412 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
413 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000414}
415
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000416MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000417 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000418 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
419 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000420}
421
422void
423TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
424 UseInitArray = UseInitArray_;
425 if (!UseInitArray)
426 return;
427
Rafael Espindolaba31e272015-01-29 17:33:21 +0000428 StaticCtorSection = getContext().getELFSection(
429 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
430 StaticDtorSection = getContext().getELFSection(
431 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000432}
433
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000434//===----------------------------------------------------------------------===//
435// MachO
436//===----------------------------------------------------------------------===//
437
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000438TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
439 : TargetLoweringObjectFile() {
440 SupportIndirectSymViaGOTPCRel = true;
441}
442
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000443/// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
444/// option string. Returns StringRef() if the option does not specify a library.
445StringRef TargetLoweringObjectFileMachO::
446getDepLibFromLinkerOpt(StringRef LinkerOption) const {
447 const char *LibCmd = "-l";
448 if (LinkerOption.startswith(LibCmd))
449 return LinkerOption.substr(strlen(LibCmd));
450 return StringRef();
451}
452
Daniel Dunbar95856122013-01-18 19:37:00 +0000453/// emitModuleFlags - Perform code emission for module flags.
Bill Wendling06df7722012-02-14 21:28:13 +0000454void TargetLoweringObjectFileMachO::
Bill Wendling734909a2012-02-15 22:36:15 +0000455emitModuleFlags(MCStreamer &Streamer,
456 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000457 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000458 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000459 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000460 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000461 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000462
Bill Wendling734909a2012-02-15 22:36:15 +0000463 for (ArrayRef<Module::ModuleFlagEntry>::iterator
464 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
465 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendling06df7722012-02-14 21:28:13 +0000466
467 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000468 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000469 continue;
470
Bill Wendling734909a2012-02-15 22:36:15 +0000471 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000472 Metadata *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000473
Daniel Dunbar95856122013-01-18 19:37:00 +0000474 if (Key == "Objective-C Image Info Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000475 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000476 } else if (Key == "Objective-C Garbage Collection" ||
477 Key == "Objective-C GC Only" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000478 Key == "Objective-C Is Simulated" ||
479 Key == "Objective-C Image Swift Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000480 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000481 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000482 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000483 } else if (Key == "Linker Options") {
484 LinkerOptions = cast<MDNode>(Val);
485 }
486 }
487
488 // Emit the linker options if present.
489 if (LinkerOptions) {
490 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
491 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
492 SmallVector<std::string, 4> StrOptions;
493
494 // Convert to strings.
495 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
496 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
497 StrOptions.push_back(MDOption->getString());
498 }
499
500 Streamer.EmitLinkerOptions(StrOptions);
501 }
Bill Wendling06df7722012-02-14 21:28:13 +0000502 }
503
Bill Wendling734909a2012-02-15 22:36:15 +0000504 // The section is mandatory. If we don't have it, then we don't have GC info.
505 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000506
Bill Wendling734909a2012-02-15 22:36:15 +0000507 StringRef Segment, Section;
508 unsigned TAA = 0, StubSize = 0;
509 bool TAAParsed;
510 std::string ErrorCode =
511 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
512 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000513 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000514 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000515 report_fatal_error("Invalid section specifier '" + Section + "': " +
516 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000517
Bill Wendling734909a2012-02-15 22:36:15 +0000518 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000519 MCSectionMachO *S = getContext().getMachOSection(
520 Segment, Section, TAA, StubSize, SectionKind::getDataNoRel());
Bill Wendling734909a2012-02-15 22:36:15 +0000521 Streamer.SwitchSection(S);
522 Streamer.EmitLabel(getContext().
Jim Grosbach6f482002015-05-18 18:43:14 +0000523 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000524 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000525 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000526 Streamer.AddBlankLine();
527}
528
David Majnemerdad0a642014-06-27 18:19:56 +0000529static void checkMachOComdat(const GlobalValue *GV) {
530 const Comdat *C = GV->getComdat();
531 if (!C)
532 return;
533
534 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
535 "' cannot be lowered.");
536}
537
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000538MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000539 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
540 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000541 // Parse the section specifier and create it if valid.
542 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000543 unsigned TAA = 0, StubSize = 0;
544 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000545
546 checkMachOComdat(GV);
547
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000548 std::string ErrorCode =
549 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000550 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000551 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000552 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000553 report_fatal_error("Global variable '" + GV->getName() +
554 "' has an invalid section specifier '" +
555 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000556 }
557
558 // Get the section.
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000559 MCSectionMachO *S =
560 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000561
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000562 // If TAA wasn't set by ParseSectionSpecifier() above,
563 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000564 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000565 TAA = S->getTypeAndAttributes();
566
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000567 // Okay, now that we got the section, verify that the TAA & StubSize agree.
568 // If the user declared multiple globals with different section flags, we need
569 // to reject it here.
570 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000571 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000572 report_fatal_error("Global variable '" + GV->getName() +
573 "' section type or attributes does not match previous"
574 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000575 }
576
577 return S;
578}
579
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000580MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
581 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
582 const TargetMachine &TM) const {
David Majnemerdad0a642014-06-27 18:19:56 +0000583 checkMachOComdat(GV);
Bill Wendling25b61db2013-11-17 10:53:13 +0000584
585 // Handle thread local data.
586 if (Kind.isThreadBSS()) return TLSBSSSection;
587 if (Kind.isThreadData()) return TLSDataSection;
588
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000589 if (Kind.isText())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000590 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
591
592 // If this is weak/linkonce, put this in a coalescable section, either in text
593 // or data depending on if it is writable.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000594 if (GV->isWeakForLinker()) {
595 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000596 return ConstTextCoalSection;
597 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000598 }
599
600 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000601 if (Kind.isMergeable1ByteCString() &&
Eric Christopher8b770652015-01-26 19:03:15 +0000602 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000603 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000604
Chris Lattneref2f8042010-03-07 04:28:09 +0000605 // Do not put 16-bit arrays in the UString section if they have an
606 // externally visible label, this runs into issues with certain linker
607 // versions.
608 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Eric Christopher8b770652015-01-26 19:03:15 +0000609 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000610 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000611
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000612 // With MachO only variables whose corresponding symbol starts with 'l' or
613 // 'L' can be merged, so we only try merging GVs with private linkage.
614 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000615 if (Kind.isMergeableConst4())
616 return FourByteConstantSection;
617 if (Kind.isMergeableConst8())
618 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000619 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000620 return SixteenByteConstantSection;
621 }
622
623 // Otherwise, if it is readonly, but not something we can specially optimize,
624 // just drop it in .const.
625 if (Kind.isReadOnly())
626 return ReadOnlySection;
627
628 // If this is marked const, put it into a const section. But if the dynamic
629 // linker needs to write to it, put it in the data segment.
630 if (Kind.isReadOnlyWithRel())
631 return ConstDataSection;
632
633 // Put zero initialized globals with strong external linkage in the
634 // DATA, __common section with the .zerofill directive.
635 if (Kind.isBSSExtern())
636 return DataCommonSection;
637
638 // Put zero initialized globals with local linkage in __DATA,__bss directive
639 // with the .zerofill directive (aka .lcomm).
640 if (Kind.isBSSLocal())
641 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000642
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000643 // Otherwise, just drop the variable in the normal data section.
644 return DataSection;
645}
646
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000647MCSection *
David Majnemer8bce66b2014-07-14 22:57:27 +0000648TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
649 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000650 // If this constant requires a relocation, we have to put it in the data
651 // segment, not in the text segment.
652 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
653 return ConstDataSection;
654
655 if (Kind.isMergeableConst4())
656 return FourByteConstantSection;
657 if (Kind.isMergeableConst8())
658 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000659 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000660 return SixteenByteConstantSection;
661 return ReadOnlySection; // .const
662}
663
Rafael Espindola15b26692014-02-09 14:50:44 +0000664const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
665 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000666 const TargetMachine &TM, MachineModuleInfo *MMI,
667 MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000668 // The mach-o version of this method defaults to returning a stub reference.
669
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000670 if (Encoding & DW_EH_PE_indirect) {
671 MachineModuleInfoMachO &MachOMMI =
672 MMI->getObjFileInfo<MachineModuleInfoMachO>();
673
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000674 MCSymbol *SSym =
675 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000676
677 // Add information about the stub reference to MachOMMI so that the stub
678 // gets emitted by the asmprinter.
Bill Wendling57e3aaa2011-10-24 23:05:43 +0000679 MachineModuleInfoImpl::StubValueTy &StubSym =
680 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
681 MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000682 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000683 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000684 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000685 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000686
687 return TargetLoweringObjectFile::
Jim Grosbach13760bd2015-05-30 01:25:56 +0000688 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Anton Korobeynikove42af362012-11-14 01:47:00 +0000689 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000690 }
691
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000692 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
693 TM, MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000694}
695
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000696MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
697 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
698 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000699 // The mach-o version of this method defaults to returning a stub reference.
700 MachineModuleInfoMachO &MachOMMI =
701 MMI->getObjFileInfo<MachineModuleInfoMachO>();
702
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000703 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000704
705 // Add information about the stub reference to MachOMMI so that the stub
706 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000707 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000708 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000709 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola08704342011-04-27 23:08:15 +0000710 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
711 }
712
713 return SSym;
714}
715
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000716const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
717 const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
718 MachineModuleInfo *MMI, MCStreamer &Streamer) const {
719 // Although MachO 32-bit targets do not explictly have a GOTPCREL relocation
720 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
721 // through a non_lazy_ptr stub instead. One advantage is that it allows the
722 // computation of deltas to final external symbols. Example:
723 //
724 // _extgotequiv:
725 // .long _extfoo
726 //
727 // _delta:
728 // .long _extgotequiv-_delta
729 //
730 // is transformed to:
731 //
732 // _delta:
733 // .long L_extfoo$non_lazy_ptr-(_delta+0)
734 //
735 // .section __IMPORT,__pointers,non_lazy_symbol_pointers
736 // L_extfoo$non_lazy_ptr:
737 // .indirect_symbol _extfoo
738 // .long 0
739 //
740 MachineModuleInfoMachO &MachOMMI =
741 MMI->getObjFileInfo<MachineModuleInfoMachO>();
742 MCContext &Ctx = getContext();
743
744 // The offset must consider the original displacement from the base symbol
745 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
746 Offset = -MV.getConstant();
747 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
748
749 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
750 // non_lazy_ptr stubs.
751 SmallString<128> Name;
752 StringRef Suffix = "$non_lazy_ptr";
753 Name += DL->getPrivateGlobalPrefix();
754 Name += Sym->getName();
755 Name += Suffix;
Jim Grosbach6f482002015-05-18 18:43:14 +0000756 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000757
758 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
759 if (!StubSym.getPointer())
760 StubSym = MachineModuleInfoImpl::
761 StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
762
763 const MCExpr *BSymExpr =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000764 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000765 const MCExpr *LHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000766 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000767
768 if (!Offset)
Jim Grosbach13760bd2015-05-30 01:25:56 +0000769 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000770
771 const MCExpr *RHS =
Jim Grosbach13760bd2015-05-30 01:25:56 +0000772 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
773 return MCBinaryExpr::createSub(LHS, RHS, Ctx);
Bruno Cardoso Lopes618c67a2015-03-06 13:49:05 +0000774}
775
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000776//===----------------------------------------------------------------------===//
777// COFF
778//===----------------------------------------------------------------------===//
779
Chris Lattner87cffa92010-05-07 17:17:41 +0000780static unsigned
781getCOFFSectionFlags(SectionKind K) {
782 unsigned Flags = 0;
783
Anton Korobeynikove4152302010-07-06 15:24:56 +0000784 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000785 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000786 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000787 else if (K.isText())
788 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000789 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000790 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar329d2022010-07-01 20:07:24 +0000791 COFF::IMAGE_SCN_CNT_CODE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000792 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000793 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000794 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
795 COFF::IMAGE_SCN_MEM_READ |
796 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000797 else if (K.isThreadLocal())
798 Flags |=
799 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
800 COFF::IMAGE_SCN_MEM_READ |
801 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000802 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000803 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000804 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
805 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000806 else if (K.isWriteable())
807 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000808 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
809 COFF::IMAGE_SCN_MEM_READ |
810 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000811
812 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000813}
814
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000815static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000816 const Comdat *C = GV->getComdat();
817 assert(C && "expected GV to have a Comdat!");
818
819 StringRef ComdatGVName = C->getName();
820 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
821 if (!ComdatGV)
822 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
823 "' does not exist.");
824
825 if (ComdatGV->getComdat() != C)
826 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000827 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000828
829 return ComdatGV;
830}
831
832static int getSelectionForCOFF(const GlobalValue *GV) {
833 if (const Comdat *C = GV->getComdat()) {
834 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
835 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
836 ComdatKey = GA->getBaseObject();
837 if (ComdatKey == GV) {
838 switch (C->getSelectionKind()) {
839 case Comdat::Any:
840 return COFF::IMAGE_COMDAT_SELECT_ANY;
841 case Comdat::ExactMatch:
842 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
843 case Comdat::Largest:
844 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
845 case Comdat::NoDuplicates:
846 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
847 case Comdat::SameSize:
848 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
849 }
850 } else {
851 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
852 }
853 } else if (GV->isWeakForLinker()) {
854 return COFF::IMAGE_COMDAT_SELECT_ANY;
855 }
856 return 0;
857}
858
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000859MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000860 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
861 const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000862 int Selection = 0;
863 unsigned Characteristics = getCOFFSectionFlags(Kind);
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000864 StringRef Name = GV->getSection();
865 StringRef COMDATSymName = "";
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000866 if (GV->hasComdat()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000867 Selection = getSelectionForCOFF(GV);
868 const GlobalValue *ComdatGV;
869 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
870 ComdatGV = getComdatGVForCOFF(GV);
871 else
872 ComdatGV = GV;
873
874 if (!ComdatGV->hasPrivateLinkage()) {
875 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
876 COMDATSymName = Sym->getName();
877 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
878 } else {
879 Selection = 0;
880 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000881 }
882 return getContext().getCOFFSection(Name,
883 Characteristics,
Nico Riecka37acf72013-07-06 12:13:10 +0000884 Kind,
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000885 COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000886 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000887}
888
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000889static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000890 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000891 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +0000892 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000893 return ".bss";
894 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +0000895 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +0000896 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
897 return ".rdata";
898 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000899}
900
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000901MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
902 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
903 const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +0000904 // If we have -ffunction-sections then we should emit the global value to a
905 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +0000906 bool EmitUniquedSection;
907 if (Kind.isText())
908 EmitUniquedSection = TM.getFunctionSections();
909 else
910 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000911
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000912 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000913 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner02844932010-05-07 21:49:09 +0000914 unsigned Characteristics = getCOFFSectionFlags(Kind);
915
Daniel Dunbar329d2022010-07-01 20:07:24 +0000916 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
David Majnemerdad0a642014-06-27 18:19:56 +0000917 int Selection = getSelectionForCOFF(GV);
918 if (!Selection)
919 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
920 const GlobalValue *ComdatGV;
921 if (GV->hasComdat())
922 ComdatGV = getComdatGVForCOFF(GV);
923 else
924 ComdatGV = GV;
925
926 if (!ComdatGV->hasPrivateLinkage()) {
927 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
928 StringRef COMDATSymName = Sym->getName();
929 return getContext().getCOFFSection(Name, Characteristics, Kind,
930 COMDATSymName, Selection);
David Majnemer7db449a2015-03-17 23:54:51 +0000931 } else {
932 SmallString<256> TmpData;
933 getNameWithPrefix(TmpData, GV, /*CannotUsePrivateLabel=*/true, Mang, TM);
934 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
935 Selection);
David Majnemerdad0a642014-06-27 18:19:56 +0000936 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000937 }
938
939 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +0000940 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000941
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000942 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +0000943 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000944
David Majnemer597be2d2014-09-22 20:39:23 +0000945 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +0000946 return ReadOnlySection;
947
David Majnemera9bdb322014-04-08 22:33:40 +0000948 // Note: we claim that common symbols are put in BSSSection, but they are
949 // really emitted with the magic .comm directive, which creates a symbol table
950 // entry but not a section.
951 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +0000952 return BSSSection;
953
954 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000955}
956
David Majnemer7db449a2015-03-17 23:54:51 +0000957void TargetLoweringObjectFileCOFF::getNameWithPrefix(
958 SmallVectorImpl<char> &OutName, const GlobalValue *GV,
959 bool CannotUsePrivateLabel, Mangler &Mang, const TargetMachine &TM) const {
960 if (GV->hasPrivateLinkage() &&
961 ((isa<Function>(GV) && TM.getFunctionSections()) ||
962 (isa<GlobalVariable>(GV) && TM.getDataSections())))
963 CannotUsePrivateLabel = true;
964
965 Mang.getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
966}
967
Rafael Espindola0709a7b2015-05-21 19:20:38 +0000968MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
Rafael Espindolaab447e42015-03-11 19:58:37 +0000969 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
970 // If the function can be removed, produce a unique section so that
971 // the table doesn't prevent the removal.
972 const Comdat *C = F.getComdat();
973 bool EmitUniqueSection = TM.getFunctionSections() || C;
974 if (!EmitUniqueSection)
975 return ReadOnlySection;
976
977 // FIXME: we should produce a symbol for F instead.
978 if (F.hasPrivateLinkage())
979 return ReadOnlySection;
980
981 MCSymbol *Sym = TM.getSymbol(&F, Mang);
982 StringRef COMDATSymName = Sym->getName();
983
984 SectionKind Kind = SectionKind::getReadOnly();
985 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
986 unsigned Characteristics = getCOFFSectionFlags(Kind);
987 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
988
989 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
990 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
991}
992
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000993StringRef TargetLoweringObjectFileCOFF::
994getDepLibFromLinkerOpt(StringRef LinkerOption) const {
995 const char *LibCmd = "/DEFAULTLIB:";
996 if (LinkerOption.startswith(LibCmd))
997 return LinkerOption.substr(strlen(LibCmd));
998 return StringRef();
999}
1000
Reid Klecknerd973ca32013-04-25 19:34:41 +00001001void TargetLoweringObjectFileCOFF::
1002emitModuleFlags(MCStreamer &Streamer,
1003 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +00001004 Mangler &Mang, const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +00001005 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001006
1007 // Look for the "Linker Options" flag, since it's the only one we support.
1008 for (ArrayRef<Module::ModuleFlagEntry>::iterator
1009 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
1010 const Module::ModuleFlagEntry &MFE = *i;
1011 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00001012 Metadata *Val = MFE.Val;
Reid Klecknerd973ca32013-04-25 19:34:41 +00001013 if (Key == "Linker Options") {
1014 LinkerOptions = cast<MDNode>(Val);
1015 break;
1016 }
1017 }
1018 if (!LinkerOptions)
1019 return;
1020
1021 // Emit the linker options to the linker .drectve section. According to the
1022 // spec, this section is a space-separated string containing flags for linker.
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001023 MCSection *Sec = getDrectveSection();
Reid Klecknerd973ca32013-04-25 19:34:41 +00001024 Streamer.SwitchSection(Sec);
1025 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
1026 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
1027 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
1028 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
Reid Klecknerd973ca32013-04-25 19:34:41 +00001029 // Lead with a space for consistency with our dllexport implementation.
Michael Kupersteinfc3e6262015-02-16 11:57:17 +00001030 std::string Directive(" ");
1031 Directive.append(MDOption->getString());
1032 Streamer.EmitBytes(Directive);
Reid Klecknerd973ca32013-04-25 19:34:41 +00001033 }
1034 }
1035}
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001036
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001037MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001038 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001039 return getContext().getAssociativeCOFFSection(
1040 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001041}
1042
Rafael Espindola0709a7b2015-05-21 19:20:38 +00001043MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +00001044 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +00001045 return getContext().getAssociativeCOFFSection(
1046 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +00001047}