blob: 17bd024ad283a5d330162e36fea973bb5cc18827 [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"
Eric Christopherd9134482014-08-04 21:25:23 +000040#include "llvm/Target/TargetSubtargetInfo.h"
Anton Korobeynikovab663a02010-02-15 22:37:53 +000041using namespace llvm;
Anton Korobeynikov31a92122010-02-21 20:28:15 +000042using namespace dwarf;
Anton Korobeynikovab663a02010-02-15 22:37:53 +000043
44//===----------------------------------------------------------------------===//
45// ELF
46//===----------------------------------------------------------------------===//
Anton Korobeynikovab663a02010-02-15 22:37:53 +000047
Rafael Espindoladaeafb42014-02-19 17:23:20 +000048MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
49 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
50 MachineModuleInfo *MMI) const {
Rafael Espindolace83fc32011-04-27 23:17:57 +000051 unsigned Encoding = getPersonalityEncoding();
Logan Chienc0029812014-05-30 16:48:56 +000052 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000053 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +000054 TM.getSymbol(GV, Mang)->getName());
Logan Chienc0029812014-05-30 16:48:56 +000055 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 Espindolaa83b1772011-04-16 03:51:21 +000058}
59
60void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
61 const TargetMachine &TM,
Rafael Espindola08704342011-04-27 23:08:15 +000062 const MCSymbol *Sym) const {
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000063 SmallString<64> NameData("DW.ref.");
64 NameData += Sym->getName();
65 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
Rafael Espindola39897762011-04-27 21:29:52 +000066 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
67 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
Rafael Espindola51d2d7a2011-06-13 03:09:13 +000068 StringRef Prefix = ".data.";
69 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
Rafael Espindola39897762011-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 Espindola39897762011-04-27 21:29:52 +000074 0, Label->getName());
Eric Christopher8b770652015-01-26 19:03:15 +000075 unsigned Size = TM.getDataLayout()->getPointerSize();
Rafael Espindola39897762011-04-27 21:29:52 +000076 Streamer.SwitchSection(Sec);
Eric Christopher8b770652015-01-26 19:03:15 +000077 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
Rafael Espindola39897762011-04-27 21:29:52 +000078 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
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
Rafael Espindolaa092f172015-02-04 21:27:24 +0000169getELFSectionFlags(SectionKind K, bool InCOMDAT) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000170 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
Rafael Espindolaf8d662a2015-02-05 14:57:47 +0000184 // FIXME: There is nothing in ELF preventing an SHF_MERGE from being
185 // in a comdat. We just avoid it for now because we don't print
186 // those .sections correctly.
Rafael Espindolaa092f172015-02-04 21:27:24 +0000187 if (!InCOMDAT && (K.isMergeableCString() || K.isMergeableConst()))
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000188 Flags |= ELF::SHF_MERGE;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000189
190 if (K.isMergeableCString())
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000191 Flags |= ELF::SHF_STRINGS;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000192
193 return Flags;
194}
195
David Majnemerdad0a642014-06-27 18:19:56 +0000196static const Comdat *getELFComdat(const GlobalValue *GV) {
197 const Comdat *C = GV->getComdat();
198 if (!C)
199 return nullptr;
200
201 if (C->getSelectionKind() != Comdat::Any)
202 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
203 C->getName() + "' cannot be lowered.");
204
205 return C;
206}
207
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000208const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
209 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
210 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000211 StringRef SectionName = GV->getSection();
212
213 // Infer section flags from the section name if we can.
214 Kind = getELFKindForNamedSection(SectionName, Kind);
215
David Majnemerdad0a642014-06-27 18:19:56 +0000216 StringRef Group = "";
Rafael Espindolaa092f172015-02-04 21:27:24 +0000217 unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
David Majnemerdad0a642014-06-27 18:19:56 +0000218 if (const Comdat *C = getELFComdat(GV)) {
219 Group = C->getName();
220 Flags |= ELF::SHF_GROUP;
221 }
Chris Lattner80c34592010-04-08 21:34:17 +0000222 return getContext().getELFSection(SectionName,
David Majnemerdad0a642014-06-27 18:19:56 +0000223 getELFSectionType(SectionName, Kind), Flags,
Rafael Espindolaba31e272015-01-29 17:33:21 +0000224 /*EntrySize=*/0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000225}
226
Rafael Espindola25d2c202015-02-11 14:44:17 +0000227/// Return the section prefix name used by options FunctionsSections and
228/// DataSections.
David Majnemer102ff692014-06-24 16:01:53 +0000229static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
Rafael Espindola25d2c202015-02-11 14:44:17 +0000230 if (Kind.isText())
Chandler Carruthd99f4272015-02-13 07:52:39 +0000231 return ".text.";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000232 if (Kind.isReadOnly())
Chandler Carruthd99f4272015-02-13 07:52:39 +0000233 return ".rodata.";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000234 if (Kind.isBSS())
Chandler Carruthd99f4272015-02-13 07:52:39 +0000235 return ".bss.";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000236 if (Kind.isThreadData())
Chandler Carruthd99f4272015-02-13 07:52:39 +0000237 return ".tdata.";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000238 if (Kind.isThreadBSS())
Chandler Carruthd99f4272015-02-13 07:52:39 +0000239 return ".tbss.";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000240 if (Kind.isDataNoRel())
Chandler Carruthd99f4272015-02-13 07:52:39 +0000241 return ".data.";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000242 if (Kind.isDataRelLocal())
Chandler Carruthd99f4272015-02-13 07:52:39 +0000243 return ".data.rel.local.";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000244 if (Kind.isDataRel())
Chandler Carruthd99f4272015-02-13 07:52:39 +0000245 return ".data.rel.";
Rafael Espindola25d2c202015-02-11 14:44:17 +0000246 if (Kind.isReadOnlyWithRelLocal())
Chandler Carruthd99f4272015-02-13 07:52:39 +0000247 return ".data.rel.ro.local.";
Chris Lattner5b212a32010-04-13 00:36:43 +0000248 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
Chandler Carruthd99f4272015-02-13 07:52:39 +0000249 return ".data.rel.ro.";
Chris Lattner5b212a32010-04-13 00:36:43 +0000250}
251
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000252const MCSection *TargetLoweringObjectFileELF::
253SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000254 Mangler &Mang, const TargetMachine &TM) const {
Rafael Espindolaa092f172015-02-04 21:27:24 +0000255 unsigned Flags = getELFSectionFlags(Kind, GV->hasComdat());
Rafael Espindolafad39012015-01-29 12:43:28 +0000256
Chris Lattner5b212a32010-04-13 00:36:43 +0000257 // If we have -ffunction-section or -fdata-section then we should emit the
258 // global value to a uniqued section specifically for it.
Rafael Espindolafad39012015-01-29 12:43:28 +0000259 bool EmitUniquedSection = false;
260 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
261 if (Kind.isText())
262 EmitUniquedSection = TM.getFunctionSections();
263 else
264 EmitUniquedSection = TM.getDataSections();
265 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000266
Rafael Espindolafad39012015-01-29 12:43:28 +0000267 if (EmitUniquedSection || GV->hasComdat()) {
David Majnemer102ff692014-06-24 16:01:53 +0000268 StringRef Prefix = getSectionPrefixForGlobal(Kind);
Chris Lattner5b212a32010-04-13 00:36:43 +0000269
David Majnemer102ff692014-06-24 16:01:53 +0000270 SmallString<128> Name(Prefix);
Chandler Carruthd99f4272015-02-13 07:52:39 +0000271 TM.getNameWithPrefix(Name, GV, Mang, true);
272
Rafael Espindola70d80152011-02-14 22:23:49 +0000273 StringRef Group = "";
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000274 if (const Comdat *C = getELFComdat(GV)) {
Rafael Espindola70d80152011-02-14 22:23:49 +0000275 Flags |= ELF::SHF_GROUP;
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000276 Group = C->getName();
Rafael Espindola70d80152011-02-14 22:23:49 +0000277 }
278
Chandler Carruthd99f4272015-02-13 07:52:39 +0000279 return getContext().getELFSection(
280 Name.str(), getELFSectionType(Name.str(), Kind), Flags, 0, Group);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000281 }
282
283 if (Kind.isText()) return TextSection;
284
Rafael Espindolaa05b3b72015-01-28 17:54:19 +0000285 if (Kind.isMergeableCString()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000286
287 // We also need alignment here.
288 // FIXME: this is getting the alignment of the character, not the
289 // alignment of the global!
290 unsigned Align =
Eric Christopher8b770652015-01-26 19:03:15 +0000291 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000292
Rafael Espindolaba31e272015-01-29 17:33:21 +0000293 unsigned EntrySize = 1;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000294 if (Kind.isMergeable2ByteCString())
Rafael Espindolaba31e272015-01-29 17:33:21 +0000295 EntrySize = 2;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000296 else if (Kind.isMergeable4ByteCString())
Rafael Espindolaba31e272015-01-29 17:33:21 +0000297 EntrySize = 4;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000298 else
299 assert(Kind.isMergeable1ByteCString() && "unknown string width");
300
Rafael Espindolaba31e272015-01-29 17:33:21 +0000301 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000302 std::string Name = SizeSpec + utostr(Align);
Rafael Espindolaba31e272015-01-29 17:33:21 +0000303 return getContext().getELFSection(
304 Name, ELF::SHT_PROGBITS,
305 ELF::SHF_ALLOC | ELF::SHF_MERGE | ELF::SHF_STRINGS, EntrySize, "");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000306 }
307
308 if (Kind.isMergeableConst()) {
309 if (Kind.isMergeableConst4() && MergeableConst4Section)
310 return MergeableConst4Section;
311 if (Kind.isMergeableConst8() && MergeableConst8Section)
312 return MergeableConst8Section;
313 if (Kind.isMergeableConst16() && MergeableConst16Section)
314 return MergeableConst16Section;
315 return ReadOnlySection; // .const
316 }
317
318 if (Kind.isReadOnly()) return ReadOnlySection;
319
320 if (Kind.isThreadData()) return TLSDataSection;
321 if (Kind.isThreadBSS()) return TLSBSSSection;
322
323 // Note: we claim that common symbols are put in BSSSection, but they are
324 // really emitted with the magic .comm directive, which creates a symbol table
325 // entry but not a section.
326 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
327
328 if (Kind.isDataNoRel()) return DataSection;
329 if (Kind.isDataRelLocal()) return DataRelLocalSection;
330 if (Kind.isDataRel()) return DataRelSection;
331 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
332
333 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
334 return DataRelROSection;
335}
336
Rafael Espindola29786d42015-02-12 17:16:46 +0000337const MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
338 const Function &F, Mangler &Mang, const TargetMachine &TM) const {
339 // If the function can be removed, produce a unique section so that
340 // the table doesn't prevent the removal.
341 const Comdat *C = F.getComdat();
342 bool EmitUniqueSection = TM.getFunctionSections() || C;
343 if (!EmitUniqueSection)
344 return ReadOnlySection;
345
346 SmallString<128> Name(".rodata.");
347 TM.getNameWithPrefix(Name, &F, Mang, true);
348
349 unsigned Flags = ELF::SHF_ALLOC;
350 StringRef Group = "";
351 if (C) {
352 Flags |= ELF::SHF_GROUP;
353 Group = C->getName();
354 }
355
356 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags, 0, Group);
357}
358
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000359/// getSectionForConstant - Given a mergeable constant with the
360/// specified size and relocation information, return a section that it
361/// should be placed in.
David Majnemer8bce66b2014-07-14 22:57:27 +0000362const MCSection *
363TargetLoweringObjectFileELF::getSectionForConstant(SectionKind Kind,
364 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000365 if (Kind.isMergeableConst4() && MergeableConst4Section)
366 return MergeableConst4Section;
367 if (Kind.isMergeableConst8() && MergeableConst8Section)
368 return MergeableConst8Section;
369 if (Kind.isMergeableConst16() && MergeableConst16Section)
370 return MergeableConst16Section;
371 if (Kind.isReadOnly())
372 return ReadOnlySection;
373
374 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
375 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
376 return DataRelROSection;
377}
378
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000379static const MCSectionELF *getStaticStructorSection(MCContext &Ctx,
380 bool UseInitArray,
381 bool IsCtor,
382 unsigned Priority,
383 const MCSymbol *KeySym) {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000384 std::string Name;
385 unsigned Type;
386 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
Rafael Espindolac4b42532014-09-04 23:03:58 +0000387 StringRef COMDAT = KeySym ? KeySym->getName() : "";
388
389 if (KeySym)
390 Flags |= ELF::SHF_GROUP;
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000391
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000392 if (UseInitArray) {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000393 if (IsCtor) {
394 Type = ELF::SHT_INIT_ARRAY;
395 Name = ".init_array";
396 } else {
397 Type = ELF::SHT_FINI_ARRAY;
398 Name = ".fini_array";
399 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000400 if (Priority != 65535) {
401 Name += '.';
402 Name += utostr(Priority);
403 }
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000404 } else {
Rafael Espindolac4b42532014-09-04 23:03:58 +0000405 // The default scheme is .ctor / .dtor, so we have to invert the priority
406 // numbering.
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000407 if (IsCtor)
408 Name = ".ctors";
409 else
410 Name = ".dtors";
Rafael Espindolac4b42532014-09-04 23:03:58 +0000411 if (Priority != 65535) {
412 Name += '.';
413 Name += utostr(65535 - Priority);
414 }
415 Type = ELF::SHT_PROGBITS;
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000416 }
Rafael Espindolac4b42532014-09-04 23:03:58 +0000417
Rafael Espindolaba31e272015-01-29 17:33:21 +0000418 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000419}
420
421const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
422 unsigned Priority, const MCSymbol *KeySym) const {
423 return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
424 KeySym);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000425}
426
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000427const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000428 unsigned Priority, const MCSymbol *KeySym) const {
Rafael Espindola7c7d7b92014-09-05 00:02:50 +0000429 return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
430 KeySym);
Rafael Espindolaca3e0ee2012-06-19 00:48:28 +0000431}
432
433void
434TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
435 UseInitArray = UseInitArray_;
436 if (!UseInitArray)
437 return;
438
Rafael Espindolaba31e272015-01-29 17:33:21 +0000439 StaticCtorSection = getContext().getELFSection(
440 ".init_array", ELF::SHT_INIT_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
441 StaticDtorSection = getContext().getELFSection(
442 ".fini_array", ELF::SHT_FINI_ARRAY, ELF::SHF_WRITE | ELF::SHF_ALLOC);
Anton Korobeynikov7722a2d2012-01-25 22:24:19 +0000443}
444
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000445//===----------------------------------------------------------------------===//
446// MachO
447//===----------------------------------------------------------------------===//
448
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000449/// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
450/// option string. Returns StringRef() if the option does not specify a library.
451StringRef TargetLoweringObjectFileMachO::
452getDepLibFromLinkerOpt(StringRef LinkerOption) const {
453 const char *LibCmd = "-l";
454 if (LinkerOption.startswith(LibCmd))
455 return LinkerOption.substr(strlen(LibCmd));
456 return StringRef();
457}
458
Daniel Dunbar95856122013-01-18 19:37:00 +0000459/// emitModuleFlags - Perform code emission for module flags.
Bill Wendling06df7722012-02-14 21:28:13 +0000460void TargetLoweringObjectFileMachO::
Bill Wendling734909a2012-02-15 22:36:15 +0000461emitModuleFlags(MCStreamer &Streamer,
462 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000463 Mangler &Mang, const TargetMachine &TM) const {
Bill Wendling06df7722012-02-14 21:28:13 +0000464 unsigned VersionVal = 0;
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000465 unsigned ImageInfoFlags = 0;
Craig Topperc0196b12014-04-14 00:51:57 +0000466 MDNode *LinkerOptions = nullptr;
Bill Wendling734909a2012-02-15 22:36:15 +0000467 StringRef SectionVal;
Bill Wendling06df7722012-02-14 21:28:13 +0000468
Bill Wendling734909a2012-02-15 22:36:15 +0000469 for (ArrayRef<Module::ModuleFlagEntry>::iterator
470 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
471 const Module::ModuleFlagEntry &MFE = *i;
Bill Wendling06df7722012-02-14 21:28:13 +0000472
473 // Ignore flags with 'Require' behavior.
Bill Wendling734909a2012-02-15 22:36:15 +0000474 if (MFE.Behavior == Module::Require)
Bill Wendling06df7722012-02-14 21:28:13 +0000475 continue;
476
Bill Wendling734909a2012-02-15 22:36:15 +0000477 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000478 Metadata *Val = MFE.Val;
Bill Wendling06df7722012-02-14 21:28:13 +0000479
Daniel Dunbar95856122013-01-18 19:37:00 +0000480 if (Key == "Objective-C Image Info Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000481 VersionVal = mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000482 } else if (Key == "Objective-C Garbage Collection" ||
483 Key == "Objective-C GC Only" ||
Manman Renc98ec0e2014-11-21 19:24:55 +0000484 Key == "Objective-C Is Simulated" ||
485 Key == "Objective-C Image Swift Version") {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000486 ImageInfoFlags |= mdconst::extract<ConstantInt>(Val)->getZExtValue();
Daniel Dunbar95856122013-01-18 19:37:00 +0000487 } else if (Key == "Objective-C Image Info Section") {
Bill Wendling734909a2012-02-15 22:36:15 +0000488 SectionVal = cast<MDString>(Val)->getString();
Daniel Dunbar95856122013-01-18 19:37:00 +0000489 } else if (Key == "Linker Options") {
490 LinkerOptions = cast<MDNode>(Val);
491 }
492 }
493
494 // Emit the linker options if present.
495 if (LinkerOptions) {
496 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
497 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
498 SmallVector<std::string, 4> StrOptions;
499
500 // Convert to strings.
501 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
502 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
503 StrOptions.push_back(MDOption->getString());
504 }
505
506 Streamer.EmitLinkerOptions(StrOptions);
507 }
Bill Wendling06df7722012-02-14 21:28:13 +0000508 }
509
Bill Wendling734909a2012-02-15 22:36:15 +0000510 // The section is mandatory. If we don't have it, then we don't have GC info.
511 if (SectionVal.empty()) return;
Bill Wendling06df7722012-02-14 21:28:13 +0000512
Bill Wendling734909a2012-02-15 22:36:15 +0000513 StringRef Segment, Section;
514 unsigned TAA = 0, StubSize = 0;
515 bool TAAParsed;
516 std::string ErrorCode =
517 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
518 TAA, TAAParsed, StubSize);
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000519 if (!ErrorCode.empty())
Bill Wendling734909a2012-02-15 22:36:15 +0000520 // If invalid, report the error with report_fatal_error.
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000521 report_fatal_error("Invalid section specifier '" + Section + "': " +
522 ErrorCode + ".");
Bill Wendling06df7722012-02-14 21:28:13 +0000523
Bill Wendling734909a2012-02-15 22:36:15 +0000524 // Get the section.
525 const MCSectionMachO *S =
526 getContext().getMachOSection(Segment, Section, TAA, StubSize,
Bill Wendlinga0009ee2012-02-15 22:47:53 +0000527 SectionKind::getDataNoRel());
Bill Wendling734909a2012-02-15 22:36:15 +0000528 Streamer.SwitchSection(S);
529 Streamer.EmitLabel(getContext().
530 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
Bill Wendling06df7722012-02-14 21:28:13 +0000531 Streamer.EmitIntValue(VersionVal, 4);
Bill Wendlingf1b14b72012-04-24 11:03:50 +0000532 Streamer.EmitIntValue(ImageInfoFlags, 4);
Bill Wendling06df7722012-02-14 21:28:13 +0000533 Streamer.AddBlankLine();
534}
535
David Majnemerdad0a642014-06-27 18:19:56 +0000536static void checkMachOComdat(const GlobalValue *GV) {
537 const Comdat *C = GV->getComdat();
538 if (!C)
539 return;
540
541 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
542 "' cannot be lowered.");
543}
544
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000545const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
546 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
547 const TargetMachine &TM) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000548 // Parse the section specifier and create it if valid.
549 StringRef Segment, Section;
Stuart Hastings12d53122011-03-19 02:42:31 +0000550 unsigned TAA = 0, StubSize = 0;
551 bool TAAParsed;
David Majnemerdad0a642014-06-27 18:19:56 +0000552
553 checkMachOComdat(GV);
554
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000555 std::string ErrorCode =
556 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
Stuart Hastings12d53122011-03-19 02:42:31 +0000557 TAA, TAAParsed, StubSize);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000558 if (!ErrorCode.empty()) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000559 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000560 report_fatal_error("Global variable '" + GV->getName() +
561 "' has an invalid section specifier '" +
562 GV->getSection() + "': " + ErrorCode + ".");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000563 }
564
565 // Get the section.
566 const MCSectionMachO *S =
Chris Lattner433d4062010-04-08 20:40:11 +0000567 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000568
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000569 // If TAA wasn't set by ParseSectionSpecifier() above,
570 // use the value returned by getMachOSection() as a default.
Stuart Hastings12d53122011-03-19 02:42:31 +0000571 if (!TAAParsed)
Stuart Hastingsb4863a42011-02-21 17:27:17 +0000572 TAA = S->getTypeAndAttributes();
573
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000574 // Okay, now that we got the section, verify that the TAA & StubSize agree.
575 // If the user declared multiple globals with different section flags, we need
576 // to reject it here.
577 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
Chris Lattner2104b8d2010-04-07 22:58:41 +0000578 // If invalid, report the error with report_fatal_error.
Benjamin Kramer1f97a5a2011-11-15 16:27:03 +0000579 report_fatal_error("Global variable '" + GV->getName() +
580 "' section type or attributes does not match previous"
581 " section specifier");
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000582 }
583
584 return S;
585}
586
587const MCSection *TargetLoweringObjectFileMachO::
588SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000589 Mangler &Mang, const TargetMachine &TM) const {
David Majnemerdad0a642014-06-27 18:19:56 +0000590 checkMachOComdat(GV);
Bill Wendling25b61db2013-11-17 10:53:13 +0000591
592 // Handle thread local data.
593 if (Kind.isThreadBSS()) return TLSBSSSection;
594 if (Kind.isThreadData()) return TLSDataSection;
595
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000596 if (Kind.isText())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000597 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
598
599 // If this is weak/linkonce, put this in a coalescable section, either in text
600 // or data depending on if it is writable.
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000601 if (GV->isWeakForLinker()) {
602 if (Kind.isReadOnly())
Arnold Schwaighoferc31c2de2013-08-08 21:04:16 +0000603 return ConstTextCoalSection;
604 return DataCoalSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000605 }
606
607 // FIXME: Alignment check should be handled by section classifier.
Chris Lattneref2f8042010-03-07 04:28:09 +0000608 if (Kind.isMergeable1ByteCString() &&
Eric Christopher8b770652015-01-26 19:03:15 +0000609 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000610 return CStringSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000611
Chris Lattneref2f8042010-03-07 04:28:09 +0000612 // Do not put 16-bit arrays in the UString section if they have an
613 // externally visible label, this runs into issues with certain linker
614 // versions.
615 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
Eric Christopher8b770652015-01-26 19:03:15 +0000616 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
Chris Lattneref2f8042010-03-07 04:28:09 +0000617 return UStringSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000618
Rafael Espindolab43d51d2014-08-28 20:13:31 +0000619 // With MachO only variables whose corresponding symbol starts with 'l' or
620 // 'L' can be merged, so we only try merging GVs with private linkage.
621 if (GV->hasPrivateLinkage() && Kind.isMergeableConst()) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000622 if (Kind.isMergeableConst4())
623 return FourByteConstantSection;
624 if (Kind.isMergeableConst8())
625 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000626 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000627 return SixteenByteConstantSection;
628 }
629
630 // Otherwise, if it is readonly, but not something we can specially optimize,
631 // just drop it in .const.
632 if (Kind.isReadOnly())
633 return ReadOnlySection;
634
635 // If this is marked const, put it into a const section. But if the dynamic
636 // linker needs to write to it, put it in the data segment.
637 if (Kind.isReadOnlyWithRel())
638 return ConstDataSection;
639
640 // Put zero initialized globals with strong external linkage in the
641 // DATA, __common section with the .zerofill directive.
642 if (Kind.isBSSExtern())
643 return DataCommonSection;
644
645 // Put zero initialized globals with local linkage in __DATA,__bss directive
646 // with the .zerofill directive (aka .lcomm).
647 if (Kind.isBSSLocal())
648 return DataBSSSection;
Michael J. Spencerfbdab0d2010-10-27 18:52:20 +0000649
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000650 // Otherwise, just drop the variable in the normal data section.
651 return DataSection;
652}
653
654const MCSection *
David Majnemer8bce66b2014-07-14 22:57:27 +0000655TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind,
656 const Constant *C) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000657 // If this constant requires a relocation, we have to put it in the data
658 // segment, not in the text segment.
659 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
660 return ConstDataSection;
661
662 if (Kind.isMergeableConst4())
663 return FourByteConstantSection;
664 if (Kind.isMergeableConst8())
665 return EightByteConstantSection;
Rafael Espindola1f3de492014-02-13 23:16:11 +0000666 if (Kind.isMergeableConst16())
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000667 return SixteenByteConstantSection;
668 return ReadOnlySection; // .const
669}
670
Rafael Espindola15b26692014-02-09 14:50:44 +0000671const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
672 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000673 const TargetMachine &TM, MachineModuleInfo *MMI,
674 MCStreamer &Streamer) const {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000675 // The mach-o version of this method defaults to returning a stub reference.
676
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000677 if (Encoding & DW_EH_PE_indirect) {
678 MachineModuleInfoMachO &MachOMMI =
679 MMI->getObjFileInfo<MachineModuleInfoMachO>();
680
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000681 MCSymbol *SSym =
682 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000683
684 // Add information about the stub reference to MachOMMI so that the stub
685 // gets emitted by the asmprinter.
Bill Wendling57e3aaa2011-10-24 23:05:43 +0000686 MachineModuleInfoImpl::StubValueTy &StubSym =
687 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
688 MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000689 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000690 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Chris Lattner2ea586b2010-03-15 20:37:38 +0000691 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
Anton Korobeynikov31a92122010-02-21 20:28:15 +0000692 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000693
694 return TargetLoweringObjectFile::
Anton Korobeynikove42af362012-11-14 01:47:00 +0000695 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
696 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000697 }
698
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000699 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
700 TM, MMI, Streamer);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000701}
702
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000703MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
704 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
705 MachineModuleInfo *MMI) const {
Rafael Espindola08704342011-04-27 23:08:15 +0000706 // The mach-o version of this method defaults to returning a stub reference.
707 MachineModuleInfoMachO &MachOMMI =
708 MMI->getObjFileInfo<MachineModuleInfoMachO>();
709
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000710 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
Rafael Espindola08704342011-04-27 23:08:15 +0000711
712 // Add information about the stub reference to MachOMMI so that the stub
713 // gets emitted by the asmprinter.
Bill Wendlinge4cc3322011-11-29 01:43:20 +0000714 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
Craig Topperc0196b12014-04-14 00:51:57 +0000715 if (!StubSym.getPointer()) {
Rafael Espindolaa3ad4e62014-02-19 20:30:41 +0000716 MCSymbol *Sym = TM.getSymbol(GV, Mang);
Rafael Espindola08704342011-04-27 23:08:15 +0000717 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
718 }
719
720 return SSym;
721}
722
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000723//===----------------------------------------------------------------------===//
724// COFF
725//===----------------------------------------------------------------------===//
726
Chris Lattner87cffa92010-05-07 17:17:41 +0000727static unsigned
728getCOFFSectionFlags(SectionKind K) {
729 unsigned Flags = 0;
730
Anton Korobeynikove4152302010-07-06 15:24:56 +0000731 if (K.isMetadata())
Chris Lattner02844932010-05-07 21:49:09 +0000732 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000733 COFF::IMAGE_SCN_MEM_DISCARDABLE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000734 else if (K.isText())
735 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000736 COFF::IMAGE_SCN_MEM_EXECUTE |
Michael J. Spencer0f83d962010-10-27 18:52:29 +0000737 COFF::IMAGE_SCN_MEM_READ |
Daniel Dunbar329d2022010-07-01 20:07:24 +0000738 COFF::IMAGE_SCN_CNT_CODE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000739 else if (K.isBSS())
Chris Lattner02844932010-05-07 21:49:09 +0000740 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000741 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
742 COFF::IMAGE_SCN_MEM_READ |
743 COFF::IMAGE_SCN_MEM_WRITE;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000744 else if (K.isThreadLocal())
745 Flags |=
746 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
747 COFF::IMAGE_SCN_MEM_READ |
748 COFF::IMAGE_SCN_MEM_WRITE;
David Majnemerb8dbebb2014-09-20 07:31:46 +0000749 else if (K.isReadOnly() || K.isReadOnlyWithRel())
Chris Lattner87cffa92010-05-07 17:17:41 +0000750 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000751 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
752 COFF::IMAGE_SCN_MEM_READ;
Chris Lattner87cffa92010-05-07 17:17:41 +0000753 else if (K.isWriteable())
754 Flags |=
Daniel Dunbar329d2022010-07-01 20:07:24 +0000755 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
756 COFF::IMAGE_SCN_MEM_READ |
757 COFF::IMAGE_SCN_MEM_WRITE;
Chris Lattner87cffa92010-05-07 17:17:41 +0000758
759 return Flags;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000760}
761
Benjamin Kramer6cbe6702014-07-07 14:47:51 +0000762static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
David Majnemerdad0a642014-06-27 18:19:56 +0000763 const Comdat *C = GV->getComdat();
764 assert(C && "expected GV to have a Comdat!");
765
766 StringRef ComdatGVName = C->getName();
767 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
768 if (!ComdatGV)
769 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
770 "' does not exist.");
771
772 if (ComdatGV->getComdat() != C)
773 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
Hans Wennborgc0f0c512014-09-19 01:14:56 +0000774 "' is not a key for its COMDAT.");
David Majnemerdad0a642014-06-27 18:19:56 +0000775
776 return ComdatGV;
777}
778
779static int getSelectionForCOFF(const GlobalValue *GV) {
780 if (const Comdat *C = GV->getComdat()) {
781 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
782 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
783 ComdatKey = GA->getBaseObject();
784 if (ComdatKey == GV) {
785 switch (C->getSelectionKind()) {
786 case Comdat::Any:
787 return COFF::IMAGE_COMDAT_SELECT_ANY;
788 case Comdat::ExactMatch:
789 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
790 case Comdat::Largest:
791 return COFF::IMAGE_COMDAT_SELECT_LARGEST;
792 case Comdat::NoDuplicates:
793 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
794 case Comdat::SameSize:
795 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
796 }
797 } else {
798 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
799 }
800 } else if (GV->isWeakForLinker()) {
801 return COFF::IMAGE_COMDAT_SELECT_ANY;
802 }
803 return 0;
804}
805
Rafael Espindoladaeafb42014-02-19 17:23:20 +0000806const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
807 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
808 const TargetMachine &TM) const {
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000809 int Selection = 0;
810 unsigned Characteristics = getCOFFSectionFlags(Kind);
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000811 StringRef Name = GV->getSection();
812 StringRef COMDATSymName = "";
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000813 if (GV->hasComdat()) {
David Majnemerdad0a642014-06-27 18:19:56 +0000814 Selection = getSelectionForCOFF(GV);
815 const GlobalValue *ComdatGV;
816 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
817 ComdatGV = getComdatGVForCOFF(GV);
818 else
819 ComdatGV = GV;
820
821 if (!ComdatGV->hasPrivateLinkage()) {
822 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
823 COMDATSymName = Sym->getName();
824 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
825 } else {
826 Selection = 0;
827 }
Michael J. Spencerf1aef752012-11-13 22:04:09 +0000828 }
829 return getContext().getCOFFSection(Name,
830 Characteristics,
Nico Riecka37acf72013-07-06 12:13:10 +0000831 Kind,
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000832 COMDATSymName,
Nico Riecka37acf72013-07-06 12:13:10 +0000833 Selection);
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000834}
835
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000836static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000837 if (Kind.isText())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000838 return ".text";
David Majnemera9bdb322014-04-08 22:33:40 +0000839 if (Kind.isBSS())
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000840 return ".bss";
841 if (Kind.isThreadLocal())
Rafael Espindola3c8e1472013-11-27 15:52:11 +0000842 return ".tls$";
David Majnemer597be2d2014-09-22 20:39:23 +0000843 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
844 return ".rdata";
845 return ".data";
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000846}
847
848
849const MCSection *TargetLoweringObjectFileCOFF::
850SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000851 Mangler &Mang, const TargetMachine &TM) const {
David Majnemer93389842014-03-23 17:47:39 +0000852 // If we have -ffunction-sections then we should emit the global value to a
853 // uniqued section specifically for it.
David Majnemer273bff42014-03-25 06:14:26 +0000854 bool EmitUniquedSection;
855 if (Kind.isText())
856 EmitUniquedSection = TM.getFunctionSections();
857 else
858 EmitUniquedSection = TM.getDataSections();
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000859
Rafael Espindola12ca34f2015-01-19 15:16:06 +0000860 if ((EmitUniquedSection && !Kind.isCommon()) || GV->hasComdat()) {
Rafael Espindola2d30ae22013-11-27 01:18:37 +0000861 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
Chris Lattner02844932010-05-07 21:49:09 +0000862 unsigned Characteristics = getCOFFSectionFlags(Kind);
863
Daniel Dunbar329d2022010-07-01 20:07:24 +0000864 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
David Majnemerdad0a642014-06-27 18:19:56 +0000865 int Selection = getSelectionForCOFF(GV);
866 if (!Selection)
867 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
868 const GlobalValue *ComdatGV;
869 if (GV->hasComdat())
870 ComdatGV = getComdatGVForCOFF(GV);
871 else
872 ComdatGV = GV;
873
874 if (!ComdatGV->hasPrivateLinkage()) {
875 MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
876 StringRef COMDATSymName = Sym->getName();
877 return getContext().getCOFFSection(Name, Characteristics, Kind,
878 COMDATSymName, Selection);
879 }
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000880 }
881
882 if (Kind.isText())
David Majnemer3d96acb2013-08-13 01:23:53 +0000883 return TextSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000884
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000885 if (Kind.isThreadLocal())
David Majnemer3d96acb2013-08-13 01:23:53 +0000886 return TLSDataSection;
Anton Korobeynikovc6b40172012-02-11 17:26:53 +0000887
David Majnemer597be2d2014-09-22 20:39:23 +0000888 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
David Majnemerf76d6b32013-08-08 01:50:52 +0000889 return ReadOnlySection;
890
David Majnemera9bdb322014-04-08 22:33:40 +0000891 // Note: we claim that common symbols are put in BSSSection, but they are
892 // really emitted with the magic .comm directive, which creates a symbol table
893 // entry but not a section.
894 if (Kind.isBSS() || Kind.isCommon())
David Majnemer3d96acb2013-08-13 01:23:53 +0000895 return BSSSection;
896
897 return DataSection;
Anton Korobeynikovab663a02010-02-15 22:37:53 +0000898}
899
Yunzhong Gaoa88d7ab2014-01-21 18:31:27 +0000900StringRef TargetLoweringObjectFileCOFF::
901getDepLibFromLinkerOpt(StringRef LinkerOption) const {
902 const char *LibCmd = "/DEFAULTLIB:";
903 if (LinkerOption.startswith(LibCmd))
904 return LinkerOption.substr(strlen(LibCmd));
905 return StringRef();
906}
907
Reid Klecknerd973ca32013-04-25 19:34:41 +0000908void TargetLoweringObjectFileCOFF::
909emitModuleFlags(MCStreamer &Streamer,
910 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
Rafael Espindolafa0f7282014-02-08 14:53:28 +0000911 Mangler &Mang, const TargetMachine &TM) const {
Craig Topperc0196b12014-04-14 00:51:57 +0000912 MDNode *LinkerOptions = nullptr;
Reid Klecknerd973ca32013-04-25 19:34:41 +0000913
914 // Look for the "Linker Options" flag, since it's the only one we support.
915 for (ArrayRef<Module::ModuleFlagEntry>::iterator
916 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
917 const Module::ModuleFlagEntry &MFE = *i;
918 StringRef Key = MFE.Key->getString();
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000919 Metadata *Val = MFE.Val;
Reid Klecknerd973ca32013-04-25 19:34:41 +0000920 if (Key == "Linker Options") {
921 LinkerOptions = cast<MDNode>(Val);
922 break;
923 }
924 }
925 if (!LinkerOptions)
926 return;
927
928 // Emit the linker options to the linker .drectve section. According to the
929 // spec, this section is a space-separated string containing flags for linker.
930 const MCSection *Sec = getDrectveSection();
931 Streamer.SwitchSection(Sec);
932 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
933 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
934 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
935 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
Reid Klecknerd973ca32013-04-25 19:34:41 +0000936 // Lead with a space for consistency with our dllexport implementation.
Michael Kupersteinfc3e6262015-02-16 11:57:17 +0000937 std::string Directive(" ");
938 Directive.append(MDOption->getString());
939 Streamer.EmitBytes(Directive);
Reid Klecknerd973ca32013-04-25 19:34:41 +0000940 }
941 }
942}
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000943
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000944const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000945 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +0000946 return getContext().getAssociativeCOFFSection(
947 cast<MCSectionCOFF>(StaticCtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000948}
949
950const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
Rafael Espindola0766ae02014-06-06 19:26:12 +0000951 unsigned Priority, const MCSymbol *KeySym) const {
Reid Kleckner7c4059e2014-09-04 17:42:03 +0000952 return getContext().getAssociativeCOFFSection(
953 cast<MCSectionCOFF>(StaticDtorSection), KeySym);
Reid Klecknerfceb76f2014-05-16 20:39:27 +0000954}