blob: 03f4a51e8b63f342248edbaf76368e86fa478e29 [file] [log] [blame]
Anton Korobeynikov362dd0b2010-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 Carruthd04a8d42012-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 Carruth0b8c9a82013-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"
Stephen Hines36b56882014-04-23 16:57:46 -070025#include "llvm/IR/Mangler.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000026#include "llvm/IR/Module.h"
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +000027#include "llvm/MC/MCContext.h"
28#include "llvm/MC/MCExpr.h"
Chris Lattnereb40a0f2010-05-07 17:17:41 +000029#include "llvm/MC/MCSectionCOFF.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/MC/MCSectionELF.h"
31#include "llvm/MC/MCSectionMachO.h"
Rafael Espindola30deafc2011-04-16 03:51:21 +000032#include "llvm/MC/MCStreamer.h"
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +000033#include "llvm/MC/MCSymbol.h"
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +000034#include "llvm/Support/Dwarf.h"
Rafael Espindolac85dca62011-01-23 04:28:49 +000035#include "llvm/Support/ELF.h"
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +000036#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
Stephen Hines36b56882014-04-23 16:57:46 -070038#include "llvm/Target/TargetLowering.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000039#include "llvm/Target/TargetMachine.h"
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +000040using namespace llvm;
Anton Korobeynikov293d5922010-02-21 20:28:15 +000041using namespace dwarf;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +000042
43//===----------------------------------------------------------------------===//
44// ELF
45//===----------------------------------------------------------------------===//
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +000046
Stephen Hines36b56882014-04-23 16:57:46 -070047MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
48 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
49 MachineModuleInfo *MMI) const {
Rafael Espindola60246a92011-04-27 23:17:57 +000050 unsigned Encoding = getPersonalityEncoding();
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -070051 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
Rafael Espindolafb66f472011-06-13 03:09:13 +000052 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
Stephen Hines36b56882014-04-23 16:57:46 -070053 TM.getSymbol(GV, Mang)->getName());
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -070054 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
55 return TM.getSymbol(GV, Mang);
56 report_fatal_error("We do not support this DWARF encoding yet!");
Rafael Espindola30deafc2011-04-16 03:51:21 +000057}
58
59void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
60 const TargetMachine &TM,
Rafael Espindola7afec9c2011-04-27 23:08:15 +000061 const MCSymbol *Sym) const {
Rafael Espindolafb66f472011-06-13 03:09:13 +000062 SmallString<64> NameData("DW.ref.");
63 NameData += Sym->getName();
64 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
Rafael Espindola018e38c2011-04-27 21:29:52 +000065 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
66 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindolafb66f472011-06-13 03:09:13 +000067 StringRef Prefix = ".data.";
68 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
Rafael Espindola018e38c2011-04-27 21:29:52 +000069 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
70 const MCSection *Sec = getContext().getELFSection(NameData,
71 ELF::SHT_PROGBITS,
72 Flags,
73 SectionKind::getDataRel(),
74 0, Label->getName());
Chandler Carruth426c2bf2012-11-01 09:14:31 +000075 unsigned Size = TM.getDataLayout()->getPointerSize();
Rafael Espindola018e38c2011-04-27 21:29:52 +000076 Streamer.SwitchSection(Sec);
Chandler Carruth426c2bf2012-11-01 09:14:31 +000077 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
Rafael Espindola018e38c2011-04-27 21:29:52 +000078 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
David Chisnallca5b7522012-02-17 16:05:50 +000079 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
Rafael Espindola018e38c2011-04-27 21:29:52 +000080 Streamer.EmitELFSize(Label, E);
81 Streamer.EmitLabel(Label);
Rafael Espindola30deafc2011-04-16 03:51:21 +000082
Rafael Espindola018e38c2011-04-27 21:29:52 +000083 Streamer.EmitSymbolValue(Sym, Size);
Rafael Espindola30deafc2011-04-16 03:51:21 +000084}
85
Stephen Hines36b56882014-04-23 16:57:46 -070086const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
87 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
88 const TargetMachine &TM, MachineModuleInfo *MMI,
89 MCStreamer &Streamer) const {
Anton Korobeynikov25efd6d2012-11-14 01:47:00 +000090
91 if (Encoding & dwarf::DW_EH_PE_indirect) {
92 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
93
Stephen Hines36b56882014-04-23 16:57:46 -070094 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
Anton Korobeynikov25efd6d2012-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 Korobeynikov25efd6d2012-11-14 01:47:00 +000098 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
Stephen Hinesdce4a402014-05-29 02:49:00 -070099 if (!StubSym.getPointer()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700100 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Anton Korobeynikov25efd6d2012-11-14 01:47:00 +0000101 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
102 }
103
104 return TargetLoweringObjectFile::
105 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
106 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
107 }
108
109 return TargetLoweringObjectFile::
Stephen Hines36b56882014-04-23 16:57:46 -0700110 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
Anton Korobeynikov25efd6d2012-11-14 01:47:00 +0000111}
112
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000113static SectionKind
114getELFKindForNamedSection(StringRef Name, SectionKind K) {
Rafael Espindolae6657982011-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 Wendling96cb1122012-07-19 00:04:14 +0000118 // section(".eh_frame") gcc will produce:
119 //
120 // .section .eh_frame,"a",@progbits
Anton Korobeynikov362dd0b2010-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 Espindolac85dca62011-01-23 04:28:49 +0000153 return ELF::SHT_INIT_ARRAY;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000154
155 if (Name == ".fini_array")
Rafael Espindolac85dca62011-01-23 04:28:49 +0000156 return ELF::SHT_FINI_ARRAY;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000157
158 if (Name == ".preinit_array")
Rafael Espindolac85dca62011-01-23 04:28:49 +0000159 return ELF::SHT_PREINIT_ARRAY;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000160
161 if (K.isBSS() || K.isThreadBSS())
Rafael Espindolac85dca62011-01-23 04:28:49 +0000162 return ELF::SHT_NOBITS;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000163
Rafael Espindolac85dca62011-01-23 04:28:49 +0000164 return ELF::SHT_PROGBITS;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000165}
166
167
168static unsigned
169getELFSectionFlags(SectionKind K) {
170 unsigned Flags = 0;
171
172 if (!K.isMetadata())
Rafael Espindola1c130262011-01-23 04:43:11 +0000173 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000174
175 if (K.isText())
Rafael Espindola1c130262011-01-23 04:43:11 +0000176 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000177
Rafael Espindolad846e3f2011-06-07 23:26:45 +0000178 if (K.isWriteable())
Rafael Espindola1c130262011-01-23 04:43:11 +0000179 Flags |= ELF::SHF_WRITE;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000180
181 if (K.isThreadLocal())
Rafael Espindola1c130262011-01-23 04:43:11 +0000182 Flags |= ELF::SHF_TLS;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000183
184 // K.isMergeableConst() is left out to honour PR4650
185 if (K.isMergeableCString() || K.isMergeableConst4() ||
186 K.isMergeableConst8() || K.isMergeableConst16())
Rafael Espindola1c130262011-01-23 04:43:11 +0000187 Flags |= ELF::SHF_MERGE;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000188
189 if (K.isMergeableCString())
Rafael Espindola1c130262011-01-23 04:43:11 +0000190 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000191
192 return Flags;
193}
194
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700195static const Comdat *getELFComdat(const GlobalValue *GV) {
196 const Comdat *C = GV->getComdat();
197 if (!C)
198 return nullptr;
199
200 if (C->getSelectionKind() != Comdat::Any)
201 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
202 C->getName() + "' cannot be lowered.");
203
204 return C;
205}
206
Stephen Hines36b56882014-04-23 16:57:46 -0700207const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
208 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
209 const TargetMachine &TM) const {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000210 StringRef SectionName = GV->getSection();
211
212 // Infer section flags from the section name if we can.
213 Kind = getELFKindForNamedSection(SectionName, Kind);
214
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700215 StringRef Group = "";
216 unsigned Flags = getELFSectionFlags(Kind);
217 if (const Comdat *C = getELFComdat(GV)) {
218 Group = C->getName();
219 Flags |= ELF::SHF_GROUP;
220 }
Chris Lattner287df1b2010-04-08 21:34:17 +0000221 return getContext().getELFSection(SectionName,
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700222 getELFSectionType(SectionName, Kind), Flags,
223 Kind, /*EntrySize=*/0, Group);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000224}
225
Chris Lattner43ac7212010-04-13 00:36:43 +0000226/// getSectionPrefixForGlobal - Return the section prefix name used by options
227/// FunctionsSections and DataSections.
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700228static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Chris Lattner43ac7212010-04-13 00:36:43 +0000229 if (Kind.isText()) return ".text.";
230 if (Kind.isReadOnly()) return ".rodata.";
Anton Korobeynikov1d2d5a02012-02-23 10:36:04 +0000231 if (Kind.isBSS()) return ".bss.";
Chris Lattner43ac7212010-04-13 00:36:43 +0000232
233 if (Kind.isThreadData()) return ".tdata.";
234 if (Kind.isThreadBSS()) return ".tbss.";
235
236 if (Kind.isDataNoRel()) return ".data.";
237 if (Kind.isDataRelLocal()) return ".data.rel.local.";
238 if (Kind.isDataRel()) return ".data.rel.";
239 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
240
241 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
242 return ".data.rel.ro.";
243}
244
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000245const MCSection *TargetLoweringObjectFileELF::
246SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Stephen Hines36b56882014-04-23 16:57:46 -0700247 Mangler &Mang, const TargetMachine &TM) const {
Chris Lattner43ac7212010-04-13 00:36:43 +0000248 // If we have -ffunction-section or -fdata-section then we should emit the
249 // global value to a uniqued section specifically for it.
250 bool EmitUniquedSection;
251 if (Kind.isText())
252 EmitUniquedSection = TM.getFunctionSections();
Michael J. Spencer579d7a32010-10-27 18:52:20 +0000253 else
Chris Lattner43ac7212010-04-13 00:36:43 +0000254 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000255
256 // If this global is linkonce/weak and the target handles this by emitting it
257 // into a 'uniqued' section name, create and return the section now.
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700258 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
Anton Korobeynikov1d2d5a02012-02-23 10:36:04 +0000259 !Kind.isCommon()) {
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700260 StringRef Prefix = getSectionPrefixForGlobal(Kind);
Chris Lattner43ac7212010-04-13 00:36:43 +0000261
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700262 SmallString<128> Name(Prefix);
Stephen Hines36b56882014-04-23 16:57:46 -0700263 TM.getNameWithPrefix(Name, GV, Mang, true);
264
Rafael Espindola5d618ef2011-02-14 22:23:49 +0000265 StringRef Group = "";
266 unsigned Flags = getELFSectionFlags(Kind);
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700267 if (GV->isWeakForLinker() || GV->hasComdat()) {
268 if (const Comdat *C = getELFComdat(GV))
269 Group = C->getName();
270 else
271 Group = Name.substr(Prefix.size());
Rafael Espindola5d618ef2011-02-14 22:23:49 +0000272 Flags |= ELF::SHF_GROUP;
273 }
274
Chris Lattner287df1b2010-04-08 21:34:17 +0000275 return getContext().getELFSection(Name.str(),
276 getELFSectionType(Name.str(), Kind),
Rafael Espindola5d618ef2011-02-14 22:23:49 +0000277 Flags, Kind, 0, Group);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000278 }
279
280 if (Kind.isText()) return TextSection;
281
282 if (Kind.isMergeable1ByteCString() ||
283 Kind.isMergeable2ByteCString() ||
284 Kind.isMergeable4ByteCString()) {
285
286 // We also need alignment here.
287 // FIXME: this is getting the alignment of the character, not the
288 // alignment of the global!
289 unsigned Align =
Micah Villmow3574eca2012-10-08 16:38:25 +0000290 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000291
292 const char *SizeSpec = ".rodata.str1.";
293 if (Kind.isMergeable2ByteCString())
294 SizeSpec = ".rodata.str2.";
295 else if (Kind.isMergeable4ByteCString())
296 SizeSpec = ".rodata.str4.";
297 else
298 assert(Kind.isMergeable1ByteCString() && "unknown string width");
299
300
301 std::string Name = SizeSpec + utostr(Align);
Rafael Espindolac85dca62011-01-23 04:28:49 +0000302 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
Rafael Espindola1c130262011-01-23 04:43:11 +0000303 ELF::SHF_ALLOC |
304 ELF::SHF_MERGE |
305 ELF::SHF_STRINGS,
Chris Lattner287df1b2010-04-08 21:34:17 +0000306 Kind);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000307 }
308
309 if (Kind.isMergeableConst()) {
310 if (Kind.isMergeableConst4() && MergeableConst4Section)
311 return MergeableConst4Section;
312 if (Kind.isMergeableConst8() && MergeableConst8Section)
313 return MergeableConst8Section;
314 if (Kind.isMergeableConst16() && MergeableConst16Section)
315 return MergeableConst16Section;
316 return ReadOnlySection; // .const
317 }
318
319 if (Kind.isReadOnly()) return ReadOnlySection;
320
321 if (Kind.isThreadData()) return TLSDataSection;
322 if (Kind.isThreadBSS()) return TLSBSSSection;
323
324 // Note: we claim that common symbols are put in BSSSection, but they are
325 // really emitted with the magic .comm directive, which creates a symbol table
326 // entry but not a section.
327 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
328
329 if (Kind.isDataNoRel()) return DataSection;
330 if (Kind.isDataRelLocal()) return DataRelLocalSection;
331 if (Kind.isDataRel()) return DataRelSection;
332 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
333
334 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
335 return DataRelROSection;
336}
337
338/// getSectionForConstant - Given a mergeable constant with the
339/// specified size and relocation information, return a section that it
340/// should be placed in.
341const MCSection *TargetLoweringObjectFileELF::
342getSectionForConstant(SectionKind Kind) const {
343 if (Kind.isMergeableConst4() && MergeableConst4Section)
344 return MergeableConst4Section;
345 if (Kind.isMergeableConst8() && MergeableConst8Section)
346 return MergeableConst8Section;
347 if (Kind.isMergeableConst16() && MergeableConst16Section)
348 return MergeableConst16Section;
349 if (Kind.isReadOnly())
350 return ReadOnlySection;
351
352 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
353 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
354 return DataRelROSection;
355}
356
Stephen Hinesdce4a402014-05-29 02:49:00 -0700357const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700358 unsigned Priority, const MCSymbol *KeySym) const {
Anton Korobeynikov4a99f592012-01-25 22:24:19 +0000359 // The default scheme is .ctor / .dtor, so we have to invert the priority
360 // numbering.
361 if (Priority == 65535)
362 return StaticCtorSection;
363
Rafael Espindolad6b43a32012-06-19 00:48:28 +0000364 if (UseInitArray) {
365 std::string Name = std::string(".init_array.") + utostr(Priority);
366 return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
367 ELF::SHF_ALLOC | ELF::SHF_WRITE,
368 SectionKind::getDataRel());
369 } else {
370 std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
371 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
372 ELF::SHF_ALLOC |ELF::SHF_WRITE,
373 SectionKind::getDataRel());
374 }
Anton Korobeynikov4a99f592012-01-25 22:24:19 +0000375}
376
Stephen Hinesdce4a402014-05-29 02:49:00 -0700377const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700378 unsigned Priority, const MCSymbol *KeySym) const {
Anton Korobeynikov4a99f592012-01-25 22:24:19 +0000379 // The default scheme is .ctor / .dtor, so we have to invert the priority
380 // numbering.
381 if (Priority == 65535)
382 return StaticDtorSection;
383
Rafael Espindolad6b43a32012-06-19 00:48:28 +0000384 if (UseInitArray) {
385 std::string Name = std::string(".fini_array.") + utostr(Priority);
386 return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
387 ELF::SHF_ALLOC | ELF::SHF_WRITE,
388 SectionKind::getDataRel());
389 } else {
390 std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
391 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
392 ELF::SHF_ALLOC |ELF::SHF_WRITE,
393 SectionKind::getDataRel());
394 }
395}
396
397void
398TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
399 UseInitArray = UseInitArray_;
400 if (!UseInitArray)
401 return;
402
403 StaticCtorSection =
404 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
405 ELF::SHF_WRITE |
406 ELF::SHF_ALLOC,
407 SectionKind::getDataRel());
408 StaticDtorSection =
409 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
410 ELF::SHF_WRITE |
411 ELF::SHF_ALLOC,
412 SectionKind::getDataRel());
Anton Korobeynikov4a99f592012-01-25 22:24:19 +0000413}
414
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000415//===----------------------------------------------------------------------===//
416// MachO
417//===----------------------------------------------------------------------===//
418
Stephen Hines36b56882014-04-23 16:57:46 -0700419/// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
420/// option string. Returns StringRef() if the option does not specify a library.
421StringRef TargetLoweringObjectFileMachO::
422getDepLibFromLinkerOpt(StringRef LinkerOption) const {
423 const char *LibCmd = "-l";
424 if (LinkerOption.startswith(LibCmd))
425 return LinkerOption.substr(strlen(LibCmd));
426 return StringRef();
427}
428
Daniel Dunbar6d49b682013-01-18 19:37:00 +0000429/// emitModuleFlags - Perform code emission for module flags.
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000430void TargetLoweringObjectFileMachO::
Bill Wendling057d5212012-02-15 22:36:15 +0000431emitModuleFlags(MCStreamer &Streamer,
432 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Stephen Hines36b56882014-04-23 16:57:46 -0700433 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000434 unsigned VersionVal = 0;
Bill Wendlingadb082c2012-04-24 11:03:50 +0000435 unsigned ImageInfoFlags = 0;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700436 MDNode *LinkerOptions = nullptr;
Bill Wendling057d5212012-02-15 22:36:15 +0000437 StringRef SectionVal;
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000438
Bill Wendling057d5212012-02-15 22:36:15 +0000439 for (ArrayRef<Module::ModuleFlagEntry>::iterator
440 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
441 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000442
443 // Ignore flags with 'Require' behavior.
Bill Wendling057d5212012-02-15 22:36:15 +0000444 if (MFE.Behavior == Module::Require)
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000445 continue;
446
Bill Wendling057d5212012-02-15 22:36:15 +0000447 StringRef Key = MFE.Key->getString();
448 Value *Val = MFE.Val;
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000449
Daniel Dunbar6d49b682013-01-18 19:37:00 +0000450 if (Key == "Objective-C Image Info Version") {
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000451 VersionVal = cast<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar6d49b682013-01-18 19:37:00 +0000452 } else if (Key == "Objective-C Garbage Collection" ||
453 Key == "Objective-C GC Only" ||
454 Key == "Objective-C Is Simulated") {
Bill Wendlingadb082c2012-04-24 11:03:50 +0000455 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar6d49b682013-01-18 19:37:00 +0000456 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling057d5212012-02-15 22:36:15 +0000457 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar6d49b682013-01-18 19:37:00 +0000458 } else if (Key == "Linker Options") {
459 LinkerOptions = cast<MDNode>(Val);
460 }
461 }
462
463 // Emit the linker options if present.
464 if (LinkerOptions) {
465 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
466 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
467 SmallVector<std::string, 4> StrOptions;
468
469 // Convert to strings.
470 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
471 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
472 StrOptions.push_back(MDOption->getString());
473 }
474
475 Streamer.EmitLinkerOptions(StrOptions);
476 }
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000477 }
478
Bill Wendling057d5212012-02-15 22:36:15 +0000479 // The section is mandatory. If we don't have it, then we don't have GC info.
480 if (SectionVal.empty()) return;
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000481
Bill Wendling057d5212012-02-15 22:36:15 +0000482 StringRef Segment, Section;
483 unsigned TAA = 0, StubSize = 0;
484 bool TAAParsed;
485 std::string ErrorCode =
486 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
487 TAA, TAAParsed, StubSize);
Bill Wendling2de3ff52012-02-15 22:47:53 +0000488 if (!ErrorCode.empty())
Bill Wendling057d5212012-02-15 22:36:15 +0000489 // If invalid, report the error with report_fatal_error.
Bill Wendling2de3ff52012-02-15 22:47:53 +0000490 report_fatal_error("Invalid section specifier '" + Section + "': " +
491 ErrorCode + ".");
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000492
Bill Wendling057d5212012-02-15 22:36:15 +0000493 // Get the section.
494 const MCSectionMachO *S =
495 getContext().getMachOSection(Segment, Section, TAA, StubSize,
Bill Wendling2de3ff52012-02-15 22:47:53 +0000496 SectionKind::getDataNoRel());
Bill Wendling057d5212012-02-15 22:36:15 +0000497 Streamer.SwitchSection(S);
498 Streamer.EmitLabel(getContext().
499 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000500 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingadb082c2012-04-24 11:03:50 +0000501 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000502 Streamer.AddBlankLine();
503}
504
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700505static void checkMachOComdat(const GlobalValue *GV) {
506 const Comdat *C = GV->getComdat();
507 if (!C)
508 return;
509
510 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
511 "' cannot be lowered.");
512}
513
Stephen Hines36b56882014-04-23 16:57:46 -0700514const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
515 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
516 const TargetMachine &TM) const {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000517 // Parse the section specifier and create it if valid.
518 StringRef Segment, Section;
Stuart Hastings65c8bca2011-03-19 02:42:31 +0000519 unsigned TAA = 0, StubSize = 0;
520 bool TAAParsed;
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700521
522 checkMachOComdat(GV);
523
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000524 std::string ErrorCode =
525 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings65c8bca2011-03-19 02:42:31 +0000526 TAA, TAAParsed, StubSize);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000527 if (!ErrorCode.empty()) {
Chris Lattner75361b62010-04-07 22:58:41 +0000528 // If invalid, report the error with report_fatal_error.
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000529 report_fatal_error("Global variable '" + GV->getName() +
530 "' has an invalid section specifier '" +
531 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000532 }
533
534 // Get the section.
535 const MCSectionMachO *S =
Chris Lattner22772212010-04-08 20:40:11 +0000536 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000537
Stuart Hastings6ad82d82011-02-21 17:27:17 +0000538 // If TAA wasn't set by ParseSectionSpecifier() above,
539 // use the value returned by getMachOSection() as a default.
Stuart Hastings65c8bca2011-03-19 02:42:31 +0000540 if (!TAAParsed)
Stuart Hastings6ad82d82011-02-21 17:27:17 +0000541 TAA = S->getTypeAndAttributes();
542
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000543 // Okay, now that we got the section, verify that the TAA & StubSize agree.
544 // If the user declared multiple globals with different section flags, we need
545 // to reject it here.
546 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner75361b62010-04-07 22:58:41 +0000547 // If invalid, report the error with report_fatal_error.
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000548 report_fatal_error("Global variable '" + GV->getName() +
549 "' section type or attributes does not match previous"
550 " section specifier");
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000551 }
552
553 return S;
554}
555
Stephen Hines36b56882014-04-23 16:57:46 -0700556bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
557 const MCSection &Section) const {
558 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
559
560 // Sections holding 1 byte strings are atomized based on the data
561 // they contain.
562 // Sections holding 2 byte strings require symbols in order to be
563 // atomized.
564 // There is no dedicated section for 4 byte strings.
565 if (SMO.getKind().isMergeable1ByteCString())
566 return false;
567
568 if (SMO.getSegmentName() == "__DATA" &&
569 SMO.getSectionName() == "__cfstring")
570 return false;
571
572 switch (SMO.getType()) {
573 default:
574 return true;
575
576 // These sections are atomized at the element boundaries without using
577 // symbols.
578 case MachO::S_4BYTE_LITERALS:
579 case MachO::S_8BYTE_LITERALS:
580 case MachO::S_16BYTE_LITERALS:
581 case MachO::S_LITERAL_POINTERS:
582 case MachO::S_NON_LAZY_SYMBOL_POINTERS:
583 case MachO::S_LAZY_SYMBOL_POINTERS:
584 case MachO::S_MOD_INIT_FUNC_POINTERS:
585 case MachO::S_MOD_TERM_FUNC_POINTERS:
586 case MachO::S_INTERPOSING:
587 return false;
588 }
589}
590
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000591const MCSection *TargetLoweringObjectFileMachO::
592SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Stephen Hines36b56882014-04-23 16:57:46 -0700593 Mangler &Mang, const TargetMachine &TM) const {
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700594 checkMachOComdat(GV);
Bill Wendlingfe128c62013-11-17 10:53:13 +0000595
596 // Handle thread local data.
597 if (Kind.isThreadBSS()) return TLSBSSSection;
598 if (Kind.isThreadData()) return TLSDataSection;
599
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000600 if (Kind.isText())
Arnold Schwaighofer9b19dfc2013-08-08 21:04:16 +0000601 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
602
603 // If this is weak/linkonce, put this in a coalescable section, either in text
604 // or data depending on if it is writable.
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000605 if (GV->isWeakForLinker()) {
606 if (Kind.isReadOnly())
Arnold Schwaighofer9b19dfc2013-08-08 21:04:16 +0000607 return ConstTextCoalSection;
608 return DataCoalSection;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000609 }
610
611 // FIXME: Alignment check should be handled by section classifier.
Chris Lattner98f15d22010-03-07 04:28:09 +0000612 if (Kind.isMergeable1ByteCString() &&
Micah Villmow3574eca2012-10-08 16:38:25 +0000613 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattner98f15d22010-03-07 04:28:09 +0000614 return CStringSection;
Michael J. Spencer579d7a32010-10-27 18:52:20 +0000615
Chris Lattner98f15d22010-03-07 04:28:09 +0000616 // Do not put 16-bit arrays in the UString section if they have an
617 // externally visible label, this runs into issues with certain linker
618 // versions.
619 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Micah Villmow3574eca2012-10-08 16:38:25 +0000620 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattner98f15d22010-03-07 04:28:09 +0000621 return UStringSection;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000622
623 if (Kind.isMergeableConst()) {
624 if (Kind.isMergeableConst4())
625 return FourByteConstantSection;
626 if (Kind.isMergeableConst8())
627 return EightByteConstantSection;
Stephen Hines36b56882014-04-23 16:57:46 -0700628 if (Kind.isMergeableConst16())
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000629 return SixteenByteConstantSection;
630 }
631
632 // Otherwise, if it is readonly, but not something we can specially optimize,
633 // just drop it in .const.
634 if (Kind.isReadOnly())
635 return ReadOnlySection;
636
637 // If this is marked const, put it into a const section. But if the dynamic
638 // linker needs to write to it, put it in the data segment.
639 if (Kind.isReadOnlyWithRel())
640 return ConstDataSection;
641
642 // Put zero initialized globals with strong external linkage in the
643 // DATA, __common section with the .zerofill directive.
644 if (Kind.isBSSExtern())
645 return DataCommonSection;
646
647 // Put zero initialized globals with local linkage in __DATA,__bss directive
648 // with the .zerofill directive (aka .lcomm).
649 if (Kind.isBSSLocal())
650 return DataBSSSection;
Michael J. Spencer579d7a32010-10-27 18:52:20 +0000651
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000652 // Otherwise, just drop the variable in the normal data section.
653 return DataSection;
654}
655
656const MCSection *
657TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
658 // If this constant requires a relocation, we have to put it in the data
659 // segment, not in the text segment.
660 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
661 return ConstDataSection;
662
663 if (Kind.isMergeableConst4())
664 return FourByteConstantSection;
665 if (Kind.isMergeableConst8())
666 return EightByteConstantSection;
Stephen Hines36b56882014-04-23 16:57:46 -0700667 if (Kind.isMergeableConst16())
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000668 return SixteenByteConstantSection;
669 return ReadOnlySection; // .const
670}
671
Stephen Hines36b56882014-04-23 16:57:46 -0700672const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
673 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
674 const TargetMachine &TM, MachineModuleInfo *MMI,
675 MCStreamer &Streamer) const {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000676 // The mach-o version of this method defaults to returning a stub reference.
677
Anton Korobeynikov293d5922010-02-21 20:28:15 +0000678 if (Encoding & DW_EH_PE_indirect) {
679 MachineModuleInfoMachO &MachOMMI =
680 MMI->getObjFileInfo<MachineModuleInfoMachO>();
681
Stephen Hines36b56882014-04-23 16:57:46 -0700682 MCSymbol *SSym =
683 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov293d5922010-02-21 20:28:15 +0000684
685 // Add information about the stub reference to MachOMMI so that the stub
686 // gets emitted by the asmprinter.
Bill Wendling67121542011-10-24 23:05:43 +0000687 MachineModuleInfoImpl::StubValueTy &StubSym =
688 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
689 MachOMMI.getGVStubEntry(SSym);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700690 if (!StubSym.getPointer()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700691 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner4c6741f2010-03-15 20:37:38 +0000692 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov293d5922010-02-21 20:28:15 +0000693 }
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000694
695 return TargetLoweringObjectFile::
Anton Korobeynikov25efd6d2012-11-14 01:47:00 +0000696 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
697 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000698 }
699
Stephen Hines36b56882014-04-23 16:57:46 -0700700 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
701 TM, MMI, Streamer);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000702}
703
Stephen Hines36b56882014-04-23 16:57:46 -0700704MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
705 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
706 MachineModuleInfo *MMI) const {
Rafael Espindola7afec9c2011-04-27 23:08:15 +0000707 // The mach-o version of this method defaults to returning a stub reference.
708 MachineModuleInfoMachO &MachOMMI =
709 MMI->getObjFileInfo<MachineModuleInfoMachO>();
710
Stephen Hines36b56882014-04-23 16:57:46 -0700711 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola7afec9c2011-04-27 23:08:15 +0000712
713 // Add information about the stub reference to MachOMMI so that the stub
714 // gets emitted by the asmprinter.
Bill Wendlingd7c24942011-11-29 01:43:20 +0000715 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700716 if (!StubSym.getPointer()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700717 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola7afec9c2011-04-27 23:08:15 +0000718 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
719 }
720
721 return SSym;
722}
723
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000724//===----------------------------------------------------------------------===//
725// COFF
726//===----------------------------------------------------------------------===//
727
Chris Lattnereb40a0f2010-05-07 17:17:41 +0000728static unsigned
729getCOFFSectionFlags(SectionKind K) {
730 unsigned Flags = 0;
731
Anton Korobeynikov36335be2010-07-06 15:24:56 +0000732 if (K.isMetadata())
Chris Lattner6e5ce282010-05-07 21:49:09 +0000733 Flags |=
Daniel Dunbar94610582010-07-01 20:07:24 +0000734 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattnereb40a0f2010-05-07 17:17:41 +0000735 else if (K.isText())
736 Flags |=
Daniel Dunbar94610582010-07-01 20:07:24 +0000737 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer3931b542010-10-27 18:52:29 +0000738 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar94610582010-07-01 20:07:24 +0000739 COFF::IMAGE_SCN_CNT_CODE;
Chris Lattner6e5ce282010-05-07 21:49:09 +0000740 else if (K.isBSS ())
741 Flags |=
Daniel Dunbar94610582010-07-01 20:07:24 +0000742 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
743 COFF::IMAGE_SCN_MEM_READ |
744 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovd4a19b62012-02-11 17:26:53 +0000745 else if (K.isThreadLocal())
746 Flags |=
747 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
748 COFF::IMAGE_SCN_MEM_READ |
749 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattnereb40a0f2010-05-07 17:17:41 +0000750 else if (K.isReadOnly())
751 Flags |=
Daniel Dunbar94610582010-07-01 20:07:24 +0000752 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
753 COFF::IMAGE_SCN_MEM_READ;
Chris Lattnereb40a0f2010-05-07 17:17:41 +0000754 else if (K.isWriteable())
755 Flags |=
Daniel Dunbar94610582010-07-01 20:07:24 +0000756 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
757 COFF::IMAGE_SCN_MEM_READ |
758 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattnereb40a0f2010-05-07 17:17:41 +0000759
760 return Flags;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000761}
762
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700763static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
764 const Comdat *C = GV->getComdat();
765 assert(C && "expected GV to have a Comdat!");
766
767 StringRef ComdatGVName = C->getName();
768 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
769 if (!ComdatGV)
770 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
771 "' does not exist.");
772
773 if (ComdatGV->getComdat() != C)
774 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
775 "' is not a key for it's COMDAT.");
776
777 return ComdatGV;
778}
779
780static int getSelectionForCOFF(const GlobalValue *GV) {
781 if (const Comdat *C = GV->getComdat()) {
782 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
783 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
784 ComdatKey = GA->getBaseObject();
785 if (ComdatKey == GV) {
786 switch (C->getSelectionKind()) {
787 case Comdat::Any:
788 return COFF::IMAGE_COMDAT_SELECT_ANY;
789 case Comdat::ExactMatch:
790 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
791 case Comdat::Largest:
792 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
793 case Comdat::NoDuplicates:
794 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
795 case Comdat::SameSize:
796 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
797 }
798 } else {
799 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
800 }
801 } else if (GV->isWeakForLinker()) {
802 return COFF::IMAGE_COMDAT_SELECT_ANY;
803 }
804 return 0;
805}
806
Stephen Hines36b56882014-04-23 16:57:46 -0700807const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
808 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
809 const TargetMachine &TM) const {
Michael J. Spencer4de58722012-11-13 22:04:09 +0000810 int Selection = 0;
811 unsigned Characteristics = getCOFFSectionFlags(Kind);
Stephen Hines36b56882014-04-23 16:57:46 -0700812 StringRef Name = GV->getSection();
813 StringRef COMDATSymName = "";
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700814 if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) {
815 Selection = getSelectionForCOFF(GV);
816 const GlobalValue *ComdatGV;
817 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
818 ComdatGV = getComdatGVForCOFF(GV);
819 else
820 ComdatGV = GV;
821
822 if (!ComdatGV->hasPrivateLinkage()) {
823 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
824 COMDATSymName = Sym->getName();
825 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
826 } else {
827 Selection = 0;
828 }
Michael J. Spencer4de58722012-11-13 22:04:09 +0000829 }
830 return getContext().getCOFFSection(Name,
831 Characteristics,
Nico Rieck80646282013-07-06 12:13:10 +0000832 Kind,
Stephen Hines36b56882014-04-23 16:57:46 -0700833 COMDATSymName,
Nico Rieck80646282013-07-06 12:13:10 +0000834 Selection);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000835}
836
Stephen Hines36b56882014-04-23 16:57:46 -0700837static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000838 if (Kind.isText())
Stephen Hines36b56882014-04-23 16:57:46 -0700839 return ".text";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700840 if (Kind.isBSS())
Stephen Hines36b56882014-04-23 16:57:46 -0700841 return ".bss";
842 if (Kind.isThreadLocal())
843 return ".tls$";
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000844 if (Kind.isWriteable())
Stephen Hines36b56882014-04-23 16:57:46 -0700845 return ".data";
846 return ".rdata";
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000847}
848
849
850const MCSection *TargetLoweringObjectFileCOFF::
851SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Stephen Hines36b56882014-04-23 16:57:46 -0700852 Mangler &Mang, const TargetMachine &TM) const {
853 // If we have -ffunction-sections then we should emit the global value to a
854 // uniqued section specifically for it.
855 bool EmitUniquedSection;
856 if (Kind.isText())
857 EmitUniquedSection = TM.getFunctionSections();
858 else
859 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000860
861 // If this global is linkonce/weak and the target handles this by emitting it
862 // into a 'uniqued' section name, create and return the section now.
Stephen Hines36b56882014-04-23 16:57:46 -0700863 // Section names depend on the name of the symbol which is not feasible if the
864 // symbol has private linkage.
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700865 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
866 !Kind.isCommon()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700867 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner6e5ce282010-05-07 21:49:09 +0000868 unsigned Characteristics = getCOFFSectionFlags(Kind);
869
Daniel Dunbar94610582010-07-01 20:07:24 +0000870 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700871 int Selection = getSelectionForCOFF(GV);
872 if (!Selection)
873 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
874 const GlobalValue *ComdatGV;
875 if (GV->hasComdat())
876 ComdatGV = getComdatGVForCOFF(GV);
877 else
878 ComdatGV = GV;
879
880 if (!ComdatGV->hasPrivateLinkage()) {
881 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
882 StringRef COMDATSymName = Sym->getName();
883 return getContext().getCOFFSection(Name, Characteristics, Kind,
884 COMDATSymName, Selection);
885 }
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000886 }
887
888 if (Kind.isText())
David Majnemer6aa93152013-08-13 01:23:53 +0000889 return TextSection;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000890
Anton Korobeynikovd4a19b62012-02-11 17:26:53 +0000891 if (Kind.isThreadLocal())
David Majnemer6aa93152013-08-13 01:23:53 +0000892 return TLSDataSection;
Anton Korobeynikovd4a19b62012-02-11 17:26:53 +0000893
David Majnemer6aa93152013-08-13 01:23:53 +0000894 if (Kind.isReadOnly())
David Majnemer9706d432013-08-08 01:50:52 +0000895 return ReadOnlySection;
896
Stephen Hinesdce4a402014-05-29 02:49:00 -0700897 // Note: we claim that common symbols are put in BSSSection, but they are
898 // really emitted with the magic .comm directive, which creates a symbol table
899 // entry but not a section.
900 if (Kind.isBSS() || Kind.isCommon())
David Majnemer6aa93152013-08-13 01:23:53 +0000901 return BSSSection;
902
903 return DataSection;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000904}
905
Stephen Hines36b56882014-04-23 16:57:46 -0700906StringRef TargetLoweringObjectFileCOFF::
907getDepLibFromLinkerOpt(StringRef LinkerOption) const {
908 const char *LibCmd = "/DEFAULTLIB:";
909 if (LinkerOption.startswith(LibCmd))
910 return LinkerOption.substr(strlen(LibCmd));
911 return StringRef();
912}
913
Reid Kleckner4b558152013-04-25 19:34:41 +0000914void TargetLoweringObjectFileCOFF::
915emitModuleFlags(MCStreamer &Streamer,
916 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Stephen Hines36b56882014-04-23 16:57:46 -0700917 Mangler &Mang, const TargetMachine &TM) const {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700918 MDNode *LinkerOptions = nullptr;
Reid Kleckner4b558152013-04-25 19:34:41 +0000919
920 // Look for the "Linker Options" flag, since it's the only one we support.
921 for (ArrayRef<Module::ModuleFlagEntry>::iterator
922 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
923 const Module::ModuleFlagEntry &MFE = *i;
924 StringRef Key = MFE.Key->getString();
925 Value *Val = MFE.Val;
926 if (Key == "Linker Options") {
927 LinkerOptions = cast<MDNode>(Val);
928 break;
929 }
930 }
931 if (!LinkerOptions)
932 return;
933
934 // Emit the linker options to the linker .drectve section. According to the
935 // spec, this section is a space-separated string containing flags for linker.
936 const MCSection *Sec = getDrectveSection();
937 Streamer.SwitchSection(Sec);
938 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
939 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
940 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
941 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
942 StringRef Op = MDOption->getString();
943 // Lead with a space for consistency with our dllexport implementation.
944 std::string Escaped(" ");
945 if (Op.find(" ") != StringRef::npos) {
946 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
947 // how to escape quotes, but it probably uses this algorithm:
948 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
949 // FIXME: Reuse escaping code from Support/Windows/Program.inc
950 Escaped.push_back('\"');
951 Escaped.append(Op);
952 Escaped.push_back('\"');
953 } else {
954 Escaped.append(Op);
955 }
956 Streamer.EmitBytes(Escaped);
957 }
958 }
959}
Stephen Hinesdce4a402014-05-29 02:49:00 -0700960
961static const MCSection *getAssociativeCOFFSection(MCContext &Ctx,
962 const MCSection *Sec,
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700963 const MCSymbol *KeySym) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700964 // Return the normal section if we don't have to be associative.
965 if (!KeySym)
966 return Sec;
967
968 // Make an associative section with the same name and kind as the normal
969 // section.
970 const MCSectionCOFF *SecCOFF = cast<MCSectionCOFF>(Sec);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700971 unsigned Characteristics =
972 SecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
973 return Ctx.getCOFFSection(SecCOFF->getSectionName(), Characteristics,
974 SecCOFF->getKind(), KeySym->getName(),
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700975 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700976}
977
978const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700979 unsigned Priority, const MCSymbol *KeySym) const {
980 return getAssociativeCOFFSection(getContext(), StaticCtorSection, KeySym);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700981}
982
983const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700984 unsigned Priority, const MCSymbol *KeySym) const {
985 return getAssociativeCOFFSection(getContext(), StaticDtorSection, KeySym);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700986}