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 StringRef 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) &&
243 StringRef Prefix = getSectionPrefixForGlobal(Kind);
245 SmallString<128> Name(Prefix);
246 TM.getNameWithPrefix(Name, GV, Mang, true);
248 StringRef Group = "";
249 unsigned Flags = getELFSectionFlags(Kind);
250 if (GV->isWeakForLinker()) {
251 Group = Name.substr(Prefix.size());
252 Flags |= ELF::SHF_GROUP;
255 return getContext().getELFSection(Name.str(),
256 getELFSectionType(Name.str(), Kind),
257 Flags, Kind, 0, Group);
260 if (Kind.isText()) return TextSection;
262 if (Kind.isMergeable1ByteCString() ||
263 Kind.isMergeable2ByteCString() ||
264 Kind.isMergeable4ByteCString()) {
266 // We also need alignment here.
267 // FIXME: this is getting the alignment of the character, not the
268 // alignment of the global!
270 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
272 const char *SizeSpec = ".rodata.str1.";
273 if (Kind.isMergeable2ByteCString())
274 SizeSpec = ".rodata.str2.";
275 else if (Kind.isMergeable4ByteCString())
276 SizeSpec = ".rodata.str4.";
278 assert(Kind.isMergeable1ByteCString() && "unknown string width");
281 std::string Name = SizeSpec + utostr(Align);
282 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
289 if (Kind.isMergeableConst()) {
290 if (Kind.isMergeableConst4() && MergeableConst4Section)
291 return MergeableConst4Section;
292 if (Kind.isMergeableConst8() && MergeableConst8Section)
293 return MergeableConst8Section;
294 if (Kind.isMergeableConst16() && MergeableConst16Section)
295 return MergeableConst16Section;
296 return ReadOnlySection; // .const
299 if (Kind.isReadOnly()) return ReadOnlySection;
301 if (Kind.isThreadData()) return TLSDataSection;
302 if (Kind.isThreadBSS()) return TLSBSSSection;
304 // Note: we claim that common symbols are put in BSSSection, but they are
305 // really emitted with the magic .comm directive, which creates a symbol table
306 // entry but not a section.
307 if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
309 if (Kind.isDataNoRel()) return DataSection;
310 if (Kind.isDataRelLocal()) return DataRelLocalSection;
311 if (Kind.isDataRel()) return DataRelSection;
312 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
314 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
315 return DataRelROSection;
318 /// getSectionForConstant - Given a mergeable constant with the
319 /// specified size and relocation information, return a section that it
320 /// should be placed in.
321 const MCSection *TargetLoweringObjectFileELF::
322 getSectionForConstant(SectionKind Kind) const {
323 if (Kind.isMergeableConst4() && MergeableConst4Section)
324 return MergeableConst4Section;
325 if (Kind.isMergeableConst8() && MergeableConst8Section)
326 return MergeableConst8Section;
327 if (Kind.isMergeableConst16() && MergeableConst16Section)
328 return MergeableConst16Section;
329 if (Kind.isReadOnly())
330 return ReadOnlySection;
332 if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
333 assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
334 return DataRelROSection;
337 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
338 unsigned Priority, const MCSymbol *KeySym) const {
339 // The default scheme is .ctor / .dtor, so we have to invert the priority
341 if (Priority == 65535)
342 return StaticCtorSection;
345 std::string Name = std::string(".init_array.") + utostr(Priority);
346 return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
347 ELF::SHF_ALLOC | ELF::SHF_WRITE,
348 SectionKind::getDataRel());
350 std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
351 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
352 ELF::SHF_ALLOC |ELF::SHF_WRITE,
353 SectionKind::getDataRel());
357 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
358 unsigned Priority, const MCSymbol *KeySym) const {
359 // The default scheme is .ctor / .dtor, so we have to invert the priority
361 if (Priority == 65535)
362 return StaticDtorSection;
365 std::string Name = std::string(".fini_array.") + utostr(Priority);
366 return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
367 ELF::SHF_ALLOC | ELF::SHF_WRITE,
368 SectionKind::getDataRel());
370 std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
371 return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
372 ELF::SHF_ALLOC |ELF::SHF_WRITE,
373 SectionKind::getDataRel());
378 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
379 UseInitArray = UseInitArray_;
384 getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
387 SectionKind::getDataRel());
389 getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
392 SectionKind::getDataRel());
395 //===----------------------------------------------------------------------===//
397 //===----------------------------------------------------------------------===//
399 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
400 /// option string. Returns StringRef() if the option does not specify a library.
401 StringRef TargetLoweringObjectFileMachO::
402 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
403 const char *LibCmd = "-l";
404 if (LinkerOption.startswith(LibCmd))
405 return LinkerOption.substr(strlen(LibCmd));
409 /// emitModuleFlags - Perform code emission for module flags.
410 void TargetLoweringObjectFileMachO::
411 emitModuleFlags(MCStreamer &Streamer,
412 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
413 Mangler &Mang, const TargetMachine &TM) const {
414 unsigned VersionVal = 0;
415 unsigned ImageInfoFlags = 0;
416 MDNode *LinkerOptions = nullptr;
417 StringRef SectionVal;
419 for (ArrayRef<Module::ModuleFlagEntry>::iterator
420 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
421 const Module::ModuleFlagEntry &MFE = *i;
423 // Ignore flags with 'Require' behavior.
424 if (MFE.Behavior == Module::Require)
427 StringRef Key = MFE.Key->getString();
428 Value *Val = MFE.Val;
430 if (Key == "Objective-C Image Info Version") {
431 VersionVal = cast<ConstantInt>(Val)->getZExtValue();
432 } else if (Key == "Objective-C Garbage Collection" ||
433 Key == "Objective-C GC Only" ||
434 Key == "Objective-C Is Simulated") {
435 ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
436 } else if (Key == "Objective-C Image Info Section") {
437 SectionVal = cast<MDString>(Val)->getString();
438 } else if (Key == "Linker Options") {
439 LinkerOptions = cast<MDNode>(Val);
443 // Emit the linker options if present.
445 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
446 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
447 SmallVector<std::string, 4> StrOptions;
449 // Convert to strings.
450 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
451 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
452 StrOptions.push_back(MDOption->getString());
455 Streamer.EmitLinkerOptions(StrOptions);
459 // The section is mandatory. If we don't have it, then we don't have GC info.
460 if (SectionVal.empty()) return;
462 StringRef Segment, Section;
463 unsigned TAA = 0, StubSize = 0;
465 std::string ErrorCode =
466 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
467 TAA, TAAParsed, StubSize);
468 if (!ErrorCode.empty())
469 // If invalid, report the error with report_fatal_error.
470 report_fatal_error("Invalid section specifier '" + Section + "': " +
474 const MCSectionMachO *S =
475 getContext().getMachOSection(Segment, Section, TAA, StubSize,
476 SectionKind::getDataNoRel());
477 Streamer.SwitchSection(S);
478 Streamer.EmitLabel(getContext().
479 GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
480 Streamer.EmitIntValue(VersionVal, 4);
481 Streamer.EmitIntValue(ImageInfoFlags, 4);
482 Streamer.AddBlankLine();
485 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
486 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
487 const TargetMachine &TM) const {
488 // Parse the section specifier and create it if valid.
489 StringRef Segment, Section;
490 unsigned TAA = 0, StubSize = 0;
492 std::string ErrorCode =
493 MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
494 TAA, TAAParsed, StubSize);
495 if (!ErrorCode.empty()) {
496 // If invalid, report the error with report_fatal_error.
497 report_fatal_error("Global variable '" + GV->getName() +
498 "' has an invalid section specifier '" +
499 GV->getSection() + "': " + ErrorCode + ".");
503 const MCSectionMachO *S =
504 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
506 // If TAA wasn't set by ParseSectionSpecifier() above,
507 // use the value returned by getMachOSection() as a default.
509 TAA = S->getTypeAndAttributes();
511 // Okay, now that we got the section, verify that the TAA & StubSize agree.
512 // If the user declared multiple globals with different section flags, we need
513 // to reject it here.
514 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
515 // If invalid, report the error with report_fatal_error.
516 report_fatal_error("Global variable '" + GV->getName() +
517 "' section type or attributes does not match previous"
518 " section specifier");
524 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
525 const MCSection &Section) const {
526 const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
528 // Sections holding 1 byte strings are atomized based on the data
530 // Sections holding 2 byte strings require symbols in order to be
532 // There is no dedicated section for 4 byte strings.
533 if (SMO.getKind().isMergeable1ByteCString())
536 if (SMO.getSegmentName() == "__DATA" &&
537 SMO.getSectionName() == "__cfstring")
540 switch (SMO.getType()) {
544 // These sections are atomized at the element boundaries without using
546 case MachO::S_4BYTE_LITERALS:
547 case MachO::S_8BYTE_LITERALS:
548 case MachO::S_16BYTE_LITERALS:
549 case MachO::S_LITERAL_POINTERS:
550 case MachO::S_NON_LAZY_SYMBOL_POINTERS:
551 case MachO::S_LAZY_SYMBOL_POINTERS:
552 case MachO::S_MOD_INIT_FUNC_POINTERS:
553 case MachO::S_MOD_TERM_FUNC_POINTERS:
554 case MachO::S_INTERPOSING:
559 const MCSection *TargetLoweringObjectFileMachO::
560 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
561 Mangler &Mang, const TargetMachine &TM) const {
563 // Handle thread local data.
564 if (Kind.isThreadBSS()) return TLSBSSSection;
565 if (Kind.isThreadData()) return TLSDataSection;
568 return GV->isWeakForLinker() ? TextCoalSection : TextSection;
570 // If this is weak/linkonce, put this in a coalescable section, either in text
571 // or data depending on if it is writable.
572 if (GV->isWeakForLinker()) {
573 if (Kind.isReadOnly())
574 return ConstTextCoalSection;
575 return DataCoalSection;
578 // FIXME: Alignment check should be handled by section classifier.
579 if (Kind.isMergeable1ByteCString() &&
580 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
581 return CStringSection;
583 // Do not put 16-bit arrays in the UString section if they have an
584 // externally visible label, this runs into issues with certain linker
586 if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
587 TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
588 return UStringSection;
590 if (Kind.isMergeableConst()) {
591 if (Kind.isMergeableConst4())
592 return FourByteConstantSection;
593 if (Kind.isMergeableConst8())
594 return EightByteConstantSection;
595 if (Kind.isMergeableConst16())
596 return SixteenByteConstantSection;
599 // Otherwise, if it is readonly, but not something we can specially optimize,
600 // just drop it in .const.
601 if (Kind.isReadOnly())
602 return ReadOnlySection;
604 // If this is marked const, put it into a const section. But if the dynamic
605 // linker needs to write to it, put it in the data segment.
606 if (Kind.isReadOnlyWithRel())
607 return ConstDataSection;
609 // Put zero initialized globals with strong external linkage in the
610 // DATA, __common section with the .zerofill directive.
611 if (Kind.isBSSExtern())
612 return DataCommonSection;
614 // Put zero initialized globals with local linkage in __DATA,__bss directive
615 // with the .zerofill directive (aka .lcomm).
616 if (Kind.isBSSLocal())
617 return DataBSSSection;
619 // Otherwise, just drop the variable in the normal data section.
624 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
625 // If this constant requires a relocation, we have to put it in the data
626 // segment, not in the text segment.
627 if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
628 return ConstDataSection;
630 if (Kind.isMergeableConst4())
631 return FourByteConstantSection;
632 if (Kind.isMergeableConst8())
633 return EightByteConstantSection;
634 if (Kind.isMergeableConst16())
635 return SixteenByteConstantSection;
636 return ReadOnlySection; // .const
639 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
640 const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
641 const TargetMachine &TM, MachineModuleInfo *MMI,
642 MCStreamer &Streamer) const {
643 // The mach-o version of this method defaults to returning a stub reference.
645 if (Encoding & DW_EH_PE_indirect) {
646 MachineModuleInfoMachO &MachOMMI =
647 MMI->getObjFileInfo<MachineModuleInfoMachO>();
650 getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
652 // Add information about the stub reference to MachOMMI so that the stub
653 // gets emitted by the asmprinter.
654 MachineModuleInfoImpl::StubValueTy &StubSym =
655 GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
656 MachOMMI.getGVStubEntry(SSym);
657 if (!StubSym.getPointer()) {
658 MCSymbol *Sym = TM.getSymbol(GV, Mang);
659 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
662 return TargetLoweringObjectFile::
663 getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
664 Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
667 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
671 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
672 const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
673 MachineModuleInfo *MMI) const {
674 // The mach-o version of this method defaults to returning a stub reference.
675 MachineModuleInfoMachO &MachOMMI =
676 MMI->getObjFileInfo<MachineModuleInfoMachO>();
678 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
680 // Add information about the stub reference to MachOMMI so that the stub
681 // gets emitted by the asmprinter.
682 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
683 if (!StubSym.getPointer()) {
684 MCSymbol *Sym = TM.getSymbol(GV, Mang);
685 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
691 //===----------------------------------------------------------------------===//
693 //===----------------------------------------------------------------------===//
696 getCOFFSectionFlags(SectionKind K) {
701 COFF::IMAGE_SCN_MEM_DISCARDABLE;
704 COFF::IMAGE_SCN_MEM_EXECUTE |
705 COFF::IMAGE_SCN_MEM_READ |
706 COFF::IMAGE_SCN_CNT_CODE;
709 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
710 COFF::IMAGE_SCN_MEM_READ |
711 COFF::IMAGE_SCN_MEM_WRITE;
712 else if (K.isThreadLocal())
714 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
715 COFF::IMAGE_SCN_MEM_READ |
716 COFF::IMAGE_SCN_MEM_WRITE;
717 else if (K.isReadOnly())
719 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
720 COFF::IMAGE_SCN_MEM_READ;
721 else if (K.isWriteable())
723 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
724 COFF::IMAGE_SCN_MEM_READ |
725 COFF::IMAGE_SCN_MEM_WRITE;
730 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
731 const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
732 const TargetMachine &TM) const {
734 unsigned Characteristics = getCOFFSectionFlags(Kind);
735 StringRef Name = GV->getSection();
736 StringRef COMDATSymName = "";
737 if (GV->isWeakForLinker()) {
738 Selection = COFF::IMAGE_COMDAT_SELECT_ANY;
739 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
740 MCSymbol *Sym = TM.getSymbol(GV, Mang);
741 COMDATSymName = Sym->getName();
743 return getContext().getCOFFSection(Name,
750 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
755 if (Kind.isThreadLocal())
757 if (Kind.isWriteable())
763 const MCSection *TargetLoweringObjectFileCOFF::
764 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
765 Mangler &Mang, const TargetMachine &TM) const {
766 // If we have -ffunction-sections then we should emit the global value to a
767 // uniqued section specifically for it.
768 bool EmitUniquedSection;
770 EmitUniquedSection = TM.getFunctionSections();
772 EmitUniquedSection = TM.getDataSections();
774 // If this global is linkonce/weak and the target handles this by emitting it
775 // into a 'uniqued' section name, create and return the section now.
776 // Section names depend on the name of the symbol which is not feasible if the
777 // symbol has private linkage.
778 if ((GV->isWeakForLinker() || EmitUniquedSection) &&
779 !GV->hasPrivateLinkage() && !Kind.isCommon()) {
780 const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
781 unsigned Characteristics = getCOFFSectionFlags(Kind);
783 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
784 MCSymbol *Sym = TM.getSymbol(GV, Mang);
785 return getContext().getCOFFSection(
786 Name, Characteristics, Kind, Sym->getName(),
787 GV->isWeakForLinker() ? COFF::IMAGE_COMDAT_SELECT_ANY
788 : COFF::IMAGE_COMDAT_SELECT_NODUPLICATES);
794 if (Kind.isThreadLocal())
795 return TLSDataSection;
797 if (Kind.isReadOnly())
798 return ReadOnlySection;
800 // Note: we claim that common symbols are put in BSSSection, but they are
801 // really emitted with the magic .comm directive, which creates a symbol table
802 // entry but not a section.
803 if (Kind.isBSS() || Kind.isCommon())
809 StringRef TargetLoweringObjectFileCOFF::
810 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
811 const char *LibCmd = "/DEFAULTLIB:";
812 if (LinkerOption.startswith(LibCmd))
813 return LinkerOption.substr(strlen(LibCmd));
817 void TargetLoweringObjectFileCOFF::
818 emitModuleFlags(MCStreamer &Streamer,
819 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
820 Mangler &Mang, const TargetMachine &TM) const {
821 MDNode *LinkerOptions = nullptr;
823 // Look for the "Linker Options" flag, since it's the only one we support.
824 for (ArrayRef<Module::ModuleFlagEntry>::iterator
825 i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
826 const Module::ModuleFlagEntry &MFE = *i;
827 StringRef Key = MFE.Key->getString();
828 Value *Val = MFE.Val;
829 if (Key == "Linker Options") {
830 LinkerOptions = cast<MDNode>(Val);
837 // Emit the linker options to the linker .drectve section. According to the
838 // spec, this section is a space-separated string containing flags for linker.
839 const MCSection *Sec = getDrectveSection();
840 Streamer.SwitchSection(Sec);
841 for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
842 MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
843 for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
844 MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
845 StringRef Op = MDOption->getString();
846 // Lead with a space for consistency with our dllexport implementation.
847 std::string Escaped(" ");
848 if (Op.find(" ") != StringRef::npos) {
849 // The PE-COFF spec says args with spaces must be quoted. It doesn't say
850 // how to escape quotes, but it probably uses this algorithm:
851 // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
852 // FIXME: Reuse escaping code from Support/Windows/Program.inc
853 Escaped.push_back('\"');
855 Escaped.push_back('\"');
859 Streamer.EmitBytes(Escaped);
864 static const MCSection *getAssociativeCOFFSection(MCContext &Ctx,
865 const MCSection *Sec,
866 const MCSymbol *KeySym) {
867 // Return the normal section if we don't have to be associative.
871 // Make an associative section with the same name and kind as the normal
873 const MCSectionCOFF *SecCOFF = cast<MCSectionCOFF>(Sec);
874 unsigned Characteristics =
875 SecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
876 return Ctx.getCOFFSection(SecCOFF->getSectionName(), Characteristics,
877 SecCOFF->getKind(), KeySym->getName(),
878 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
881 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
882 unsigned Priority, const MCSymbol *KeySym) const {
883 return getAssociativeCOFFSection(getContext(), StaticCtorSection, KeySym);
886 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
887 unsigned Priority, const MCSymbol *KeySym) const {
888 return getAssociativeCOFFSection(getContext(), StaticDtorSection, KeySym);