LLVM API Documentation

TargetLoweringObjectFileImpl.cpp
Go to the documentation of this file.
00001 //===-- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info --===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements classes used to handle lowerings specific to common
00011 // object file formats.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
00016 #include "llvm/ADT/SmallString.h"
00017 #include "llvm/ADT/StringExtras.h"
00018 #include "llvm/ADT/Triple.h"
00019 #include "llvm/CodeGen/MachineModuleInfoImpls.h"
00020 #include "llvm/IR/Constants.h"
00021 #include "llvm/IR/DataLayout.h"
00022 #include "llvm/IR/DerivedTypes.h"
00023 #include "llvm/IR/Function.h"
00024 #include "llvm/IR/GlobalVariable.h"
00025 #include "llvm/IR/Mangler.h"
00026 #include "llvm/IR/Module.h"
00027 #include "llvm/MC/MCContext.h"
00028 #include "llvm/MC/MCExpr.h"
00029 #include "llvm/MC/MCSectionCOFF.h"
00030 #include "llvm/MC/MCSectionELF.h"
00031 #include "llvm/MC/MCSectionMachO.h"
00032 #include "llvm/MC/MCStreamer.h"
00033 #include "llvm/MC/MCSymbol.h"
00034 #include "llvm/Support/Dwarf.h"
00035 #include "llvm/Support/ELF.h"
00036 #include "llvm/Support/ErrorHandling.h"
00037 #include "llvm/Support/raw_ostream.h"
00038 #include "llvm/Target/TargetLowering.h"
00039 #include "llvm/Target/TargetMachine.h"
00040 using namespace llvm;
00041 using namespace dwarf;
00042 
00043 //===----------------------------------------------------------------------===//
00044 //                                  ELF
00045 //===----------------------------------------------------------------------===//
00046 
00047 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
00048     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
00049     MachineModuleInfo *MMI) const {
00050   unsigned Encoding = getPersonalityEncoding();
00051   switch (Encoding & 0x70) {
00052   default:
00053     report_fatal_error("We do not support this DWARF encoding yet!");
00054   case dwarf::DW_EH_PE_absptr:
00055     return TM.getSymbol(GV, Mang);
00056   case dwarf::DW_EH_PE_pcrel: {
00057     return getContext().GetOrCreateSymbol(StringRef("DW.ref.") +
00058                                           TM.getSymbol(GV, Mang)->getName());
00059   }
00060   }
00061 }
00062 
00063 void TargetLoweringObjectFileELF::emitPersonalityValue(MCStreamer &Streamer,
00064                                                        const TargetMachine &TM,
00065                                                        const MCSymbol *Sym) const {
00066   SmallString<64> NameData("DW.ref.");
00067   NameData += Sym->getName();
00068   MCSymbol *Label = getContext().GetOrCreateSymbol(NameData);
00069   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
00070   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
00071   StringRef Prefix = ".data.";
00072   NameData.insert(NameData.begin(), Prefix.begin(), Prefix.end());
00073   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
00074   const MCSection *Sec = getContext().getELFSection(NameData,
00075                                                     ELF::SHT_PROGBITS,
00076                                                     Flags,
00077                                                     SectionKind::getDataRel(),
00078                                                     0, Label->getName());
00079   unsigned Size = TM.getDataLayout()->getPointerSize();
00080   Streamer.SwitchSection(Sec);
00081   Streamer.EmitValueToAlignment(TM.getDataLayout()->getPointerABIAlignment());
00082   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
00083   const MCExpr *E = MCConstantExpr::Create(Size, getContext());
00084   Streamer.EmitELFSize(Label, E);
00085   Streamer.EmitLabel(Label);
00086 
00087   Streamer.EmitSymbolValue(Sym, Size);
00088 }
00089 
00090 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
00091     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
00092     const TargetMachine &TM, MachineModuleInfo *MMI,
00093     MCStreamer &Streamer) const {
00094 
00095   if (Encoding & dwarf::DW_EH_PE_indirect) {
00096     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
00097 
00098     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", Mang, TM);
00099 
00100     // Add information about the stub reference to ELFMMI so that the stub
00101     // gets emitted by the asmprinter.
00102     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
00103     if (!StubSym.getPointer()) {
00104       MCSymbol *Sym = TM.getSymbol(GV, Mang);
00105       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00106     }
00107 
00108     return TargetLoweringObjectFile::
00109       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
00110                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
00111   }
00112 
00113   return TargetLoweringObjectFile::
00114     getTTypeGlobalReference(GV, Encoding, Mang, TM, MMI, Streamer);
00115 }
00116 
00117 static SectionKind
00118 getELFKindForNamedSection(StringRef Name, SectionKind K) {
00119   // N.B.: The defaults used in here are no the same ones used in MC.
00120   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
00121   // both gas and MC will produce a section with no flags. Given
00122   // section(".eh_frame") gcc will produce:
00123   //
00124   //   .section   .eh_frame,"a",@progbits
00125   if (Name.empty() || Name[0] != '.') return K;
00126 
00127   // Some lame default implementation based on some magic section names.
00128   if (Name == ".bss" ||
00129       Name.startswith(".bss.") ||
00130       Name.startswith(".gnu.linkonce.b.") ||
00131       Name.startswith(".llvm.linkonce.b.") ||
00132       Name == ".sbss" ||
00133       Name.startswith(".sbss.") ||
00134       Name.startswith(".gnu.linkonce.sb.") ||
00135       Name.startswith(".llvm.linkonce.sb."))
00136     return SectionKind::getBSS();
00137 
00138   if (Name == ".tdata" ||
00139       Name.startswith(".tdata.") ||
00140       Name.startswith(".gnu.linkonce.td.") ||
00141       Name.startswith(".llvm.linkonce.td."))
00142     return SectionKind::getThreadData();
00143 
00144   if (Name == ".tbss" ||
00145       Name.startswith(".tbss.") ||
00146       Name.startswith(".gnu.linkonce.tb.") ||
00147       Name.startswith(".llvm.linkonce.tb."))
00148     return SectionKind::getThreadBSS();
00149 
00150   return K;
00151 }
00152 
00153 
00154 static unsigned getELFSectionType(StringRef Name, SectionKind K) {
00155 
00156   if (Name == ".init_array")
00157     return ELF::SHT_INIT_ARRAY;
00158 
00159   if (Name == ".fini_array")
00160     return ELF::SHT_FINI_ARRAY;
00161 
00162   if (Name == ".preinit_array")
00163     return ELF::SHT_PREINIT_ARRAY;
00164 
00165   if (K.isBSS() || K.isThreadBSS())
00166     return ELF::SHT_NOBITS;
00167 
00168   return ELF::SHT_PROGBITS;
00169 }
00170 
00171 
00172 static unsigned
00173 getELFSectionFlags(SectionKind K) {
00174   unsigned Flags = 0;
00175 
00176   if (!K.isMetadata())
00177     Flags |= ELF::SHF_ALLOC;
00178 
00179   if (K.isText())
00180     Flags |= ELF::SHF_EXECINSTR;
00181 
00182   if (K.isWriteable())
00183     Flags |= ELF::SHF_WRITE;
00184 
00185   if (K.isThreadLocal())
00186     Flags |= ELF::SHF_TLS;
00187 
00188   // K.isMergeableConst() is left out to honour PR4650
00189   if (K.isMergeableCString() || K.isMergeableConst4() ||
00190       K.isMergeableConst8() || K.isMergeableConst16())
00191     Flags |= ELF::SHF_MERGE;
00192 
00193   if (K.isMergeableCString())
00194     Flags |= ELF::SHF_STRINGS;
00195 
00196   return Flags;
00197 }
00198 
00199 const MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
00200     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00201     const TargetMachine &TM) const {
00202   StringRef SectionName = GV->getSection();
00203 
00204   // Infer section flags from the section name if we can.
00205   Kind = getELFKindForNamedSection(SectionName, Kind);
00206 
00207   return getContext().getELFSection(SectionName,
00208                                     getELFSectionType(SectionName, Kind),
00209                                     getELFSectionFlags(Kind), Kind);
00210 }
00211 
00212 /// getSectionPrefixForGlobal - Return the section prefix name used by options
00213 /// FunctionsSections and DataSections.
00214 static const char *getSectionPrefixForGlobal(SectionKind Kind) {
00215   if (Kind.isText())                 return ".text.";
00216   if (Kind.isReadOnly())             return ".rodata.";
00217   if (Kind.isBSS())                  return ".bss.";
00218 
00219   if (Kind.isThreadData())           return ".tdata.";
00220   if (Kind.isThreadBSS())            return ".tbss.";
00221 
00222   if (Kind.isDataNoRel())            return ".data.";
00223   if (Kind.isDataRelLocal())         return ".data.rel.local.";
00224   if (Kind.isDataRel())              return ".data.rel.";
00225   if (Kind.isReadOnlyWithRelLocal()) return ".data.rel.ro.local.";
00226 
00227   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00228   return ".data.rel.ro.";
00229 }
00230 
00231 
00232 const MCSection *TargetLoweringObjectFileELF::
00233 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00234                        Mangler &Mang, const TargetMachine &TM) const {
00235   // If we have -ffunction-section or -fdata-section then we should emit the
00236   // global value to a uniqued section specifically for it.
00237   bool EmitUniquedSection;
00238   if (Kind.isText())
00239     EmitUniquedSection = TM.getFunctionSections();
00240   else
00241     EmitUniquedSection = TM.getDataSections();
00242 
00243   // If this global is linkonce/weak and the target handles this by emitting it
00244   // into a 'uniqued' section name, create and return the section now.
00245   if ((GV->isWeakForLinker() || EmitUniquedSection) &&
00246       !Kind.isCommon()) {
00247     const char *Prefix;
00248     Prefix = getSectionPrefixForGlobal(Kind);
00249 
00250     SmallString<128> Name(Prefix, Prefix+strlen(Prefix));
00251     TM.getNameWithPrefix(Name, GV, Mang, true);
00252 
00253     StringRef Group = "";
00254     unsigned Flags = getELFSectionFlags(Kind);
00255     if (GV->isWeakForLinker()) {
00256       Group = Name.substr(strlen(Prefix));
00257       Flags |= ELF::SHF_GROUP;
00258     }
00259 
00260     return getContext().getELFSection(Name.str(),
00261                                       getELFSectionType(Name.str(), Kind),
00262                                       Flags, Kind, 0, Group);
00263   }
00264 
00265   if (Kind.isText()) return TextSection;
00266 
00267   if (Kind.isMergeable1ByteCString() ||
00268       Kind.isMergeable2ByteCString() ||
00269       Kind.isMergeable4ByteCString()) {
00270 
00271     // We also need alignment here.
00272     // FIXME: this is getting the alignment of the character, not the
00273     // alignment of the global!
00274     unsigned Align =
00275       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV));
00276 
00277     const char *SizeSpec = ".rodata.str1.";
00278     if (Kind.isMergeable2ByteCString())
00279       SizeSpec = ".rodata.str2.";
00280     else if (Kind.isMergeable4ByteCString())
00281       SizeSpec = ".rodata.str4.";
00282     else
00283       assert(Kind.isMergeable1ByteCString() && "unknown string width");
00284 
00285 
00286     std::string Name = SizeSpec + utostr(Align);
00287     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
00288                                       ELF::SHF_ALLOC |
00289                                       ELF::SHF_MERGE |
00290                                       ELF::SHF_STRINGS,
00291                                       Kind);
00292   }
00293 
00294   if (Kind.isMergeableConst()) {
00295     if (Kind.isMergeableConst4() && MergeableConst4Section)
00296       return MergeableConst4Section;
00297     if (Kind.isMergeableConst8() && MergeableConst8Section)
00298       return MergeableConst8Section;
00299     if (Kind.isMergeableConst16() && MergeableConst16Section)
00300       return MergeableConst16Section;
00301     return ReadOnlySection;  // .const
00302   }
00303 
00304   if (Kind.isReadOnly())             return ReadOnlySection;
00305 
00306   if (Kind.isThreadData())           return TLSDataSection;
00307   if (Kind.isThreadBSS())            return TLSBSSSection;
00308 
00309   // Note: we claim that common symbols are put in BSSSection, but they are
00310   // really emitted with the magic .comm directive, which creates a symbol table
00311   // entry but not a section.
00312   if (Kind.isBSS() || Kind.isCommon()) return BSSSection;
00313 
00314   if (Kind.isDataNoRel())            return DataSection;
00315   if (Kind.isDataRelLocal())         return DataRelLocalSection;
00316   if (Kind.isDataRel())              return DataRelSection;
00317   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
00318 
00319   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00320   return DataRelROSection;
00321 }
00322 
00323 /// getSectionForConstant - Given a mergeable constant with the
00324 /// specified size and relocation information, return a section that it
00325 /// should be placed in.
00326 const MCSection *TargetLoweringObjectFileELF::
00327 getSectionForConstant(SectionKind Kind) const {
00328   if (Kind.isMergeableConst4() && MergeableConst4Section)
00329     return MergeableConst4Section;
00330   if (Kind.isMergeableConst8() && MergeableConst8Section)
00331     return MergeableConst8Section;
00332   if (Kind.isMergeableConst16() && MergeableConst16Section)
00333     return MergeableConst16Section;
00334   if (Kind.isReadOnly())
00335     return ReadOnlySection;
00336 
00337   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
00338   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00339   return DataRelROSection;
00340 }
00341 
00342 const MCSection *
00343 TargetLoweringObjectFileELF::getStaticCtorSection(unsigned Priority) const {
00344   // The default scheme is .ctor / .dtor, so we have to invert the priority
00345   // numbering.
00346   if (Priority == 65535)
00347     return StaticCtorSection;
00348 
00349   if (UseInitArray) {
00350     std::string Name = std::string(".init_array.") + utostr(Priority);
00351     return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
00352                                       ELF::SHF_ALLOC | ELF::SHF_WRITE,
00353                                       SectionKind::getDataRel());
00354   } else {
00355     std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
00356     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
00357                                       ELF::SHF_ALLOC |ELF::SHF_WRITE,
00358                                       SectionKind::getDataRel());
00359   }
00360 }
00361 
00362 const MCSection *
00363 TargetLoweringObjectFileELF::getStaticDtorSection(unsigned Priority) const {
00364   // The default scheme is .ctor / .dtor, so we have to invert the priority
00365   // numbering.
00366   if (Priority == 65535)
00367     return StaticDtorSection;
00368 
00369   if (UseInitArray) {
00370     std::string Name = std::string(".fini_array.") + utostr(Priority);
00371     return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
00372                                       ELF::SHF_ALLOC | ELF::SHF_WRITE,
00373                                       SectionKind::getDataRel());
00374   } else {
00375     std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
00376     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
00377                                       ELF::SHF_ALLOC |ELF::SHF_WRITE,
00378                                       SectionKind::getDataRel());
00379   }
00380 }
00381 
00382 void
00383 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
00384   UseInitArray = UseInitArray_;
00385   if (!UseInitArray)
00386     return;
00387 
00388   StaticCtorSection =
00389     getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
00390                                ELF::SHF_WRITE |
00391                                ELF::SHF_ALLOC,
00392                                SectionKind::getDataRel());
00393   StaticDtorSection =
00394     getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
00395                                ELF::SHF_WRITE |
00396                                ELF::SHF_ALLOC,
00397                                SectionKind::getDataRel());
00398 }
00399 
00400 //===----------------------------------------------------------------------===//
00401 //                                 MachO
00402 //===----------------------------------------------------------------------===//
00403 
00404 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
00405 /// option string. Returns StringRef() if the option does not specify a library.
00406 StringRef TargetLoweringObjectFileMachO::
00407 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
00408   const char *LibCmd = "-l";
00409   if (LinkerOption.startswith(LibCmd))
00410     return LinkerOption.substr(strlen(LibCmd));
00411   return StringRef();
00412 }
00413 
00414 /// emitModuleFlags - Perform code emission for module flags.
00415 void TargetLoweringObjectFileMachO::
00416 emitModuleFlags(MCStreamer &Streamer,
00417                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00418                 Mangler &Mang, const TargetMachine &TM) const {
00419   unsigned VersionVal = 0;
00420   unsigned ImageInfoFlags = 0;
00421   MDNode *LinkerOptions = nullptr;
00422   StringRef SectionVal;
00423 
00424   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00425          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00426     const Module::ModuleFlagEntry &MFE = *i;
00427 
00428     // Ignore flags with 'Require' behavior.
00429     if (MFE.Behavior == Module::Require)
00430       continue;
00431 
00432     StringRef Key = MFE.Key->getString();
00433     Value *Val = MFE.Val;
00434 
00435     if (Key == "Objective-C Image Info Version") {
00436       VersionVal = cast<ConstantInt>(Val)->getZExtValue();
00437     } else if (Key == "Objective-C Garbage Collection" ||
00438                Key == "Objective-C GC Only" ||
00439                Key == "Objective-C Is Simulated") {
00440       ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
00441     } else if (Key == "Objective-C Image Info Section") {
00442       SectionVal = cast<MDString>(Val)->getString();
00443     } else if (Key == "Linker Options") {
00444       LinkerOptions = cast<MDNode>(Val);
00445     }
00446   }
00447 
00448   // Emit the linker options if present.
00449   if (LinkerOptions) {
00450     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00451       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00452       SmallVector<std::string, 4> StrOptions;
00453 
00454       // Convert to strings.
00455       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00456         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00457         StrOptions.push_back(MDOption->getString());
00458       }
00459 
00460       Streamer.EmitLinkerOptions(StrOptions);
00461     }
00462   }
00463 
00464   // The section is mandatory. If we don't have it, then we don't have GC info.
00465   if (SectionVal.empty()) return;
00466 
00467   StringRef Segment, Section;
00468   unsigned TAA = 0, StubSize = 0;
00469   bool TAAParsed;
00470   std::string ErrorCode =
00471     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
00472                                           TAA, TAAParsed, StubSize);
00473   if (!ErrorCode.empty())
00474     // If invalid, report the error with report_fatal_error.
00475     report_fatal_error("Invalid section specifier '" + Section + "': " +
00476                        ErrorCode + ".");
00477 
00478   // Get the section.
00479   const MCSectionMachO *S =
00480     getContext().getMachOSection(Segment, Section, TAA, StubSize,
00481                                  SectionKind::getDataNoRel());
00482   Streamer.SwitchSection(S);
00483   Streamer.EmitLabel(getContext().
00484                      GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
00485   Streamer.EmitIntValue(VersionVal, 4);
00486   Streamer.EmitIntValue(ImageInfoFlags, 4);
00487   Streamer.AddBlankLine();
00488 }
00489 
00490 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
00491     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00492     const TargetMachine &TM) const {
00493   // Parse the section specifier and create it if valid.
00494   StringRef Segment, Section;
00495   unsigned TAA = 0, StubSize = 0;
00496   bool TAAParsed;
00497   std::string ErrorCode =
00498     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
00499                                           TAA, TAAParsed, StubSize);
00500   if (!ErrorCode.empty()) {
00501     // If invalid, report the error with report_fatal_error.
00502     report_fatal_error("Global variable '" + GV->getName() +
00503                        "' has an invalid section specifier '" +
00504                        GV->getSection() + "': " + ErrorCode + ".");
00505   }
00506 
00507   // Get the section.
00508   const MCSectionMachO *S =
00509     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
00510 
00511   // If TAA wasn't set by ParseSectionSpecifier() above,
00512   // use the value returned by getMachOSection() as a default.
00513   if (!TAAParsed)
00514     TAA = S->getTypeAndAttributes();
00515 
00516   // Okay, now that we got the section, verify that the TAA & StubSize agree.
00517   // If the user declared multiple globals with different section flags, we need
00518   // to reject it here.
00519   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
00520     // If invalid, report the error with report_fatal_error.
00521     report_fatal_error("Global variable '" + GV->getName() +
00522                        "' section type or attributes does not match previous"
00523                        " section specifier");
00524   }
00525 
00526   return S;
00527 }
00528 
00529 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
00530     const MCSection &Section) const {
00531     const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
00532 
00533     // Sections holding 1 byte strings are atomized based on the data
00534     // they contain.
00535     // Sections holding 2 byte strings require symbols in order to be
00536     // atomized.
00537     // There is no dedicated section for 4 byte strings.
00538     if (SMO.getKind().isMergeable1ByteCString())
00539       return false;
00540 
00541     if (SMO.getSegmentName() == "__DATA" &&
00542         SMO.getSectionName() == "__cfstring")
00543       return false;
00544 
00545     switch (SMO.getType()) {
00546     default:
00547       return true;
00548 
00549       // These sections are atomized at the element boundaries without using
00550       // symbols.
00551     case MachO::S_4BYTE_LITERALS:
00552     case MachO::S_8BYTE_LITERALS:
00553     case MachO::S_16BYTE_LITERALS:
00554     case MachO::S_LITERAL_POINTERS:
00555     case MachO::S_NON_LAZY_SYMBOL_POINTERS:
00556     case MachO::S_LAZY_SYMBOL_POINTERS:
00557     case MachO::S_MOD_INIT_FUNC_POINTERS:
00558     case MachO::S_MOD_TERM_FUNC_POINTERS:
00559     case MachO::S_INTERPOSING:
00560       return false;
00561     }
00562 }
00563 
00564 const MCSection *TargetLoweringObjectFileMachO::
00565 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00566                        Mangler &Mang, const TargetMachine &TM) const {
00567 
00568   // Handle thread local data.
00569   if (Kind.isThreadBSS()) return TLSBSSSection;
00570   if (Kind.isThreadData()) return TLSDataSection;
00571 
00572   if (Kind.isText())
00573     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
00574 
00575   // If this is weak/linkonce, put this in a coalescable section, either in text
00576   // or data depending on if it is writable.
00577   if (GV->isWeakForLinker()) {
00578     if (Kind.isReadOnly())
00579       return ConstTextCoalSection;
00580     return DataCoalSection;
00581   }
00582 
00583   // FIXME: Alignment check should be handled by section classifier.
00584   if (Kind.isMergeable1ByteCString() &&
00585       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
00586     return CStringSection;
00587 
00588   // Do not put 16-bit arrays in the UString section if they have an
00589   // externally visible label, this runs into issues with certain linker
00590   // versions.
00591   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
00592       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
00593     return UStringSection;
00594 
00595   if (Kind.isMergeableConst()) {
00596     if (Kind.isMergeableConst4())
00597       return FourByteConstantSection;
00598     if (Kind.isMergeableConst8())
00599       return EightByteConstantSection;
00600     if (Kind.isMergeableConst16())
00601       return SixteenByteConstantSection;
00602   }
00603 
00604   // Otherwise, if it is readonly, but not something we can specially optimize,
00605   // just drop it in .const.
00606   if (Kind.isReadOnly())
00607     return ReadOnlySection;
00608 
00609   // If this is marked const, put it into a const section.  But if the dynamic
00610   // linker needs to write to it, put it in the data segment.
00611   if (Kind.isReadOnlyWithRel())
00612     return ConstDataSection;
00613 
00614   // Put zero initialized globals with strong external linkage in the
00615   // DATA, __common section with the .zerofill directive.
00616   if (Kind.isBSSExtern())
00617     return DataCommonSection;
00618 
00619   // Put zero initialized globals with local linkage in __DATA,__bss directive
00620   // with the .zerofill directive (aka .lcomm).
00621   if (Kind.isBSSLocal())
00622     return DataBSSSection;
00623 
00624   // Otherwise, just drop the variable in the normal data section.
00625   return DataSection;
00626 }
00627 
00628 const MCSection *
00629 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
00630   // If this constant requires a relocation, we have to put it in the data
00631   // segment, not in the text segment.
00632   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
00633     return ConstDataSection;
00634 
00635   if (Kind.isMergeableConst4())
00636     return FourByteConstantSection;
00637   if (Kind.isMergeableConst8())
00638     return EightByteConstantSection;
00639   if (Kind.isMergeableConst16())
00640     return SixteenByteConstantSection;
00641   return ReadOnlySection;  // .const
00642 }
00643 
00644 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
00645     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
00646     const TargetMachine &TM, MachineModuleInfo *MMI,
00647     MCStreamer &Streamer) const {
00648   // The mach-o version of this method defaults to returning a stub reference.
00649 
00650   if (Encoding & DW_EH_PE_indirect) {
00651     MachineModuleInfoMachO &MachOMMI =
00652       MMI->getObjFileInfo<MachineModuleInfoMachO>();
00653 
00654     MCSymbol *SSym =
00655         getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
00656 
00657     // Add information about the stub reference to MachOMMI so that the stub
00658     // gets emitted by the asmprinter.
00659     MachineModuleInfoImpl::StubValueTy &StubSym =
00660       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
00661                                   MachOMMI.getGVStubEntry(SSym);
00662     if (!StubSym.getPointer()) {
00663       MCSymbol *Sym = TM.getSymbol(GV, Mang);
00664       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00665     }
00666 
00667     return TargetLoweringObjectFile::
00668       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
00669                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
00670   }
00671 
00672   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
00673                                                            TM, MMI, Streamer);
00674 }
00675 
00676 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
00677     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
00678     MachineModuleInfo *MMI) const {
00679   // The mach-o version of this method defaults to returning a stub reference.
00680   MachineModuleInfoMachO &MachOMMI =
00681     MMI->getObjFileInfo<MachineModuleInfoMachO>();
00682 
00683   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
00684 
00685   // Add information about the stub reference to MachOMMI so that the stub
00686   // gets emitted by the asmprinter.
00687   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
00688   if (!StubSym.getPointer()) {
00689     MCSymbol *Sym = TM.getSymbol(GV, Mang);
00690     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00691   }
00692 
00693   return SSym;
00694 }
00695 
00696 //===----------------------------------------------------------------------===//
00697 //                                  COFF
00698 //===----------------------------------------------------------------------===//
00699 
00700 static unsigned
00701 getCOFFSectionFlags(SectionKind K) {
00702   unsigned Flags = 0;
00703 
00704   if (K.isMetadata())
00705     Flags |=
00706       COFF::IMAGE_SCN_MEM_DISCARDABLE;
00707   else if (K.isText())
00708     Flags |=
00709       COFF::IMAGE_SCN_MEM_EXECUTE |
00710       COFF::IMAGE_SCN_MEM_READ |
00711       COFF::IMAGE_SCN_CNT_CODE;
00712   else if (K.isBSS ())
00713     Flags |=
00714       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
00715       COFF::IMAGE_SCN_MEM_READ |
00716       COFF::IMAGE_SCN_MEM_WRITE;
00717   else if (K.isThreadLocal())
00718     Flags |=
00719       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00720       COFF::IMAGE_SCN_MEM_READ |
00721       COFF::IMAGE_SCN_MEM_WRITE;
00722   else if (K.isReadOnly())
00723     Flags |=
00724       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00725       COFF::IMAGE_SCN_MEM_READ;
00726   else if (K.isWriteable())
00727     Flags |=
00728       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00729       COFF::IMAGE_SCN_MEM_READ |
00730       COFF::IMAGE_SCN_MEM_WRITE;
00731 
00732   return Flags;
00733 }
00734 
00735 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
00736     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00737     const TargetMachine &TM) const {
00738   int Selection = 0;
00739   unsigned Characteristics = getCOFFSectionFlags(Kind);
00740   StringRef Name = GV->getSection();
00741   StringRef COMDATSymName = "";
00742   if (GV->isWeakForLinker()) {
00743     Selection = COFF::IMAGE_COMDAT_SELECT_ANY;
00744     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00745     MCSymbol *Sym = TM.getSymbol(GV, Mang);
00746     COMDATSymName = Sym->getName();
00747   }
00748   return getContext().getCOFFSection(Name,
00749                                      Characteristics,
00750                                      Kind,
00751                                      COMDATSymName,
00752                                      Selection);
00753 }
00754 
00755 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
00756   if (Kind.isText())
00757     return ".text";
00758   if (Kind.isBSS())
00759     return ".bss";
00760   if (Kind.isThreadLocal())
00761     return ".tls$";
00762   if (Kind.isWriteable())
00763     return ".data";
00764   return ".rdata";
00765 }
00766 
00767 
00768 const MCSection *TargetLoweringObjectFileCOFF::
00769 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00770                        Mangler &Mang, const TargetMachine &TM) const {
00771   // If we have -ffunction-sections then we should emit the global value to a
00772   // uniqued section specifically for it.
00773   bool EmitUniquedSection;
00774   if (Kind.isText())
00775     EmitUniquedSection = TM.getFunctionSections();
00776   else
00777     EmitUniquedSection = TM.getDataSections();
00778 
00779   // If this global is linkonce/weak and the target handles this by emitting it
00780   // into a 'uniqued' section name, create and return the section now.
00781   // Section names depend on the name of the symbol which is not feasible if the
00782   // symbol has private linkage.
00783   if ((GV->isWeakForLinker() || EmitUniquedSection) &&
00784       !GV->hasPrivateLinkage() && !Kind.isCommon()) {
00785     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
00786     unsigned Characteristics = getCOFFSectionFlags(Kind);
00787 
00788     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00789     MCSymbol *Sym = TM.getSymbol(GV, Mang);
00790     return getContext().getCOFFSection(
00791         Name, Characteristics, Kind, Sym->getName(),
00792         GV->isWeakForLinker() ? COFF::IMAGE_COMDAT_SELECT_ANY
00793                               : COFF::IMAGE_COMDAT_SELECT_NODUPLICATES);
00794   }
00795 
00796   if (Kind.isText())
00797     return TextSection;
00798 
00799   if (Kind.isThreadLocal())
00800     return TLSDataSection;
00801 
00802   if (Kind.isReadOnly())
00803     return ReadOnlySection;
00804 
00805   // Note: we claim that common symbols are put in BSSSection, but they are
00806   // really emitted with the magic .comm directive, which creates a symbol table
00807   // entry but not a section.
00808   if (Kind.isBSS() || Kind.isCommon())
00809     return BSSSection;
00810 
00811   return DataSection;
00812 }
00813 
00814 StringRef TargetLoweringObjectFileCOFF::
00815 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
00816   const char *LibCmd = "/DEFAULTLIB:";
00817   if (LinkerOption.startswith(LibCmd))
00818     return LinkerOption.substr(strlen(LibCmd));
00819   return StringRef();
00820 }
00821 
00822 void TargetLoweringObjectFileCOFF::
00823 emitModuleFlags(MCStreamer &Streamer,
00824                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00825                 Mangler &Mang, const TargetMachine &TM) const {
00826   MDNode *LinkerOptions = nullptr;
00827 
00828   // Look for the "Linker Options" flag, since it's the only one we support.
00829   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00830        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00831     const Module::ModuleFlagEntry &MFE = *i;
00832     StringRef Key = MFE.Key->getString();
00833     Value *Val = MFE.Val;
00834     if (Key == "Linker Options") {
00835       LinkerOptions = cast<MDNode>(Val);
00836       break;
00837     }
00838   }
00839   if (!LinkerOptions)
00840     return;
00841 
00842   // Emit the linker options to the linker .drectve section.  According to the
00843   // spec, this section is a space-separated string containing flags for linker.
00844   const MCSection *Sec = getDrectveSection();
00845   Streamer.SwitchSection(Sec);
00846   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00847     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00848     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00849       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00850       StringRef Op = MDOption->getString();
00851       // Lead with a space for consistency with our dllexport implementation.
00852       std::string Escaped(" ");
00853       if (Op.find(" ") != StringRef::npos) {
00854         // The PE-COFF spec says args with spaces must be quoted.  It doesn't say
00855         // how to escape quotes, but it probably uses this algorithm:
00856         // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
00857         // FIXME: Reuse escaping code from Support/Windows/Program.inc
00858         Escaped.push_back('\"');
00859         Escaped.append(Op);
00860         Escaped.push_back('\"');
00861       } else {
00862         Escaped.append(Op);
00863       }
00864       Streamer.EmitBytes(Escaped);
00865     }
00866   }
00867 }