Look for the 'Is Simulated' module flag. This indicates that the program is compiled...
[oota-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 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Module.h"
21 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCExpr.h"
24 #include "llvm/MC/MCSectionMachO.h"
25 #include "llvm/MC/MCSectionELF.h"
26 #include "llvm/MC/MCSectionCOFF.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/MC/MCSymbol.h"
29 #include "llvm/Target/Mangler.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/Dwarf.h"
34 #include "llvm/Support/ELF.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/StringExtras.h"
39 #include "llvm/ADT/Triple.h"
40 using namespace llvm;
41 using namespace dwarf;
42
43 //===----------------------------------------------------------------------===//
44 //                                  ELF
45 //===----------------------------------------------------------------------===//
46
47 MCSymbol *
48 TargetLoweringObjectFileELF::getCFIPersonalitySymbol(const GlobalValue *GV,
49                                                      Mangler *Mang,
50                                                 MachineModuleInfo *MMI) const {
51   unsigned Encoding = getPersonalityEncoding();
52   switch (Encoding & 0x70) {
53   default:
54     report_fatal_error("We do not support this DWARF encoding yet!");
55   case dwarf::DW_EH_PE_absptr:
56     return  Mang->getSymbol(GV);
57   case dwarf::DW_EH_PE_pcrel: {
58     return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
59                                           Mang->getSymbol(GV)->getName());
60   }
61   }
62 }
63
64 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
65                                                        const TargetMachine &TM,
66                                                        const MCSymbol *Sym) const {
67   SmallString<64> NameData("DW.ref.");
68   NameData += Sym->getName();
69   MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
70   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
71   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
72   StringRef Prefix = ".data.";
73   NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
74   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
75   const MCSection *Sec = getContext().getELFSection(NameData,
76                                                     ELF::SHT_PROGBITS,
77                                                     Flags,
78                                                     SectionKind::getDataRel(),
79                                                     0, Label->getName());
80   unsigned Size = TM.getTargetData()->getPointerSize();
81   Streamer.SwitchSection(Sec);
82   Streamer.EmitValueToAlignment(TM.getTargetData()->getPointerABIAlignment());
83   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
84   const MCExpr *E = MCConstantExpr::Create(Size, getContext());
85   Streamer.EmitELFSize(Label, E);
86   Streamer.EmitLabel(Label);
87
88   Streamer.EmitSymbolValue(Sym, Size);
89 }
90
91 static SectionKind
92 getELFKindForNamedSection(StringRef Name, SectionKind K) {
93   // N.B.: The defaults used in here are no the same ones used in MC.
94   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
95   // both gas and MC will produce a section with no flags. Given
96   // section(".eh_frame") gcc will produce
97   // .section   .eh_frame,"a",@progbits
98   if (Name.empty() || Name[0] != '.') return K;
99
100   // Some lame default implementation based on some magic section names.
101   if (Name == ".bss" ||
102       Name.startswith(".bss.") ||
103       Name.startswith(".gnu.linkonce.b.") ||
104       Name.startswith(".llvm.linkonce.b.") ||
105       Name == ".sbss" ||
106       Name.startswith(".sbss.") ||
107       Name.startswith(".gnu.linkonce.sb.") ||
108       Name.startswith(".llvm.linkonce.sb."))
109     return SectionKind::getBSS();
110
111   if (Name == ".tdata" ||
112       Name.startswith(".tdata.") ||
113       Name.startswith(".gnu.linkonce.td.") ||
114       Name.startswith(".llvm.linkonce.td."))
115     return SectionKind::getThreadData();
116
117   if (Name == ".tbss" ||
118       Name.startswith(".tbss.") ||
119       Name.startswith(".gnu.linkonce.tb.") ||
120       Name.startswith(".llvm.linkonce.tb."))
121     return SectionKind::getThreadBSS();
122
123   return K;
124 }
125
126
127 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
128
129   if (Name == ".init_array")
130     return ELF::SHT_INIT_ARRAY;
131
132   if (Name == ".fini_array")
133     return ELF::SHT_FINI_ARRAY;
134
135   if (Name == ".preinit_array")
136     return ELF::SHT_PREINIT_ARRAY;
137
138   if (K.isBSS() || K.isThreadBSS())
139     return ELF::SHT_NOBITS;
140
141   return ELF::SHT_PROGBITS;
142 }
143
144
145 static unsigned
146 getELFSectionFlags(SectionKind K) {
147   unsigned Flags = 0;
148
149   if (!K.isMetadata())
150     Flags |= ELF::SHF_ALLOC;
151
152   if (K.isText())
153     Flags |= ELF::SHF_EXECINSTR;
154
155   if (K.isWriteable())
156     Flags |= ELF::SHF_WRITE;
157
158   if (K.isThreadLocal())
159     Flags |= ELF::SHF_TLS;
160
161   // K.isMergeableConst() is left out to honour PR4650
162   if (K.isMergeableCString() || K.isMergeableConst4() ||
163       K.isMergeableConst8() || K.isMergeableConst16())
164     Flags |= ELF::SHF_MERGE;
165
166   if (K.isMergeableCString())
167     Flags |= ELF::SHF_STRINGS;
168
169   return Flags;
170 }
171
172
173 const MCSection *TargetLoweringObjectFileELF::
174 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
175                          Mangler *Mang, const TargetMachine &TM) const {
176   StringRef SectionName = GV->getSection();
177
178   // Infer section flags from the section name if we can.
179   Kind = getELFKindForNamedSection(SectionName, Kind);
180
181   return getContext().getELFSection(SectionName,
182                                     getELFSectionType(SectionName, Kind),
183                                     getELFSectionFlags(Kind), Kind);
184 }
185
186 /// getSectionPrefixForGlobal - Return the section prefix name used by options
187 /// FunctionsSections and DataSections.
188 static const char *getSectionPrefixForGlobal(SectionKind Kind) {
189   if (Kind.isText())                 return ".text.";
190   if (Kind.isReadOnly())             return ".rodata.";
191   if (Kind.isBSS())                  return ".bss.";
192
193   if (Kind.isThreadData())           return ".tdata.";
194   if (Kind.isThreadBSS())            return ".tbss.";
195
196   if (Kind.isDataNoRel())            return ".data.";
197   if (Kind.isDataRelLocal())         return ".data.rel.local.";
198   if (Kind.isDataRel())              return ".data.rel.";
199   if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
200
201   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
202   return ".data.rel.ro.";
203 }
204
205
206 const MCSection *TargetLoweringObjectFileELF::
207 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
208                        Mangler *Mang, const TargetMachine &TM) const {
209   // If we have -ffunction-section or -fdata-section then we should emit the
210   // global value to a uniqued section specifically for it.
211   bool EmitUniquedSection;
212   if (Kind.isText())
213     EmitUniquedSection = TM.getFunctionSections();
214   else
215     EmitUniquedSection = TM.getDataSections();
216
217   // If this global is linkonce/weak and the target handles this by emitting it
218   // into a 'uniqued' section name, create and return the section now.
219   if ((GV->isWeakForLinker() || EmitUniquedSection) &&
220       !Kind.isCommon()) {
221     const char *Prefix;
222     Prefix = getSectionPrefixForGlobal(Kind);
223
224     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
225     MCSymbol *Sym = Mang->getSymbol(GV);
226     Name.append(Sym->getName().begin(), Sym->getName().end());
227     StringRef Group = "";
228     unsigned Flags = getELFSectionFlags(Kind);
229     if (GV->isWeakForLinker()) {
230       Group = Sym->getName();
231       Flags |= ELF::SHF_GROUP;
232     }
233
234     return getContext().getELFSection(Name.str(),
235                                       getELFSectionType(Name.str(), Kind),
236                                       Flags, Kind, 0, Group);
237   }
238
239   if (Kind.isText()) return TextSection;
240
241   if (Kind.isMergeable1ByteCString() ||
242       Kind.isMergeable2ByteCString() ||
243       Kind.isMergeable4ByteCString()) {
244
245     // We also need alignment here.
246     // FIXME: this is getting the alignment of the character, not the
247     // alignment of the global!
248     unsigned Align =
249       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV));
250
251     const char *SizeSpec = ".rodata.str1.";
252     if (Kind.isMergeable2ByteCString())
253       SizeSpec = ".rodata.str2.";
254     else if (Kind.isMergeable4ByteCString())
255       SizeSpec = ".rodata.str4.";
256     else
257       assert(Kind.isMergeable1ByteCString() && "unknown string width");
258
259
260     std::string Name = SizeSpec + utostr(Align);
261     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
262                                       ELF::SHF_ALLOC |
263                                       ELF::SHF_MERGE |
264                                       ELF::SHF_STRINGS,
265                                       Kind);
266   }
267
268   if (Kind.isMergeableConst()) {
269     if (Kind.isMergeableConst4() && MergeableConst4Section)
270       return MergeableConst4Section;
271     if (Kind.isMergeableConst8() && MergeableConst8Section)
272       return MergeableConst8Section;
273     if (Kind.isMergeableConst16() && MergeableConst16Section)
274       return MergeableConst16Section;
275     return ReadOnlySection;  // .const
276   }
277
278   if (Kind.isReadOnly())             return ReadOnlySection;
279
280   if (Kind.isThreadData())           return TLSDataSection;
281   if (Kind.isThreadBSS())            return TLSBSSSection;
282
283   // Note: we claim that common symbols are put in BSSSection, but they are
284   // really emitted with the magic .comm directive, which creates a symbol table
285   // entry but not a section.
286   if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
287
288   if (Kind.isDataNoRel())            return DataSection;
289   if (Kind.isDataRelLocal())         return DataRelLocalSection;
290   if (Kind.isDataRel())              return DataRelSection;
291   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
292
293   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
294   return DataRelROSection;
295 }
296
297 /// getSectionForConstant - Given a mergeable constant with the
298 /// specified size and relocation information, return a section that it
299 /// should be placed in.
300 const MCSection *TargetLoweringObjectFileELF::
301 getSectionForConstant(SectionKind Kind) const {
302   if (Kind.isMergeableConst4() && MergeableConst4Section)
303     return MergeableConst4Section;
304   if (Kind.isMergeableConst8() && MergeableConst8Section)
305     return MergeableConst8Section;
306   if (Kind.isMergeableConst16() && MergeableConst16Section)
307     return MergeableConst16Section;
308   if (Kind.isReadOnly())
309     return ReadOnlySection;
310
311   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
312   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
313   return DataRelROSection;
314 }
315
316 const MCExpr *TargetLoweringObjectFileELF::
317 getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
318                                MachineModuleInfo *MMI,
319                                unsigned Encoding, MCStreamer &Streamer) const {
320
321   if (Encoding & dwarf::DW_EH_PE_indirect) {
322     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
323
324     SmallString<128> Name;
325     Mang->getNameWithPrefix(Name, GV, true);
326     Name += ".DW.stub";
327
328     // Add information about the stub reference to ELFMMI so that the stub
329     // gets emitted by the asmprinter.
330     MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
331     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
332     if (StubSym.getPointer() == 0) {
333       MCSymbol *Sym = Mang->getSymbol(GV);
334       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
335     }
336
337     return TargetLoweringObjectFile::
338       getExprForDwarfReference(SSym, Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
339   }
340
341   return TargetLoweringObjectFile::
342     getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, Streamer);
343 }
344
345 const MCSection *
346 TargetLoweringObjectFileELF::getStaticCtorSection(unsigned Priority) const {
347   // The default scheme is .ctor / .dtor, so we have to invert the priority
348   // numbering.
349   if (Priority == 65535)
350     return StaticCtorSection;
351
352   std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
353   return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
354                                     ELF::SHF_ALLOC |ELF::SHF_WRITE,
355                                     SectionKind::getDataRel());
356 }
357
358 const MCSection *
359 TargetLoweringObjectFileELF::getStaticDtorSection(unsigned Priority) const {
360   // The default scheme is .ctor / .dtor, so we have to invert the priority
361   // numbering.
362   if (Priority == 65535)
363     return StaticDtorSection;
364
365   std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
366   return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
367                                     ELF::SHF_ALLOC |ELF::SHF_WRITE,
368                                     SectionKind::getDataRel());
369 }
370
371 //===----------------------------------------------------------------------===//
372 //                                 MachO
373 //===----------------------------------------------------------------------===//
374
375 /// emitModuleFlags - Emit the module flags that specify the garbage collection
376 /// information.
377 void TargetLoweringObjectFileMachO::
378 emitModuleFlags(MCStreamer &Streamer,
379                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
380                 Mangler *Mang, const TargetMachine &TM) const {
381   unsigned VersionVal = 0;
382   unsigned ImageInfoFlags = 0;
383   StringRef SectionVal;
384
385   for (ArrayRef<Module::ModuleFlagEntry>::iterator
386          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
387     const Module::ModuleFlagEntry &MFE = *i;
388
389     // Ignore flags with 'Require' behavior.
390     if (MFE.Behavior == Module::Require)
391       continue;
392
393     StringRef Key = MFE.Key->getString();
394     Value *Val = MFE.Val;
395
396     if (Key == "Objective-C Image Info Version")
397       VersionVal = cast<ConstantInt>(Val)->getZExtValue();
398     else if (Key == "Objective-C Garbage Collection" ||
399              Key == "Objective-C GC Only" ||
400              Key == "Objective-C Is Simulated")
401       ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
402     else if (Key == "Objective-C Image Info Section")
403       SectionVal = cast<MDString>(Val)->getString();
404   }
405
406   // The section is mandatory. If we don't have it, then we don't have GC info.
407   if (SectionVal.empty()) return;
408
409   StringRef Segment, Section;
410   unsigned TAA = 0, StubSize = 0;
411   bool TAAParsed;
412   std::string ErrorCode =
413     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
414                                           TAA, TAAParsed, StubSize);
415   if (!ErrorCode.empty())
416     // If invalid, report the error with report_fatal_error.
417     report_fatal_error("Invalid section specifier '" + Section + "': " +
418                        ErrorCode + ".");
419
420   // Get the section.
421   const MCSectionMachO *S =
422     getContext().getMachOSection(Segment, Section, TAA, StubSize,
423                                  SectionKind::getDataNoRel());
424   Streamer.SwitchSection(S);
425   Streamer.EmitLabel(getContext().
426                      GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
427   Streamer.EmitIntValue(VersionVal, 4);
428   Streamer.EmitIntValue(ImageInfoFlags, 4);
429   Streamer.AddBlankLine();
430 }
431
432 const MCSection *TargetLoweringObjectFileMachO::
433 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
434                          Mangler *Mang, const TargetMachine &TM) const {
435   // Parse the section specifier and create it if valid.
436   StringRef Segment, Section;
437   unsigned TAA = 0, StubSize = 0;
438   bool TAAParsed;
439   std::string ErrorCode =
440     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
441                                           TAA, TAAParsed, StubSize);
442   if (!ErrorCode.empty()) {
443     // If invalid, report the error with report_fatal_error.
444     report_fatal_error("Global variable '" + GV->getName() +
445                        "' has an invalid section specifier '" +
446                        GV->getSection() + "': " + ErrorCode + ".");
447   }
448
449   // Get the section.
450   const MCSectionMachO *S =
451     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
452
453   // If TAA wasn't set by ParseSectionSpecifier() above,
454   // use the value returned by getMachOSection() as a default.
455   if (!TAAParsed)
456     TAA = S->getTypeAndAttributes();
457
458   // Okay, now that we got the section, verify that the TAA & StubSize agree.
459   // If the user declared multiple globals with different section flags, we need
460   // to reject it here.
461   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
462     // If invalid, report the error with report_fatal_error.
463     report_fatal_error("Global variable '" + GV->getName() +
464                        "' section type or attributes does not match previous"
465                        " section specifier");
466   }
467
468   return S;
469 }
470
471 const MCSection *TargetLoweringObjectFileMachO::
472 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
473                        Mangler *Mang, const TargetMachine &TM) const {
474
475   // Handle thread local data.
476   if (Kind.isThreadBSS()) return TLSBSSSection;
477   if (Kind.isThreadData()) return TLSDataSection;
478
479   if (Kind.isText())
480     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
481
482   // If this is weak/linkonce, put this in a coalescable section, either in text
483   // or data depending on if it is writable.
484   if (GV->isWeakForLinker()) {
485     if (Kind.isReadOnly())
486       return ConstTextCoalSection;
487     return DataCoalSection;
488   }
489
490   // FIXME: Alignment check should be handled by section classifier.
491   if (Kind.isMergeable1ByteCString() &&
492       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
493     return CStringSection;
494
495   // Do not put 16-bit arrays in the UString section if they have an
496   // externally visible label, this runs into issues with certain linker
497   // versions.
498   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
499       TM.getTargetData()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
500     return UStringSection;
501
502   if (Kind.isMergeableConst()) {
503     if (Kind.isMergeableConst4())
504       return FourByteConstantSection;
505     if (Kind.isMergeableConst8())
506       return EightByteConstantSection;
507     if (Kind.isMergeableConst16() && SixteenByteConstantSection)
508       return SixteenByteConstantSection;
509   }
510
511   // Otherwise, if it is readonly, but not something we can specially optimize,
512   // just drop it in .const.
513   if (Kind.isReadOnly())
514     return ReadOnlySection;
515
516   // If this is marked const, put it into a const section.  But if the dynamic
517   // linker needs to write to it, put it in the data segment.
518   if (Kind.isReadOnlyWithRel())
519     return ConstDataSection;
520
521   // Put zero initialized globals with strong external linkage in the
522   // DATA, __common section with the .zerofill directive.
523   if (Kind.isBSSExtern())
524     return DataCommonSection;
525
526   // Put zero initialized globals with local linkage in __DATA,__bss directive
527   // with the .zerofill directive (aka .lcomm).
528   if (Kind.isBSSLocal())
529     return DataBSSSection;
530
531   // Otherwise, just drop the variable in the normal data section.
532   return DataSection;
533 }
534
535 const MCSection *
536 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
537   // If this constant requires a relocation, we have to put it in the data
538   // segment, not in the text segment.
539   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
540     return ConstDataSection;
541
542   if (Kind.isMergeableConst4())
543     return FourByteConstantSection;
544   if (Kind.isMergeableConst8())
545     return EightByteConstantSection;
546   if (Kind.isMergeableConst16() && SixteenByteConstantSection)
547     return SixteenByteConstantSection;
548   return ReadOnlySection;  // .const
549 }
550
551 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
552 /// not to emit the UsedDirective for some symbols in llvm.used.
553 // FIXME: REMOVE this (rdar://7071300)
554 bool TargetLoweringObjectFileMachO::
555 shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *Mang) const {
556   /// On Darwin, internally linked data beginning with "L" or "l" does not have
557   /// the directive emitted (this occurs in ObjC metadata).
558   if (!GV) return false;
559
560   // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
561   if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
562     // FIXME: ObjC metadata is currently emitted as internal symbols that have
563     // \1L and \0l prefixes on them.  Fix them to be Private/LinkerPrivate and
564     // this horrible hack can go away.
565     MCSymbol *Sym = Mang->getSymbol(GV);
566     if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l')
567       return false;
568   }
569
570   return true;
571 }
572
573 const MCExpr *TargetLoweringObjectFileMachO::
574 getExprForDwarfGlobalReference(const GlobalValue *GV, Mangler *Mang,
575                                MachineModuleInfo *MMI, unsigned Encoding,
576                                MCStreamer &Streamer) const {
577   // The mach-o version of this method defaults to returning a stub reference.
578
579   if (Encoding & DW_EH_PE_indirect) {
580     MachineModuleInfoMachO &MachOMMI =
581       MMI->getObjFileInfo<MachineModuleInfoMachO>();
582
583     SmallString<128> Name;
584     Mang->getNameWithPrefix(Name, GV, true);
585     Name += "$non_lazy_ptr";
586
587     // Add information about the stub reference to MachOMMI so that the stub
588     // gets emitted by the asmprinter.
589     MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
590     MachineModuleInfoImpl::StubValueTy &StubSym =
591       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
592                                   MachOMMI.getGVStubEntry(SSym);
593     if (StubSym.getPointer() == 0) {
594       MCSymbol *Sym = Mang->getSymbol(GV);
595       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
596     }
597
598     return TargetLoweringObjectFile::
599       getExprForDwarfReference(SSym, Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
600   }
601
602   return TargetLoweringObjectFile::
603     getExprForDwarfGlobalReference(GV, Mang, MMI, Encoding, Streamer);
604 }
605
606 MCSymbol *TargetLoweringObjectFileMachO::
607 getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang,
608                         MachineModuleInfo *MMI) const {
609   // The mach-o version of this method defaults to returning a stub reference.
610   MachineModuleInfoMachO &MachOMMI =
611     MMI->getObjFileInfo<MachineModuleInfoMachO>();
612
613   SmallString<128> Name;
614   Mang->getNameWithPrefix(Name, GV, true);
615   Name += "$non_lazy_ptr";
616
617   // Add information about the stub reference to MachOMMI so that the stub
618   // gets emitted by the asmprinter.
619   MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
620   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
621   if (StubSym.getPointer() == 0) {
622     MCSymbol *Sym = Mang->getSymbol(GV);
623     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
624   }
625
626   return SSym;
627 }
628
629 //===----------------------------------------------------------------------===//
630 //                                  COFF
631 //===----------------------------------------------------------------------===//
632
633 static unsigned
634 getCOFFSectionFlags(SectionKind K) {
635   unsigned Flags = 0;
636
637   if (K.isMetadata())
638     Flags |=
639       COFF::IMAGE_SCN_MEM_DISCARDABLE;
640   else if (K.isText())
641     Flags |=
642       COFF::IMAGE_SCN_MEM_EXECUTE |
643       COFF::IMAGE_SCN_MEM_READ |
644       COFF::IMAGE_SCN_CNT_CODE;
645   else if (K.isBSS ())
646     Flags |=
647       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
648       COFF::IMAGE_SCN_MEM_READ |
649       COFF::IMAGE_SCN_MEM_WRITE;
650   else if (K.isThreadLocal())
651     Flags |=
652       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
653       COFF::IMAGE_SCN_MEM_READ |
654       COFF::IMAGE_SCN_MEM_WRITE;
655   else if (K.isReadOnly())
656     Flags |=
657       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
658       COFF::IMAGE_SCN_MEM_READ;
659   else if (K.isWriteable())
660     Flags |=
661       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
662       COFF::IMAGE_SCN_MEM_READ |
663       COFF::IMAGE_SCN_MEM_WRITE;
664
665   return Flags;
666 }
667
668 const MCSection *TargetLoweringObjectFileCOFF::
669 getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind,
670                          Mangler *Mang, const TargetMachine &TM) const {
671   return getContext().getCOFFSection(GV->getSection(),
672                                      getCOFFSectionFlags(Kind),
673                                      Kind);
674 }
675
676 static const char *getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind) {
677   if (Kind.isText())
678     return ".text$";
679   if (Kind.isBSS ())
680     return ".bss$";
681   if (Kind.isThreadLocal())
682     return ".tls$";
683   if (Kind.isWriteable())
684     return ".data$";
685   return ".rdata$";
686 }
687
688
689 const MCSection *TargetLoweringObjectFileCOFF::
690 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
691                        Mangler *Mang, const TargetMachine &TM) const {
692
693   // If this global is linkonce/weak and the target handles this by emitting it
694   // into a 'uniqued' section name, create and return the section now.
695   if (GV->isWeakForLinker()) {
696     const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
697     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
698     MCSymbol *Sym = Mang->getSymbol(GV);
699     Name.append(Sym->getName().begin() + 1, Sym->getName().end());
700
701     unsigned Characteristics = getCOFFSectionFlags(Kind);
702
703     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
704
705     return getContext().getCOFFSection(Name.str(), Characteristics,
706                           COFF::IMAGE_COMDAT_SELECT_ANY, Kind);
707   }
708
709   if (Kind.isText())
710     return getTextSection();
711
712   if (Kind.isThreadLocal())
713     return getTLSDataSection();
714
715   return getDataSection();
716 }
717