CodeGen: Avoid multiple strlen calls
[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/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;
42
43 //===----------------------------------------------------------------------===//
44 //                                  ELF
45 //===----------------------------------------------------------------------===//
46
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!");
57 }
58
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,
71                                                     ELF::SHT_PROGBITS,
72                                                     Flags,
73                                                     SectionKind::getDataRel(),
74                                                     0, Label->getName());
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);
82
83   Streamer.EmitSymbolValue(Sym, Size);
84 }
85
86 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
87     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
88     const TargetMachine &TM, MachineModuleInfo *MMI,
89     MCStreamer &Streamer) const {
90
91   if (Encoding & dwarf::DW_EH_PE_indirect) {
92     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
93
94     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
95
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());
102     }
103
104     return TargetLoweringObjectFile::
105       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
106                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
107   }
108
109   return TargetLoweringObjectFile::
110     getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
111 }
112
113 static SectionKind
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:
119   //
120   //   .section   .eh_frame,"a",@progbits
121   if (Name.empty() || Name[0] != '.') return K;
122
123   // Some lame default implementation based on some magic section names.
124   if (Name == ".bss" ||
125       Name.startswith(".bss.") ||
126       Name.startswith(".gnu.linkonce.b.") ||
127       Name.startswith(".llvm.linkonce.b.") ||
128       Name == ".sbss" ||
129       Name.startswith(".sbss.") ||
130       Name.startswith(".gnu.linkonce.sb.") ||
131       Name.startswith(".llvm.linkonce.sb."))
132     return SectionKind::getBSS();
133
134   if (Name == ".tdata" ||
135       Name.startswith(".tdata.") ||
136       Name.startswith(".gnu.linkonce.td.") ||
137       Name.startswith(".llvm.linkonce.td."))
138     return SectionKind::getThreadData();
139
140   if (Name == ".tbss" ||
141       Name.startswith(".tbss.") ||
142       Name.startswith(".gnu.linkonce.tb.") ||
143       Name.startswith(".llvm.linkonce.tb."))
144     return SectionKind::getThreadBSS();
145
146   return K;
147 }
148
149
150 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
151
152   if (Name == ".init_array")
153     return ELF::SHT_INIT_ARRAY;
154
155   if (Name == ".fini_array")
156     return ELF::SHT_FINI_ARRAY;
157
158   if (Name == ".preinit_array")
159     return ELF::SHT_PREINIT_ARRAY;
160
161   if (K.isBSS() || K.isThreadBSS())
162     return ELF::SHT_NOBITS;
163
164   return ELF::SHT_PROGBITS;
165 }
166
167
168 static unsigned
169 getELFSectionFlags(SectionKind K) {
170   unsigned Flags = 0;
171
172   if (!K.isMetadata())
173     Flags |= ELF::SHF_ALLOC;
174
175   if (K.isText())
176     Flags |= ELF::SHF_EXECINSTR;
177
178   if (K.isWriteable())
179     Flags |= ELF::SHF_WRITE;
180
181   if (K.isThreadLocal())
182     Flags |= ELF::SHF_TLS;
183
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;
188
189   if (K.isMergeableCString())
190     Flags |= ELF::SHF_STRINGS;
191
192   return Flags;
193 }
194
195 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
196     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
197     const TargetMachine &TM) const {
198   StringRef SectionName = GV->getSection();
199
200   // Infer section flags from the section name if we can.
201   Kind = getELFKindForNamedSection(SectionName, Kind);
202
203   return getContext().getELFSection(SectionName,
204                                     getELFSectionType(SectionName, Kind),
205                                     getELFSectionFlags(Kind), Kind);
206 }
207
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.";
214
215   if (Kind.isThreadData())           return ".tdata.";
216   if (Kind.isThreadBSS())            return ".tbss.";
217
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.";
222
223   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
224   return ".data.rel.ro.";
225 }
226
227
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;
234   if (Kind.isText())
235     EmitUniquedSection = TM.getFunctionSections();
236   else
237     EmitUniquedSection = TM.getDataSections();
238
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) &&
242       !Kind.isCommon()) {
243     StringRef Prefix = getSectionPrefixForGlobal(Kind);
244
245     SmallString<128> Name(Prefix);
246     TM.getNameWithPrefix(Name, GV, Mang, true);
247
248     StringRef Group = "";
249     unsigned Flags = getELFSectionFlags(Kind);
250     if (GV->isWeakForLinker()) {
251       Group = Name.substr(Prefix.size());
252       Flags |= ELF::SHF_GROUP;
253     }
254
255     return getContext().getELFSection(Name.str(),
256                                       getELFSectionType(Name.str(), Kind),
257                                       Flags, Kind, 0, Group);
258   }
259
260   if (Kind.isText()) return TextSection;
261
262   if (Kind.isMergeable1ByteCString() ||
263       Kind.isMergeable2ByteCString() ||
264       Kind.isMergeable4ByteCString()) {
265
266     // We also need alignment here.
267     // FIXME: this is getting the alignment of the character, not the
268     // alignment of the global!
269     unsigned Align =
270       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
271
272     const char *SizeSpec = ".rodata.str1.";
273     if (Kind.isMergeable2ByteCString())
274       SizeSpec = ".rodata.str2.";
275     else if (Kind.isMergeable4ByteCString())
276       SizeSpec = ".rodata.str4.";
277     else
278       assert(Kind.isMergeable1ByteCString() && "unknown string width");
279
280
281     std::string Name = SizeSpec + utostr(Align);
282     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
283                                       ELF::SHF_ALLOC |
284                                       ELF::SHF_MERGE |
285                                       ELF::SHF_STRINGS,
286                                       Kind);
287   }
288
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
297   }
298
299   if (Kind.isReadOnly())             return ReadOnlySection;
300
301   if (Kind.isThreadData())           return TLSDataSection;
302   if (Kind.isThreadBSS())            return TLSBSSSection;
303
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;
308
309   if (Kind.isDataNoRel())            return DataSection;
310   if (Kind.isDataRelLocal())         return DataRelLocalSection;
311   if (Kind.isDataRel())              return DataRelSection;
312   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
313
314   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
315   return DataRelROSection;
316 }
317
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;
331
332   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
333   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
334   return DataRelROSection;
335 }
336
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
340   // numbering.
341   if (Priority == 65535)
342     return StaticCtorSection;
343
344   if (UseInitArray) {
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());
349   } else {
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());
354   }
355 }
356
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
360   // numbering.
361   if (Priority == 65535)
362     return StaticDtorSection;
363
364   if (UseInitArray) {
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());
369   } else {
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());
374   }
375 }
376
377 void
378 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
379   UseInitArray = UseInitArray_;
380   if (!UseInitArray)
381     return;
382
383   StaticCtorSection =
384     getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
385                                ELF::SHF_WRITE |
386                                ELF::SHF_ALLOC,
387                                SectionKind::getDataRel());
388   StaticDtorSection =
389     getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
390                                ELF::SHF_WRITE |
391                                ELF::SHF_ALLOC,
392                                SectionKind::getDataRel());
393 }
394
395 //===----------------------------------------------------------------------===//
396 //                                 MachO
397 //===----------------------------------------------------------------------===//
398
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));
406   return StringRef();
407 }
408
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;
418
419   for (ArrayRef<Module::ModuleFlagEntry>::iterator
420          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
421     const Module::ModuleFlagEntry &MFE = *i;
422
423     // Ignore flags with 'Require' behavior.
424     if (MFE.Behavior == Module::Require)
425       continue;
426
427     StringRef Key = MFE.Key->getString();
428     Value *Val = MFE.Val;
429
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);
440     }
441   }
442
443   // Emit the linker options if present.
444   if (LinkerOptions) {
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;
448
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());
453       }
454
455       Streamer.EmitLinkerOptions(StrOptions);
456     }
457   }
458
459   // The section is mandatory. If we don't have it, then we don't have GC info.
460   if (SectionVal.empty()) return;
461
462   StringRef Segment, Section;
463   unsigned TAA = 0, StubSize = 0;
464   bool TAAParsed;
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 + "': " +
471                        ErrorCode + ".");
472
473   // Get the 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();
483 }
484
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;
491   bool TAAParsed;
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 + ".");
500   }
501
502   // Get the section.
503   const MCSectionMachO *S =
504     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
505
506   // If TAA wasn't set by ParseSectionSpecifier() above,
507   // use the value returned by getMachOSection() as a default.
508   if (!TAAParsed)
509     TAA = S->getTypeAndAttributes();
510
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");
519   }
520
521   return S;
522 }
523
524 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
525     const MCSection &Section) const {
526     const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
527
528     // Sections holding 1 byte strings are atomized based on the data
529     // they contain.
530     // Sections holding 2 byte strings require symbols in order to be
531     // atomized.
532     // There is no dedicated section for 4 byte strings.
533     if (SMO.getKind().isMergeable1ByteCString())
534       return false;
535
536     if (SMO.getSegmentName() == "__DATA" &&
537         SMO.getSectionName() == "__cfstring")
538       return false;
539
540     switch (SMO.getType()) {
541     default:
542       return true;
543
544       // These sections are atomized at the element boundaries without using
545       // symbols.
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:
555       return false;
556     }
557 }
558
559 const MCSection *TargetLoweringObjectFileMachO::
560 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
561                        Mangler &Mang, const TargetMachine &TM) const {
562
563   // Handle thread local data.
564   if (Kind.isThreadBSS()) return TLSBSSSection;
565   if (Kind.isThreadData()) return TLSDataSection;
566
567   if (Kind.isText())
568     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
569
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;
576   }
577
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;
582
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
585   // versions.
586   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
587       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
588     return UStringSection;
589
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;
597   }
598
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;
603
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;
608
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;
613
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;
618
619   // Otherwise, just drop the variable in the normal data section.
620   return DataSection;
621 }
622
623 const MCSection *
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;
629
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
637 }
638
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.
644
645   if (Encoding & DW_EH_PE_indirect) {
646     MachineModuleInfoMachO &MachOMMI =
647       MMI->getObjFileInfo<MachineModuleInfoMachO>();
648
649     MCSymbol *SSym =
650         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
651
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());
660     }
661
662     return TargetLoweringObjectFile::
663       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
664                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
665   }
666
667   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
668                                                            TM, MMI, Streamer);
669 }
670
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>();
677
678   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
679
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());
686   }
687
688   return SSym;
689 }
690
691 //===----------------------------------------------------------------------===//
692 //                                  COFF
693 //===----------------------------------------------------------------------===//
694
695 static unsigned
696 getCOFFSectionFlags(SectionKind K) {
697   unsigned Flags = 0;
698
699   if (K.isMetadata())
700     Flags |=
701       COFF::IMAGE_SCN_MEM_DISCARDABLE;
702   else if (K.isText())
703     Flags |=
704       COFF::IMAGE_SCN_MEM_EXECUTE |
705       COFF::IMAGE_SCN_MEM_READ |
706       COFF::IMAGE_SCN_CNT_CODE;
707   else if (K.isBSS ())
708     Flags |=
709       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
710       COFF::IMAGE_SCN_MEM_READ |
711       COFF::IMAGE_SCN_MEM_WRITE;
712   else if (K.isThreadLocal())
713     Flags |=
714       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
715       COFF::IMAGE_SCN_MEM_READ |
716       COFF::IMAGE_SCN_MEM_WRITE;
717   else if (K.isReadOnly())
718     Flags |=
719       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
720       COFF::IMAGE_SCN_MEM_READ;
721   else if (K.isWriteable())
722     Flags |=
723       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
724       COFF::IMAGE_SCN_MEM_READ |
725       COFF::IMAGE_SCN_MEM_WRITE;
726
727   return Flags;
728 }
729
730 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
731     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
732     const TargetMachine &TM) const {
733   int Selection = 0;
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();
742   }
743   return getContext().getCOFFSection(Name,
744                                      Characteristics,
745                                      Kind,
746                                      COMDATSymName,
747                                      Selection);
748 }
749
750 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
751   if (Kind.isText())
752     return ".text";
753   if (Kind.isBSS())
754     return ".bss";
755   if (Kind.isThreadLocal())
756     return ".tls$";
757   if (Kind.isWriteable())
758     return ".data";
759   return ".rdata";
760 }
761
762
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;
769   if (Kind.isText())
770     EmitUniquedSection = TM.getFunctionSections();
771   else
772     EmitUniquedSection = TM.getDataSections();
773
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);
782
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);
789   }
790
791   if (Kind.isText())
792     return TextSection;
793
794   if (Kind.isThreadLocal())
795     return TLSDataSection;
796
797   if (Kind.isReadOnly())
798     return ReadOnlySection;
799
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())
804     return BSSSection;
805
806   return DataSection;
807 }
808
809 StringRef TargetLoweringObjectFileCOFF::
810 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
811   const char *LibCmd = "/DEFAULTLIB:";
812   if (LinkerOption.startswith(LibCmd))
813     return LinkerOption.substr(strlen(LibCmd));
814   return StringRef();
815 }
816
817 void TargetLoweringObjectFileCOFF::
818 emitModuleFlags(MCStreamer &Streamer,
819                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
820                 Mangler &Mang, const TargetMachine &TM) const {
821   MDNode *LinkerOptions = nullptr;
822
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);
831       break;
832     }
833   }
834   if (!LinkerOptions)
835     return;
836
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('\"');
854         Escaped.append(Op);
855         Escaped.push_back('\"');
856       } else {
857         Escaped.append(Op);
858       }
859       Streamer.EmitBytes(Escaped);
860     }
861   }
862 }
863
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.
868   if (!KeySym)
869     return Sec;
870
871   // Make an associative section with the same name and kind as the normal
872   // section.
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);
879 }
880
881 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
882     unsigned Priority, const MCSymbol *KeySym) const {
883   return getAssociativeCOFFSection(getContext(), StaticCtorSection, KeySym);
884 }
885
886 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
887     unsigned Priority, const MCSymbol *KeySym) const {
888   return getAssociativeCOFFSection(getContext(), StaticDtorSection, KeySym);
889 }