1 //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements classes used to handle lowerings specific to common
11 // object file formats.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
20 #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"
25 #include "llvm/IR/Mangler.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/MC/MCContext.h"
28 #include "llvm/MC/MCExpr.h"
29 #include "llvm/MC/MCSectionCOFF.h"
30 #include "llvm/MC/MCSectionELF.h"
31 #include "llvm/MC/MCSectionMachO.h"
32 #include "llvm/MC/MCStreamer.h"
33 #include "llvm/MC/MCSymbol.h"
34 #include "llvm/Support/Dwarf.h"
35 #include "llvm/Support/ELF.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetLowering.h"
39 #include "llvm/Target/TargetMachine.h"
41 using namespace dwarf;
43 //===----------------------------------------------------------------------===//
45 //===----------------------------------------------------------------------===//
47 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
48 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
49 MachineModuleInfo *MMI) const {
50 unsigned Encoding = getPersonalityEncoding();
51 if ((Encoding & 0x80) == dwarf::DW_EH_PE_indirect)
52 return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
53 TM.getSymbol(GV, Mang)->getName());
54 if ((Encoding & 0x70) == dwarf::DW_EH_PE_absptr)
55 return TM.getSymbol(GV, Mang);
56 report_fatal_error("We do not support this DWARF encoding yet!");
59 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
60 const TargetMachine &TM,
61 const MCSymbol *Sym) const {
62 SmallString<64> NameData("DW.ref.");
63 NameData += Sym->getName();
64 MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
65 Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
66 Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
67 StringRef Prefix = ".data.";
68 NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
69 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
70 const MCSection *Sec = getContext().getELFSection(NameData,
73 SectionKind::getDataRel(),
75 unsigned Size = TM.getDataLayout()->getPointerSize();
76 Streamer.SwitchSection(Sec);
77 Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
78 Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
79 const MCExpr *E = MCConstantExpr::Create(Size, getContext());
80 Streamer.EmitELFSize(Label, E);
81 Streamer.EmitLabel(Label);
83 Streamer.EmitSymbolValue(Sym, Size);
86 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
87 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
88 const TargetMachine &TM, MachineModuleInfo *MMI,
89 MCStreamer &Streamer) const {
91 if (Encoding & dwarf::DW_EH_PE_indirect) {
92 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
94 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
96 // Add information about the stub reference to ELFMMI so that the stub
97 // gets emitted by the asmprinter.
98 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
99 if (!StubSym.getPointer()) {
100 MCSymbol *Sym = TM.getSymbol(GV, Mang);
101 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
104 return TargetLoweringObjectFile::
105 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
106 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
109 return TargetLoweringObjectFile::
110 getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
114 getELFKindForNamedSection(StringRef Name, SectionKind K) {
115 // 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
118 // section(".eh_frame") gcc will produce:
120 // .section .eh_frame,"a",@progbits
121 if (Name.empty() || Name[0] != '.') return K;
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.") ||
129 Name.startswith(".sbss.") ||
130 Name.startswith(".gnu.linkonce.sb.") ||
131 Name.startswith(".llvm.linkonce.sb."))
132 return SectionKind::getBSS();
134 if (Name == ".tdata" ||
135 Name.startswith(".tdata.") ||
136 Name.startswith(".gnu.linkonce.td.") ||
137 Name.startswith(".llvm.linkonce.td."))
138 return SectionKind::getThreadData();
140 if (Name == ".tbss" ||
141 Name.startswith(".tbss.") ||
142 Name.startswith(".gnu.linkonce.tb.") ||
143 Name.startswith(".llvm.linkonce.tb."))
144 return SectionKind::getThreadBSS();
150 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
152 if (Name == ".init_array")
153 return ELF::SHT_INIT_ARRAY;
155 if (Name == ".fini_array")
156 return ELF::SHT_FINI_ARRAY;
158 if (Name == ".preinit_array")
159 return ELF::SHT_PREINIT_ARRAY;
161 if (K.isBSS() || K.isThreadBSS())
162 return ELF::SHT_NOBITS;
164 return ELF::SHT_PROGBITS;
169 getELFSectionFlags(SectionKind K) {
173 Flags |= ELF::SHF_ALLOC;
176 Flags |= ELF::SHF_EXECINSTR;
179 Flags |= ELF::SHF_WRITE;
181 if (K.isThreadLocal())
182 Flags |= ELF::SHF_TLS;
184 // K.isMergeableConst() is left out to honour PR4650
185 if (K.isMergeableCString() || K.isMergeableConst4() ||
186 K.isMergeableConst8() || K.isMergeableConst16())
187 Flags |= ELF::SHF_MERGE;
189 if (K.isMergeableCString())
190 Flags |= ELF::SHF_STRINGS;
195 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
196 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
197 const TargetMachine &TM) const {
198 StringRef SectionName = GV->getSection();
200 // Infer section flags from the section name if we can.
201 Kind = getELFKindForNamedSection(SectionName, Kind);
203 return getContext().getELFSection(SectionName,
204 getELFSectionType(SectionName, Kind),
205 getELFSectionFlags(Kind), Kind);
208 /// getSectionPrefixForGlobal - Return the section prefix name used by options
209 /// FunctionsSections and DataSections.
210 static const char *getSectionPrefixForGlobal(SectionKind Kind) {
211 if (Kind.isText()) return ".text.";
212 if (Kind.isReadOnly()) return ".rodata.";
213 if (Kind.isBSS()) return ".bss.";
215 if (Kind.isThreadData()) return ".tdata.";
216 if (Kind.isThreadBSS()) return ".tbss.";
218 if (Kind.isDataNoRel()) return ".data.";
219 if (Kind.isDataRelLocal()) return ".data.rel.local.";
220 if (Kind.isDataRel()) return ".data.rel.";
221 if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
223 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
224 return ".data.rel.ro.";
228 const MCSection *TargetLoweringObjectFileELF::
229 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
230 Mangler &Mang, const TargetMachine &TM) const {
231 // If we have -ffunction-section or -fdata-section then we should emit the
232 // global value to a uniqued section specifically for it.
233 bool EmitUniquedSection;
235 EmitUniquedSection = TM.getFunctionSections();
237 EmitUniquedSection = TM.getDataSections();
239 // If this global is linkonce/weak and the target handles this by emitting it
240 // into a 'uniqued' section name, create and return the section now.
241 if ((GV->isWeakForLinker() || EmitUniquedSection) &&
244 Prefix = getSectionPrefixForGlobal(Kind);
246 SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
247 TM.getNameWithPrefix(Name, GV, Mang, true);
249 StringRef Group = "";
250 unsigned Flags = getELFSectionFlags(Kind);
251 if (GV->isWeakForLinker()) {
252 Group = Name.substr(strlen(Prefix));
253 Flags |= ELF::SHF_GROUP;
256 return getContext().getELFSection(Name.str(),
257 getELFSectionType(Name.str(), Kind),
258 Flags, Kind, 0, Group);
261 if (Kind.isText()) return TextSection;
263 if (Kind.isMergeable1ByteCString() ||
264 Kind.isMergeable2ByteCString() ||
265 Kind.isMergeable4ByteCString()) {
267 // We also need alignment here.
268 // FIXME: this is getting the alignment of the character, not the
269 // alignment of the global!
271 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
273 const char *SizeSpec = ".rodata.str1.";
274 if (Kind.isMergeable2ByteCString())
275 SizeSpec = ".rodata.str2.";
276 else if (Kind.isMergeable4ByteCString())
277 SizeSpec = ".rodata.str4.";
279 assert(Kind.isMergeable1ByteCString() && "unknown string width");
282 std::string Name = SizeSpec + utostr(Align);
283 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
290 if (Kind.isMergeableConst()) {
291 if (Kind.isMergeableConst4() && MergeableConst4Section)
292 return MergeableConst4Section;
293 if (Kind.isMergeableConst8() && MergeableConst8Section)
294 return MergeableConst8Section;
295 if (Kind.isMergeableConst16() && MergeableConst16Section)
296 return MergeableConst16Section;
297 return ReadOnlySection; // .const
300 if (Kind.isReadOnly()) return ReadOnlySection;
302 if (Kind.isThreadData()) return TLSDataSection;
303 if (Kind.isThreadBSS()) return TLSBSSSection;
305 // Note: we claim that common symbols are put in BSSSection, but they are
306 // really emitted with the magic .comm directive, which creates a symbol table
307 // entry but not a section.
308 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
310 if (Kind.isDataNoRel()) return DataSection;
311 if (Kind.isDataRelLocal()) return DataRelLocalSection;
312 if (Kind.isDataRel()) return DataRelSection;
313 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
315 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
316 return DataRelROSection;
319 /// getSectionForConstant - Given a mergeable constant with the
320 /// specified size and relocation information, return a section that it
321 /// should be placed in.
322 const MCSection *TargetLoweringObjectFileELF::
323 getSectionForConstant(SectionKind Kind) const {
324 if (Kind.isMergeableConst4() && MergeableConst4Section)
325 return MergeableConst4Section;
326 if (Kind.isMergeableConst8() && MergeableConst8Section)
327 return MergeableConst8Section;
328 if (Kind.isMergeableConst16() && MergeableConst16Section)
329 return MergeableConst16Section;
330 if (Kind.isReadOnly())
331 return ReadOnlySection;
333 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
334 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
335 return DataRelROSection;
338 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
339 unsigned Priority, const MCSymbol *KeySym, const MCSection *KeySec) const {
340 // The default scheme is .ctor / .dtor, so we have to invert the priority
342 if (Priority == 65535)
343 return StaticCtorSection;
346 std::string Name = std::string(".init_array.") + utostr(Priority);
347 return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
348 ELF::SHF_ALLOC | ELF::SHF_WRITE,
349 SectionKind::getDataRel());
351 std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
352 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
353 ELF::SHF_ALLOC |ELF::SHF_WRITE,
354 SectionKind::getDataRel());
358 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
359 unsigned Priority, const MCSymbol *KeySym, const MCSection *KeySec) const {
360 // The default scheme is .ctor / .dtor, so we have to invert the priority
362 if (Priority == 65535)
363 return StaticDtorSection;
366 std::string Name = std::string(".fini_array.") + utostr(Priority);
367 return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
368 ELF::SHF_ALLOC | ELF::SHF_WRITE,
369 SectionKind::getDataRel());
371 std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
372 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
373 ELF::SHF_ALLOC |ELF::SHF_WRITE,
374 SectionKind::getDataRel());
379 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
380 UseInitArray = UseInitArray_;
385 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
388 SectionKind::getDataRel());
390 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
393 SectionKind::getDataRel());
396 //===----------------------------------------------------------------------===//
398 //===----------------------------------------------------------------------===//
400 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
401 /// option string. Returns StringRef() if the option does not specify a library.
402 StringRef TargetLoweringObjectFileMachO::
403 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
404 const char *LibCmd = "-l";
405 if (LinkerOption.startswith(LibCmd))
406 return LinkerOption.substr(strlen(LibCmd));
410 /// emitModuleFlags - Perform code emission for module flags.
411 void TargetLoweringObjectFileMachO::
412 emitModuleFlags(MCStreamer &Streamer,
413 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
414 Mangler &Mang, const TargetMachine &TM) const {
415 unsigned VersionVal = 0;
416 unsigned ImageInfoFlags = 0;
417 MDNode *LinkerOptions = nullptr;
418 StringRef SectionVal;
420 for (ArrayRef<Module::ModuleFlagEntry>::iterator
421 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
422 const Module::ModuleFlagEntry &MFE = *i;
424 // Ignore flags with 'Require' behavior.
425 if (MFE.Behavior == Module::Require)
428 StringRef Key = MFE.Key->getString();
429 Value *Val = MFE.Val;
431 if (Key == "Objective-C Image Info Version") {
432 VersionVal = cast<ConstantInt>(Val)->getZExtValue();
433 } else if (Key == "Objective-C Garbage Collection" ||
434 Key == "Objective-C GC Only" ||
435 Key == "Objective-C Is Simulated") {
436 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
437 } else if (Key == "Objective-C Image Info Section") {
438 SectionVal = cast<MDString>(Val)->getString();
439 } else if (Key == "Linker Options") {
440 LinkerOptions = cast<MDNode>(Val);
444 // Emit the linker options if present.
446 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
447 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
448 SmallVector<std::string, 4> StrOptions;
450 // Convert to strings.
451 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
452 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
453 StrOptions.push_back(MDOption->getString());
456 Streamer.EmitLinkerOptions(StrOptions);
460 // The section is mandatory. If we don't have it, then we don't have GC info.
461 if (SectionVal.empty()) return;
463 StringRef Segment, Section;
464 unsigned TAA = 0, StubSize = 0;
466 std::string ErrorCode =
467 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
468 TAA, TAAParsed, StubSize);
469 if (!ErrorCode.empty())
470 // If invalid, report the error with report_fatal_error.
471 report_fatal_error("Invalid section specifier '" + Section + "': " +
475 const MCSectionMachO *S =
476 getContext().getMachOSection(Segment, Section, TAA, StubSize,
477 SectionKind::getDataNoRel());
478 Streamer.SwitchSection(S);
479 Streamer.EmitLabel(getContext().
480 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
481 Streamer.EmitIntValue(VersionVal, 4);
482 Streamer.EmitIntValue(ImageInfoFlags, 4);
483 Streamer.AddBlankLine();
486 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
487 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
488 const TargetMachine &TM) const {
489 // Parse the section specifier and create it if valid.
490 StringRef Segment, Section;
491 unsigned TAA = 0, StubSize = 0;
493 std::string ErrorCode =
494 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
495 TAA, TAAParsed, StubSize);
496 if (!ErrorCode.empty()) {
497 // If invalid, report the error with report_fatal_error.
498 report_fatal_error("Global variable '" + GV->getName() +
499 "' has an invalid section specifier '" +
500 GV->getSection() + "': " + ErrorCode + ".");
504 const MCSectionMachO *S =
505 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
507 // If TAA wasn't set by ParseSectionSpecifier() above,
508 // use the value returned by getMachOSection() as a default.
510 TAA = S->getTypeAndAttributes();
512 // Okay, now that we got the section, verify that the TAA & StubSize agree.
513 // If the user declared multiple globals with different section flags, we need
514 // to reject it here.
515 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
516 // If invalid, report the error with report_fatal_error.
517 report_fatal_error("Global variable '" + GV->getName() +
518 "' section type or attributes does not match previous"
519 " section specifier");
525 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
526 const MCSection &Section) const {
527 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
529 // Sections holding 1 byte strings are atomized based on the data
531 // Sections holding 2 byte strings require symbols in order to be
533 // There is no dedicated section for 4 byte strings.
534 if (SMO.getKind().isMergeable1ByteCString())
537 if (SMO.getSegmentName() == "__DATA" &&
538 SMO.getSectionName() == "__cfstring")
541 switch (SMO.getType()) {
545 // These sections are atomized at the element boundaries without using
547 case MachO::S_4BYTE_LITERALS:
548 case MachO::S_8BYTE_LITERALS:
549 case MachO::S_16BYTE_LITERALS:
550 case MachO::S_LITERAL_POINTERS:
551 case MachO::S_NON_LAZY_SYMBOL_POINTERS:
552 case MachO::S_LAZY_SYMBOL_POINTERS:
553 case MachO::S_MOD_INIT_FUNC_POINTERS:
554 case MachO::S_MOD_TERM_FUNC_POINTERS:
555 case MachO::S_INTERPOSING:
560 const MCSection *TargetLoweringObjectFileMachO::
561 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
562 Mangler &Mang, const TargetMachine &TM) const {
564 // Handle thread local data.
565 if (Kind.isThreadBSS()) return TLSBSSSection;
566 if (Kind.isThreadData()) return TLSDataSection;
569 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
571 // If this is weak/linkonce, put this in a coalescable section, either in text
572 // or data depending on if it is writable.
573 if (GV->isWeakForLinker()) {
574 if (Kind.isReadOnly())
575 return ConstTextCoalSection;
576 return DataCoalSection;
579 // FIXME: Alignment check should be handled by section classifier.
580 if (Kind.isMergeable1ByteCString() &&
581 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
582 return CStringSection;
584 // Do not put 16-bit arrays in the UString section if they have an
585 // externally visible label, this runs into issues with certain linker
587 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
588 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
589 return UStringSection;
591 if (Kind.isMergeableConst()) {
592 if (Kind.isMergeableConst4())
593 return FourByteConstantSection;
594 if (Kind.isMergeableConst8())
595 return EightByteConstantSection;
596 if (Kind.isMergeableConst16())
597 return SixteenByteConstantSection;
600 // Otherwise, if it is readonly, but not something we can specially optimize,
601 // just drop it in .const.
602 if (Kind.isReadOnly())
603 return ReadOnlySection;
605 // If this is marked const, put it into a const section. But if the dynamic
606 // linker needs to write to it, put it in the data segment.
607 if (Kind.isReadOnlyWithRel())
608 return ConstDataSection;
610 // Put zero initialized globals with strong external linkage in the
611 // DATA, __common section with the .zerofill directive.
612 if (Kind.isBSSExtern())
613 return DataCommonSection;
615 // Put zero initialized globals with local linkage in __DATA,__bss directive
616 // with the .zerofill directive (aka .lcomm).
617 if (Kind.isBSSLocal())
618 return DataBSSSection;
620 // Otherwise, just drop the variable in the normal data section.
625 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
626 // If this constant requires a relocation, we have to put it in the data
627 // segment, not in the text segment.
628 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
629 return ConstDataSection;
631 if (Kind.isMergeableConst4())
632 return FourByteConstantSection;
633 if (Kind.isMergeableConst8())
634 return EightByteConstantSection;
635 if (Kind.isMergeableConst16())
636 return SixteenByteConstantSection;
637 return ReadOnlySection; // .const
640 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
641 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
642 const TargetMachine &TM, MachineModuleInfo *MMI,
643 MCStreamer &Streamer) const {
644 // The mach-o version of this method defaults to returning a stub reference.
646 if (Encoding & DW_EH_PE_indirect) {
647 MachineModuleInfoMachO &MachOMMI =
648 MMI->getObjFileInfo<MachineModuleInfoMachO>();
651 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
653 // Add information about the stub reference to MachOMMI so that the stub
654 // gets emitted by the asmprinter.
655 MachineModuleInfoImpl::StubValueTy &StubSym =
656 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
657 MachOMMI.getGVStubEntry(SSym);
658 if (!StubSym.getPointer()) {
659 MCSymbol *Sym = TM.getSymbol(GV, Mang);
660 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
663 return TargetLoweringObjectFile::
664 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
665 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
668 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
672 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
673 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
674 MachineModuleInfo *MMI) const {
675 // The mach-o version of this method defaults to returning a stub reference.
676 MachineModuleInfoMachO &MachOMMI =
677 MMI->getObjFileInfo<MachineModuleInfoMachO>();
679 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
681 // Add information about the stub reference to MachOMMI so that the stub
682 // gets emitted by the asmprinter.
683 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
684 if (!StubSym.getPointer()) {
685 MCSymbol *Sym = TM.getSymbol(GV, Mang);
686 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
692 //===----------------------------------------------------------------------===//
694 //===----------------------------------------------------------------------===//
697 getCOFFSectionFlags(SectionKind K) {
702 COFF::IMAGE_SCN_MEM_DISCARDABLE;
705 COFF::IMAGE_SCN_MEM_EXECUTE |
706 COFF::IMAGE_SCN_MEM_READ |
707 COFF::IMAGE_SCN_CNT_CODE;
710 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
711 COFF::IMAGE_SCN_MEM_READ |
712 COFF::IMAGE_SCN_MEM_WRITE;
713 else if (K.isThreadLocal())
715 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
716 COFF::IMAGE_SCN_MEM_READ |
717 COFF::IMAGE_SCN_MEM_WRITE;
718 else if (K.isReadOnly())
720 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
721 COFF::IMAGE_SCN_MEM_READ;
722 else if (K.isWriteable())
724 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
725 COFF::IMAGE_SCN_MEM_READ |
726 COFF::IMAGE_SCN_MEM_WRITE;
731 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
732 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
733 const TargetMachine &TM) const {
735 unsigned Characteristics = getCOFFSectionFlags(Kind);
736 StringRef Name = GV->getSection();
737 StringRef COMDATSymName = "";
738 if (GV->isWeakForLinker()) {
739 Selection = COFF::IMAGE_COMDAT_SELECT_ANY;
740 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
741 MCSymbol *Sym = TM.getSymbol(GV, Mang);
742 COMDATSymName = Sym->getName();
744 return getContext().getCOFFSection(Name,
751 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
756 if (Kind.isThreadLocal())
758 if (Kind.isWriteable())
764 const MCSection *TargetLoweringObjectFileCOFF::
765 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
766 Mangler &Mang, const TargetMachine &TM) const {
767 // If we have -ffunction-sections then we should emit the global value to a
768 // uniqued section specifically for it.
769 bool EmitUniquedSection;
771 EmitUniquedSection = TM.getFunctionSections();
773 EmitUniquedSection = TM.getDataSections();
775 // If this global is linkonce/weak and the target handles this by emitting it
776 // into a 'uniqued' section name, create and return the section now.
777 // Section names depend on the name of the symbol which is not feasible if the
778 // symbol has private linkage.
779 if ((GV->isWeakForLinker() || EmitUniquedSection) &&
780 !GV->hasPrivateLinkage() && !Kind.isCommon()) {
781 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
782 unsigned Characteristics = getCOFFSectionFlags(Kind);
784 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
785 MCSymbol *Sym = TM.getSymbol(GV, Mang);
786 return getContext().getCOFFSection(
787 Name, Characteristics, Kind, Sym->getName(),
788 GV->isWeakForLinker() ? COFF::IMAGE_COMDAT_SELECT_ANY
789 : COFF::IMAGE_COMDAT_SELECT_NODUPLICATES);
795 if (Kind.isThreadLocal())
796 return TLSDataSection;
798 if (Kind.isReadOnly())
799 return ReadOnlySection;
801 // Note: we claim that common symbols are put in BSSSection, but they are
802 // really emitted with the magic .comm directive, which creates a symbol table
803 // entry but not a section.
804 if (Kind.isBSS() || Kind.isCommon())
810 StringRef TargetLoweringObjectFileCOFF::
811 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
812 const char *LibCmd = "/DEFAULTLIB:";
813 if (LinkerOption.startswith(LibCmd))
814 return LinkerOption.substr(strlen(LibCmd));
818 void TargetLoweringObjectFileCOFF::
819 emitModuleFlags(MCStreamer &Streamer,
820 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
821 Mangler &Mang, const TargetMachine &TM) const {
822 MDNode *LinkerOptions = nullptr;
824 // Look for the "Linker Options" flag, since it's the only one we support.
825 for (ArrayRef<Module::ModuleFlagEntry>::iterator
826 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
827 const Module::ModuleFlagEntry &MFE = *i;
828 StringRef Key = MFE.Key->getString();
829 Value *Val = MFE.Val;
830 if (Key == "Linker Options") {
831 LinkerOptions = cast<MDNode>(Val);
838 // Emit the linker options to the linker .drectve section. According to the
839 // spec, this section is a space-separated string containing flags for linker.
840 const MCSection *Sec = getDrectveSection();
841 Streamer.SwitchSection(Sec);
842 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
843 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
844 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
845 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
846 StringRef Op = MDOption->getString();
847 // Lead with a space for consistency with our dllexport implementation.
848 std::string Escaped(" ");
849 if (Op.find(" ") != StringRef::npos) {
850 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
851 // how to escape quotes, but it probably uses this algorithm:
852 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
853 // FIXME: Reuse escaping code from Support/Windows/Program.inc
854 Escaped.push_back('\"');
856 Escaped.push_back('\"');
860 Streamer.EmitBytes(Escaped);
865 static const MCSection *getAssociativeCOFFSection(MCContext &Ctx,
866 const MCSection *Sec,
867 const MCSymbol *KeySym,
868 const MCSection *KeySec) {
869 // Return the normal section if we don't have to be associative.
873 // Make an associative section with the same name and kind as the normal
875 const MCSectionCOFF *SecCOFF = cast<MCSectionCOFF>(Sec);
876 const MCSectionCOFF *KeySecCOFF = cast<MCSectionCOFF>(KeySec);
877 unsigned Characteristics =
878 SecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
879 return Ctx.getCOFFSection(SecCOFF->getSectionName(), Characteristics,
880 SecCOFF->getKind(), KeySym->getName(),
881 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, KeySecCOFF);
884 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
885 unsigned Priority, const MCSymbol *KeySym, const MCSection *KeySec) const {
886 return getAssociativeCOFFSection(getContext(), StaticCtorSection, KeySym, KeySec);
889 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
890 unsigned Priority, const MCSymbol *KeySym, const MCSection *KeySec) const {
891 return getAssociativeCOFFSection(getContext(), StaticDtorSection, KeySym, KeySec);