LLVM API Documentation

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
TargetLoweringObjectFileImpl.cpp
Go to the documentation of this file.
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 
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.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/Module.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCExpr.h"
28 #include "llvm/MC/MCSectionCOFF.h"
29 #include "llvm/MC/MCSectionELF.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/MC/MCSymbol.h"
33 #include "llvm/Support/Dwarf.h"
34 #include "llvm/Support/ELF.h"
37 #include "llvm/Target/Mangler.h"
39 using namespace llvm;
40 using namespace dwarf;
41 
42 //===----------------------------------------------------------------------===//
43 // ELF
44 //===----------------------------------------------------------------------===//
45 
46 MCSymbol *
48  Mangler *Mang,
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!");
55  return getSymbol(*Mang, GV);
56  case dwarf::DW_EH_PE_pcrel: {
57  return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
58  getSymbol(*Mang, GV)->getName());
59  }
60  }
61 }
62 
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,
78  0, Label->getName());
79  unsigned Size = TM.getDataLayout()->getPointerSize();
80  Streamer.SwitchSection(Sec);
83  const MCExpr *E = MCConstantExpr::Create(Size, getContext());
84  Streamer.EmitELFSize(Label, E);
85  Streamer.EmitLabel(Label);
86 
87  Streamer.EmitSymbolValue(Sym, Size);
88 }
89 
92  MachineModuleInfo *MMI, unsigned Encoding,
93  MCStreamer &Streamer) const {
94 
95  if (Encoding & dwarf::DW_EH_PE_indirect) {
97 
99  Mang->getNameWithPrefix(Name, GV, true);
100  Name += ".DW.stub";
101 
102  // Add information about the stub reference to ELFMMI so that the stub
103  // gets emitted by the asmprinter.
104  MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
105  MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
106  if (StubSym.getPointer() == 0) {
107  MCSymbol *Sym = getSymbol(*Mang, GV);
109  }
110 
112  getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
113  Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
114  }
115 
117  getTTypeGlobalReference(GV, Mang, MMI, Encoding, Streamer);
118 }
119 
120 static SectionKind
122  // N.B.: The defaults used in here are no the same ones used in MC.
123  // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
124  // both gas and MC will produce a section with no flags. Given
125  // section(".eh_frame") gcc will produce:
126  //
127  // .section .eh_frame,"a",@progbits
128  if (Name.empty() || Name[0] != '.') return K;
129 
130  // Some lame default implementation based on some magic section names.
131  if (Name == ".bss" ||
132  Name.startswith(".bss.") ||
133  Name.startswith(".gnu.linkonce.b.") ||
134  Name.startswith(".llvm.linkonce.b.") ||
135  Name == ".sbss" ||
136  Name.startswith(".sbss.") ||
137  Name.startswith(".gnu.linkonce.sb.") ||
138  Name.startswith(".llvm.linkonce.sb."))
139  return SectionKind::getBSS();
140 
141  if (Name == ".tdata" ||
142  Name.startswith(".tdata.") ||
143  Name.startswith(".gnu.linkonce.td.") ||
144  Name.startswith(".llvm.linkonce.td."))
146 
147  if (Name == ".tbss" ||
148  Name.startswith(".tbss.") ||
149  Name.startswith(".gnu.linkonce.tb.") ||
150  Name.startswith(".llvm.linkonce.tb."))
151  return SectionKind::getThreadBSS();
152 
153  return K;
154 }
155 
156 
158 
159  if (Name == ".init_array")
160  return ELF::SHT_INIT_ARRAY;
161 
162  if (Name == ".fini_array")
163  return ELF::SHT_FINI_ARRAY;
164 
165  if (Name == ".preinit_array")
166  return ELF::SHT_PREINIT_ARRAY;
167 
168  if (K.isBSS() || K.isThreadBSS())
169  return ELF::SHT_NOBITS;
170 
171  return ELF::SHT_PROGBITS;
172 }
173 
174 
175 static unsigned
177  unsigned Flags = 0;
178 
179  if (!K.isMetadata())
180  Flags |= ELF::SHF_ALLOC;
181 
182  if (K.isText())
183  Flags |= ELF::SHF_EXECINSTR;
184 
185  if (K.isWriteable())
186  Flags |= ELF::SHF_WRITE;
187 
188  if (K.isThreadLocal())
189  Flags |= ELF::SHF_TLS;
190 
191  // K.isMergeableConst() is left out to honour PR4650
192  if (K.isMergeableCString() || K.isMergeableConst4() ||
194  Flags |= ELF::SHF_MERGE;
195 
196  if (K.isMergeableCString())
197  Flags |= ELF::SHF_STRINGS;
198 
199  return Flags;
200 }
201 
202 
205  Mangler *Mang, const TargetMachine &TM) const {
206  StringRef SectionName = GV->getSection();
207 
208  // Infer section flags from the section name if we can.
209  Kind = getELFKindForNamedSection(SectionName, Kind);
210 
211  return getContext().getELFSection(SectionName,
212  getELFSectionType(SectionName, Kind),
213  getELFSectionFlags(Kind), Kind);
214 }
215 
216 /// getSectionPrefixForGlobal - Return the section prefix name used by options
217 /// FunctionsSections and DataSections.
219  if (Kind.isText()) return ".text.";
220  if (Kind.isReadOnly()) return ".rodata.";
221  if (Kind.isBSS()) return ".bss.";
222 
223  if (Kind.isThreadData()) return ".tdata.";
224  if (Kind.isThreadBSS()) return ".tbss.";
225 
226  if (Kind.isDataNoRel()) return ".data.";
227  if (Kind.isDataRelLocal()) return ".data.rel.local.";
228  if (Kind.isDataRel()) return ".data.rel.";
229  if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
230 
231  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
232  return ".data.rel.ro.";
233 }
234 
235 
238  Mangler *Mang, const TargetMachine &TM) const {
239  // If we have -ffunction-section or -fdata-section then we should emit the
240  // global value to a uniqued section specifically for it.
241  bool EmitUniquedSection;
242  if (Kind.isText())
243  EmitUniquedSection = TM.getFunctionSections();
244  else
245  EmitUniquedSection = TM.getDataSections();
246 
247  // If this global is linkonce/weak and the target handles this by emitting it
248  // into a 'uniqued' section name, create and return the section now.
249  if ((GV->isWeakForLinker() || EmitUniquedSection) &&
250  !Kind.isCommon()) {
251  const char *Prefix;
252  Prefix = getSectionPrefixForGlobal(Kind);
253 
254  SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
255  MCSymbol *Sym = getSymbol(*Mang, GV);
256  Name.append(Sym->getName().begin(), Sym->getName().end());
257  StringRef Group = "";
258  unsigned Flags = getELFSectionFlags(Kind);
259  if (GV->isWeakForLinker()) {
260  Group = Sym->getName();
261  Flags |= ELF::SHF_GROUP;
262  }
263 
264  return getContext().getELFSection(Name.str(),
265  getELFSectionType(Name.str(), Kind),
266  Flags, Kind, 0, Group);
267  }
268 
269  if (Kind.isText()) return TextSection;
270 
271  if (Kind.isMergeable1ByteCString() ||
272  Kind.isMergeable2ByteCString() ||
273  Kind.isMergeable4ByteCString()) {
274 
275  // We also need alignment here.
276  // FIXME: this is getting the alignment of the character, not the
277  // alignment of the global!
278  unsigned Align =
279  TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
280 
281  const char *SizeSpec = ".rodata.str1.";
282  if (Kind.isMergeable2ByteCString())
283  SizeSpec = ".rodata.str2.";
284  else if (Kind.isMergeable4ByteCString())
285  SizeSpec = ".rodata.str4.";
286  else
287  assert(Kind.isMergeable1ByteCString() && "unknown string width");
288 
289 
290  std::string Name = SizeSpec + utostr(Align);
291  return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
292  ELF::SHF_ALLOC |
293  ELF::SHF_MERGE |
294  ELF::SHF_STRINGS,
295  Kind);
296  }
297 
298  if (Kind.isMergeableConst()) {
299  if (Kind.isMergeableConst4() && MergeableConst4Section)
300  return MergeableConst4Section;
301  if (Kind.isMergeableConst8() && MergeableConst8Section)
302  return MergeableConst8Section;
303  if (Kind.isMergeableConst16() && MergeableConst16Section)
304  return MergeableConst16Section;
305  return ReadOnlySection; // .const
306  }
307 
308  if (Kind.isReadOnly()) return ReadOnlySection;
309 
310  if (Kind.isThreadData()) return TLSDataSection;
311  if (Kind.isThreadBSS()) return TLSBSSSection;
312 
313  // Note: we claim that common symbols are put in BSSSection, but they are
314  // really emitted with the magic .comm directive, which creates a symbol table
315  // entry but not a section.
316  if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
317 
318  if (Kind.isDataNoRel()) return DataSection;
319  if (Kind.isDataRelLocal()) return DataRelLocalSection;
320  if (Kind.isDataRel()) return DataRelSection;
321  if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
322 
323  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
324  return DataRelROSection;
325 }
326 
327 /// getSectionForConstant - Given a mergeable constant with the
328 /// specified size and relocation information, return a section that it
329 /// should be placed in.
332  if (Kind.isMergeableConst4() && MergeableConst4Section)
333  return MergeableConst4Section;
334  if (Kind.isMergeableConst8() && MergeableConst8Section)
335  return MergeableConst8Section;
336  if (Kind.isMergeableConst16() && MergeableConst16Section)
337  return MergeableConst16Section;
338  if (Kind.isReadOnly())
339  return ReadOnlySection;
340 
341  if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
342  assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
343  return DataRelROSection;
344 }
345 
346 const MCSection *
348  // The default scheme is .ctor / .dtor, so we have to invert the priority
349  // numbering.
350  if (Priority == 65535)
351  return StaticCtorSection;
352 
353  if (UseInitArray) {
354  std::string Name = std::string(".init_array.") + utostr(Priority);
355  return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
356  ELF::SHF_ALLOC | ELF::SHF_WRITE,
358  } else {
359  std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
360  return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
361  ELF::SHF_ALLOC |ELF::SHF_WRITE,
363  }
364 }
365 
366 const MCSection *
368  // The default scheme is .ctor / .dtor, so we have to invert the priority
369  // numbering.
370  if (Priority == 65535)
371  return StaticDtorSection;
372 
373  if (UseInitArray) {
374  std::string Name = std::string(".fini_array.") + utostr(Priority);
375  return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
376  ELF::SHF_ALLOC | ELF::SHF_WRITE,
378  } else {
379  std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
380  return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
381  ELF::SHF_ALLOC |ELF::SHF_WRITE,
383  }
384 }
385 
386 void
388  UseInitArray = UseInitArray_;
389  if (!UseInitArray)
390  return;
391 
392  StaticCtorSection =
393  getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
394  ELF::SHF_WRITE |
395  ELF::SHF_ALLOC,
397  StaticDtorSection =
398  getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
399  ELF::SHF_WRITE |
400  ELF::SHF_ALLOC,
402 }
403 
404 //===----------------------------------------------------------------------===//
405 // MachO
406 //===----------------------------------------------------------------------===//
407 
408 /// emitModuleFlags - Perform code emission for module flags.
412  Mangler *Mang, const TargetMachine &TM) const {
413  unsigned VersionVal = 0;
414  unsigned ImageInfoFlags = 0;
415  MDNode *LinkerOptions = 0;
416  StringRef SectionVal;
417 
419  i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
420  const Module::ModuleFlagEntry &MFE = *i;
421 
422  // Ignore flags with 'Require' behavior.
423  if (MFE.Behavior == Module::Require)
424  continue;
425 
426  StringRef Key = MFE.Key->getString();
427  Value *Val = MFE.Val;
428 
429  if (Key == "Objective-C Image Info Version") {
430  VersionVal = cast<ConstantInt>(Val)->getZExtValue();
431  } else if (Key == "Objective-C Garbage Collection" ||
432  Key == "Objective-C GC Only" ||
433  Key == "Objective-C Is Simulated") {
434  ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
435  } else if (Key == "Objective-C Image Info Section") {
436  SectionVal = cast<MDString>(Val)->getString();
437  } else if (Key == "Linker Options") {
438  LinkerOptions = cast<MDNode>(Val);
439  }
440  }
441 
442  // Emit the linker options if present.
443  if (LinkerOptions) {
444  for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
445  MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
446  SmallVector<std::string, 4> StrOptions;
447 
448  // Convert to strings.
449  for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
450  MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
451  StrOptions.push_back(MDOption->getString());
452  }
453 
454  Streamer.EmitLinkerOptions(StrOptions);
455  }
456  }
457 
458  // The section is mandatory. If we don't have it, then we don't have GC info.
459  if (SectionVal.empty()) return;
460 
461  StringRef Segment, Section;
462  unsigned TAA = 0, StubSize = 0;
463  bool TAAParsed;
464  std::string ErrorCode =
465  MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
466  TAA, TAAParsed, StubSize);
467  if (!ErrorCode.empty())
468  // If invalid, report the error with report_fatal_error.
469  report_fatal_error("Invalid section specifier '" + Section + "': " +
470  ErrorCode + ".");
471 
472  // Get the section.
473  const MCSectionMachO *S =
474  getContext().getMachOSection(Segment, Section, TAA, StubSize,
476  Streamer.SwitchSection(S);
477  Streamer.EmitLabel(getContext().
478  GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
479  Streamer.EmitIntValue(VersionVal, 4);
480  Streamer.EmitIntValue(ImageInfoFlags, 4);
481  Streamer.AddBlankLine();
482 }
483 
486  Mangler *Mang, const TargetMachine &TM) const {
487  // Parse the section specifier and create it if valid.
488  StringRef Segment, Section;
489  unsigned TAA = 0, StubSize = 0;
490  bool TAAParsed;
491  std::string ErrorCode =
493  TAA, TAAParsed, StubSize);
494  if (!ErrorCode.empty()) {
495  // If invalid, report the error with report_fatal_error.
496  report_fatal_error("Global variable '" + GV->getName() +
497  "' has an invalid section specifier '" +
498  GV->getSection() + "': " + ErrorCode + ".");
499  }
500 
501  // Get the section.
502  const MCSectionMachO *S =
503  getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
504 
505  // If TAA wasn't set by ParseSectionSpecifier() above,
506  // use the value returned by getMachOSection() as a default.
507  if (!TAAParsed)
508  TAA = S->getTypeAndAttributes();
509 
510  // Okay, now that we got the section, verify that the TAA & StubSize agree.
511  // If the user declared multiple globals with different section flags, we need
512  // to reject it here.
513  if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
514  // If invalid, report the error with report_fatal_error.
515  report_fatal_error("Global variable '" + GV->getName() +
516  "' section type or attributes does not match previous"
517  " section specifier");
518  }
519 
520  return S;
521 }
522 
525  Mangler *Mang, const TargetMachine &TM) const {
526 
527  // Handle thread local data.
528  if (Kind.isThreadBSS()) return TLSBSSSection;
529  if (Kind.isThreadData()) return TLSDataSection;
530 
531  if (Kind.isText())
532  return GV->isWeakForLinker() ? TextCoalSection : TextSection;
533 
534  // If this is weak/linkonce, put this in a coalescable section, either in text
535  // or data depending on if it is writable.
536  if (GV->isWeakForLinker()) {
537  if (Kind.isReadOnly())
538  return ConstTextCoalSection;
539  return DataCoalSection;
540  }
541 
542  // FIXME: Alignment check should be handled by section classifier.
543  if (Kind.isMergeable1ByteCString() &&
544  TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
545  return CStringSection;
546 
547  // Do not put 16-bit arrays in the UString section if they have an
548  // externally visible label, this runs into issues with certain linker
549  // versions.
550  if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
551  TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
552  return UStringSection;
553 
554  if (Kind.isMergeableConst()) {
555  if (Kind.isMergeableConst4())
556  return FourByteConstantSection;
557  if (Kind.isMergeableConst8())
558  return EightByteConstantSection;
559  if (Kind.isMergeableConst16() && SixteenByteConstantSection)
560  return SixteenByteConstantSection;
561  }
562 
563  // Otherwise, if it is readonly, but not something we can specially optimize,
564  // just drop it in .const.
565  if (Kind.isReadOnly())
566  return ReadOnlySection;
567 
568  // If this is marked const, put it into a const section. But if the dynamic
569  // linker needs to write to it, put it in the data segment.
570  if (Kind.isReadOnlyWithRel())
571  return ConstDataSection;
572 
573  // Put zero initialized globals with strong external linkage in the
574  // DATA, __common section with the .zerofill directive.
575  if (Kind.isBSSExtern())
576  return DataCommonSection;
577 
578  // Put zero initialized globals with local linkage in __DATA,__bss directive
579  // with the .zerofill directive (aka .lcomm).
580  if (Kind.isBSSLocal())
581  return DataBSSSection;
582 
583  // Otherwise, just drop the variable in the normal data section.
584  return DataSection;
585 }
586 
587 const MCSection *
589  // If this constant requires a relocation, we have to put it in the data
590  // segment, not in the text segment.
591  if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
592  return ConstDataSection;
593 
594  if (Kind.isMergeableConst4())
595  return FourByteConstantSection;
596  if (Kind.isMergeableConst8())
597  return EightByteConstantSection;
598  if (Kind.isMergeableConst16() && SixteenByteConstantSection)
599  return SixteenByteConstantSection;
600  return ReadOnlySection; // .const
601 }
602 
603 /// shouldEmitUsedDirectiveFor - This hook allows targets to selectively decide
604 /// not to emit the UsedDirective for some symbols in llvm.used.
605 // FIXME: REMOVE this (rdar://7071300)
608  /// On Darwin, internally linked data beginning with "L" or "l" does not have
609  /// the directive emitted (this occurs in ObjC metadata).
610  if (!GV) return false;
611 
612  // Check whether the mangled name has the "Private" or "LinkerPrivate" prefix.
613  if (GV->hasLocalLinkage() && !isa<Function>(GV)) {
614  // FIXME: ObjC metadata is currently emitted as internal symbols that have
615  // \1L and \0l prefixes on them. Fix them to be Private/LinkerPrivate and
616  // this horrible hack can go away.
617  MCSymbol *Sym = getSymbol(*Mang, GV);
618  if (Sym->getName()[0] == 'L' || Sym->getName()[0] == 'l')
619  return false;
620  }
621 
622  return true;
623 }
624 
627  MachineModuleInfo *MMI, unsigned Encoding,
628  MCStreamer &Streamer) const {
629  // The mach-o version of this method defaults to returning a stub reference.
630 
631  if (Encoding & DW_EH_PE_indirect) {
632  MachineModuleInfoMachO &MachOMMI =
634 
636  Mang->getNameWithPrefix(Name, GV, true);
637  Name += "$non_lazy_ptr";
638 
639  // Add information about the stub reference to MachOMMI so that the stub
640  // gets emitted by the asmprinter.
641  MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
643  GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
644  MachOMMI.getGVStubEntry(SSym);
645  if (StubSym.getPointer() == 0) {
646  MCSymbol *Sym = getSymbol(*Mang, GV);
648  }
649 
651  getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
652  Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
653  }
654 
656  getTTypeGlobalReference(GV, Mang, MMI, Encoding, Streamer);
657 }
658 
661  MachineModuleInfo *MMI) const {
662  // The mach-o version of this method defaults to returning a stub reference.
663  MachineModuleInfoMachO &MachOMMI =
665 
667  Mang->getNameWithPrefix(Name, GV, true);
668  Name += "$non_lazy_ptr";
669 
670  // Add information about the stub reference to MachOMMI so that the stub
671  // gets emitted by the asmprinter.
672  MCSymbol *SSym = getContext().GetOrCreateSymbol(Name.str());
673  MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
674  if (StubSym.getPointer() == 0) {
675  MCSymbol *Sym = getSymbol(*Mang, GV);
677  }
678 
679  return SSym;
680 }
681 
682 //===----------------------------------------------------------------------===//
683 // COFF
684 //===----------------------------------------------------------------------===//
685 
686 static unsigned
688  unsigned Flags = 0;
689 
690  if (K.isMetadata())
691  Flags |=
692  COFF::IMAGE_SCN_MEM_DISCARDABLE;
693  else if (K.isText())
694  Flags |=
695  COFF::IMAGE_SCN_MEM_EXECUTE |
696  COFF::IMAGE_SCN_MEM_READ |
697  COFF::IMAGE_SCN_CNT_CODE;
698  else if (K.isBSS ())
699  Flags |=
700  COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
701  COFF::IMAGE_SCN_MEM_READ |
702  COFF::IMAGE_SCN_MEM_WRITE;
703  else if (K.isThreadLocal())
704  Flags |=
705  COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
706  COFF::IMAGE_SCN_MEM_READ |
707  COFF::IMAGE_SCN_MEM_WRITE;
708  else if (K.isReadOnly())
709  Flags |=
710  COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
711  COFF::IMAGE_SCN_MEM_READ;
712  else if (K.isWriteable())
713  Flags |=
714  COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
715  COFF::IMAGE_SCN_MEM_READ |
716  COFF::IMAGE_SCN_MEM_WRITE;
717 
718  return Flags;
719 }
720 
723  Mangler *Mang, const TargetMachine &TM) const {
724  int Selection = 0;
725  unsigned Characteristics = getCOFFSectionFlags(Kind);
726  SmallString<128> Name(GV->getSection().c_str());
727  if (GV->isWeakForLinker()) {
728  Selection = COFF::IMAGE_COMDAT_SELECT_ANY;
729  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
730  Name.append("$");
731  Mang->getNameWithPrefix(Name, GV, false, false);
732  }
733  return getContext().getCOFFSection(Name,
734  Characteristics,
735  Kind,
736  Selection);
737 }
738 
740  if (Kind.isText())
741  return ".text$";
742  if (Kind.isBSS ())
743  return ".bss$";
744  if (Kind.isThreadLocal()) {
745  // 'LLVM' is just an arbitary string to ensure that the section name gets
746  // sorted in between '.tls$AAA' and '.tls$ZZZ' by the linker.
747  return ".tls$LLVM";
748  }
749  if (Kind.isWriteable())
750  return ".data$";
751  return ".rdata$";
752 }
753 
754 
757  Mangler *Mang, const TargetMachine &TM) const {
758 
759  // If this global is linkonce/weak and the target handles this by emitting it
760  // into a 'uniqued' section name, create and return the section now.
761  if (GV->isWeakForLinker()) {
762  const char *Prefix = getCOFFSectionPrefixForUniqueGlobal(Kind);
763  SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
764  Mang->getNameWithPrefix(Name, GV, false, false);
765 
766  unsigned Characteristics = getCOFFSectionFlags(Kind);
767 
768  Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
769 
770  return getContext().getCOFFSection(Name.str(), Characteristics,
772  }
773 
774  if (Kind.isText())
775  return TextSection;
776 
777  if (Kind.isThreadLocal())
778  return TLSDataSection;
779 
780  if (Kind.isReadOnly())
781  return ReadOnlySection;
782 
783  if (Kind.isBSS())
784  return BSSSection;
785 
786  return DataSection;
787 }
788 
792  Mangler *Mang, const TargetMachine &TM) const {
793  MDNode *LinkerOptions = 0;
794 
795  // Look for the "Linker Options" flag, since it's the only one we support.
797  i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
798  const Module::ModuleFlagEntry &MFE = *i;
799  StringRef Key = MFE.Key->getString();
800  Value *Val = MFE.Val;
801  if (Key == "Linker Options") {
802  LinkerOptions = cast<MDNode>(Val);
803  break;
804  }
805  }
806  if (!LinkerOptions)
807  return;
808 
809  // Emit the linker options to the linker .drectve section. According to the
810  // spec, this section is a space-separated string containing flags for linker.
811  const MCSection *Sec = getDrectveSection();
812  Streamer.SwitchSection(Sec);
813  for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
814  MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
815  for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
816  MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
817  StringRef Op = MDOption->getString();
818  // Lead with a space for consistency with our dllexport implementation.
819  std::string Escaped(" ");
820  if (Op.find(" ") != StringRef::npos) {
821  // The PE-COFF spec says args with spaces must be quoted. It doesn't say
822  // how to escape quotes, but it probably uses this algorithm:
823  // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
824  // FIXME: Reuse escaping code from Support/Windows/Program.inc
825  Escaped.push_back('\"');
826  Escaped.append(Op);
827  Escaped.push_back('\"');
828  } else {
829  Escaped.append(Op);
830  }
831  Streamer.EmitBytes(Escaped);
832  }
833  }
834 }
PointerIntPair< MCSymbol *, 1, bool > StubValueTy
StubValueTy & getHiddenGVStubEntry(MCSymbol *Sym)
StringRef getString() const
Definition: Metadata.h:46
bool isMergeableConst() const
Definition: SectionKind.h:153
virtual const MCSection * SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, const TargetMachine &TM) const
.type _foo, STT_OBJECT # aka
Definition: MCDirectives.h:25
static const MCConstantExpr * Create(int64_t Value, MCContext &Ctx)
Definition: MCExpr.cpp:152
virtual void AddBlankLine()
AddBlankLine - Emit a blank line to a .s file to pretty it up.
Definition: MCStreamer.h:215
bool isBSSExtern() const
Definition: SectionKind.h:178
unsigned getPointerSize(unsigned AS=0) const
Definition: DataLayout.h:261
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang, MachineModuleInfo *MMI, unsigned Encoding, MCStreamer &Streamer) const
virtual void emitModuleFlags(MCStreamer &Streamer, ArrayRef< Module::ModuleFlagEntry > ModuleFlags, Mangler *Mang, const TargetMachine &TM) const
unsigned getNumOperands() const
getNumOperands - Return number of MDNode operands.
Definition: Metadata.h:142
static SectionKind getDataRel()
Definition: SectionKind.h:229
iterator end() const
Definition: ArrayRef.h:98
void getNameWithPrefix(SmallVectorImpl< char > &OutName, const GlobalValue *GV, bool isImplicitlyPrivate, bool UseGlobalPrefix=true)
Definition: Mangler.cpp:90
bool isMergeable2ByteCString() const
Definition: SectionKind.h:150
bool isBSS() const
Definition: SectionKind.h:176
bool isReadOnlyWithRel() const
Definition: SectionKind.h:192
iterator insert(iterator I, const char &Elt)
Definition: SmallVector.h:537
virtual void emitPersonalityValue(MCStreamer &Streamer, const TargetMachine &TM, const MCSymbol *Sym) const
MDNode - a tuple of other values.
Definition: Metadata.h:69
virtual const MCSection * getSectionForConstant(SectionKind Kind) const
bool isMergeableCString() const
Definition: SectionKind.h:145
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(const char *reason, bool gen_crash_diag=true)
StringRef getName() const
Definition: Value.cpp:167
Value * getOperand(unsigned i) const LLVM_READONLY
getOperand - Return specified operand.
Definition: Metadata.cpp:307
ModFlagBehavior Behavior
Definition: Module.h:185
unsigned getPointerABIAlignment(unsigned AS=0) const
Definition: DataLayout.h:240
static SectionKind getBSS()
Definition: SectionKind.h:225
virtual const MCSection * getSectionForConstant(SectionKind Kind) const
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang, MachineModuleInfo *MMI, unsigned Encoding, MCStreamer &Streamer) const
virtual const MCSection * getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, const TargetMachine &TM) const
const MCExpr * getTTypeReference(const MCSymbolRefExpr *Sym, unsigned Encoding, MCStreamer &Streamer) const
virtual void EmitBytes(StringRef Data)=0
virtual const MCSection * getStaticDtorSection(unsigned Priority=65535) const
static unsigned getCOFFSectionFlags(SectionKind K)
virtual MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang, MachineModuleInfo *MMI) const
bool isWriteable() const
Definition: SectionKind.h:161
bool isMergeable4ByteCString() const
Definition: SectionKind.h:151
void SwitchSection(const MCSection *Section, const MCExpr *Subsection=0)
Definition: MCStreamer.h:284
virtual bool shouldEmitUsedDirectiveFor(const GlobalValue *GV, Mangler *) const
static const char * getCOFFSectionPrefixForUniqueGlobal(SectionKind Kind)
static std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:88
unsigned getStubSize() const
static SectionKind getThreadData()
Definition: SectionKind.h:224
virtual void EmitIntValue(uint64_t Value, unsigned Size)
Definition: MCStreamer.cpp:104
bool isMergeableConst16() const
Definition: SectionKind.h:159
iterator begin() const
Definition: StringRef.h:97
static const MCSymbolRefExpr * Create(const MCSymbol *Symbol, MCContext &Ctx)
Definition: MCExpr.h:270
static bool isWeakForLinker(LinkageTypes Linkage)
Definition: GlobalValue.h:183
void append(in_iter S, in_iter E)
Append from an iterator pair.
Definition: SmallString.h:77
bool isDataNoRel() const
Definition: SectionKind.h:190
.hidden (ELF)
Definition: MCDirectives.h:31
bool isMetadata() const
Definition: SectionKind.h:137
cl::opt< bool > UseInitArray("use-init-array", cl::desc("Use .init_array instead of .ctors."), cl::init(false))
static std::string ParseSectionSpecifier(StringRef Spec, StringRef &Segment, StringRef &Section, unsigned &TAA, bool &TAAParsed, unsigned &StubSize)
bool isText() const
Definition: SectionKind.h:138
bool hasHiddenVisibility() const
Definition: GlobalValue.h:89
bool isThreadData() const
Definition: SectionKind.h:170
static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K)
bool isMergeable1ByteCString() const
Definition: SectionKind.h:149
virtual void EmitELFSize(MCSymbol *Symbol, const MCExpr *Value)=0
virtual bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute)=0
EmitSymbolAttribute - Add the given Attribute to Symbol.
iterator begin() const
Definition: ArrayRef.h:97
static bool getDataSections()
static bool getFunctionSections()
bool isBSSLocal() const
Definition: SectionKind.h:177
const std::string & getSection() const
Definition: GlobalValue.h:96
bool isThreadBSS() const
Definition: SectionKind.h:169
StubValueTy & getGVStubEntry(MCSymbol *Sym)
virtual const MCSection * getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, const TargetMachine &TM) const
virtual const MCSection * SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, const TargetMachine &TM) const
virtual void EmitValueToAlignment(unsigned ByteAlignment, int64_t Value=0, unsigned ValueSize=1, unsigned MaxBytesToEmit=0)=0
StubValueTy & getGVStubEntry(MCSymbol *Sym)
bool isThreadLocal() const
Definition: SectionKind.h:165
unsigned getPreferredAlignment(const GlobalVariable *GV) const
Definition: DataLayout.cpp:679
bool hasExternalLinkage() const
Definition: GlobalValue.h:194
PointerTy getPointer() const
bool startswith(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:208
static SectionKind getThreadBSS()
Definition: SectionKind.h:223
virtual void EmitLabel(MCSymbol *Symbol)
Definition: MCStreamer.cpp:212
static SectionKind getDataNoRel()
Definition: SectionKind.h:231
size_t strlen(const char *s);
bool isMergeableConst8() const
Definition: SectionKind.h:158
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:270
static cl::opt< AlignMode > Align(cl::desc("Load/store alignment support"), cl::Hidden, cl::init(DefaultAlign), cl::values(clEnumValN(DefaultAlign,"arm-default-align","Generate unaligned accesses only on hardware/OS ""combinations that are known to support them"), clEnumValN(StrictAlign,"arm-strict-align","Disallow all unaligned memory accesses"), clEnumValN(NoStrictAlign,"arm-no-strict-align","Allow unaligned memory accesses"), clEnumValEnd))
virtual const MCSection * SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, const TargetMachine &TM) const
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:70
std::string getName(ID id, ArrayRef< Type * > Tys=None)
Definition: Function.cpp:400
static const size_t npos
Definition: StringRef.h:45
virtual const MCExpr * getTTypeGlobalReference(const GlobalValue *GV, Mangler *Mang, MachineModuleInfo *MMI, unsigned Encoding, MCStreamer &Streamer) const
virtual void EmitLinkerOptions(ArrayRef< std::string > Kind)
Definition: MCStreamer.h:348
virtual const DataLayout * getDataLayout() const
virtual void emitModuleFlags(MCStreamer &Streamer, ArrayRef< Module::ModuleFlagEntry > ModuleFlags, Mangler *Mang, const TargetMachine &TM) const
emitModuleFlags - Perform code emission for module flags.
virtual const MCSection * getStaticCtorSection(unsigned Priority=65535) const
virtual MCSymbol * getCFIPersonalitySymbol(const GlobalValue *GV, Mangler *Mang, MachineModuleInfo *MMI) const
bool isCommon() const
Definition: SectionKind.h:180
bool hasLocalLinkage() const
Definition: GlobalValue.h:211
virtual const MCSection * getExplicitSectionGlobal(const GlobalValue *GV, SectionKind Kind, Mangler *Mang, const TargetMachine &TM) const
unsigned getTypeAndAttributes() const
LLVM Value Representation.
Definition: Value.h:66
bool isMergeableConst4() const
Definition: SectionKind.h:157
iterator end() const
Definition: StringRef.h:99
bool isReadOnlyWithRelLocal() const
Definition: SectionKind.h:196
void EmitSymbolValue(const MCSymbol *Sym, unsigned Size)
Definition: MCStreamer.cpp:145
static unsigned getELFSectionFlags(SectionKind K)
bool isDataRel() const
Definition: SectionKind.h:182
COFF::SectionCharacteristics Characteristics
Definition: COFFYAML.cpp:196
static const char * getSectionPrefixForGlobal(SectionKind Kind)
static unsigned getELFSectionType(StringRef Name, SectionKind K)
bool isDataRelLocal() const
Definition: SectionKind.h:186
bool isReadOnly() const
Definition: SectionKind.h:140
bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:110