blob: f59efa35031c434a6cd224dec99d820380940621 [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"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000033#include "llvm/MC/MCSymbol.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000034#include "llvm/Support/Dwarf.h"
Rafael Espindolaaea49582011-01-23 04:28:49 +000035#include "llvm/Support/ELF.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000036#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/raw_ostream.h"
Rafael Espindoladaeafb42014-02-19 17:23:20 +000038#include "llvm/Target/TargetLowering.h"
Chandler Carruth442f7842014-03-04 10:07:28 +000039#include "llvm/Target/TargetMachine.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000040using namespace llvm;
Anton Korobeynikov31a92122010-02-21 20:28:15 +000041using namespace dwarf;
Anton Korobeynikovab663a02010-02-15 22:37:53 +000042
43//===----------------------------------------------------------------------===//
44// ELF
45//===----------------------------------------------------------------------===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +000046
Rafael Espindoladaeafb42014-02-19 17:23:20 +000047MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
48 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
49 MachineModuleInfo *MMI) const {
Rafael Espindolace83fc32011-04-27 23:17:57 +000050 unsigned Encoding = getPersonalityEncoding();
Logan Chienc0029812014-05-30 16:48:56 +000051 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000052 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +000053 TM.getSymbol(GV, Mang)->getName());
Logan Chienc0029812014-05-30 16:48:56 +000054 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 Espindolaa83b1772011-04-16 03:51:21 +000057}
58
59void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
60 const TargetMachine &TM,
Rafael Espindola08704342011-04-27 23:08:15 +000061 const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000062 SmallString<64> NameData("DW.ref.");
63 NameData += Sym->getName();
64 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
Rafael Espindola39897762011-04-27 21:29:52 +000065 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
66 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000067 StringRef Prefix = ".data.";
68 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
Rafael Espindola39897762011-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 Carruth5da3f052012-11-01 09:14:31 +000075 unsigned Size = TM.getDataLayout()->getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +000076 Streamer.SwitchSection(Sec);
Chandler Carruth5da3f052012-11-01 09:14:31 +000077 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +000078 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
David Chisnall8fa17162012-02-17 16:05:50 +000079 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
Rafael Espindola39897762011-04-27 21:29:52 +000080 Streamer.EmitELFSize(Label, E);
81 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::
105 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
106 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
167
168static unsigned
169getELFSectionFlags(SectionKind K) {
170 unsigned Flags = 0;
171
172 if (!K.isMetadata())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000173 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000174
175 if (K.isText())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000176 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000177
Rafael Espindolac85e0d82011-06-07 23:26:45 +0000178 if (K.isWriteable())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000179 Flags |= ELF::SHF_WRITE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000180
181 if (K.isThreadLocal())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000182 Flags |= ELF::SHF_TLS;
Anton Korobeynikovab663a02010-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 Espindola0e7e34e2011-01-23 04:43:11 +0000187 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000188
189 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000190 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000191
192 return Flags;
193}
194
David Majnemerdad0a642014-06-27 18:19:56 +0000195static 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
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000207const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
208 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
209 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-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
David Majnemerdad0a642014-06-27 18:19:56 +0000215 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 Lattner80c34592010-04-08 21:34:17 +0000221 return getContext().getELFSection(SectionName,
David Majnemerdad0a642014-06-27 18:19:56 +0000222 getELFSectionType(SectionName, Kind), Flags,
223 Kind, /*EntrySize=*/0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000224}
225
Chris Lattner5b212a32010-04-13 00:36:43 +0000226/// getSectionPrefixForGlobal - Return the section prefix name used by options
227/// FunctionsSections and DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000228static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Chris Lattner5b212a32010-04-13 00:36:43 +0000229 if (Kind.isText()) return ".text.";
230 if (Kind.isReadOnly()) return ".rodata.";
Anton Korobeynikova22828e2012-02-23 10:36:04 +0000231 if (Kind.isBSS()) return ".bss.";
Chris Lattner5b212a32010-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 Korobeynikovab663a02010-02-15 22:37:53 +0000245const MCSection *TargetLoweringObjectFileELF::
246SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000247 Mangler &Mang, const TargetMachine &TM) const {
Chris Lattner5b212a32010-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. Spencerfbdab0d2010-10-27 18:52:20 +0000253 else
Chris Lattner5b212a32010-04-13 00:36:43 +0000254 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-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.
David Majnemerdad0a642014-06-27 18:19:56 +0000258 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
Anton Korobeynikova22828e2012-02-23 10:36:04 +0000259 !Kind.isCommon()) {
David Majnemer102ff692014-06-24 16:01:53 +0000260 StringRef Prefix = getSectionPrefixForGlobal(Kind);
Chris Lattner5b212a32010-04-13 00:36:43 +0000261
David Majnemer102ff692014-06-24 16:01:53 +0000262 SmallString<128> Name(Prefix);
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000263 TM.getNameWithPrefix(Name, GV, Mang, true);
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000264
Rafael Espindola70d80152011-02-14 22:23:49 +0000265 StringRef Group = "";
266 unsigned Flags = getELFSectionFlags(Kind);
David Majnemerdad0a642014-06-27 18:19:56 +0000267 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 Espindola70d80152011-02-14 22:23:49 +0000272 Flags |= ELF::SHF_GROUP;
273 }
274
Chris Lattner80c34592010-04-08 21:34:17 +0000275 return getContext().getELFSection(Name.str(),
276 getELFSectionType(Name.str(), Kind),
Rafael Espindola70d80152011-02-14 22:23:49 +0000277 Flags, Kind, 0, Group);
Anton Korobeynikovab663a02010-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 Villmowcdfe20b2012-10-08 16:38:25 +0000290 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
Anton Korobeynikovab663a02010-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 Espindolaaea49582011-01-23 04:28:49 +0000302 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000303 ELF::SHF_ALLOC |
304 ELF::SHF_MERGE |
305 ELF::SHF_STRINGS,
Chris Lattner80c34592010-04-08 21:34:17 +0000306 Kind);
Anton Korobeynikovab663a02010-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.
David Majnemer8bce66b2014-07-14 22:57:27 +0000341const MCSection *
342TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
343 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000344 if (Kind.isMergeableConst4() && MergeableConst4Section)
345 return MergeableConst4Section;
346 if (Kind.isMergeableConst8() && MergeableConst8Section)
347 return MergeableConst8Section;
348 if (Kind.isMergeableConst16() && MergeableConst16Section)
349 return MergeableConst16Section;
350 if (Kind.isReadOnly())
351 return ReadOnlySection;
352
353 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
354 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
355 return DataRelROSection;
356}
357
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000358const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000359 unsigned Priority, const MCSymbol *KeySym) const {
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000360 // The default scheme is .ctor / .dtor, so we have to invert the priority
361 // numbering.
362 if (Priority == 65535)
363 return StaticCtorSection;
364
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000365 if (UseInitArray) {
366 std::string Name = std::string(".init_array.") + utostr(Priority);
367 return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
368 ELF::SHF_ALLOC | ELF::SHF_WRITE,
369 SectionKind::getDataRel());
370 } else {
371 std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
372 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
373 ELF::SHF_ALLOC |ELF::SHF_WRITE,
374 SectionKind::getDataRel());
375 }
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000376}
377
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000378const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000379 unsigned Priority, const MCSymbol *KeySym) const {
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000380 // The default scheme is .ctor / .dtor, so we have to invert the priority
381 // numbering.
382 if (Priority == 65535)
383 return StaticDtorSection;
384
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000385 if (UseInitArray) {
386 std::string Name = std::string(".fini_array.") + utostr(Priority);
387 return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
388 ELF::SHF_ALLOC | ELF::SHF_WRITE,
389 SectionKind::getDataRel());
390 } else {
391 std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
392 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
393 ELF::SHF_ALLOC |ELF::SHF_WRITE,
394 SectionKind::getDataRel());
395 }
396}
397
398void
399TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
400 UseInitArray = UseInitArray_;
401 if (!UseInitArray)
402 return;
403
404 StaticCtorSection =
405 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
406 ELF::SHF_WRITE |
407 ELF::SHF_ALLOC,
408 SectionKind::getDataRel());
409 StaticDtorSection =
410 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
411 ELF::SHF_WRITE |
412 ELF::SHF_ALLOC,
413 SectionKind::getDataRel());
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000414}
415
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000416//===----------------------------------------------------------------------===//
417// MachO
418//===----------------------------------------------------------------------===//
419
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000420/// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
421/// option string. Returns StringRef() if the option does not specify a library.
422StringRef TargetLoweringObjectFileMachO::
423getDepLibFromLinkerOpt(StringRef LinkerOption) const {
424 const char *LibCmd = "-l";
425 if (LinkerOption.startswith(LibCmd))
426 return LinkerOption.substr(strlen(LibCmd));
427 return StringRef();
428}
429
Daniel Dunbar95856122013-01-18 19:37:00 +0000430/// emitModuleFlags - Perform code emission for module flags.
Bill Wendling06df7722012-02-14 21:28:13 +0000431void TargetLoweringObjectFileMachO::
Bill Wendling734909a2012-02-15 22:36:15 +0000432emitModuleFlags(MCStreamer &Streamer,
433 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000434 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000435 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000436 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000437 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000438 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000439
Bill Wendling734909a2012-02-15 22:36:15 +0000440 for (ArrayRef<Module::ModuleFlagEntry>::iterator
441 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
442 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendling06df7722012-02-14 21:28:13 +0000443
444 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000445 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000446 continue;
447
Bill Wendling734909a2012-02-15 22:36:15 +0000448 StringRef Key = MFE.Key->getString();
449 Value *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000450
Daniel Dunbar95856122013-01-18 19:37:00 +0000451 if (Key == "Objective-C Image Info Version") {
Bill Wendling06df7722012-02-14 21:28:13 +0000452 VersionVal = cast<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000453 } else if (Key == "Objective-C Garbage Collection" ||
454 Key == "Objective-C GC Only" ||
455 Key == "Objective-C Is Simulated") {
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000456 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000457 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000458 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000459 } else if (Key == "Linker Options") {
460 LinkerOptions = cast<MDNode>(Val);
461 }
462 }
463
464 // Emit the linker options if present.
465 if (LinkerOptions) {
466 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
467 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
468 SmallVector<std::string, 4> StrOptions;
469
470 // Convert to strings.
471 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
472 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
473 StrOptions.push_back(MDOption->getString());
474 }
475
476 Streamer.EmitLinkerOptions(StrOptions);
477 }
Bill Wendling06df7722012-02-14 21:28:13 +0000478 }
479
Bill Wendling734909a2012-02-15 22:36:15 +0000480 // The section is mandatory. If we don't have it, then we don't have GC info.
481 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000482
Bill Wendling734909a2012-02-15 22:36:15 +0000483 StringRef Segment, Section;
484 unsigned TAA = 0, StubSize = 0;
485 bool TAAParsed;
486 std::string ErrorCode =
487 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
488 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000489 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000490 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000491 report_fatal_error("Invalid section specifier '" + Section + "': " +
492 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000493
Bill Wendling734909a2012-02-15 22:36:15 +0000494 // Get the section.
495 const MCSectionMachO *S =
496 getContext().getMachOSection(Segment, Section, TAA, StubSize,
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000497 SectionKind::getDataNoRel());
Bill Wendling734909a2012-02-15 22:36:15 +0000498 Streamer.SwitchSection(S);
499 Streamer.EmitLabel(getContext().
500 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000501 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000502 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000503 Streamer.AddBlankLine();
504}
505
David Majnemerdad0a642014-06-27 18:19:56 +0000506static void checkMachOComdat(const GlobalValue *GV) {
507 const Comdat *C = GV->getComdat();
508 if (!C)
509 return;
510
511 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
512 "' cannot be lowered.");
513}
514
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000515const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
516 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
517 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000518 // Parse the section specifier and create it if valid.
519 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000520 unsigned TAA = 0, StubSize = 0;
521 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000522
523 checkMachOComdat(GV);
524
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000525 std::string ErrorCode =
526 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000527 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000528 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000529 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000530 report_fatal_error("Global variable '" + GV->getName() +
531 "' has an invalid section specifier '" +
532 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000533 }
534
535 // Get the section.
536 const MCSectionMachO *S =
Chris Lattner433d4062010-04-08 20:40:11 +0000537 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000538
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000539 // If TAA wasn't set by ParseSectionSpecifier() above,
540 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000541 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000542 TAA = S->getTypeAndAttributes();
543
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000544 // Okay, now that we got the section, verify that the TAA & StubSize agree.
545 // If the user declared multiple globals with different section flags, we need
546 // to reject it here.
547 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000548 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000549 report_fatal_error("Global variable '" + GV->getName() +
550 "' section type or attributes does not match previous"
551 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000552 }
553
554 return S;
555}
556
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000557bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
558 const MCSection &Section) const {
559 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
560
561 // Sections holding 1 byte strings are atomized based on the data
562 // they contain.
563 // Sections holding 2 byte strings require symbols in order to be
564 // atomized.
565 // There is no dedicated section for 4 byte strings.
566 if (SMO.getKind().isMergeable1ByteCString())
567 return false;
568
569 if (SMO.getSegmentName() == "__DATA" &&
570 SMO.getSectionName() == "__cfstring")
571 return false;
572
573 switch (SMO.getType()) {
574 default:
575 return true;
576
577 // These sections are atomized at the element boundaries without using
578 // symbols.
David Majnemer7b583052014-03-07 07:36:05 +0000579 case MachO::S_4BYTE_LITERALS:
580 case MachO::S_8BYTE_LITERALS:
581 case MachO::S_16BYTE_LITERALS:
582 case MachO::S_LITERAL_POINTERS:
583 case MachO::S_NON_LAZY_SYMBOL_POINTERS:
584 case MachO::S_LAZY_SYMBOL_POINTERS:
585 case MachO::S_MOD_INIT_FUNC_POINTERS:
586 case MachO::S_MOD_TERM_FUNC_POINTERS:
587 case MachO::S_INTERPOSING:
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000588 return false;
589 }
590}
591
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000592const MCSection *TargetLoweringObjectFileMachO::
593SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000594 Mangler &Mang, const TargetMachine &TM) const {
David Majnemerdad0a642014-06-27 18:19:56 +0000595 checkMachOComdat(GV);
Bill Wendling25b61db2013-11-17 10:53:13 +0000596
597 // Handle thread local data.
598 if (Kind.isThreadBSS()) return TLSBSSSection;
599 if (Kind.isThreadData()) return TLSDataSection;
600
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000601 if (Kind.isText())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000602 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
603
604 // If this is weak/linkonce, put this in a coalescable section, either in text
605 // or data depending on if it is writable.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000606 if (GV->isWeakForLinker()) {
607 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000608 return ConstTextCoalSection;
609 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000610 }
611
612 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000613 if (Kind.isMergeable1ByteCString() &&
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000614 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000615 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000616
Chris Lattneref2f8042010-03-07 04:28:09 +0000617 // Do not put 16-bit arrays in the UString section if they have an
618 // externally visible label, this runs into issues with certain linker
619 // versions.
620 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000621 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000622 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000623
624 if (Kind.isMergeableConst()) {
625 if (Kind.isMergeableConst4())
626 return FourByteConstantSection;
627 if (Kind.isMergeableConst8())
628 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000629 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000630 return SixteenByteConstantSection;
631 }
632
633 // Otherwise, if it is readonly, but not something we can specially optimize,
634 // just drop it in .const.
635 if (Kind.isReadOnly())
636 return ReadOnlySection;
637
638 // If this is marked const, put it into a const section. But if the dynamic
639 // linker needs to write to it, put it in the data segment.
640 if (Kind.isReadOnlyWithRel())
641 return ConstDataSection;
642
643 // Put zero initialized globals with strong external linkage in the
644 // DATA, __common section with the .zerofill directive.
645 if (Kind.isBSSExtern())
646 return DataCommonSection;
647
648 // Put zero initialized globals with local linkage in __DATA,__bss directive
649 // with the .zerofill directive (aka .lcomm).
650 if (Kind.isBSSLocal())
651 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000652
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000653 // Otherwise, just drop the variable in the normal data section.
654 return DataSection;
655}
656
657const MCSection *
David Majnemer8bce66b2014-07-14 22:57:27 +0000658TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
659 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000660 // If this constant requires a relocation, we have to put it in the data
661 // segment, not in the text segment.
662 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
663 return ConstDataSection;
664
665 if (Kind.isMergeableConst4())
666 return FourByteConstantSection;
667 if (Kind.isMergeableConst8())
668 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000669 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000670 return SixteenByteConstantSection;
671 return ReadOnlySection; // .const
672}
673
Rafael Espindola15b26692014-02-09 14:50:44 +0000674const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
675 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000676 const TargetMachine &TM, MachineModuleInfo *MMI,
677 MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000678 // The mach-o version of this method defaults to returning a stub reference.
679
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000680 if (Encoding & DW_EH_PE_indirect) {
681 MachineModuleInfoMachO &MachOMMI =
682 MMI->getObjFileInfo<MachineModuleInfoMachO>();
683
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000684 MCSymbol *SSym =
685 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000686
687 // Add information about the stub reference to MachOMMI so that the stub
688 // gets emitted by the asmprinter.
Bill Wendling57e3aaa2011-10-24 23:05:43 +0000689 MachineModuleInfoImpl::StubValueTy &StubSym =
690 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
691 MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000692 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000693 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000694 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000695 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000696
697 return TargetLoweringObjectFile::
Anton Korobeynikove42af362012-11-14 01:47:00 +0000698 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
699 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000700 }
701
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000702 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
703 TM, MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000704}
705
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000706MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
707 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
708 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000709 // The mach-o version of this method defaults to returning a stub reference.
710 MachineModuleInfoMachO &MachOMMI =
711 MMI->getObjFileInfo<MachineModuleInfoMachO>();
712
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000713 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000714
715 // Add information about the stub reference to MachOMMI so that the stub
716 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000717 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000718 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000719 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola08704342011-04-27 23:08:15 +0000720 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
721 }
722
723 return SSym;
724}
725
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000726//===----------------------------------------------------------------------===//
727// COFF
728//===----------------------------------------------------------------------===//
729
Chris Lattner87cffa92010-05-07 17:17:41 +0000730static unsigned
731getCOFFSectionFlags(SectionKind K) {
732 unsigned Flags = 0;
733
Anton Korobeynikove4152302010-07-06 15:24:56 +0000734 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000735 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000736 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000737 else if (K.isText())
738 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000739 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000740 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar329d2022010-07-01 20:07:24 +0000741 COFF::IMAGE_SCN_CNT_CODE;
Chris Lattner02844932010-05-07 21:49:09 +0000742 else if (K.isBSS ())
743 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000744 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
745 COFF::IMAGE_SCN_MEM_READ |
746 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000747 else if (K.isThreadLocal())
748 Flags |=
749 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
750 COFF::IMAGE_SCN_MEM_READ |
751 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000752 else if (K.isReadOnly())
753 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000754 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
755 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000756 else if (K.isWriteable())
757 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000758 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
759 COFF::IMAGE_SCN_MEM_READ |
760 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000761
762 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000763}
764
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000765static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000766 const Comdat *C = GV->getComdat();
767 assert(C && "expected GV to have a Comdat!");
768
769 StringRef ComdatGVName = C->getName();
770 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
771 if (!ComdatGV)
772 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
773 "' does not exist.");
774
775 if (ComdatGV->getComdat() != C)
776 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
777 "' is not a key for it's COMDAT.");
778
779 return ComdatGV;
780}
781
782static int getSelectionForCOFF(const GlobalValue *GV) {
783 if (const Comdat *C = GV->getComdat()) {
784 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
785 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
786 ComdatKey = GA->getBaseObject();
787 if (ComdatKey == GV) {
788 switch (C->getSelectionKind()) {
789 case Comdat::Any:
790 return COFF::IMAGE_COMDAT_SELECT_ANY;
791 case Comdat::ExactMatch:
792 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
793 case Comdat::Largest:
794 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
795 case Comdat::NoDuplicates:
796 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
797 case Comdat::SameSize:
798 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
799 }
800 } else {
801 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
802 }
803 } else if (GV->isWeakForLinker()) {
804 return COFF::IMAGE_COMDAT_SELECT_ANY;
805 }
806 return 0;
807}
808
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000809const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
810 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
811 const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000812 int Selection = 0;
813 unsigned Characteristics = getCOFFSectionFlags(Kind);
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000814 StringRef Name = GV->getSection();
815 StringRef COMDATSymName = "";
David Majnemerdad0a642014-06-27 18:19:56 +0000816 if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) {
817 Selection = getSelectionForCOFF(GV);
818 const GlobalValue *ComdatGV;
819 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
820 ComdatGV = getComdatGVForCOFF(GV);
821 else
822 ComdatGV = GV;
823
824 if (!ComdatGV->hasPrivateLinkage()) {
825 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
826 COMDATSymName = Sym->getName();
827 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
828 } else {
829 Selection = 0;
830 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000831 }
832 return getContext().getCOFFSection(Name,
833 Characteristics,
Nico Riecka37acf72013-07-06 12:13:10 +0000834 Kind,
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000835 COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000836 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000837}
838
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000839static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000840 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000841 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +0000842 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000843 return ".bss";
844 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +0000845 return ".tls$";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000846 if (Kind.isWriteable())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000847 return ".data";
848 return ".rdata";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000849}
850
851
852const MCSection *TargetLoweringObjectFileCOFF::
853SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000854 Mangler &Mang, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +0000855 // If we have -ffunction-sections then we should emit the global value to a
856 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +0000857 bool EmitUniquedSection;
858 if (Kind.isText())
859 EmitUniquedSection = TM.getFunctionSections();
860 else
861 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000862
863 // If this global is linkonce/weak and the target handles this by emitting it
864 // into a 'uniqued' section name, create and return the section now.
David Majnemer273bff42014-03-25 06:14:26 +0000865 // Section names depend on the name of the symbol which is not feasible if the
866 // symbol has private linkage.
David Majnemerdad0a642014-06-27 18:19:56 +0000867 if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
868 !Kind.isCommon()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000869 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner02844932010-05-07 21:49:09 +0000870 unsigned Characteristics = getCOFFSectionFlags(Kind);
871
Daniel Dunbar329d2022010-07-01 20:07:24 +0000872 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
David Majnemerdad0a642014-06-27 18:19:56 +0000873 int Selection = getSelectionForCOFF(GV);
874 if (!Selection)
875 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
876 const GlobalValue *ComdatGV;
877 if (GV->hasComdat())
878 ComdatGV = getComdatGVForCOFF(GV);
879 else
880 ComdatGV = GV;
881
882 if (!ComdatGV->hasPrivateLinkage()) {
883 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
884 StringRef COMDATSymName = Sym->getName();
885 return getContext().getCOFFSection(Name, Characteristics, Kind,
886 COMDATSymName, Selection);
887 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000888 }
889
890 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +0000891 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000892
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000893 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +0000894 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000895
David Majnemer3d96acb2013-08-13 01:23:53 +0000896 if (Kind.isReadOnly())
David Majnemerf76d6b32013-08-08 01:50:52 +0000897 return ReadOnlySection;
898
David Majnemera9bdb322014-04-08 22:33:40 +0000899 // Note: we claim that common symbols are put in BSSSection, but they are
900 // really emitted with the magic .comm directive, which creates a symbol table
901 // entry but not a section.
902 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +0000903 return BSSSection;
904
905 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000906}
907
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000908StringRef TargetLoweringObjectFileCOFF::
909getDepLibFromLinkerOpt(StringRef LinkerOption) const {
910 const char *LibCmd = "/DEFAULTLIB:";
911 if (LinkerOption.startswith(LibCmd))
912 return LinkerOption.substr(strlen(LibCmd));
913 return StringRef();
914}
915
Reid Klecknerd973ca32013-04-25 19:34:41 +0000916void TargetLoweringObjectFileCOFF::
917emitModuleFlags(MCStreamer &Streamer,
918 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000919 Mangler &Mang, const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000920 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +0000921
922 // Look for the "Linker Options" flag, since it's the only one we support.
923 for (ArrayRef<Module::ModuleFlagEntry>::iterator
924 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
925 const Module::ModuleFlagEntry &MFE = *i;
926 StringRef Key = MFE.Key->getString();
927 Value *Val = MFE.Val;
928 if (Key == "Linker Options") {
929 LinkerOptions = cast<MDNode>(Val);
930 break;
931 }
932 }
933 if (!LinkerOptions)
934 return;
935
936 // Emit the linker options to the linker .drectve section. According to the
937 // spec, this section is a space-separated string containing flags for linker.
938 const MCSection *Sec = getDrectveSection();
939 Streamer.SwitchSection(Sec);
940 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
941 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
942 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
943 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
944 StringRef Op = MDOption->getString();
945 // Lead with a space for consistency with our dllexport implementation.
946 std::string Escaped(" ");
947 if (Op.find(" ") != StringRef::npos) {
948 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
949 // how to escape quotes, but it probably uses this algorithm:
950 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
951 // FIXME: Reuse escaping code from Support/Windows/Program.inc
952 Escaped.push_back('\"');
953 Escaped.append(Op);
954 Escaped.push_back('\"');
955 } else {
956 Escaped.append(Op);
957 }
958 Streamer.EmitBytes(Escaped);
959 }
960 }
961}
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000962
963static const MCSection *getAssociativeCOFFSection(MCContext &Ctx,
964 const MCSection *Sec,
Rafael Espindola0766ae02014-06-06 19:26:12 +0000965 const MCSymbol *KeySym) {
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000966 // Return the normal section if we don't have to be associative.
967 if (!KeySym)
968 return Sec;
969
970 // Make an associative section with the same name and kind as the normal
971 // section.
972 const MCSectionCOFF *SecCOFF = cast<MCSectionCOFF>(Sec);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000973 unsigned Characteristics =
974 SecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
975 return Ctx.getCOFFSection(SecCOFF->getSectionName(), Characteristics,
976 SecCOFF->getKind(), KeySym->getName(),
Rafael Espindola0766ae02014-06-06 19:26:12 +0000977 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000978}
979
980const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000981 unsigned Priority, const MCSymbol *KeySym) const {
982 return getAssociativeCOFFSection(getContext(), StaticCtorSection, KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000983}
984
985const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000986 unsigned Priority, const MCSymbol *KeySym) const {
987 return getAssociativeCOFFSection(getContext(), StaticDtorSection, KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000988}