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