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