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 *TargetLoweringObjectFileELF::
00342 getSectionForConstant(SectionKind Kind) const {
00343   if (Kind.isMergeableConst4() && MergeableConst4Section)
00344     return MergeableConst4Section;
00345   if (Kind.isMergeableConst8() && MergeableConst8Section)
00346     return MergeableConst8Section;
00347   if (Kind.isMergeableConst16() && MergeableConst16Section)
00348     return MergeableConst16Section;
00349   if (Kind.isReadOnly())
00350     return ReadOnlySection;
00351 
00352   if (Kind.isReadOnlyWithRelLocal()) return DataRelROLocalSection;
00353   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
00354   return DataRelROSection;
00355 }
00356 
00357 const MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
00358     unsigned Priority, const MCSymbol *KeySym) const {
00359   // The default scheme is .ctor / .dtor, so we have to invert the priority
00360   // numbering.
00361   if (Priority == 65535)
00362     return StaticCtorSection;
00363 
00364   if (UseInitArray) {
00365     std::string Name = std::string(".init_array.") + utostr(Priority);
00366     return getContext().getELFSection(Name, ELF::SHT_INIT_ARRAY,
00367                                       ELF::SHF_ALLOC | ELF::SHF_WRITE,
00368                                       SectionKind::getDataRel());
00369   } else {
00370     std::string Name = std::string(".ctors.") + utostr(65535 - Priority);
00371     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
00372                                       ELF::SHF_ALLOC |ELF::SHF_WRITE,
00373                                       SectionKind::getDataRel());
00374   }
00375 }
00376 
00377 const MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
00378     unsigned Priority, const MCSymbol *KeySym) const {
00379   // The default scheme is .ctor / .dtor, so we have to invert the priority
00380   // numbering.
00381   if (Priority == 65535)
00382     return StaticDtorSection;
00383 
00384   if (UseInitArray) {
00385     std::string Name = std::string(".fini_array.") + utostr(Priority);
00386     return getContext().getELFSection(Name, ELF::SHT_FINI_ARRAY,
00387                                       ELF::SHF_ALLOC | ELF::SHF_WRITE,
00388                                       SectionKind::getDataRel());
00389   } else {
00390     std::string Name = std::string(".dtors.") + utostr(65535 - Priority);
00391     return getContext().getELFSection(Name, ELF::SHT_PROGBITS,
00392                                       ELF::SHF_ALLOC |ELF::SHF_WRITE,
00393                                       SectionKind::getDataRel());
00394   }
00395 }
00396 
00397 void
00398 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
00399   UseInitArray = UseInitArray_;
00400   if (!UseInitArray)
00401     return;
00402 
00403   StaticCtorSection =
00404     getContext().getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
00405                                ELF::SHF_WRITE |
00406                                ELF::SHF_ALLOC,
00407                                SectionKind::getDataRel());
00408   StaticDtorSection =
00409     getContext().getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
00410                                ELF::SHF_WRITE |
00411                                ELF::SHF_ALLOC,
00412                                SectionKind::getDataRel());
00413 }
00414 
00415 //===----------------------------------------------------------------------===//
00416 //                                 MachO
00417 //===----------------------------------------------------------------------===//
00418 
00419 /// getDepLibFromLinkerOpt - Extract the dependent library name from a linker
00420 /// option string. Returns StringRef() if the option does not specify a library.
00421 StringRef TargetLoweringObjectFileMachO::
00422 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
00423   const char *LibCmd = "-l";
00424   if (LinkerOption.startswith(LibCmd))
00425     return LinkerOption.substr(strlen(LibCmd));
00426   return StringRef();
00427 }
00428 
00429 /// emitModuleFlags - Perform code emission for module flags.
00430 void TargetLoweringObjectFileMachO::
00431 emitModuleFlags(MCStreamer &Streamer,
00432                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00433                 Mangler &Mang, const TargetMachine &TM) const {
00434   unsigned VersionVal = 0;
00435   unsigned ImageInfoFlags = 0;
00436   MDNode *LinkerOptions = nullptr;
00437   StringRef SectionVal;
00438 
00439   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00440          i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00441     const Module::ModuleFlagEntry &MFE = *i;
00442 
00443     // Ignore flags with 'Require' behavior.
00444     if (MFE.Behavior == Module::Require)
00445       continue;
00446 
00447     StringRef Key = MFE.Key->getString();
00448     Value *Val = MFE.Val;
00449 
00450     if (Key == "Objective-C Image Info Version") {
00451       VersionVal = cast<ConstantInt>(Val)->getZExtValue();
00452     } else if (Key == "Objective-C Garbage Collection" ||
00453                Key == "Objective-C GC Only" ||
00454                Key == "Objective-C Is Simulated") {
00455       ImageInfoFlags |= cast<ConstantInt>(Val)->getZExtValue();
00456     } else if (Key == "Objective-C Image Info Section") {
00457       SectionVal = cast<MDString>(Val)->getString();
00458     } else if (Key == "Linker Options") {
00459       LinkerOptions = cast<MDNode>(Val);
00460     }
00461   }
00462 
00463   // Emit the linker options if present.
00464   if (LinkerOptions) {
00465     for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00466       MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00467       SmallVector<std::string, 4> StrOptions;
00468 
00469       // Convert to strings.
00470       for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00471         MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00472         StrOptions.push_back(MDOption->getString());
00473       }
00474 
00475       Streamer.EmitLinkerOptions(StrOptions);
00476     }
00477   }
00478 
00479   // The section is mandatory. If we don't have it, then we don't have GC info.
00480   if (SectionVal.empty()) return;
00481 
00482   StringRef Segment, Section;
00483   unsigned TAA = 0, StubSize = 0;
00484   bool TAAParsed;
00485   std::string ErrorCode =
00486     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
00487                                           TAA, TAAParsed, StubSize);
00488   if (!ErrorCode.empty())
00489     // If invalid, report the error with report_fatal_error.
00490     report_fatal_error("Invalid section specifier '" + Section + "': " +
00491                        ErrorCode + ".");
00492 
00493   // Get the section.
00494   const MCSectionMachO *S =
00495     getContext().getMachOSection(Segment, Section, TAA, StubSize,
00496                                  SectionKind::getDataNoRel());
00497   Streamer.SwitchSection(S);
00498   Streamer.EmitLabel(getContext().
00499                      GetOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
00500   Streamer.EmitIntValue(VersionVal, 4);
00501   Streamer.EmitIntValue(ImageInfoFlags, 4);
00502   Streamer.AddBlankLine();
00503 }
00504 
00505 static void checkMachOComdat(const GlobalValue *GV) {
00506   const Comdat *C = GV->getComdat();
00507   if (!C)
00508     return;
00509 
00510   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
00511                      "' cannot be lowered.");
00512 }
00513 
00514 const MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
00515     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00516     const TargetMachine &TM) const {
00517   // Parse the section specifier and create it if valid.
00518   StringRef Segment, Section;
00519   unsigned TAA = 0, StubSize = 0;
00520   bool TAAParsed;
00521 
00522   checkMachOComdat(GV);
00523 
00524   std::string ErrorCode =
00525     MCSectionMachO::ParseSectionSpecifier(GV->getSection(), Segment, Section,
00526                                           TAA, TAAParsed, StubSize);
00527   if (!ErrorCode.empty()) {
00528     // If invalid, report the error with report_fatal_error.
00529     report_fatal_error("Global variable '" + GV->getName() +
00530                        "' has an invalid section specifier '" +
00531                        GV->getSection() + "': " + ErrorCode + ".");
00532   }
00533 
00534   // Get the section.
00535   const MCSectionMachO *S =
00536     getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
00537 
00538   // If TAA wasn't set by ParseSectionSpecifier() above,
00539   // use the value returned by getMachOSection() as a default.
00540   if (!TAAParsed)
00541     TAA = S->getTypeAndAttributes();
00542 
00543   // Okay, now that we got the section, verify that the TAA & StubSize agree.
00544   // If the user declared multiple globals with different section flags, we need
00545   // to reject it here.
00546   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
00547     // If invalid, report the error with report_fatal_error.
00548     report_fatal_error("Global variable '" + GV->getName() +
00549                        "' section type or attributes does not match previous"
00550                        " section specifier");
00551   }
00552 
00553   return S;
00554 }
00555 
00556 bool TargetLoweringObjectFileMachO::isSectionAtomizableBySymbols(
00557     const MCSection &Section) const {
00558     const MCSectionMachO &SMO = static_cast<const MCSectionMachO&>(Section);
00559 
00560     // Sections holding 1 byte strings are atomized based on the data
00561     // they contain.
00562     // Sections holding 2 byte strings require symbols in order to be
00563     // atomized.
00564     // There is no dedicated section for 4 byte strings.
00565     if (SMO.getKind().isMergeable1ByteCString())
00566       return false;
00567 
00568     if (SMO.getSegmentName() == "__DATA" &&
00569         SMO.getSectionName() == "__cfstring")
00570       return false;
00571 
00572     switch (SMO.getType()) {
00573     default:
00574       return true;
00575 
00576       // These sections are atomized at the element boundaries without using
00577       // symbols.
00578     case MachO::S_4BYTE_LITERALS:
00579     case MachO::S_8BYTE_LITERALS:
00580     case MachO::S_16BYTE_LITERALS:
00581     case MachO::S_LITERAL_POINTERS:
00582     case MachO::S_NON_LAZY_SYMBOL_POINTERS:
00583     case MachO::S_LAZY_SYMBOL_POINTERS:
00584     case MachO::S_MOD_INIT_FUNC_POINTERS:
00585     case MachO::S_MOD_TERM_FUNC_POINTERS:
00586     case MachO::S_INTERPOSING:
00587       return false;
00588     }
00589 }
00590 
00591 const MCSection *TargetLoweringObjectFileMachO::
00592 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00593                        Mangler &Mang, const TargetMachine &TM) const {
00594   checkMachOComdat(GV);
00595 
00596   // Handle thread local data.
00597   if (Kind.isThreadBSS()) return TLSBSSSection;
00598   if (Kind.isThreadData()) return TLSDataSection;
00599 
00600   if (Kind.isText())
00601     return GV->isWeakForLinker() ? TextCoalSection : TextSection;
00602 
00603   // If this is weak/linkonce, put this in a coalescable section, either in text
00604   // or data depending on if it is writable.
00605   if (GV->isWeakForLinker()) {
00606     if (Kind.isReadOnly())
00607       return ConstTextCoalSection;
00608     return DataCoalSection;
00609   }
00610 
00611   // FIXME: Alignment check should be handled by section classifier.
00612   if (Kind.isMergeable1ByteCString() &&
00613       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
00614     return CStringSection;
00615 
00616   // Do not put 16-bit arrays in the UString section if they have an
00617   // externally visible label, this runs into issues with certain linker
00618   // versions.
00619   if (Kind.isMergeable2ByteCString() && !GV->hasExternalLinkage() &&
00620       TM.getDataLayout()->getPreferredAlignment(cast<GlobalVariable>(GV)) < 32)
00621     return UStringSection;
00622 
00623   if (Kind.isMergeableConst()) {
00624     if (Kind.isMergeableConst4())
00625       return FourByteConstantSection;
00626     if (Kind.isMergeableConst8())
00627       return EightByteConstantSection;
00628     if (Kind.isMergeableConst16())
00629       return SixteenByteConstantSection;
00630   }
00631 
00632   // Otherwise, if it is readonly, but not something we can specially optimize,
00633   // just drop it in .const.
00634   if (Kind.isReadOnly())
00635     return ReadOnlySection;
00636 
00637   // If this is marked const, put it into a const section.  But if the dynamic
00638   // linker needs to write to it, put it in the data segment.
00639   if (Kind.isReadOnlyWithRel())
00640     return ConstDataSection;
00641 
00642   // Put zero initialized globals with strong external linkage in the
00643   // DATA, __common section with the .zerofill directive.
00644   if (Kind.isBSSExtern())
00645     return DataCommonSection;
00646 
00647   // Put zero initialized globals with local linkage in __DATA,__bss directive
00648   // with the .zerofill directive (aka .lcomm).
00649   if (Kind.isBSSLocal())
00650     return DataBSSSection;
00651 
00652   // Otherwise, just drop the variable in the normal data section.
00653   return DataSection;
00654 }
00655 
00656 const MCSection *
00657 TargetLoweringObjectFileMachO::getSectionForConstant(SectionKind Kind) const {
00658   // If this constant requires a relocation, we have to put it in the data
00659   // segment, not in the text segment.
00660   if (Kind.isDataRel() || Kind.isReadOnlyWithRel())
00661     return ConstDataSection;
00662 
00663   if (Kind.isMergeableConst4())
00664     return FourByteConstantSection;
00665   if (Kind.isMergeableConst8())
00666     return EightByteConstantSection;
00667   if (Kind.isMergeableConst16())
00668     return SixteenByteConstantSection;
00669   return ReadOnlySection;  // .const
00670 }
00671 
00672 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
00673     const GlobalValue *GV, unsigned Encoding, Mangler &Mang,
00674     const TargetMachine &TM, MachineModuleInfo *MMI,
00675     MCStreamer &Streamer) const {
00676   // The mach-o version of this method defaults to returning a stub reference.
00677 
00678   if (Encoding & DW_EH_PE_indirect) {
00679     MachineModuleInfoMachO &MachOMMI =
00680       MMI->getObjFileInfo<MachineModuleInfoMachO>();
00681 
00682     MCSymbol *SSym =
00683         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 =
00688       GV->hasHiddenVisibility() ? MachOMMI.getHiddenGVStubEntry(SSym) :
00689                                   MachOMMI.getGVStubEntry(SSym);
00690     if (!StubSym.getPointer()) {
00691       MCSymbol *Sym = TM.getSymbol(GV, Mang);
00692       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00693     }
00694 
00695     return TargetLoweringObjectFile::
00696       getTTypeReference(MCSymbolRefExpr::Create(SSym, getContext()),
00697                         Encoding & ~dwarf::DW_EH_PE_indirect, Streamer);
00698   }
00699 
00700   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, Mang,
00701                                                            TM, MMI, Streamer);
00702 }
00703 
00704 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
00705     const GlobalValue *GV, Mangler &Mang, const TargetMachine &TM,
00706     MachineModuleInfo *MMI) const {
00707   // The mach-o version of this method defaults to returning a stub reference.
00708   MachineModuleInfoMachO &MachOMMI =
00709     MMI->getObjFileInfo<MachineModuleInfoMachO>();
00710 
00711   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", Mang, TM);
00712 
00713   // Add information about the stub reference to MachOMMI so that the stub
00714   // gets emitted by the asmprinter.
00715   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
00716   if (!StubSym.getPointer()) {
00717     MCSymbol *Sym = TM.getSymbol(GV, Mang);
00718     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
00719   }
00720 
00721   return SSym;
00722 }
00723 
00724 //===----------------------------------------------------------------------===//
00725 //                                  COFF
00726 //===----------------------------------------------------------------------===//
00727 
00728 static unsigned
00729 getCOFFSectionFlags(SectionKind K) {
00730   unsigned Flags = 0;
00731 
00732   if (K.isMetadata())
00733     Flags |=
00734       COFF::IMAGE_SCN_MEM_DISCARDABLE;
00735   else if (K.isText())
00736     Flags |=
00737       COFF::IMAGE_SCN_MEM_EXECUTE |
00738       COFF::IMAGE_SCN_MEM_READ |
00739       COFF::IMAGE_SCN_CNT_CODE;
00740   else if (K.isBSS ())
00741     Flags |=
00742       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
00743       COFF::IMAGE_SCN_MEM_READ |
00744       COFF::IMAGE_SCN_MEM_WRITE;
00745   else if (K.isThreadLocal())
00746     Flags |=
00747       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00748       COFF::IMAGE_SCN_MEM_READ |
00749       COFF::IMAGE_SCN_MEM_WRITE;
00750   else if (K.isReadOnly())
00751     Flags |=
00752       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00753       COFF::IMAGE_SCN_MEM_READ;
00754   else if (K.isWriteable())
00755     Flags |=
00756       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
00757       COFF::IMAGE_SCN_MEM_READ |
00758       COFF::IMAGE_SCN_MEM_WRITE;
00759 
00760   return Flags;
00761 }
00762 
00763 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
00764   const Comdat *C = GV->getComdat();
00765   assert(C && "expected GV to have a Comdat!");
00766 
00767   StringRef ComdatGVName = C->getName();
00768   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
00769   if (!ComdatGV)
00770     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
00771                        "' does not exist.");
00772 
00773   if (ComdatGV->getComdat() != C)
00774     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
00775                        "' is not a key for it's COMDAT.");
00776 
00777   return ComdatGV;
00778 }
00779 
00780 static int getSelectionForCOFF(const GlobalValue *GV) {
00781   if (const Comdat *C = GV->getComdat()) {
00782     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
00783     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
00784       ComdatKey = GA->getBaseObject();
00785     if (ComdatKey == GV) {
00786       switch (C->getSelectionKind()) {
00787       case Comdat::Any:
00788         return COFF::IMAGE_COMDAT_SELECT_ANY;
00789       case Comdat::ExactMatch:
00790         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
00791       case Comdat::Largest:
00792         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
00793       case Comdat::NoDuplicates:
00794         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
00795       case Comdat::SameSize:
00796         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
00797       }
00798     } else {
00799       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
00800     }
00801   } else if (GV->isWeakForLinker()) {
00802     return COFF::IMAGE_COMDAT_SELECT_ANY;
00803   }
00804   return 0;
00805 }
00806 
00807 const MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
00808     const GlobalValue *GV, SectionKind Kind, Mangler &Mang,
00809     const TargetMachine &TM) const {
00810   int Selection = 0;
00811   unsigned Characteristics = getCOFFSectionFlags(Kind);
00812   StringRef Name = GV->getSection();
00813   StringRef COMDATSymName = "";
00814   if ((GV->isWeakForLinker() || GV->hasComdat()) && !Kind.isCommon()) {
00815     Selection = getSelectionForCOFF(GV);
00816     const GlobalValue *ComdatGV;
00817     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
00818       ComdatGV = getComdatGVForCOFF(GV);
00819     else
00820       ComdatGV = GV;
00821 
00822     if (!ComdatGV->hasPrivateLinkage()) {
00823       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
00824       COMDATSymName = Sym->getName();
00825       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00826     } else {
00827       Selection = 0;
00828     }
00829   }
00830   return getContext().getCOFFSection(Name,
00831                                      Characteristics,
00832                                      Kind,
00833                                      COMDATSymName,
00834                                      Selection);
00835 }
00836 
00837 static const char *getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
00838   if (Kind.isText())
00839     return ".text";
00840   if (Kind.isBSS())
00841     return ".bss";
00842   if (Kind.isThreadLocal())
00843     return ".tls$";
00844   if (Kind.isWriteable())
00845     return ".data";
00846   return ".rdata";
00847 }
00848 
00849 
00850 const MCSection *TargetLoweringObjectFileCOFF::
00851 SelectSectionForGlobal(const GlobalValue *GV, SectionKind Kind,
00852                        Mangler &Mang, const TargetMachine &TM) const {
00853   // If we have -ffunction-sections then we should emit the global value to a
00854   // uniqued section specifically for it.
00855   bool EmitUniquedSection;
00856   if (Kind.isText())
00857     EmitUniquedSection = TM.getFunctionSections();
00858   else
00859     EmitUniquedSection = TM.getDataSections();
00860 
00861   // If this global is linkonce/weak and the target handles this by emitting it
00862   // into a 'uniqued' section name, create and return the section now.
00863   // Section names depend on the name of the symbol which is not feasible if the
00864   // symbol has private linkage.
00865   if ((GV->isWeakForLinker() || EmitUniquedSection || GV->hasComdat()) &&
00866       !Kind.isCommon()) {
00867     const char *Name = getCOFFSectionNameForUniqueGlobal(Kind);
00868     unsigned Characteristics = getCOFFSectionFlags(Kind);
00869 
00870     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
00871     int Selection = getSelectionForCOFF(GV);
00872     if (!Selection)
00873       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
00874     const GlobalValue *ComdatGV;
00875     if (GV->hasComdat())
00876       ComdatGV = getComdatGVForCOFF(GV);
00877     else
00878       ComdatGV = GV;
00879 
00880     if (!ComdatGV->hasPrivateLinkage()) {
00881       MCSymbol *Sym = TM.getSymbol(ComdatGV, Mang);
00882       StringRef COMDATSymName = Sym->getName();
00883       return getContext().getCOFFSection(Name, Characteristics, Kind,
00884                                          COMDATSymName, Selection);
00885     }
00886   }
00887 
00888   if (Kind.isText())
00889     return TextSection;
00890 
00891   if (Kind.isThreadLocal())
00892     return TLSDataSection;
00893 
00894   if (Kind.isReadOnly())
00895     return ReadOnlySection;
00896 
00897   // Note: we claim that common symbols are put in BSSSection, but they are
00898   // really emitted with the magic .comm directive, which creates a symbol table
00899   // entry but not a section.
00900   if (Kind.isBSS() || Kind.isCommon())
00901     return BSSSection;
00902 
00903   return DataSection;
00904 }
00905 
00906 StringRef TargetLoweringObjectFileCOFF::
00907 getDepLibFromLinkerOpt(StringRef LinkerOption) const {
00908   const char *LibCmd = "/DEFAULTLIB:";
00909   if (LinkerOption.startswith(LibCmd))
00910     return LinkerOption.substr(strlen(LibCmd));
00911   return StringRef();
00912 }
00913 
00914 void TargetLoweringObjectFileCOFF::
00915 emitModuleFlags(MCStreamer &Streamer,
00916                 ArrayRef<Module::ModuleFlagEntry> ModuleFlags,
00917                 Mangler &Mang, const TargetMachine &TM) const {
00918   MDNode *LinkerOptions = nullptr;
00919 
00920   // Look for the "Linker Options" flag, since it's the only one we support.
00921   for (ArrayRef<Module::ModuleFlagEntry>::iterator
00922        i = ModuleFlags.begin(), e = ModuleFlags.end(); i != e; ++i) {
00923     const Module::ModuleFlagEntry &MFE = *i;
00924     StringRef Key = MFE.Key->getString();
00925     Value *Val = MFE.Val;
00926     if (Key == "Linker Options") {
00927       LinkerOptions = cast<MDNode>(Val);
00928       break;
00929     }
00930   }
00931   if (!LinkerOptions)
00932     return;
00933 
00934   // Emit the linker options to the linker .drectve section.  According to the
00935   // spec, this section is a space-separated string containing flags for linker.
00936   const MCSection *Sec = getDrectveSection();
00937   Streamer.SwitchSection(Sec);
00938   for (unsigned i = 0, e = LinkerOptions->getNumOperands(); i != e; ++i) {
00939     MDNode *MDOptions = cast<MDNode>(LinkerOptions->getOperand(i));
00940     for (unsigned ii = 0, ie = MDOptions->getNumOperands(); ii != ie; ++ii) {
00941       MDString *MDOption = cast<MDString>(MDOptions->getOperand(ii));
00942       StringRef Op = MDOption->getString();
00943       // Lead with a space for consistency with our dllexport implementation.
00944       std::string Escaped(" ");
00945       if (Op.find(" ") != StringRef::npos) {
00946         // The PE-COFF spec says args with spaces must be quoted.  It doesn't say
00947         // how to escape quotes, but it probably uses this algorithm:
00948         // http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
00949         // FIXME: Reuse escaping code from Support/Windows/Program.inc
00950         Escaped.push_back('\"');
00951         Escaped.append(Op);
00952         Escaped.push_back('\"');
00953       } else {
00954         Escaped.append(Op);
00955       }
00956       Streamer.EmitBytes(Escaped);
00957     }
00958   }
00959 }
00960 
00961 static const MCSection *getAssociativeCOFFSection(MCContext &Ctx,
00962                                                   const MCSection *Sec,
00963                                                   const MCSymbol *KeySym) {
00964   // Return the normal section if we don't have to be associative.
00965   if (!KeySym)
00966     return Sec;
00967 
00968   // Make an associative section with the same name and kind as the normal
00969   // section.
00970   const MCSectionCOFF *SecCOFF = cast<MCSectionCOFF>(Sec);
00971   unsigned Characteristics =
00972       SecCOFF->getCharacteristics() | COFF::IMAGE_SCN_LNK_COMDAT;
00973   return Ctx.getCOFFSection(SecCOFF->getSectionName(), Characteristics,
00974                             SecCOFF->getKind(), KeySym->getName(),
00975                             COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE);
00976 }
00977 
00978 const MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
00979     unsigned Priority, const MCSymbol *KeySym) const {
00980   return getAssociativeCOFFSection(getContext(), StaticCtorSection, KeySym);
00981 }
00982 
00983 const MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
00984     unsigned Priority, const MCSymbol *KeySym) const {
00985   return getAssociativeCOFFSection(getContext(), StaticDtorSection, KeySym);
00986 }