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