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