blob: c1b34f7f55fda59662a5d00698ddd1d39e1068f4 [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"
Stephen Hines37ed9c12014-12-01 14:51:49 -080040#include "llvm/Target/TargetSubtargetInfo.h"
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +000041using namespace llvm;
Anton Korobeynikov293d5922010-02-21 20:28:15 +000042using namespace dwarf;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +000043
44//===----------------------------------------------------------------------===//
45// ELF
46//===----------------------------------------------------------------------===//
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +000047
Stephen Hines36b56882014-04-23 16:57:46 -070048MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
49 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
50 MachineModuleInfo *MMI) const {
Rafael Espindola60246a92011-04-27 23:17:57 +000051 unsigned Encoding = getPersonalityEncoding();
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -070052 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
Rafael Espindolafb66f472011-06-13 03:09:13 +000053 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
Stephen Hines36b56882014-04-23 16:57:46 -070054 TM.getSymbol(GV, Mang)->getName());
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -070055 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
56 return TM.getSymbol(GV, Mang);
57 report_fatal_error("We do not support this DWARF encoding yet!");
Rafael Espindola30deafc2011-04-16 03:51:21 +000058}
59
60void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
61 const TargetMachine &TM,
Rafael Espindola7afec9c2011-04-27 23:08:15 +000062 const MCSymbol *Sym) const {
Rafael Espindolafb66f472011-06-13 03:09:13 +000063 SmallString<64> NameData("DW.ref.");
64 NameData += Sym->getName();
65 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
Rafael Espindola018e38c2011-04-27 21:29:52 +000066 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
67 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindolafb66f472011-06-13 03:09:13 +000068 StringRef Prefix = ".data.";
69 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
Rafael Espindola018e38c2011-04-27 21:29:52 +000070 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
71 const MCSection *Sec = getContext().getELFSection(NameData,
72 ELF::SHT_PROGBITS,
73 Flags,
Rafael Espindola018e38c2011-04-27 21:29:52 +000074 0, Label->getName());
Stephen Hinesebe69fe2015-03-23 12:10:34 -070075 unsigned Size = TM.getDataLayout()->getPointerSize();
Rafael Espindola018e38c2011-04-27 21:29:52 +000076 Streamer.SwitchSection(Sec);
Stephen Hinesebe69fe2015-03-23 12:10:34 -070077 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
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700167static unsigned getELFSectionFlags(SectionKind K) {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000168 unsigned Flags = 0;
169
170 if (!K.isMetadata())
Rafael Espindola1c130262011-01-23 04:43:11 +0000171 Flags |= ELF::SHF_ALLOC;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000172
173 if (K.isText())
Rafael Espindola1c130262011-01-23 04:43:11 +0000174 Flags |= ELF::SHF_EXECINSTR;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000175
Rafael Espindolad846e3f2011-06-07 23:26:45 +0000176 if (K.isWriteable())
Rafael Espindola1c130262011-01-23 04:43:11 +0000177 Flags |= ELF::SHF_WRITE;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000178
179 if (K.isThreadLocal())
Rafael Espindola1c130262011-01-23 04:43:11 +0000180 Flags |= ELF::SHF_TLS;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000181
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700182 if (K.isMergeableCString() || K.isMergeableConst())
Rafael Espindola1c130262011-01-23 04:43:11 +0000183 Flags |= ELF::SHF_MERGE;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000184
185 if (K.isMergeableCString())
Rafael Espindola1c130262011-01-23 04:43:11 +0000186 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000187
188 return Flags;
189}
190
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700191static const Comdat *getELFComdat(const GlobalValue *GV) {
192 const Comdat *C = GV->getComdat();
193 if (!C)
194 return nullptr;
195
196 if (C->getSelectionKind() != Comdat::Any)
197 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
198 C->getName() + "' cannot be lowered.");
199
200 return C;
201}
202
Stephen Hines36b56882014-04-23 16:57:46 -0700203const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
204 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
205 const TargetMachine &TM) const {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000206 StringRef SectionName = GV->getSection();
207
208 // Infer section flags from the section name if we can.
209 Kind = getELFKindForNamedSection(SectionName, Kind);
210
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700211 StringRef Group = "";
212 unsigned Flags = getELFSectionFlags(Kind);
213 if (const Comdat *C = getELFComdat(GV)) {
214 Group = C->getName();
215 Flags |= ELF::SHF_GROUP;
216 }
Chris Lattner287df1b2010-04-08 21:34:17 +0000217 return getContext().getELFSection(SectionName,
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700218 getELFSectionType(SectionName, Kind), Flags,
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700219 /*EntrySize=*/0, Group);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000220}
221
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700222/// Return the section prefix name used by options FunctionsSections and
223/// DataSections.
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700224static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700225 if (Kind.isText())
226 return ".text";
227 if (Kind.isReadOnly())
228 return ".rodata";
229 if (Kind.isBSS())
230 return ".bss";
231 if (Kind.isThreadData())
232 return ".tdata";
233 if (Kind.isThreadBSS())
234 return ".tbss";
235 if (Kind.isDataNoRel())
236 return ".data";
237 if (Kind.isDataRelLocal())
238 return ".data.rel.local";
239 if (Kind.isDataRel())
240 return ".data.rel";
241 if (Kind.isReadOnlyWithRelLocal())
242 return ".data.rel.ro.local";
Chris Lattner43ac7212010-04-13 00:36:43 +0000243 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700244 return ".data.rel.ro";
Chris Lattner43ac7212010-04-13 00:36:43 +0000245}
246
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000247const MCSection *TargetLoweringObjectFileELF::
248SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Stephen Hines36b56882014-04-23 16:57:46 -0700249 Mangler &Mang, const TargetMachine &TM) const {
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700250 unsigned Flags = getELFSectionFlags(Kind);
251
Chris Lattner43ac7212010-04-13 00:36:43 +0000252 // If we have -ffunction-section or -fdata-section then we should emit the
253 // global value to a uniqued section specifically for it.
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700254 bool EmitUniqueSection = false;
255 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
256 if (Kind.isText())
257 EmitUniqueSection = TM.getFunctionSections();
258 else
259 EmitUniqueSection = TM.getDataSections();
260 }
261 EmitUniqueSection |= GV->hasComdat();
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000262
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700263 unsigned EntrySize = 0;
264 if (Kind.isMergeableCString()) {
265 if (Kind.isMergeable2ByteCString()) {
266 EntrySize = 2;
267 } else if (Kind.isMergeable4ByteCString()) {
268 EntrySize = 4;
269 } else {
270 EntrySize = 1;
271 assert(Kind.isMergeable1ByteCString() && "unknown string width");
Rafael Espindola5d618ef2011-02-14 22:23:49 +0000272 }
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700273 } else if (Kind.isMergeableConst()) {
274 if (Kind.isMergeableConst4()) {
275 EntrySize = 4;
276 } else if (Kind.isMergeableConst8()) {
277 EntrySize = 8;
278 } else {
279 assert(Kind.isMergeableConst16() && "unknown data width");
280 EntrySize = 16;
281 }
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000282 }
283
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700284 StringRef Group = "";
285 if (const Comdat *C = getELFComdat(GV)) {
286 Flags |= ELF::SHF_GROUP;
287 Group = C->getName();
288 }
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000289
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700290 bool UniqueSectionNames = TM.getUniqueSectionNames();
291 SmallString<128> Name;
292 if (Kind.isMergeableCString()) {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000293 // We also need alignment here.
294 // FIXME: this is getting the alignment of the character, not the
295 // alignment of the global!
296 unsigned Align =
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700297 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000298
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700299 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
300 Name = SizeSpec + utostr(Align);
301 } else if (Kind.isMergeableConst()) {
302 Name = ".rodata.cst";
303 Name += utostr(EntrySize);
304 } else {
305 Name = getSectionPrefixForGlobal(Kind);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000306 }
307
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700308 if (EmitUniqueSection && UniqueSectionNames) {
309 Name.push_back('.');
310 TM.getNameWithPrefix(Name, GV, Mang, true);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000311 }
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700312 return getContext().getELFSection(Name, getELFSectionType(Name, Kind), Flags,
313 EntrySize, Group,
314 EmitUniqueSection && !UniqueSectionNames);
315}
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000316
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700317const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
318 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
319 // If the function can be removed, produce a unique section so that
320 // the table doesn't prevent the removal.
321 const Comdat *C = F.getComdat();
322 bool EmitUniqueSection = TM.getFunctionSections() || C;
323 if (!EmitUniqueSection)
324 return ReadOnlySection;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000325
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700326 return SelectSectionForGlobal(&F, SectionKind::getReadOnly(), Mang, TM);
327}
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000328
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700329bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
330 bool UsesLabelDifference, const Function &F) const {
331 // We can always create relative relocations, so use another section
332 // that can be marked non-executable.
333 return false;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000334}
335
336/// getSectionForConstant - Given a mergeable constant with the
337/// specified size and relocation information, return a section that it
338/// should be placed in.
Stephen Hines37ed9c12014-12-01 14:51:49 -0800339const MCSection *
340TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
341 const Constant *C) const {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000342 if (Kind.isMergeableConst4() && MergeableConst4Section)
343 return MergeableConst4Section;
344 if (Kind.isMergeableConst8() && MergeableConst8Section)
345 return MergeableConst8Section;
346 if (Kind.isMergeableConst16() && MergeableConst16Section)
347 return MergeableConst16Section;
348 if (Kind.isReadOnly())
349 return ReadOnlySection;
350
351 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
352 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
353 return DataRelROSection;
354}
355
Stephen Hines37ed9c12014-12-01 14:51:49 -0800356static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
357 bool UseInitArray,
358 bool IsCtor,
359 unsigned Priority,
360 const MCSymbol *KeySym) {
361 std::string Name;
362 unsigned Type;
363 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800364 StringRef COMDAT = KeySym ? KeySym->getName() : "";
365
366 if (KeySym)
367 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov4a99f592012-01-25 22:24:19 +0000368
Rafael Espindolad6b43a32012-06-19 00:48:28 +0000369 if (UseInitArray) {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800370 if (IsCtor) {
371 Type = ELF::SHT_INIT_ARRAY;
372 Name = ".init_array";
373 } else {
374 Type = ELF::SHT_FINI_ARRAY;
375 Name = ".fini_array";
376 }
377 if (Priority != 65535) {
378 Name += '.';
379 Name += utostr(Priority);
380 }
Rafael Espindolad6b43a32012-06-19 00:48:28 +0000381 } else {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800382 // The default scheme is .ctor / .dtor, so we have to invert the priority
383 // numbering.
384 if (IsCtor)
385 Name = ".ctors";
386 else
387 Name = ".dtors";
388 if (Priority != 65535) {
389 Name += '.';
390 Name += utostr(65535 - Priority);
391 }
392 Type = ELF::SHT_PROGBITS;
Rafael Espindolad6b43a32012-06-19 00:48:28 +0000393 }
Stephen Hines37ed9c12014-12-01 14:51:49 -0800394
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700395 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Stephen Hines37ed9c12014-12-01 14:51:49 -0800396}
397
398const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
399 unsigned Priority, const MCSymbol *KeySym) const {
400 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
401 KeySym);
Anton Korobeynikov4a99f592012-01-25 22:24:19 +0000402}
403
Stephen Hinesdce4a402014-05-29 02:49:00 -0700404const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700405 unsigned Priority, const MCSymbol *KeySym) const {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800406 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
407 KeySym);
Rafael Espindolad6b43a32012-06-19 00:48:28 +0000408}
409
410void
411TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
412 UseInitArray = UseInitArray_;
413 if (!UseInitArray)
414 return;
415
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700416 StaticCtorSection = getContext().getELFSection(
417 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
418 StaticDtorSection = getContext().getELFSection(
419 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov4a99f592012-01-25 22:24:19 +0000420}
421
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000422//===----------------------------------------------------------------------===//
423// MachO
424//===----------------------------------------------------------------------===//
425
Stephen Hines36b56882014-04-23 16:57:46 -0700426/// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
427/// option string. Returns StringRef() if the option does not specify a library.
428StringRef TargetLoweringObjectFileMachO::
429getDepLibFromLinkerOpt(StringRef LinkerOption) const {
430 const char *LibCmd = "-l";
431 if (LinkerOption.startswith(LibCmd))
432 return LinkerOption.substr(strlen(LibCmd));
433 return StringRef();
434}
435
Daniel Dunbar6d49b682013-01-18 19:37:00 +0000436/// emitModuleFlags - Perform code emission for module flags.
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000437void TargetLoweringObjectFileMachO::
Bill Wendling057d5212012-02-15 22:36:15 +0000438emitModuleFlags(MCStreamer &Streamer,
439 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Stephen Hines36b56882014-04-23 16:57:46 -0700440 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000441 unsigned VersionVal = 0;
Bill Wendlingadb082c2012-04-24 11:03:50 +0000442 unsigned ImageInfoFlags = 0;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700443 MDNode *LinkerOptions = nullptr;
Bill Wendling057d5212012-02-15 22:36:15 +0000444 StringRef SectionVal;
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000445
Bill Wendling057d5212012-02-15 22:36:15 +0000446 for (ArrayRef<Module::ModuleFlagEntry>::iterator
447 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
448 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000449
450 // Ignore flags with 'Require' behavior.
Bill Wendling057d5212012-02-15 22:36:15 +0000451 if (MFE.Behavior == Module::Require)
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000452 continue;
453
Bill Wendling057d5212012-02-15 22:36:15 +0000454 StringRef Key = MFE.Key->getString();
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700455 Metadata *Val = MFE.Val;
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000456
Daniel Dunbar6d49b682013-01-18 19:37:00 +0000457 if (Key == "Objective-C Image Info Version") {
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700458 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar6d49b682013-01-18 19:37:00 +0000459 } else if (Key == "Objective-C Garbage Collection" ||
460 Key == "Objective-C GC Only" ||
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700461 Key == "Objective-C Is Simulated" ||
462 Key == "Objective-C Image Swift Version") {
463 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar6d49b682013-01-18 19:37:00 +0000464 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling057d5212012-02-15 22:36:15 +0000465 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar6d49b682013-01-18 19:37:00 +0000466 } else if (Key == "Linker Options") {
467 LinkerOptions = cast<MDNode>(Val);
468 }
469 }
470
471 // Emit the linker options if present.
472 if (LinkerOptions) {
473 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
474 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
475 SmallVector<std::string, 4> StrOptions;
476
477 // Convert to strings.
478 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
479 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
480 StrOptions.push_back(MDOption->getString());
481 }
482
483 Streamer.EmitLinkerOptions(StrOptions);
484 }
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000485 }
486
Bill Wendling057d5212012-02-15 22:36:15 +0000487 // The section is mandatory. If we don't have it, then we don't have GC info.
488 if (SectionVal.empty()) return;
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000489
Bill Wendling057d5212012-02-15 22:36:15 +0000490 StringRef Segment, Section;
491 unsigned TAA = 0, StubSize = 0;
492 bool TAAParsed;
493 std::string ErrorCode =
494 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
495 TAA, TAAParsed, StubSize);
Bill Wendling2de3ff52012-02-15 22:47:53 +0000496 if (!ErrorCode.empty())
Bill Wendling057d5212012-02-15 22:36:15 +0000497 // If invalid, report the error with report_fatal_error.
Bill Wendling2de3ff52012-02-15 22:47:53 +0000498 report_fatal_error("Invalid section specifier '" + Section + "': " +
499 ErrorCode + ".");
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000500
Bill Wendling057d5212012-02-15 22:36:15 +0000501 // Get the section.
502 const MCSectionMachO *S =
503 getContext().getMachOSection(Segment, Section, TAA, StubSize,
Bill Wendling2de3ff52012-02-15 22:47:53 +0000504 SectionKind::getDataNoRel());
Bill Wendling057d5212012-02-15 22:36:15 +0000505 Streamer.SwitchSection(S);
506 Streamer.EmitLabel(getContext().
507 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000508 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingadb082c2012-04-24 11:03:50 +0000509 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendlingb464d3f2012-02-14 21:28:13 +0000510 Streamer.AddBlankLine();
511}
512
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700513static void checkMachOComdat(const GlobalValue *GV) {
514 const Comdat *C = GV->getComdat();
515 if (!C)
516 return;
517
518 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
519 "' cannot be lowered.");
520}
521
Stephen Hines36b56882014-04-23 16:57:46 -0700522const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
523 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
524 const TargetMachine &TM) const {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000525 // Parse the section specifier and create it if valid.
526 StringRef Segment, Section;
Stuart Hastings65c8bca2011-03-19 02:42:31 +0000527 unsigned TAA = 0, StubSize = 0;
528 bool TAAParsed;
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700529
530 checkMachOComdat(GV);
531
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000532 std::string ErrorCode =
533 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings65c8bca2011-03-19 02:42:31 +0000534 TAA, TAAParsed, StubSize);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000535 if (!ErrorCode.empty()) {
Chris Lattner75361b62010-04-07 22:58:41 +0000536 // If invalid, report the error with report_fatal_error.
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000537 report_fatal_error("Global variable '" + GV->getName() +
538 "' has an invalid section specifier '" +
539 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000540 }
541
542 // Get the section.
543 const MCSectionMachO *S =
Chris Lattner22772212010-04-08 20:40:11 +0000544 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000545
Stuart Hastings6ad82d82011-02-21 17:27:17 +0000546 // If TAA wasn't set by ParseSectionSpecifier() above,
547 // use the value returned by getMachOSection() as a default.
Stuart Hastings65c8bca2011-03-19 02:42:31 +0000548 if (!TAAParsed)
Stuart Hastings6ad82d82011-02-21 17:27:17 +0000549 TAA = S->getTypeAndAttributes();
550
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000551 // Okay, now that we got the section, verify that the TAA & StubSize agree.
552 // If the user declared multiple globals with different section flags, we need
553 // to reject it here.
554 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner75361b62010-04-07 22:58:41 +0000555 // If invalid, report the error with report_fatal_error.
Benjamin Kramera7b0cb72011-11-15 16:27:03 +0000556 report_fatal_error("Global variable '" + GV->getName() +
557 "' section type or attributes does not match previous"
558 " section specifier");
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000559 }
560
561 return S;
562}
563
564const MCSection *TargetLoweringObjectFileMachO::
565SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Stephen Hines36b56882014-04-23 16:57:46 -0700566 Mangler &Mang, const TargetMachine &TM) const {
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700567 checkMachOComdat(GV);
Bill Wendlingfe128c62013-11-17 10:53:13 +0000568
569 // Handle thread local data.
570 if (Kind.isThreadBSS()) return TLSBSSSection;
571 if (Kind.isThreadData()) return TLSDataSection;
572
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000573 if (Kind.isText())
Arnold Schwaighofer9b19dfc2013-08-08 21:04:16 +0000574 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
575
576 // If this is weak/linkonce, put this in a coalescable section, either in text
577 // or data depending on if it is writable.
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000578 if (GV->isWeakForLinker()) {
579 if (Kind.isReadOnly())
Arnold Schwaighofer9b19dfc2013-08-08 21:04:16 +0000580 return ConstTextCoalSection;
581 return DataCoalSection;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000582 }
583
584 // FIXME: Alignment check should be handled by section classifier.
Chris Lattner98f15d22010-03-07 04:28:09 +0000585 if (Kind.isMergeable1ByteCString() &&
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700586 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattner98f15d22010-03-07 04:28:09 +0000587 return CStringSection;
Michael J. Spencer579d7a32010-10-27 18:52:20 +0000588
Chris Lattner98f15d22010-03-07 04:28:09 +0000589 // Do not put 16-bit arrays in the UString section if they have an
590 // externally visible label, this runs into issues with certain linker
591 // versions.
592 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700593 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattner98f15d22010-03-07 04:28:09 +0000594 return UStringSection;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000595
Stephen Hines37ed9c12014-12-01 14:51:49 -0800596 // With MachO only variables whose corresponding symbol starts with 'l' or
597 // 'L' can be merged, so we only try merging GVs with private linkage.
598 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000599 if (Kind.isMergeableConst4())
600 return FourByteConstantSection;
601 if (Kind.isMergeableConst8())
602 return EightByteConstantSection;
Stephen Hines36b56882014-04-23 16:57:46 -0700603 if (Kind.isMergeableConst16())
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000604 return SixteenByteConstantSection;
605 }
606
607 // Otherwise, if it is readonly, but not something we can specially optimize,
608 // just drop it in .const.
609 if (Kind.isReadOnly())
610 return ReadOnlySection;
611
612 // If this is marked const, put it into a const section. But if the dynamic
613 // linker needs to write to it, put it in the data segment.
614 if (Kind.isReadOnlyWithRel())
615 return ConstDataSection;
616
617 // Put zero initialized globals with strong external linkage in the
618 // DATA, __common section with the .zerofill directive.
619 if (Kind.isBSSExtern())
620 return DataCommonSection;
621
622 // Put zero initialized globals with local linkage in __DATA,__bss directive
623 // with the .zerofill directive (aka .lcomm).
624 if (Kind.isBSSLocal())
625 return DataBSSSection;
Michael J. Spencer579d7a32010-10-27 18:52:20 +0000626
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000627 // Otherwise, just drop the variable in the normal data section.
628 return DataSection;
629}
630
631const MCSection *
Stephen Hines37ed9c12014-12-01 14:51:49 -0800632TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
633 const Constant *C) const {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000634 // If this constant requires a relocation, we have to put it in the data
635 // segment, not in the text segment.
636 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
637 return ConstDataSection;
638
639 if (Kind.isMergeableConst4())
640 return FourByteConstantSection;
641 if (Kind.isMergeableConst8())
642 return EightByteConstantSection;
Stephen Hines36b56882014-04-23 16:57:46 -0700643 if (Kind.isMergeableConst16())
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000644 return SixteenByteConstantSection;
645 return ReadOnlySection; // .const
646}
647
Stephen Hines36b56882014-04-23 16:57:46 -0700648const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
649 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
650 const TargetMachine &TM, MachineModuleInfo *MMI,
651 MCStreamer &Streamer) const {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000652 // The mach-o version of this method defaults to returning a stub reference.
653
Anton Korobeynikov293d5922010-02-21 20:28:15 +0000654 if (Encoding & DW_EH_PE_indirect) {
655 MachineModuleInfoMachO &MachOMMI =
656 MMI->getObjFileInfo<MachineModuleInfoMachO>();
657
Stephen Hines36b56882014-04-23 16:57:46 -0700658 MCSymbol *SSym =
659 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov293d5922010-02-21 20:28:15 +0000660
661 // Add information about the stub reference to MachOMMI so that the stub
662 // gets emitted by the asmprinter.
Bill Wendling67121542011-10-24 23:05:43 +0000663 MachineModuleInfoImpl::StubValueTy &StubSym =
664 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
665 MachOMMI.getGVStubEntry(SSym);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700666 if (!StubSym.getPointer()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700667 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner4c6741f2010-03-15 20:37:38 +0000668 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov293d5922010-02-21 20:28:15 +0000669 }
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000670
671 return TargetLoweringObjectFile::
Anton Korobeynikov25efd6d2012-11-14 01:47:00 +0000672 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
673 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000674 }
675
Stephen Hines36b56882014-04-23 16:57:46 -0700676 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
677 TM, MMI, Streamer);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000678}
679
Stephen Hines36b56882014-04-23 16:57:46 -0700680MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
681 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
682 MachineModuleInfo *MMI) const {
Rafael Espindola7afec9c2011-04-27 23:08:15 +0000683 // The mach-o version of this method defaults to returning a stub reference.
684 MachineModuleInfoMachO &MachOMMI =
685 MMI->getObjFileInfo<MachineModuleInfoMachO>();
686
Stephen Hines36b56882014-04-23 16:57:46 -0700687 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola7afec9c2011-04-27 23:08:15 +0000688
689 // Add information about the stub reference to MachOMMI so that the stub
690 // gets emitted by the asmprinter.
Bill Wendlingd7c24942011-11-29 01:43:20 +0000691 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700692 if (!StubSym.getPointer()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700693 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola7afec9c2011-04-27 23:08:15 +0000694 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
695 }
696
697 return SSym;
698}
699
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000700//===----------------------------------------------------------------------===//
701// COFF
702//===----------------------------------------------------------------------===//
703
Chris Lattnereb40a0f2010-05-07 17:17:41 +0000704static unsigned
705getCOFFSectionFlags(SectionKind K) {
706 unsigned Flags = 0;
707
Anton Korobeynikov36335be2010-07-06 15:24:56 +0000708 if (K.isMetadata())
Chris Lattner6e5ce282010-05-07 21:49:09 +0000709 Flags |=
Daniel Dunbar94610582010-07-01 20:07:24 +0000710 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattnereb40a0f2010-05-07 17:17:41 +0000711 else if (K.isText())
712 Flags |=
Daniel Dunbar94610582010-07-01 20:07:24 +0000713 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer3931b542010-10-27 18:52:29 +0000714 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar94610582010-07-01 20:07:24 +0000715 COFF::IMAGE_SCN_CNT_CODE;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800716 else if (K.isBSS())
Chris Lattner6e5ce282010-05-07 21:49:09 +0000717 Flags |=
Daniel Dunbar94610582010-07-01 20:07:24 +0000718 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
719 COFF::IMAGE_SCN_MEM_READ |
720 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovd4a19b62012-02-11 17:26:53 +0000721 else if (K.isThreadLocal())
722 Flags |=
723 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
724 COFF::IMAGE_SCN_MEM_READ |
725 COFF::IMAGE_SCN_MEM_WRITE;
Stephen Hines37ed9c12014-12-01 14:51:49 -0800726 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattnereb40a0f2010-05-07 17:17:41 +0000727 Flags |=
Daniel Dunbar94610582010-07-01 20:07:24 +0000728 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
729 COFF::IMAGE_SCN_MEM_READ;
Chris Lattnereb40a0f2010-05-07 17:17:41 +0000730 else if (K.isWriteable())
731 Flags |=
Daniel Dunbar94610582010-07-01 20:07:24 +0000732 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
733 COFF::IMAGE_SCN_MEM_READ |
734 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattnereb40a0f2010-05-07 17:17:41 +0000735
736 return Flags;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000737}
738
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700739static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
740 const Comdat *C = GV->getComdat();
741 assert(C && "expected GV to have a Comdat!");
742
743 StringRef ComdatGVName = C->getName();
744 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
745 if (!ComdatGV)
746 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
747 "' does not exist.");
748
749 if (ComdatGV->getComdat() != C)
750 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Stephen Hines37ed9c12014-12-01 14:51:49 -0800751 "' is not a key for its COMDAT.");
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700752
753 return ComdatGV;
754}
755
756static int getSelectionForCOFF(const GlobalValue *GV) {
757 if (const Comdat *C = GV->getComdat()) {
758 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
759 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
760 ComdatKey = GA->getBaseObject();
761 if (ComdatKey == GV) {
762 switch (C->getSelectionKind()) {
763 case Comdat::Any:
764 return COFF::IMAGE_COMDAT_SELECT_ANY;
765 case Comdat::ExactMatch:
766 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
767 case Comdat::Largest:
768 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
769 case Comdat::NoDuplicates:
770 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
771 case Comdat::SameSize:
772 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
773 }
774 } else {
775 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
776 }
777 } else if (GV->isWeakForLinker()) {
778 return COFF::IMAGE_COMDAT_SELECT_ANY;
779 }
780 return 0;
781}
782
Stephen Hines36b56882014-04-23 16:57:46 -0700783const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
784 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
785 const TargetMachine &TM) const {
Michael J. Spencer4de58722012-11-13 22:04:09 +0000786 int Selection = 0;
787 unsigned Characteristics = getCOFFSectionFlags(Kind);
Stephen Hines36b56882014-04-23 16:57:46 -0700788 StringRef Name = GV->getSection();
789 StringRef COMDATSymName = "";
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700790 if (GV->hasComdat()) {
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700791 Selection = getSelectionForCOFF(GV);
792 const GlobalValue *ComdatGV;
793 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
794 ComdatGV = getComdatGVForCOFF(GV);
795 else
796 ComdatGV = GV;
797
798 if (!ComdatGV->hasPrivateLinkage()) {
799 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
800 COMDATSymName = Sym->getName();
801 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
802 } else {
803 Selection = 0;
804 }
Michael J. Spencer4de58722012-11-13 22:04:09 +0000805 }
806 return getContext().getCOFFSection(Name,
807 Characteristics,
Nico Rieck80646282013-07-06 12:13:10 +0000808 Kind,
Stephen Hines36b56882014-04-23 16:57:46 -0700809 COMDATSymName,
Nico Rieck80646282013-07-06 12:13:10 +0000810 Selection);
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000811}
812
Stephen Hines36b56882014-04-23 16:57:46 -0700813static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000814 if (Kind.isText())
Stephen Hines36b56882014-04-23 16:57:46 -0700815 return ".text";
Stephen Hinesdce4a402014-05-29 02:49:00 -0700816 if (Kind.isBSS())
Stephen Hines36b56882014-04-23 16:57:46 -0700817 return ".bss";
818 if (Kind.isThreadLocal())
819 return ".tls$";
Stephen Hines37ed9c12014-12-01 14:51:49 -0800820 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
821 return ".rdata";
822 return ".data";
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000823}
824
825
826const MCSection *TargetLoweringObjectFileCOFF::
827SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Stephen Hines36b56882014-04-23 16:57:46 -0700828 Mangler &Mang, const TargetMachine &TM) const {
829 // If we have -ffunction-sections then we should emit the global value to a
830 // uniqued section specifically for it.
831 bool EmitUniquedSection;
832 if (Kind.isText())
833 EmitUniquedSection = TM.getFunctionSections();
834 else
835 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000836
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700837 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
Stephen Hines36b56882014-04-23 16:57:46 -0700838 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner6e5ce282010-05-07 21:49:09 +0000839 unsigned Characteristics = getCOFFSectionFlags(Kind);
840
Daniel Dunbar94610582010-07-01 20:07:24 +0000841 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700842 int Selection = getSelectionForCOFF(GV);
843 if (!Selection)
844 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
845 const GlobalValue *ComdatGV;
846 if (GV->hasComdat())
847 ComdatGV = getComdatGVForCOFF(GV);
848 else
849 ComdatGV = GV;
850
851 if (!ComdatGV->hasPrivateLinkage()) {
852 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
853 StringRef COMDATSymName = Sym->getName();
854 return getContext().getCOFFSection(Name, Characteristics, Kind,
855 COMDATSymName, Selection);
856 }
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000857 }
858
859 if (Kind.isText())
David Majnemer6aa93152013-08-13 01:23:53 +0000860 return TextSection;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000861
Anton Korobeynikovd4a19b62012-02-11 17:26:53 +0000862 if (Kind.isThreadLocal())
David Majnemer6aa93152013-08-13 01:23:53 +0000863 return TLSDataSection;
Anton Korobeynikovd4a19b62012-02-11 17:26:53 +0000864
Stephen Hines37ed9c12014-12-01 14:51:49 -0800865 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemer9706d432013-08-08 01:50:52 +0000866 return ReadOnlySection;
867
Stephen Hinesdce4a402014-05-29 02:49:00 -0700868 // Note: we claim that common symbols are put in BSSSection, but they are
869 // really emitted with the magic .comm directive, which creates a symbol table
870 // entry but not a section.
871 if (Kind.isBSS() || Kind.isCommon())
David Majnemer6aa93152013-08-13 01:23:53 +0000872 return BSSSection;
873
874 return DataSection;
Anton Korobeynikov362dd0b2010-02-15 22:37:53 +0000875}
876
Stephen Hines36b56882014-04-23 16:57:46 -0700877StringRef TargetLoweringObjectFileCOFF::
878getDepLibFromLinkerOpt(StringRef LinkerOption) const {
879 const char *LibCmd = "/DEFAULTLIB:";
880 if (LinkerOption.startswith(LibCmd))
881 return LinkerOption.substr(strlen(LibCmd));
882 return StringRef();
883}
884
Reid Kleckner4b558152013-04-25 19:34:41 +0000885void TargetLoweringObjectFileCOFF::
886emitModuleFlags(MCStreamer &Streamer,
887 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Stephen Hines36b56882014-04-23 16:57:46 -0700888 Mangler &Mang, const TargetMachine &TM) const {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700889 MDNode *LinkerOptions = nullptr;
Reid Kleckner4b558152013-04-25 19:34:41 +0000890
891 // Look for the "Linker Options" flag, since it's the only one we support.
892 for (ArrayRef<Module::ModuleFlagEntry>::iterator
893 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
894 const Module::ModuleFlagEntry &MFE = *i;
895 StringRef Key = MFE.Key->getString();
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700896 Metadata *Val = MFE.Val;
Reid Kleckner4b558152013-04-25 19:34:41 +0000897 if (Key == "Linker Options") {
898 LinkerOptions = cast<MDNode>(Val);
899 break;
900 }
901 }
902 if (!LinkerOptions)
903 return;
904
905 // Emit the linker options to the linker .drectve section. According to the
906 // spec, this section is a space-separated string containing flags for linker.
907 const MCSection *Sec = getDrectveSection();
908 Streamer.SwitchSection(Sec);
909 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
910 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
911 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
912 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
Reid Kleckner4b558152013-04-25 19:34:41 +0000913 // Lead with a space for consistency with our dllexport implementation.
Stephen Hinesebe69fe2015-03-23 12:10:34 -0700914 std::string Directive(" ");
915 Directive.append(MDOption->getString());
916 Streamer.EmitBytes(Directive);
Reid Kleckner4b558152013-04-25 19:34:41 +0000917 }
918 }
919}
Stephen Hinesdce4a402014-05-29 02:49:00 -0700920
Stephen Hinesdce4a402014-05-29 02:49:00 -0700921const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700922 unsigned Priority, const MCSymbol *KeySym) const {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800923 return getContext().getAssociativeCOFFSection(
924 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700925}
926
927const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Stephen Hinesc6a4f5e2014-07-21 00:45:20 -0700928 unsigned Priority, const MCSymbol *KeySym) const {
Stephen Hines37ed9c12014-12-01 14:51:49 -0800929 return getContext().getAssociativeCOFFSection(
930 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700931}