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