]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - lib/CodeGen/TargetLoweringObjectFileImpl.cpp
clarify comment
[opencl/llvm.git] / lib / CodeGen / TargetLoweringObjectFileImpl.cpp
1 //===-- 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 //===----------------------------------------------------------------------===//
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"
40 using namespace llvm;
41 using namespace dwarf;
43 //===----------------------------------------------------------------------===//
44 //                                  ELF
45 //===----------------------------------------------------------------------===//
47 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
48     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
49     MachineModuleInfo *MMI) const {
50   unsigned Encoding = getPersonalityEncoding();
51   switch (Encoding & 0x70) {
52   default:
53     report_fatal_error("We do not support this DWARF encoding yet!");
54   case dwarf::DW_EH_PE_absptr:
55     return TM.getSymbol(GV, Mang);
56   case dwarf::DW_EH_PE_pcrel: {
57     return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
58                                           TM.getSymbol(GV, Mang)->getName());
59   }
60   }
61 }
63 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
64                                                        const TargetMachine &TM,
65                                                        const MCSymbol *Sym) const {
66   SmallString<64> NameData("DW.ref.");
67   NameData += Sym->getName();
68   MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
69   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
70   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
71   StringRef Prefix = ".data.";
72   NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
73   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
74   const MCSection *Sec = getContext().getELFSection(NameData,
75                                                     ELF::SHT_PROGBITS,
76                                                     Flags,
77                                                     SectionKind::getDataRel(),
78                                                     0, Label->getName());
79   unsigned Size = TM.getDataLayout()->getPointerSize();
80   Streamer.SwitchSection(Sec);
81   Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
82   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
83   const MCExpr *E = MCConstantExpr::Create(Size, getContext());
84   Streamer.EmitELFSize(Label, E);
85   Streamer.EmitLabel(Label);
87   Streamer.EmitSymbolValue(Sym, Size);
88 }
90 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
91     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
92     const TargetMachine &TM, MachineModuleInfo *MMI,
93     MCStreamer &Streamer) const {
95   if (Encoding & dwarf::DW_EH_PE_indirect) {
96     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
98     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
100     // Add information about the stub reference to ELFMMI so that the stub
101     // gets emitted by the asmprinter.
102     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
103     if (StubSym.getPointer() == 0) {
104       MCSymbol *Sym = TM.getSymbol(GV, Mang);
105       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
106     }
108     return TargetLoweringObjectFile::
109       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
110                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
111   }
113   return TargetLoweringObjectFile::
114     getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
117 static SectionKind
118 getELFKindForNamedSection(StringRef Name, SectionKind K) {
119   // N.B.: The defaults used in here are no the same ones used in MC.
120   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
121   // both gas and MC will produce a section with no flags. Given
122   // section(".eh_frame") gcc will produce:
123   //
124   //   .section   .eh_frame,"a",@progbits
125   if (Name.empty() || Name[0] != '.') return K;
127   // Some lame default implementation based on some magic section names.
128   if (Name == ".bss" ||
129       Name.startswith(".bss.") ||
130       Name.startswith(".gnu.linkonce.b.") ||
131       Name.startswith(".llvm.linkonce.b.") ||
132       Name == ".sbss" ||
133       Name.startswith(".sbss.") ||
134       Name.startswith(".gnu.linkonce.sb.") ||
135       Name.startswith(".llvm.linkonce.sb."))
136     return SectionKind::getBSS();
138   if (Name == ".tdata" ||
139       Name.startswith(".tdata.") ||
140       Name.startswith(".gnu.linkonce.td.") ||
141       Name.startswith(".llvm.linkonce.td."))
142     return SectionKind::getThreadData();
144   if (Name == ".tbss" ||
145       Name.startswith(".tbss.") ||
146       Name.startswith(".gnu.linkonce.tb.") ||
147       Name.startswith(".llvm.linkonce.tb."))
148     return SectionKind::getThreadBSS();
150   return K;
154 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
156   if (Name == ".init_array")
157     return ELF::SHT_INIT_ARRAY;
159   if (Name == ".fini_array")
160     return ELF::SHT_FINI_ARRAY;
162   if (Name == ".preinit_array")
163     return ELF::SHT_PREINIT_ARRAY;
165   if (K.isBSS() || K.isThreadBSS())
166     return ELF::SHT_NOBITS;
168   return ELF::SHT_PROGBITS;
172 static unsigned
173 getELFSectionFlags(SectionKind K) {
174   unsigned Flags = 0;
176   if (!K.isMetadata())
177     Flags |= ELF::SHF_ALLOC;
179   if (K.isText())
180     Flags |= ELF::SHF_EXECINSTR;
182   if (K.isWriteable())
183     Flags |= ELF::SHF_WRITE;
185   if (K.isThreadLocal())
186     Flags |= ELF::SHF_TLS;
188   // K.isMergeableConst() is left out to honour PR4650
189   if (K.isMergeableCString() || K.isMergeableConst4() ||
190       K.isMergeableConst8() || K.isMergeableConst16())
191     Flags |= ELF::SHF_MERGE;
193   if (K.isMergeableCString())
194     Flags |= ELF::SHF_STRINGS;
196   return Flags;
199 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
200     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
201     const TargetMachine &TM) const {
202   StringRef SectionName = GV->getSection();
204   // Infer section flags from the section name if we can.
205   Kind = getELFKindForNamedSection(SectionName, Kind);
207   return getContext().getELFSection(SectionName,
208                                     getELFSectionType(SectionName, Kind),
209                                     getELFSectionFlags(Kind), Kind);
212 /// getSectionPrefixForGlobal - Return the section prefix name used by options
213 /// FunctionsSections and DataSections.
214 static const char *getSectionPrefixForGlobal(SectionKind Kind) {
215   if (Kind.isText())                 return ".text.";
216   if (Kind.isReadOnly())             return ".rodata.";
217   if (Kind.isBSS())                  return ".bss.";
219   if (Kind.isThreadData())           return ".tdata.";
220   if (Kind.isThreadBSS())            return ".tbss.";
222   if (Kind.isDataNoRel())            return ".data.";
223   if (Kind.isDataRelLocal())         return ".data.rel.local.";
224   if (Kind.isDataRel())              return ".data.rel.";
225   if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
227   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
228   return ".data.rel.ro.";
232 const MCSection *TargetLoweringObjectFileELF::
233 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
234                        Mangler &Mang, const TargetMachine &TM) const {
235   // If we have -ffunction-section or -fdata-section then we should emit the
236   // global value to a uniqued section specifically for it.
237   bool EmitUniquedSection;
238   if (Kind.isText())
239     EmitUniquedSection = TM.getFunctionSections();
240   else
241     EmitUniquedSection = TM.getDataSections();
243   // If this global is linkonce/weak and the target handles this by emitting it
244   // into a 'uniqued' section name, create and return the section now.
245   if ((GV->isWeakForLinker() || EmitUniquedSection) &&
246       !Kind.isCommon()) {
247     const char *Prefix;
248     Prefix = getSectionPrefixForGlobal(Kind);
250     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
251     TM.getNameWithPrefix(Name, GV, Mang, true);
253     StringRef Group = "";
254     unsigned Flags = getELFSectionFlags(Kind);
255     if (GV->isWeakForLinker()) {
256       Group = Name.substr(strlen(Prefix));
257       Flags |= ELF::SHF_GROUP;
258     }
260     return getContext().getELFSection(Name.str(),
261                                       getELFSectionType(Name.str(), Kind),
262                                       Flags, Kind, 0, Group);
263   }
265   if (Kind.isText()) return TextSection;
267   if (Kind.isMergeable1ByteCString() ||
268       Kind.isMergeable2ByteCString() ||
269       Kind.isMergeable4ByteCString()) {
271     // We also need alignment here.
272     // FIXME: this is getting the alignment of the character, not the
273     // alignment of the global!
274     unsigned Align =
275       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
277     const char *SizeSpec = ".rodata.str1.";
278     if (Kind.isMergeable2ByteCString())
279       SizeSpec = ".rodata.str2.";
280     else if (Kind.isMergeable4ByteCString())
281       SizeSpec = ".rodata.str4.";
282     else
283       assert(Kind.isMergeable1ByteCString() && "unknown string width");
286     std::string Name = SizeSpec + utostr(Align);
287     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
288                                       ELF::SHF_ALLOC |
289                                       ELF::SHF_MERGE |
290                                       ELF::SHF_STRINGS,
291                                       Kind);
292   }
294   if (Kind.isMergeableConst()) {
295     if (Kind.isMergeableConst4() && MergeableConst4Section)
296       return MergeableConst4Section;
297     if (Kind.isMergeableConst8() && MergeableConst8Section)
298       return MergeableConst8Section;
299     if (Kind.isMergeableConst16() && MergeableConst16Section)
300       return MergeableConst16Section;
301     return ReadOnlySection;  // .const
302   }
304   if (Kind.isReadOnly())             return ReadOnlySection;
306   if (Kind.isThreadData())           return TLSDataSection;
307   if (Kind.isThreadBSS())            return TLSBSSSection;
309   // Note: we claim that common symbols are put in BSSSection, but they are
310   // really emitted with the magic .comm directive, which creates a symbol table
311   // entry but not a section.
312   if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
314   if (Kind.isDataNoRel())            return DataSection;
315   if (Kind.isDataRelLocal())         return DataRelLocalSection;
316   if (Kind.isDataRel())              return DataRelSection;
317   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
319   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
320   return DataRelROSection;
323 /// getSectionForConstant - Given a mergeable constant with the
324 /// specified size and relocation information, return a section that it
325 /// should be placed in.
326 const MCSection *TargetLoweringObjectFileELF::
327 getSectionForConstant(SectionKind Kind) const {
328   if (Kind.isMergeableConst4() && MergeableConst4Section)
329     return MergeableConst4Section;
330   if (Kind.isMergeableConst8() && MergeableConst8Section)
331     return MergeableConst8Section;
332   if (Kind.isMergeableConst16() && MergeableConst16Section)
333     return MergeableConst16Section;
334   if (Kind.isReadOnly())
335     return ReadOnlySection;
337   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
338   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
339   return DataRelROSection;
342 const MCSection *
343 TargetLoweringObjectFileELF::getStaticCtorSection(unsigned Priority) const {
344   // The default scheme is .ctor / .dtor, so we have to invert the priority
345   // numbering.
346   if (Priority == 65535)
347     return StaticCtorSection;
349   if (UseInitArray) {
350     std::string Name = std::string(".init_array.") + utostr(Priority);
351     return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
352                                       ELF::SHF_ALLOC | ELF::SHF_WRITE,
353                                       SectionKind::getDataRel());
354   } else {
355     std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
356     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
357                                       ELF::SHF_ALLOC |ELF::SHF_WRITE,
358                                       SectionKind::getDataRel());
359   }
362 const MCSection *
363 TargetLoweringObjectFileELF::getStaticDtorSection(unsigned Priority) const {
364   // The default scheme is .ctor / .dtor, so we have to invert the priority
365   // numbering.
366   if (Priority == 65535)
367     return StaticDtorSection;
369   if (UseInitArray) {
370     std::string Name = std::string(".fini_array.") + utostr(Priority);
371     return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
372                                       ELF::SHF_ALLOC | ELF::SHF_WRITE,
373                                       SectionKind::getDataRel());
374   } else {
375     std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
376     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
377                                       ELF::SHF_ALLOC |ELF::SHF_WRITE,
378                                       SectionKind::getDataRel());
379   }
382 void
383 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
384   UseInitArray = UseInitArray_;
385   if (!UseInitArray)
386     return;
388   StaticCtorSection =
389     getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
390                                ELF::SHF_WRITE |
391                                ELF::SHF_ALLOC,
392                                SectionKind::getDataRel());
393   StaticDtorSection =
394     getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
395                                ELF::SHF_WRITE |
396                                ELF::SHF_ALLOC,
397                                SectionKind::getDataRel());
400 //===----------------------------------------------------------------------===//
401 //                                 MachO
402 //===----------------------------------------------------------------------===//
404 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
405 /// option string. Returns StringRef() if the option does not specify a library.
406 StringRef TargetLoweringObjectFileMachO::
407 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
408   const char *LibCmd = "-l";
409   if (LinkerOption.startswith(LibCmd))
410     return LinkerOption.substr(strlen(LibCmd));
411   return StringRef();
414 /// emitModuleFlags - Perform code emission for module flags.
415 void TargetLoweringObjectFileMachO::
416 emitModuleFlags(MCStreamer &Streamer,
417                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
418                 Mangler &Mang, const TargetMachine &TM) const {
419   unsigned VersionVal = 0;
420   unsigned ImageInfoFlags = 0;
421   MDNode *LinkerOptions = 0;
422   StringRef SectionVal;
424   for (ArrayRef<Module::ModuleFlagEntry>::iterator
425          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
426     const Module::ModuleFlagEntry &MFE = *i;
428     // Ignore flags with 'Require' behavior.
429     if (MFE.Behavior == Module::Require)
430       continue;
432     StringRef Key = MFE.Key->getString();
433     Value *Val = MFE.Val;
435     if (Key == "Objective-C Image Info Version") {
436       VersionVal = cast<ConstantInt>(Val)->getZExtValue();
437     } else if (Key == "Objective-C Garbage Collection" ||
438                Key == "Objective-C GC Only" ||
439                Key == "Objective-C Is Simulated") {
440       ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
441     } else if (Key == "Objective-C Image Info Section") {
442       SectionVal = cast<MDString>(Val)->getString();
443     } else if (Key == "Linker Options") {
444       LinkerOptions = cast<MDNode>(Val);
445     }
446   }
448   // Emit the linker options if present.
449   if (LinkerOptions) {
450     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
451       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
452       SmallVector<std::string, 4> StrOptions;
454       // Convert to strings.
455       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
456         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
457         StrOptions.push_back(MDOption->getString());
458       }
460       Streamer.EmitLinkerOptions(StrOptions);
461     }
462   }
464   // The section is mandatory. If we don't have it, then we don't have GC info.
465   if (SectionVal.empty()) return;
467   StringRef Segment, Section;
468   unsigned TAA = 0, StubSize = 0;
469   bool TAAParsed;
470   std::string ErrorCode =
471     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
472                                           TAA, TAAParsed, StubSize);
473   if (!ErrorCode.empty())
474     // If invalid, report the error with report_fatal_error.
475     report_fatal_error("Invalid section specifier '" + Section + "': " +
476                        ErrorCode + ".");
478   // Get the section.
479   const MCSectionMachO *S =
480     getContext().getMachOSection(Segment, Section, TAA, StubSize,
481                                  SectionKind::getDataNoRel());
482   Streamer.SwitchSection(S);
483   Streamer.EmitLabel(getContext().
484                      GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
485   Streamer.EmitIntValue(VersionVal, 4);
486   Streamer.EmitIntValue(ImageInfoFlags, 4);
487   Streamer.AddBlankLine();
490 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
491     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
492     const TargetMachine &TM) const {
493   // Parse the section specifier and create it if valid.
494   StringRef Segment, Section;
495   unsigned TAA = 0, StubSize = 0;
496   bool TAAParsed;
497   std::string ErrorCode =
498     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
499                                           TAA, TAAParsed, StubSize);
500   if (!ErrorCode.empty()) {
501     // If invalid, report the error with report_fatal_error.
502     report_fatal_error("Global variable '" + GV->getName() +
503                        "' has an invalid section specifier '" +
504                        GV->getSection() + "': " + ErrorCode + ".");
505   }
507   // Get the section.
508   const MCSectionMachO *S =
509     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
511   // If TAA wasn't set by ParseSectionSpecifier() above,
512   // use the value returned by getMachOSection() as a default.
513   if (!TAAParsed)
514     TAA = S->getTypeAndAttributes();
516   // Okay, now that we got the section, verify that the TAA & StubSize agree.
517   // If the user declared multiple globals with different section flags, we need
518   // to reject it here.
519   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
520     // If invalid, report the error with report_fatal_error.
521     report_fatal_error("Global variable '" + GV->getName() +
522                        "' section type or attributes does not match previous"
523                        " section specifier");
524   }
526   return S;
529 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
530     const MCSection &Section) const {
531     const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
533     // Sections holding 1 byte strings are atomized based on the data
534     // they contain.
535     // Sections holding 2 byte strings require symbols in order to be
536     // atomized.
537     // There is no dedicated section for 4 byte strings.
538     if (SMO.getKind().isMergeable1ByteCString())
539       return false;
541     if (SMO.getSegmentName() == "__DATA" &&
542         SMO.getSectionName() == "__cfstring")
543       return false;
545     switch (SMO.getType()) {
546     default:
547       return true;
549       // These sections are atomized at the element boundaries without using
550       // symbols.
551     case MachO::S_4BYTE_LITERALS:
552     case MachO::S_8BYTE_LITERALS:
553     case MachO::S_16BYTE_LITERALS:
554     case MachO::S_LITERAL_POINTERS:
555     case MachO::S_NON_LAZY_SYMBOL_POINTERS:
556     case MachO::S_LAZY_SYMBOL_POINTERS:
557     case MachO::S_MOD_INIT_FUNC_POINTERS:
558     case MachO::S_MOD_TERM_FUNC_POINTERS:
559     case MachO::S_INTERPOSING:
560       return false;
561     }
564 const MCSection *TargetLoweringObjectFileMachO::
565 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
566                        Mangler &Mang, const TargetMachine &TM) const {
568   // Handle thread local data.
569   if (Kind.isThreadBSS()) return TLSBSSSection;
570   if (Kind.isThreadData()) return TLSDataSection;
572   if (Kind.isText())
573     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
575   // If this is weak/linkonce, put this in a coalescable section, either in text
576   // or data depending on if it is writable.
577   if (GV->isWeakForLinker()) {
578     if (Kind.isReadOnly())
579       return ConstTextCoalSection;
580     return DataCoalSection;
581   }
583   // FIXME: Alignment check should be handled by section classifier.
584   if (Kind.isMergeable1ByteCString() &&
585       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
586     return CStringSection;
588   // Do not put 16-bit arrays in the UString section if they have an
589   // externally visible label, this runs into issues with certain linker
590   // versions.
591   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
592       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
593     return UStringSection;
595   if (Kind.isMergeableConst()) {
596     if (Kind.isMergeableConst4())
597       return FourByteConstantSection;
598     if (Kind.isMergeableConst8())
599       return EightByteConstantSection;
600     if (Kind.isMergeableConst16())
601       return SixteenByteConstantSection;
602   }
604   // Otherwise, if it is readonly, but not something we can specially optimize,
605   // just drop it in .const.
606   if (Kind.isReadOnly())
607     return ReadOnlySection;
609   // If this is marked const, put it into a const section.  But if the dynamic
610   // linker needs to write to it, put it in the data segment.
611   if (Kind.isReadOnlyWithRel())
612     return ConstDataSection;
614   // Put zero initialized globals with strong external linkage in the
615   // DATA, __common section with the .zerofill directive.
616   if (Kind.isBSSExtern())
617     return DataCommonSection;
619   // Put zero initialized globals with local linkage in __DATA,__bss directive
620   // with the .zerofill directive (aka .lcomm).
621   if (Kind.isBSSLocal())
622     return DataBSSSection;
624   // Otherwise, just drop the variable in the normal data section.
625   return DataSection;
628 const MCSection *
629 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
630   // If this constant requires a relocation, we have to put it in the data
631   // segment, not in the text segment.
632   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
633     return ConstDataSection;
635   if (Kind.isMergeableConst4())
636     return FourByteConstantSection;
637   if (Kind.isMergeableConst8())
638     return EightByteConstantSection;
639   if (Kind.isMergeableConst16())
640     return SixteenByteConstantSection;
641   return ReadOnlySection;  // .const
644 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
645     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
646     const TargetMachine &TM, MachineModuleInfo *MMI,
647     MCStreamer &Streamer) const {
648   // The mach-o version of this method defaults to returning a stub reference.
650   if (Encoding & DW_EH_PE_indirect) {
651     MachineModuleInfoMachO &MachOMMI =
652       MMI->getObjFileInfo<MachineModuleInfoMachO>();
654     MCSymbol *SSym =
655         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
657     // Add information about the stub reference to MachOMMI so that the stub
658     // gets emitted by the asmprinter.
659     MachineModuleInfoImpl::StubValueTy &StubSym =
660       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
661                                   MachOMMI.getGVStubEntry(SSym);
662     if (StubSym.getPointer() == 0) {
663       MCSymbol *Sym = TM.getSymbol(GV, Mang);
664       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
665     }
667     return TargetLoweringObjectFile::
668       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
669                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
670   }
672   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
673                                                            TM, MMI, Streamer);
676 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
677     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
678     MachineModuleInfo *MMI) const {
679   // The mach-o version of this method defaults to returning a stub reference.
680   MachineModuleInfoMachO &MachOMMI =
681     MMI->getObjFileInfo<MachineModuleInfoMachO>();
683   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
685   // Add information about the stub reference to MachOMMI so that the stub
686   // gets emitted by the asmprinter.
687   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
688   if (StubSym.getPointer() == 0) {
689     MCSymbol *Sym = TM.getSymbol(GV, Mang);
690     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
691   }
693   return SSym;
696 //===----------------------------------------------------------------------===//
697 //                                  COFF
698 //===----------------------------------------------------------------------===//
700 static unsigned
701 getCOFFSectionFlags(SectionKind K) {
702   unsigned Flags = 0;
704   if (K.isMetadata())
705     Flags |=
706       COFF::IMAGE_SCN_MEM_DISCARDABLE;
707   else if (K.isText())
708     Flags |=
709       COFF::IMAGE_SCN_MEM_EXECUTE |
710       COFF::IMAGE_SCN_MEM_READ |
711       COFF::IMAGE_SCN_CNT_CODE;
712   else if (K.isBSS ())
713     Flags |=
714       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
715       COFF::IMAGE_SCN_MEM_READ |
716       COFF::IMAGE_SCN_MEM_WRITE;
717   else if (K.isThreadLocal())
718     Flags |=
719       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
720       COFF::IMAGE_SCN_MEM_READ |
721       COFF::IMAGE_SCN_MEM_WRITE;
722   else if (K.isReadOnly())
723     Flags |=
724       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
725       COFF::IMAGE_SCN_MEM_READ;
726   else if (K.isWriteable())
727     Flags |=
728       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
729       COFF::IMAGE_SCN_MEM_READ |
730       COFF::IMAGE_SCN_MEM_WRITE;
732   return Flags;
735 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
736     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
737     const TargetMachine &TM) const {
738   int Selection = 0;
739   unsigned Characteristics = getCOFFSectionFlags(Kind);
740   StringRef Name = GV->getSection();
741   StringRef COMDATSymName = "";
742   if (GV->isWeakForLinker()) {
743     Selection = COFF::IMAGE_COMDAT_SELECT_ANY;
744     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
745     MCSymbol *Sym = TM.getSymbol(GV, Mang);
746     COMDATSymName = Sym->getName();
747   }
748   return getContext().getCOFFSection(Name,
749                                      Characteristics,
750                                      Kind,
751                                      COMDATSymName,
752                                      Selection);
755 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
756   if (Kind.isText())
757     return ".text";
758   if (Kind.isBSS ())
759     return ".bss";
760   if (Kind.isThreadLocal())
761     return ".tls$";
762   if (Kind.isWriteable())
763     return ".data";
764   return ".rdata";
768 const MCSection *TargetLoweringObjectFileCOFF::
769 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
770                        Mangler &Mang, const TargetMachine &TM) const {
771   // If we have -ffunction-sections then we should emit the global value to a
772   // uniqued section specifically for it.
773   bool EmitUniquedSection;
774   if (Kind.isText())
775     EmitUniquedSection = TM.getFunctionSections();
776   else
777     EmitUniquedSection = TM.getDataSections();
779   // If this global is linkonce/weak and the target handles this by emitting it
780   // into a 'uniqued' section name, create and return the section now.
781   // Section names depend on the name of the symbol which is not feasible if the
782   // symbol has private linkage.
783   if ((GV->isWeakForLinker() || EmitUniquedSection) &&
784       !GV->hasPrivateLinkage()) {
785     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
786     unsigned Characteristics = getCOFFSectionFlags(Kind);
788     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
789     MCSymbol *Sym = TM.getSymbol(GV, Mang);
790     return getContext().getCOFFSection(
791         Name, Characteristics, Kind, Sym->getName(),
792         GV->isWeakForLinker() ? COFF::IMAGE_COMDAT_SELECT_ANY
793                               : COFF::IMAGE_COMDAT_SELECT_NODUPLICATES);
794   }
796   if (Kind.isText())
797     return TextSection;
799   if (Kind.isThreadLocal())
800     return TLSDataSection;
802   if (Kind.isReadOnly())
803     return ReadOnlySection;
805   if (Kind.isBSS())
806     return BSSSection;
808   return DataSection;
811 StringRef TargetLoweringObjectFileCOFF::
812 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
813   const char *LibCmd = "/DEFAULTLIB:";
814   if (LinkerOption.startswith(LibCmd))
815     return LinkerOption.substr(strlen(LibCmd));
816   return StringRef();
819 void TargetLoweringObjectFileCOFF::
820 emitModuleFlags(MCStreamer &Streamer,
821                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
822                 Mangler &Mang, const TargetMachine &TM) const {
823   MDNode *LinkerOptions = 0;
825   // Look for the "Linker Options" flag, since it's the only one we support.
826   for (ArrayRef<Module::ModuleFlagEntry>::iterator
827        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
828     const Module::ModuleFlagEntry &MFE = *i;
829     StringRef Key = MFE.Key->getString();
830     Value *Val = MFE.Val;
831     if (Key == "Linker Options") {
832       LinkerOptions = cast<MDNode>(Val);
833       break;
834     }
835   }
836   if (!LinkerOptions)
837     return;
839   // Emit the linker options to the linker .drectve section.  According to the
840   // spec, this section is a space-separated string containing flags for linker.
841   const MCSection *Sec = getDrectveSection();
842   Streamer.SwitchSection(Sec);
843   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
844     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
845     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
846       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
847       StringRef Op = MDOption->getString();
848       // Lead with a space for consistency with our dllexport implementation.
849       std::string Escaped(" ");
850       if (Op.find(" ") != StringRef::npos) {
851         // The PE-COFF spec says args with spaces must be quoted.  It doesn't say
852         // how to escape quotes, but it probably uses this algorithm:
853         // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
854         // FIXME: Reuse escaping code from Support/Windows/Program.inc
855         Escaped.push_back('\"');
856         Escaped.append(Op);
857         Escaped.push_back('\"');
858       } else {
859         Escaped.append(Op);
860       }
861       Streamer.EmitBytes(Escaped);
862     }
863   }