LCOV - code coverage report
Current view: top level - lib/CodeGen - TargetLoweringObjectFileImpl.cpp (source / functions) Hit Total Coverage
Test: llvm-toolchain.info Lines: 593 626 94.7 %
Date: 2018-07-13 00:08:38 Functions: 58 61 95.1 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
       2             : //
       3             : //                     The LLVM Compiler Infrastructure
       4             : //
       5             : // This file is distributed under the University of Illinois Open Source
       6             : // License. See LICENSE.TXT for details.
       7             : //
       8             : //===----------------------------------------------------------------------===//
       9             : //
      10             : // This file implements classes used to handle lowerings specific to common
      11             : // object file formats.
      12             : //
      13             : //===----------------------------------------------------------------------===//
      14             : 
      15             : #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
      16             : #include "llvm/ADT/SmallString.h"
      17             : #include "llvm/ADT/SmallVector.h"
      18             : #include "llvm/ADT/StringExtras.h"
      19             : #include "llvm/ADT/StringRef.h"
      20             : #include "llvm/ADT/Triple.h"
      21             : #include "llvm/BinaryFormat/COFF.h"
      22             : #include "llvm/BinaryFormat/Dwarf.h"
      23             : #include "llvm/BinaryFormat/ELF.h"
      24             : #include "llvm/BinaryFormat/MachO.h"
      25             : #include "llvm/CodeGen/MachineModuleInfo.h"
      26             : #include "llvm/CodeGen/MachineModuleInfoImpls.h"
      27             : #include "llvm/IR/Comdat.h"
      28             : #include "llvm/IR/Constants.h"
      29             : #include "llvm/IR/DataLayout.h"
      30             : #include "llvm/IR/DerivedTypes.h"
      31             : #include "llvm/IR/Function.h"
      32             : #include "llvm/IR/GlobalAlias.h"
      33             : #include "llvm/IR/GlobalObject.h"
      34             : #include "llvm/IR/GlobalValue.h"
      35             : #include "llvm/IR/GlobalVariable.h"
      36             : #include "llvm/IR/Mangler.h"
      37             : #include "llvm/IR/Metadata.h"
      38             : #include "llvm/IR/Module.h"
      39             : #include "llvm/IR/Type.h"
      40             : #include "llvm/MC/MCAsmInfo.h"
      41             : #include "llvm/MC/MCContext.h"
      42             : #include "llvm/MC/MCExpr.h"
      43             : #include "llvm/MC/MCSectionCOFF.h"
      44             : #include "llvm/MC/MCSectionELF.h"
      45             : #include "llvm/MC/MCSectionMachO.h"
      46             : #include "llvm/MC/MCSectionWasm.h"
      47             : #include "llvm/MC/MCStreamer.h"
      48             : #include "llvm/MC/MCSymbol.h"
      49             : #include "llvm/MC/MCSymbolELF.h"
      50             : #include "llvm/MC/MCValue.h"
      51             : #include "llvm/MC/SectionKind.h"
      52             : #include "llvm/ProfileData/InstrProf.h"
      53             : #include "llvm/Support/Casting.h"
      54             : #include "llvm/Support/CodeGen.h"
      55             : #include "llvm/Support/Format.h"
      56             : #include "llvm/Support/ErrorHandling.h"
      57             : #include "llvm/Support/raw_ostream.h"
      58             : #include "llvm/Target/TargetMachine.h"
      59             : #include <cassert>
      60             : #include <string>
      61             : 
      62             : using namespace llvm;
      63             : using namespace dwarf;
      64             : 
      65       21456 : static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
      66             :                              StringRef &Section) {
      67             :   SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
      68       21456 :   M.getModuleFlagsMetadata(ModuleFlags);
      69             : 
      70       36706 :   for (const auto &MFE: ModuleFlags) {
      71             :     // Ignore flags with 'Require' behaviour.
      72        7625 :     if (MFE.Behavior == Module::Require)
      73           0 :       continue;
      74             : 
      75        7625 :     StringRef Key = MFE.Key->getString();
      76             :     if (Key == "Objective-C Image Info Version") {
      77         112 :       Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
      78             :     } else if (Key == "Objective-C Garbage Collection" ||
      79             :                Key == "Objective-C GC Only" ||
      80             :                Key == "Objective-C Is Simulated" ||
      81             :                Key == "Objective-C Class Properties" ||
      82             :                Key == "Objective-C Image Swift Version") {
      83         224 :       Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
      84             :     } else if (Key == "Objective-C Image Info Section") {
      85          56 :       Section = cast<MDString>(MFE.Val)->getString();
      86             :     }
      87             :   }
      88       21456 : }
      89             : 
      90             : //===----------------------------------------------------------------------===//
      91             : //                                  ELF
      92             : //===----------------------------------------------------------------------===//
      93             : 
      94       18122 : void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
      95             :                                                      Module &M) const {
      96       18122 :   auto &C = getContext();
      97             : 
      98       18122 :   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
      99          28 :     auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
     100             :                               ELF::SHF_EXCLUDE);
     101             : 
     102          28 :     Streamer.SwitchSection(S);
     103             : 
     104          64 :     for (const auto &Operand : LinkerOptions->operands()) {
     105          36 :       if (cast<MDNode>(Operand)->getNumOperands() != 2)
     106           0 :         report_fatal_error("invalid llvm.linker.options");
     107         180 :       for (const auto &Option : cast<MDNode>(Operand)->operands()) {
     108         144 :         Streamer.EmitBytes(cast<MDString>(Option)->getString());
     109          72 :         Streamer.EmitIntValue(0, 1);
     110             :       }
     111             :     }
     112             :   }
     113             : 
     114       18122 :   unsigned Version = 0;
     115       18122 :   unsigned Flags = 0;
     116       18122 :   StringRef Section;
     117             : 
     118       18122 :   GetObjCImageInfo(M, Version, Flags, Section);
     119       18122 :   if (Section.empty())
     120       18094 :     return;
     121             : 
     122          28 :   auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
     123          28 :   Streamer.SwitchSection(S);
     124          56 :   Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
     125          28 :   Streamer.EmitIntValue(Version, 4);
     126          28 :   Streamer.EmitIntValue(Flags, 4);
     127          28 :   Streamer.AddBlankLine();
     128             : }
     129             : 
     130        5576 : MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
     131             :     const GlobalValue *GV, const TargetMachine &TM,
     132             :     MachineModuleInfo *MMI) const {
     133        5576 :   unsigned Encoding = getPersonalityEncoding();
     134        5576 :   if ((Encoding & 0x80) == DW_EH_PE_indirect)
     135        6996 :     return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
     136       11660 :                                           TM.getSymbol(GV)->getName());
     137        3244 :   if ((Encoding & 0x70) == DW_EH_PE_absptr)
     138        3244 :     return TM.getSymbol(GV);
     139           0 :   report_fatal_error("We do not support this DWARF encoding yet!");
     140             : }
     141             : 
     142          86 : void TargetLoweringObjectFileELF::emitPersonalityValue(
     143             :     MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
     144             :   SmallString<64> NameData("DW.ref.");
     145             :   NameData += Sym->getName();
     146             :   MCSymbolELF *Label =
     147         172 :       cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
     148          86 :   Streamer.EmitSymbolAttribute(Label, MCSA_Hidden);
     149          86 :   Streamer.EmitSymbolAttribute(Label, MCSA_Weak);
     150             :   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
     151         258 :   MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
     152          86 :                                                    ELF::SHT_PROGBITS, Flags, 0);
     153          86 :   unsigned Size = DL.getPointerSize();
     154          86 :   Streamer.SwitchSection(Sec);
     155          86 :   Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0));
     156          86 :   Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject);
     157          86 :   const MCExpr *E = MCConstantExpr::create(Size, getContext());
     158          86 :   Streamer.emitELFSize(Label, E);
     159          86 :   Streamer.EmitLabel(Label);
     160             : 
     161          86 :   Streamer.EmitSymbolValue(Sym, Size);
     162          86 : }
     163             : 
     164         103 : const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
     165             :     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
     166             :     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
     167         103 :   if (Encoding & DW_EH_PE_indirect) {
     168          49 :     MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
     169             : 
     170          98 :     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
     171             : 
     172             :     // Add information about the stub reference to ELFMMI so that the stub
     173             :     // gets emitted by the asmprinter.
     174             :     MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
     175          49 :     if (!StubSym.getPointer()) {
     176          27 :       MCSymbol *Sym = TM.getSymbol(GV);
     177          54 :       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
     178             :     }
     179             : 
     180             :     return TargetLoweringObjectFile::
     181          49 :       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
     182          49 :                         Encoding & ~DW_EH_PE_indirect, Streamer);
     183             :   }
     184             : 
     185          54 :   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
     186          54 :                                                            MMI, Streamer);
     187             : }
     188             : 
     189         681 : static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
     190             :   // N.B.: The defaults used in here are not the same ones used in MC.
     191             :   // We follow gcc, MC follows gas. For example, given ".section .eh_frame",
     192             :   // both gas and MC will produce a section with no flags. Given
     193             :   // section(".eh_frame") gcc will produce:
     194             :   //
     195             :   //   .section   .eh_frame,"a",@progbits
     196             : 
     197        1362 :   if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
     198             :                                       /*AddSegmentInfo=*/false))
     199             :     return SectionKind::getMetadata();
     200             : 
     201        1360 :   if (Name.empty() || Name[0] != '.') return K;
     202             : 
     203             :   // Default implementation based on some magic section names.
     204             :   if (Name == ".bss" ||
     205             :       Name.startswith(".bss.") ||
     206             :       Name.startswith(".gnu.linkonce.b.") ||
     207             :       Name.startswith(".llvm.linkonce.b.") ||
     208             :       Name == ".sbss" ||
     209             :       Name.startswith(".sbss.") ||
     210             :       Name.startswith(".gnu.linkonce.sb.") ||
     211             :       Name.startswith(".llvm.linkonce.sb."))
     212             :     return SectionKind::getBSS();
     213             : 
     214             :   if (Name == ".tdata" ||
     215             :       Name.startswith(".tdata.") ||
     216             :       Name.startswith(".gnu.linkonce.td.") ||
     217             :       Name.startswith(".llvm.linkonce.td."))
     218             :     return SectionKind::getThreadData();
     219             : 
     220             :   if (Name == ".tbss" ||
     221             :       Name.startswith(".tbss.") ||
     222             :       Name.startswith(".gnu.linkonce.tb.") ||
     223             :       Name.startswith(".llvm.linkonce.tb."))
     224             :     return SectionKind::getThreadBSS();
     225             : 
     226         488 :   return K;
     227             : }
     228             : 
     229      276599 : static unsigned getELFSectionType(StringRef Name, SectionKind K) {
     230             :   // Use SHT_NOTE for section whose name starts with ".note" to allow
     231             :   // emitting ELF notes from C variable declaration.
     232             :   // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
     233             :   if (Name.startswith(".note"))
     234             :     return ELF::SHT_NOTE;
     235             : 
     236             :   if (Name == ".init_array")
     237             :     return ELF::SHT_INIT_ARRAY;
     238             : 
     239             :   if (Name == ".fini_array")
     240             :     return ELF::SHT_FINI_ARRAY;
     241             : 
     242             :   if (Name == ".preinit_array")
     243             :     return ELF::SHT_PREINIT_ARRAY;
     244             : 
     245      276595 :   if (K.isBSS() || K.isThreadBSS())
     246             :     return ELF::SHT_NOBITS;
     247             : 
     248             :   return ELF::SHT_PROGBITS;
     249             : }
     250             : 
     251      276568 : static unsigned getELFSectionFlags(SectionKind K) {
     252             :   unsigned Flags = 0;
     253             : 
     254      276568 :   if (!K.isMetadata())
     255             :     Flags |= ELF::SHF_ALLOC;
     256             : 
     257      276568 :   if (K.isText())
     258      196830 :     Flags |= ELF::SHF_EXECINSTR;
     259             : 
     260      276568 :   if (K.isExecuteOnly())
     261          88 :     Flags |= ELF::SHF_ARM_PURECODE;
     262             : 
     263             :   if (K.isWriteable())
     264       39731 :     Flags |= ELF::SHF_WRITE;
     265             : 
     266      276568 :   if (K.isThreadLocal())
     267         200 :     Flags |= ELF::SHF_TLS;
     268             : 
     269      515221 :   if (K.isMergeableCString() || K.isMergeableConst())
     270       38470 :     Flags |= ELF::SHF_MERGE;
     271             : 
     272      276568 :   if (K.isMergeableCString())
     273       37915 :     Flags |= ELF::SHF_STRINGS;
     274             : 
     275      276568 :   return Flags;
     276             : }
     277             : 
     278      276599 : static const Comdat *getELFComdat(const GlobalValue *GV) {
     279      276599 :   const Comdat *C = GV->getComdat();
     280      276599 :   if (!C)
     281             :     return nullptr;
     282             : 
     283       29810 :   if (C->getSelectionKind() != Comdat::Any)
     284           0 :     report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" +
     285           0 :                        C->getName() + "' cannot be lowered.");
     286             : 
     287             :   return C;
     288             : }
     289             : 
     290      276568 : static const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO,
     291             :                                               const TargetMachine &TM) {
     292      276568 :   MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
     293      276568 :   if (!MD)
     294             :     return nullptr;
     295             : 
     296             :   const MDOperand &Op = MD->getOperand(0);
     297          22 :   if (!Op.get())
     298             :     return nullptr;
     299             : 
     300             :   auto *VM = dyn_cast<ValueAsMetadata>(Op);
     301             :   if (!VM)
     302           0 :     report_fatal_error("MD_associated operand is not ValueAsMetadata");
     303             : 
     304          20 :   GlobalObject *OtherGO = dyn_cast<GlobalObject>(VM->getValue());
     305          18 :   return OtherGO ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGO)) : nullptr;
     306             : }
     307             : 
     308         681 : MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
     309             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
     310         681 :   StringRef SectionName = GO->getSection();
     311             : 
     312             :   // Check if '#pragma clang section' name is applicable.
     313             :   // Note that pragma directive overrides -ffunction-section, -fdata-section
     314             :   // and so section name is exactly as user specified and not uniqued.
     315             :   const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
     316         164 :   if (GV && GV->hasImplicitSection()) {
     317          13 :     auto Attrs = GV->getAttributes();
     318          33 :     if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
     319           7 :       SectionName = Attrs.getAttribute("bss-section").getValueAsString();
     320          12 :     } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
     321           3 :       SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
     322           6 :     } else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
     323           3 :       SectionName = Attrs.getAttribute("data-section").getValueAsString();
     324             :     }
     325             :   }
     326             :   const Function *F = dyn_cast<Function>(GO);
     327         517 :   if (F && F->hasFnAttribute("implicit-section-name")) {
     328           2 :     SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
     329             :   }
     330             : 
     331             :   // Infer section flags from the section name if we can.
     332         681 :   Kind = getELFKindForNamedSection(SectionName, Kind);
     333             : 
     334             :   StringRef Group = "";
     335         681 :   unsigned Flags = getELFSectionFlags(Kind);
     336         681 :   if (const Comdat *C = getELFComdat(GO)) {
     337           3 :     Group = C->getName();
     338           3 :     Flags |= ELF::SHF_GROUP;
     339             :   }
     340             : 
     341             :   // A section can have at most one associated section. Put each global with
     342             :   // MD_associated in a unique section.
     343             :   unsigned UniqueID = MCContext::GenericSectionID;
     344         681 :   const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
     345         681 :   if (AssociatedSymbol) {
     346           6 :     UniqueID = NextUniqueID++;
     347           6 :     Flags |= ELF::SHF_LINK_ORDER;
     348             :   }
     349             : 
     350        2043 :   MCSectionELF *Section = getContext().getELFSection(
     351             :       SectionName, getELFSectionType(SectionName, Kind), Flags,
     352         681 :       /*EntrySize=*/0, Group, UniqueID, AssociatedSymbol);
     353             :   // Make sure that we did not get some other section with incompatible sh_link.
     354             :   // This should not be possible due to UniqueID code above.
     355             :   assert(Section->getAssociatedSymbol() == AssociatedSymbol &&
     356             :          "Associated symbol mismatch between sections");
     357         681 :   return Section;
     358             : }
     359             : 
     360             : /// Return the section prefix name used by options FunctionsSections and
     361             : /// DataSections.
     362      239024 : static StringRef getSectionPrefixForGlobal(SectionKind Kind) {
     363      239024 :   if (Kind.isText())
     364      197720 :     return ".text";
     365             :   if (Kind.isReadOnly())
     366        1555 :     return ".rodata";
     367       39749 :   if (Kind.isBSS())
     368       28487 :     return ".bss";
     369       11262 :   if (Kind.isThreadData())
     370         100 :     return ".tdata";
     371       11162 :   if (Kind.isThreadBSS())
     372         100 :     return ".tbss";
     373       11062 :   if (Kind.isData())
     374        7150 :     return ".data";
     375             :   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
     376        3912 :   return ".data.rel.ro";
     377             : }
     378             : 
     379      275918 : static MCSectionELF *selectELFSectionForGlobal(
     380             :     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
     381             :     const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
     382             :     unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
     383             :   unsigned EntrySize = 0;
     384      275918 :   if (Kind.isMergeableCString()) {
     385       37914 :     if (Kind.isMergeable2ByteCString()) {
     386             :       EntrySize = 2;
     387       37872 :     } else if (Kind.isMergeable4ByteCString()) {
     388             :       EntrySize = 4;
     389             :     } else {
     390             :       EntrySize = 1;
     391             :       assert(Kind.isMergeable1ByteCString() && "unknown string width");
     392             :     }
     393      238004 :   } else if (Kind.isMergeableConst()) {
     394         555 :     if (Kind.isMergeableConst4()) {
     395             :       EntrySize = 4;
     396         422 :     } else if (Kind.isMergeableConst8()) {
     397             :       EntrySize = 8;
     398         281 :     } else if (Kind.isMergeableConst16()) {
     399             :       EntrySize = 16;
     400             :     } else {
     401             :       assert(Kind.isMergeableConst32() && "unknown data width");
     402             :       EntrySize = 32;
     403             :     }
     404             :   }
     405             : 
     406             :   StringRef Group = "";
     407      275918 :   if (const Comdat *C = getELFComdat(GO)) {
     408       29807 :     Flags |= ELF::SHF_GROUP;
     409       29807 :     Group = C->getName();
     410             :   }
     411             : 
     412             :   bool UniqueSectionNames = TM.getUniqueSectionNames();
     413             :   SmallString<128> Name;
     414      275918 :   if (Kind.isMergeableCString()) {
     415             :     // We also need alignment here.
     416             :     // FIXME: this is getting the alignment of the character, not the
     417             :     // alignment of the global!
     418       37914 :     unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment(
     419       37914 :         cast<GlobalVariable>(GO));
     420             : 
     421      113742 :     std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
     422      113742 :     Name = SizeSpec + utostr(Align);
     423      238004 :   } else if (Kind.isMergeableConst()) {
     424             :     Name = ".rodata.cst";
     425        1110 :     Name += utostr(EntrySize);
     426             :   } else {
     427      237449 :     Name = getSectionPrefixForGlobal(Kind);
     428             :   }
     429             : 
     430             :   if (const auto *F = dyn_cast<Function>(GO)) {
     431      196344 :     const auto &OptionalPrefix = F->getSectionPrefix();
     432      196344 :     if (OptionalPrefix)
     433             :       Name += *OptionalPrefix;
     434             :   }
     435             : 
     436      275918 :   if (EmitUniqueSection && UniqueSectionNames) {
     437       62294 :     Name.push_back('.');
     438       62294 :     TM.getNameWithPrefix(Name, GO, Mang, true);
     439             :   }
     440             :   unsigned UniqueID = MCContext::GenericSectionID;
     441      275918 :   if (EmitUniqueSection && !UniqueSectionNames) {
     442           7 :     UniqueID = *NextUniqueID;
     443           7 :     (*NextUniqueID)++;
     444             :   }
     445             :   // Use 0 as the unique ID for execute-only text
     446      275918 :   if (Kind.isExecuteOnly())
     447             :     UniqueID = 0;
     448      551836 :   return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
     449      551836 :                            EntrySize, Group, UniqueID, AssociatedSymbol);
     450             : }
     451             : 
     452      275887 : MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
     453             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
     454      275887 :   unsigned Flags = getELFSectionFlags(Kind);
     455             : 
     456             :   // If we have -ffunction-section or -fdata-section then we should emit the
     457             :   // global value to a uniqued section specifically for it.
     458             :   bool EmitUniqueSection = false;
     459      275887 :   if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
     460      237418 :     if (Kind.isText())
     461             :       EmitUniqueSection = TM.getFunctionSections();
     462             :     else
     463             :       EmitUniqueSection = TM.getDataSections();
     464             :   }
     465      275887 :   EmitUniqueSection |= GO->hasComdat();
     466             : 
     467      275887 :   const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM);
     468      275887 :   if (AssociatedSymbol) {
     469             :     EmitUniqueSection = true;
     470          12 :     Flags |= ELF::SHF_LINK_ORDER;
     471             :   }
     472             : 
     473      275887 :   MCSectionELF *Section = selectELFSectionForGlobal(
     474             :       getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags,
     475      275887 :       &NextUniqueID, AssociatedSymbol);
     476             :   assert(Section->getAssociatedSymbol() == AssociatedSymbol);
     477      275887 :   return Section;
     478             : }
     479             : 
     480         157 : MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
     481             :     const Function &F, const TargetMachine &TM) const {
     482             :   // If the function can be removed, produce a unique section so that
     483             :   // the table doesn't prevent the removal.
     484         157 :   const Comdat *C = F.getComdat();
     485         157 :   bool EmitUniqueSection = TM.getFunctionSections() || C;
     486             :   if (!EmitUniqueSection)
     487         126 :     return ReadOnlySection;
     488             : 
     489          31 :   return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
     490             :                                    getMangler(), TM, EmitUniqueSection,
     491             :                                    ELF::SHF_ALLOC, &NextUniqueID,
     492          31 :                                    /* AssociatedSymbol */ nullptr);
     493             : }
     494             : 
     495         151 : bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
     496             :     bool UsesLabelDifference, const Function &F) const {
     497             :   // We can always create relative relocations, so use another section
     498             :   // that can be marked non-executable.
     499         151 :   return false;
     500             : }
     501             : 
     502             : /// Given a mergeable constant with the specified size and relocation
     503             : /// information, return a section that it should be placed in.
     504       20550 : MCSection *TargetLoweringObjectFileELF::getSectionForConstant(
     505             :     const DataLayout &DL, SectionKind Kind, const Constant *C,
     506             :     unsigned &Align) const {
     507       20550 :   if (Kind.isMergeableConst4() && MergeableConst4Section)
     508             :     return MergeableConst4Section;
     509       18427 :   if (Kind.isMergeableConst8() && MergeableConst8Section)
     510             :     return MergeableConst8Section;
     511       16970 :   if (Kind.isMergeableConst16() && MergeableConst16Section)
     512             :     return MergeableConst16Section;
     513        5519 :   if (Kind.isMergeableConst32() && MergeableConst32Section)
     514             :     return MergeableConst32Section;
     515             :   if (Kind.isReadOnly())
     516        1278 :     return ReadOnlySection;
     517             : 
     518             :   assert(Kind.isReadOnlyWithRel() && "Unknown section kind");
     519          17 :   return DataRelROSection;
     520             : }
     521             : 
     522         323 : static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray,
     523             :                                               bool IsCtor, unsigned Priority,
     524             :                                               const MCSymbol *KeySym) {
     525             :   std::string Name;
     526             :   unsigned Type;
     527             :   unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE;
     528         345 :   StringRef COMDAT = KeySym ? KeySym->getName() : "";
     529             : 
     530         323 :   if (KeySym)
     531             :     Flags |= ELF::SHF_GROUP;
     532             : 
     533         323 :   if (UseInitArray) {
     534         295 :     if (IsCtor) {
     535             :       Type = ELF::SHT_INIT_ARRAY;
     536             :       Name = ".init_array";
     537             :     } else {
     538             :       Type = ELF::SHT_FINI_ARRAY;
     539             :       Name = ".fini_array";
     540             :     }
     541         295 :     if (Priority != 65535) {
     542             :       Name += '.';
     543         186 :       Name += utostr(Priority);
     544             :     }
     545             :   } else {
     546             :     // The default scheme is .ctor / .dtor, so we have to invert the priority
     547             :     // numbering.
     548          28 :     if (IsCtor)
     549             :       Name = ".ctors";
     550             :     else
     551             :       Name = ".dtors";
     552          28 :     if (Priority != 65535)
     553          36 :       raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
     554             :     Type = ELF::SHT_PROGBITS;
     555             :   }
     556             : 
     557         646 :   return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT);
     558             : }
     559             : 
     560         315 : MCSection *TargetLoweringObjectFileELF::getStaticCtorSection(
     561             :     unsigned Priority, const MCSymbol *KeySym) const {
     562         315 :   return getStaticStructorSection(getContext(), UseInitArray, true, Priority,
     563         315 :                                   KeySym);
     564             : }
     565             : 
     566           8 : MCSection *TargetLoweringObjectFileELF::getStaticDtorSection(
     567             :     unsigned Priority, const MCSymbol *KeySym) const {
     568           8 :   return getStaticStructorSection(getContext(), UseInitArray, false, Priority,
     569           8 :                                   KeySym);
     570             : }
     571             : 
     572          11 : const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference(
     573             :     const GlobalValue *LHS, const GlobalValue *RHS,
     574             :     const TargetMachine &TM) const {
     575             :   // We may only use a PLT-relative relocation to refer to unnamed_addr
     576             :   // functions.
     577          18 :   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
     578             :     return nullptr;
     579             : 
     580             :   // Basic sanity checks.
     581          12 :   if (LHS->getType()->getPointerAddressSpace() != 0 ||
     582          24 :       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
     583             :       RHS->isThreadLocal())
     584             :     return nullptr;
     585             : 
     586           6 :   return MCBinaryExpr::createSub(
     587          12 :       MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind,
     588           6 :                               getContext()),
     589           6 :       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
     590             : }
     591             : 
     592             : void
     593       11318 : TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) {
     594       11318 :   UseInitArray = UseInitArray_;
     595       11318 :   MCContext &Ctx = getContext();
     596       11318 :   if (!UseInitArray) {
     597         191 :     StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS,
     598             :                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
     599             : 
     600         191 :     StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS,
     601             :                                           ELF::SHF_ALLOC | ELF::SHF_WRITE);
     602         191 :     return;
     603             :   }
     604             : 
     605       11127 :   StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY,
     606             :                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
     607       11127 :   StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY,
     608             :                                         ELF::SHF_WRITE | ELF::SHF_ALLOC);
     609             : }
     610             : 
     611             : //===----------------------------------------------------------------------===//
     612             : //                                 MachO
     613             : //===----------------------------------------------------------------------===//
     614             : 
     615        5105 : TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO()
     616        5105 :   : TargetLoweringObjectFile() {
     617        5105 :   SupportIndirectSymViaGOTPCRel = true;
     618        5105 : }
     619             : 
     620        2617 : void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx,
     621             :                                                const TargetMachine &TM) {
     622        2617 :   TargetLoweringObjectFile::Initialize(Ctx, TM);
     623        2617 :   if (TM.getRelocationModel() == Reloc::Static) {
     624          50 :     StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0,
     625             :                                             SectionKind::getData());
     626          50 :     StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0,
     627             :                                             SectionKind::getData());
     628             :   } else {
     629        2567 :     StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func",
     630             :                                             MachO::S_MOD_INIT_FUNC_POINTERS,
     631             :                                             SectionKind::getData());
     632        2567 :     StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func",
     633             :                                             MachO::S_MOD_TERM_FUNC_POINTERS,
     634             :                                             SectionKind::getData());
     635             :   }
     636        2617 : }
     637             : 
     638        2601 : void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer,
     639             :                                                        Module &M) const {
     640             :   // Emit the linker options if present.
     641        2601 :   if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
     642          11 :     for (const auto &Option : LinkerOptions->operands()) {
     643           6 :       SmallVector<std::string, 4> StrOptions;
     644          22 :       for (const auto &Piece : cast<MDNode>(Option)->operands())
     645          24 :         StrOptions.push_back(cast<MDString>(Piece)->getString());
     646          12 :       Streamer.EmitLinkerOptions(StrOptions);
     647             :     }
     648             :   }
     649             : 
     650        2601 :   unsigned VersionVal = 0;
     651        2601 :   unsigned ImageInfoFlags = 0;
     652        2601 :   StringRef SectionVal;
     653             : 
     654        2601 :   GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal);
     655             : 
     656             :   // The section is mandatory. If we don't have it, then we don't have GC info.
     657        2601 :   if (SectionVal.empty())
     658        2576 :     return;
     659             : 
     660          25 :   StringRef Segment, Section;
     661          25 :   unsigned TAA = 0, StubSize = 0;
     662             :   bool TAAParsed;
     663             :   std::string ErrorCode =
     664             :     MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section,
     665          25 :                                           TAA, TAAParsed, StubSize);
     666          25 :   if (!ErrorCode.empty())
     667             :     // If invalid, report the error with report_fatal_error.
     668           0 :     report_fatal_error("Invalid section specifier '" + Section + "': " +
     669             :                        ErrorCode + ".");
     670             : 
     671             :   // Get the section.
     672          25 :   MCSectionMachO *S = getContext().getMachOSection(
     673          25 :       Segment, Section, TAA, StubSize, SectionKind::getData());
     674          25 :   Streamer.SwitchSection(S);
     675          75 :   Streamer.EmitLabel(getContext().
     676          50 :                      getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO")));
     677          25 :   Streamer.EmitIntValue(VersionVal, 4);
     678          25 :   Streamer.EmitIntValue(ImageInfoFlags, 4);
     679          25 :   Streamer.AddBlankLine();
     680             : }
     681             : 
     682       20683 : static void checkMachOComdat(const GlobalValue *GV) {
     683       20683 :   const Comdat *C = GV->getComdat();
     684       20683 :   if (!C)
     685       20682 :     return;
     686             : 
     687           2 :   report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() +
     688             :                      "' cannot be lowered.");
     689             : }
     690             : 
     691         816 : MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal(
     692             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
     693             :   // Parse the section specifier and create it if valid.
     694         816 :   StringRef Segment, Section;
     695         816 :   unsigned TAA = 0, StubSize = 0;
     696             :   bool TAAParsed;
     697             : 
     698         816 :   checkMachOComdat(GO);
     699             : 
     700             :   std::string ErrorCode =
     701             :     MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section,
     702         816 :                                           TAA, TAAParsed, StubSize);
     703         816 :   if (!ErrorCode.empty()) {
     704             :     // If invalid, report the error with report_fatal_error.
     705           0 :     report_fatal_error("Global variable '" + GO->getName() +
     706             :                        "' has an invalid section specifier '" +
     707           0 :                        GO->getSection() + "': " + ErrorCode + ".");
     708             :   }
     709             : 
     710             :   // Get the section.
     711             :   MCSectionMachO *S =
     712         816 :       getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind);
     713             : 
     714             :   // If TAA wasn't set by ParseSectionSpecifier() above,
     715             :   // use the value returned by getMachOSection() as a default.
     716         816 :   if (!TAAParsed)
     717         192 :     TAA = S->getTypeAndAttributes();
     718             : 
     719             :   // Okay, now that we got the section, verify that the TAA & StubSize agree.
     720             :   // If the user declared multiple globals with different section flags, we need
     721             :   // to reject it here.
     722         816 :   if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) {
     723             :     // If invalid, report the error with report_fatal_error.
     724           0 :     report_fatal_error("Global variable '" + GO->getName() +
     725             :                        "' section type or attributes does not match previous"
     726             :                        " section specifier");
     727             :   }
     728             : 
     729         816 :   return S;
     730             : }
     731             : 
     732       19867 : MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal(
     733             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
     734       19867 :   checkMachOComdat(GO);
     735             : 
     736             :   // Handle thread local data.
     737       19866 :   if (Kind.isThreadBSS()) return TLSBSSSection;
     738       19790 :   if (Kind.isThreadData()) return TLSDataSection;
     739             : 
     740       19780 :   if (Kind.isText())
     741       18312 :     return GO->isWeakForLinker() ? TextCoalSection : TextSection;
     742             : 
     743             :   // If this is weak/linkonce, put this in a coalescable section, either in text
     744             :   // or data depending on if it is writable.
     745             :   if (GO->isWeakForLinker()) {
     746             :     if (Kind.isReadOnly())
     747          37 :       return ConstTextCoalSection;
     748          77 :     if (Kind.isReadOnlyWithRel())
     749           6 :       return ConstDataCoalSection;
     750          71 :     return DataCoalSection;
     751             :   }
     752             : 
     753             :   // FIXME: Alignment check should be handled by section classifier.
     754        1649 :   if (Kind.isMergeable1ByteCString() &&
     755         400 :       GO->getParent()->getDataLayout().getPreferredAlignment(
     756             :           cast<GlobalVariable>(GO)) < 32)
     757         400 :     return CStringSection;
     758             : 
     759             :   // Do not put 16-bit arrays in the UString section if they have an
     760             :   // externally visible label, this runs into issues with certain linker
     761             :   // versions.
     762         860 :   if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() &&
     763           4 :       GO->getParent()->getDataLayout().getPreferredAlignment(
     764             :           cast<GlobalVariable>(GO)) < 32)
     765           4 :     return UStringSection;
     766             : 
     767             :   // With MachO only variables whose corresponding symbol starts with 'l' or
     768             :   // 'L' can be merged, so we only try merging GVs with private linkage.
     769        1079 :   if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) {
     770          35 :     if (Kind.isMergeableConst4())
     771           3 :       return FourByteConstantSection;
     772          32 :     if (Kind.isMergeableConst8())
     773           6 :       return EightByteConstantSection;
     774          26 :     if (Kind.isMergeableConst16())
     775          23 :       return SixteenByteConstantSection;
     776             :   }
     777             : 
     778             :   // Otherwise, if it is readonly, but not something we can specially optimize,
     779             :   // just drop it in .const.
     780             :   if (Kind.isReadOnly())
     781         235 :     return ReadOnlySection;
     782             : 
     783             :   // If this is marked const, put it into a const section.  But if the dynamic
     784             :   // linker needs to write to it, put it in the data segment.
     785         578 :   if (Kind.isReadOnlyWithRel())
     786          83 :     return ConstDataSection;
     787             : 
     788             :   // Put zero initialized globals with strong external linkage in the
     789             :   // DATA, __common section with the .zerofill directive.
     790         495 :   if (Kind.isBSSExtern())
     791         181 :     return DataCommonSection;
     792             : 
     793             :   // Put zero initialized globals with local linkage in __DATA,__bss directive
     794             :   // with the .zerofill directive (aka .lcomm).
     795         314 :   if (Kind.isBSSLocal())
     796         145 :     return DataBSSSection;
     797             : 
     798             :   // Otherwise, just drop the variable in the normal data section.
     799         169 :   return DataSection;
     800             : }
     801             : 
     802        1081 : MCSection *TargetLoweringObjectFileMachO::getSectionForConstant(
     803             :     const DataLayout &DL, SectionKind Kind, const Constant *C,
     804             :     unsigned &Align) const {
     805             :   // If this constant requires a relocation, we have to put it in the data
     806             :   // segment, not in the text segment.
     807        1081 :   if (Kind.isData() || Kind.isReadOnlyWithRel())
     808           0 :     return ConstDataSection;
     809             : 
     810        1081 :   if (Kind.isMergeableConst4())
     811         248 :     return FourByteConstantSection;
     812         833 :   if (Kind.isMergeableConst8())
     813         111 :     return EightByteConstantSection;
     814         722 :   if (Kind.isMergeableConst16())
     815         519 :     return SixteenByteConstantSection;
     816         203 :   return ReadOnlySection;  // .const
     817             : }
     818             : 
     819           8 : const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference(
     820             :     const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
     821             :     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
     822             :   // The mach-o version of this method defaults to returning a stub reference.
     823             : 
     824           8 :   if (Encoding & DW_EH_PE_indirect) {
     825             :     MachineModuleInfoMachO &MachOMMI =
     826           8 :       MMI->getObjFileInfo<MachineModuleInfoMachO>();
     827             : 
     828          16 :     MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
     829             : 
     830             :     // Add information about the stub reference to MachOMMI so that the stub
     831             :     // gets emitted by the asmprinter.
     832             :     MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
     833           8 :     if (!StubSym.getPointer()) {
     834           7 :       MCSymbol *Sym = TM.getSymbol(GV);
     835          14 :       StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
     836             :     }
     837             : 
     838             :     return TargetLoweringObjectFile::
     839           8 :       getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
     840           8 :                         Encoding & ~DW_EH_PE_indirect, Streamer);
     841             :   }
     842             : 
     843           0 :   return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
     844           0 :                                                            MMI, Streamer);
     845             : }
     846             : 
     847          24 : MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol(
     848             :     const GlobalValue *GV, const TargetMachine &TM,
     849             :     MachineModuleInfo *MMI) const {
     850             :   // The mach-o version of this method defaults to returning a stub reference.
     851             :   MachineModuleInfoMachO &MachOMMI =
     852          24 :     MMI->getObjFileInfo<MachineModuleInfoMachO>();
     853             : 
     854          48 :   MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM);
     855             : 
     856             :   // Add information about the stub reference to MachOMMI so that the stub
     857             :   // gets emitted by the asmprinter.
     858             :   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym);
     859          24 :   if (!StubSym.getPointer()) {
     860          15 :     MCSymbol *Sym = TM.getSymbol(GV);
     861          30 :     StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
     862             :   }
     863             : 
     864          24 :   return SSym;
     865             : }
     866             : 
     867          10 : const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel(
     868             :     const MCSymbol *Sym, const MCValue &MV, int64_t Offset,
     869             :     MachineModuleInfo *MMI, MCStreamer &Streamer) const {
     870             :   // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation
     871             :   // as 64-bit do, we replace the GOT equivalent by accessing the final symbol
     872             :   // through a non_lazy_ptr stub instead. One advantage is that it allows the
     873             :   // computation of deltas to final external symbols. Example:
     874             :   //
     875             :   //    _extgotequiv:
     876             :   //       .long   _extfoo
     877             :   //
     878             :   //    _delta:
     879             :   //       .long   _extgotequiv-_delta
     880             :   //
     881             :   // is transformed to:
     882             :   //
     883             :   //    _delta:
     884             :   //       .long   L_extfoo$non_lazy_ptr-(_delta+0)
     885             :   //
     886             :   //       .section        __IMPORT,__pointers,non_lazy_symbol_pointers
     887             :   //    L_extfoo$non_lazy_ptr:
     888             :   //       .indirect_symbol        _extfoo
     889             :   //       .long   0
     890             :   //
     891             :   MachineModuleInfoMachO &MachOMMI =
     892          10 :     MMI->getObjFileInfo<MachineModuleInfoMachO>();
     893          10 :   MCContext &Ctx = getContext();
     894             : 
     895             :   // The offset must consider the original displacement from the base symbol
     896             :   // since 32-bit targets don't have a GOTPCREL to fold the PC displacement.
     897          10 :   Offset = -MV.getConstant();
     898          10 :   const MCSymbol *BaseSym = &MV.getSymB()->getSymbol();
     899             : 
     900             :   // Access the final symbol via sym$non_lazy_ptr and generate the appropriated
     901             :   // non_lazy_ptr stubs.
     902             :   SmallString<128> Name;
     903             :   StringRef Suffix = "$non_lazy_ptr";
     904          10 :   Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix();
     905             :   Name += Sym->getName();
     906             :   Name += Suffix;
     907          10 :   MCSymbol *Stub = Ctx.getOrCreateSymbol(Name);
     908             : 
     909             :   MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub);
     910          10 :   if (!StubSym.getPointer())
     911           4 :     StubSym = MachineModuleInfoImpl::
     912             :       StubValueTy(const_cast<MCSymbol *>(Sym), true /* access indirectly */);
     913             : 
     914             :   const MCExpr *BSymExpr =
     915          10 :     MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx);
     916             :   const MCExpr *LHS =
     917          10 :     MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx);
     918             : 
     919          10 :   if (!Offset)
     920           2 :     return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx);
     921             : 
     922             :   const MCExpr *RHS =
     923           8 :     MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx);
     924           8 :   return MCBinaryExpr::createSub(LHS, RHS, Ctx);
     925             : }
     926             : 
     927             : static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo,
     928             :                                const MCSection &Section) {
     929        1053 :   if (!AsmInfo.isSectionAtomizableBySymbols(Section))
     930             :     return true;
     931             : 
     932             :   // If it is not dead stripped, it is safe to use private labels.
     933             :   const MCSectionMachO &SMO = cast<MCSectionMachO>(Section);
     934         742 :   if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP))
     935             :     return true;
     936             : 
     937             :   return false;
     938             : }
     939             : 
     940        1053 : void TargetLoweringObjectFileMachO::getNameWithPrefix(
     941             :     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
     942             :     const TargetMachine &TM) const {
     943             :   bool CannotUsePrivateLabel = true;
     944        1053 :   if (auto *GO = GV->getBaseObject()) {
     945        1053 :     SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM);
     946        1053 :     const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM);
     947        1053 :     CannotUsePrivateLabel =
     948        1053 :         !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection);
     949             :   }
     950        1053 :   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
     951        1053 : }
     952             : 
     953             : //===----------------------------------------------------------------------===//
     954             : //                                  COFF
     955             : //===----------------------------------------------------------------------===//
     956             : 
     957             : static unsigned
     958         325 : getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) {
     959             :   unsigned Flags = 0;
     960         325 :   bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb;
     961             : 
     962         325 :   if (K.isMetadata())
     963             :     Flags |=
     964             :       COFF::IMAGE_SCN_MEM_DISCARDABLE;
     965         325 :   else if (K.isText())
     966             :     Flags |=
     967             :       COFF::IMAGE_SCN_MEM_EXECUTE |
     968             :       COFF::IMAGE_SCN_MEM_READ |
     969         132 :       COFF::IMAGE_SCN_CNT_CODE |
     970             :       (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0);
     971         193 :   else if (K.isBSS())
     972             :     Flags |=
     973             :       COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
     974             :       COFF::IMAGE_SCN_MEM_READ |
     975             :       COFF::IMAGE_SCN_MEM_WRITE;
     976         178 :   else if (K.isThreadLocal())
     977             :     Flags |=
     978             :       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
     979             :       COFF::IMAGE_SCN_MEM_READ |
     980             :       COFF::IMAGE_SCN_MEM_WRITE;
     981         104 :   else if (K.isReadOnly() || K.isReadOnlyWithRel())
     982             :     Flags |=
     983             :       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
     984             :       COFF::IMAGE_SCN_MEM_READ;
     985             :   else if (K.isWriteable())
     986             :     Flags |=
     987             :       COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
     988             :       COFF::IMAGE_SCN_MEM_READ |
     989             :       COFF::IMAGE_SCN_MEM_WRITE;
     990             : 
     991         325 :   return Flags;
     992             : }
     993             : 
     994         439 : static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) {
     995         439 :   const Comdat *C = GV->getComdat();
     996             :   assert(C && "expected GV to have a Comdat!");
     997             : 
     998         439 :   StringRef ComdatGVName = C->getName();
     999         439 :   const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName);
    1000         439 :   if (!ComdatGV)
    1001           1 :     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
    1002             :                        "' does not exist.");
    1003             : 
    1004         438 :   if (ComdatGV->getComdat() != C)
    1005           1 :     report_fatal_error("Associative COMDAT symbol '" + ComdatGVName +
    1006             :                        "' is not a key for its COMDAT.");
    1007             : 
    1008         437 :   return ComdatGV;
    1009             : }
    1010             : 
    1011         301 : static int getSelectionForCOFF(const GlobalValue *GV) {
    1012         301 :   if (const Comdat *C = GV->getComdat()) {
    1013         222 :     const GlobalValue *ComdatKey = getComdatGVForCOFF(GV);
    1014             :     if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey))
    1015          20 :       ComdatKey = GA->getBaseObject();
    1016         220 :     if (ComdatKey == GV) {
    1017         211 :       switch (C->getSelectionKind()) {
    1018             :       case Comdat::Any:
    1019             :         return COFF::IMAGE_COMDAT_SELECT_ANY;
    1020           1 :       case Comdat::ExactMatch:
    1021           1 :         return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH;
    1022          21 :       case Comdat::Largest:
    1023          21 :         return COFF::IMAGE_COMDAT_SELECT_LARGEST;
    1024           1 :       case Comdat::NoDuplicates:
    1025           1 :         return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
    1026           2 :       case Comdat::SameSize:
    1027           2 :         return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE;
    1028             :       }
    1029             :     } else {
    1030             :       return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
    1031             :     }
    1032             :   }
    1033             :   return 0;
    1034             : }
    1035             : 
    1036          23 : MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal(
    1037             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
    1038             :   int Selection = 0;
    1039          23 :   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
    1040          23 :   StringRef Name = GO->getSection();
    1041             :   StringRef COMDATSymName = "";
    1042          23 :   if (GO->hasComdat()) {
    1043           3 :     Selection = getSelectionForCOFF(GO);
    1044             :     const GlobalValue *ComdatGV;
    1045           3 :     if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE)
    1046           0 :       ComdatGV = getComdatGVForCOFF(GO);
    1047             :     else
    1048             :       ComdatGV = GO;
    1049             : 
    1050           3 :     if (!ComdatGV->hasPrivateLinkage()) {
    1051           3 :       MCSymbol *Sym = TM.getSymbol(ComdatGV);
    1052           3 :       COMDATSymName = Sym->getName();
    1053           3 :       Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
    1054             :     } else {
    1055             :       Selection = 0;
    1056             :     }
    1057             :   }
    1058             : 
    1059          23 :   return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName,
    1060          23 :                                      Selection);
    1061             : }
    1062             : 
    1063         302 : static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) {
    1064         302 :   if (Kind.isText())
    1065         128 :     return ".text";
    1066         174 :   if (Kind.isBSS())
    1067          15 :     return ".bss";
    1068         159 :   if (Kind.isThreadLocal())
    1069           1 :     return ".tls$";
    1070          90 :   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
    1071         125 :     return ".rdata";
    1072          33 :   return ".data";
    1073             : }
    1074             : 
    1075        3367 : MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal(
    1076             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
    1077             :   // If we have -ffunction-sections then we should emit the global value to a
    1078             :   // uniqued section specifically for it.
    1079             :   bool EmitUniquedSection;
    1080        3367 :   if (Kind.isText())
    1081             :     EmitUniquedSection = TM.getFunctionSections();
    1082             :   else
    1083             :     EmitUniquedSection = TM.getDataSections();
    1084             : 
    1085        6651 :   if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) {
    1086         298 :     SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind);
    1087             : 
    1088         298 :     unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
    1089             : 
    1090         298 :     Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
    1091         298 :     int Selection = getSelectionForCOFF(GO);
    1092         296 :     if (!Selection)
    1093             :       Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES;
    1094             :     const GlobalValue *ComdatGV;
    1095         296 :     if (GO->hasComdat())
    1096         217 :       ComdatGV = getComdatGVForCOFF(GO);
    1097             :     else
    1098             :       ComdatGV = GO;
    1099             : 
    1100             :     unsigned UniqueID = MCContext::GenericSectionID;
    1101         296 :     if (EmitUniquedSection)
    1102          83 :       UniqueID = NextUniqueID++;
    1103             : 
    1104         296 :     if (!ComdatGV->hasPrivateLinkage()) {
    1105         294 :       MCSymbol *Sym = TM.getSymbol(ComdatGV);
    1106         294 :       StringRef COMDATSymName = Sym->getName();
    1107             : 
    1108             :       // Append "$symbol" to the section name when targetting mingw. The ld.bfd
    1109             :       // COFF linker will not properly handle comdats otherwise.
    1110             :       if (getTargetTriple().isWindowsGNUEnvironment())
    1111          12 :         raw_svector_ostream(Name) << '$' << COMDATSymName;
    1112             : 
    1113         294 :       return getContext().getCOFFSection(Name, Characteristics, Kind,
    1114         294 :                                          COMDATSymName, Selection, UniqueID);
    1115             :     } else {
    1116             :       SmallString<256> TmpData;
    1117           2 :       getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true);
    1118           2 :       return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData,
    1119           2 :                                          Selection, UniqueID);
    1120             :     }
    1121             :   }
    1122             : 
    1123        3069 :   if (Kind.isText())
    1124        2716 :     return TextSection;
    1125             : 
    1126         353 :   if (Kind.isThreadLocal())
    1127          37 :     return TLSDataSection;
    1128             : 
    1129         202 :   if (Kind.isReadOnly() || Kind.isReadOnlyWithRel())
    1130         117 :     return ReadOnlySection;
    1131             : 
    1132             :   // Note: we claim that common symbols are put in BSSSection, but they are
    1133             :   // really emitted with the magic .comm directive, which creates a symbol table
    1134             :   // entry but not a section.
    1135         284 :   if (Kind.isBSS() || Kind.isCommon())
    1136         114 :     return BSSSection;
    1137             : 
    1138          85 :   return DataSection;
    1139             : }
    1140             : 
    1141         334 : void TargetLoweringObjectFileCOFF::getNameWithPrefix(
    1142             :     SmallVectorImpl<char> &OutName, const GlobalValue *GV,
    1143             :     const TargetMachine &TM) const {
    1144             :   bool CannotUsePrivateLabel = false;
    1145         668 :   if (GV->hasPrivateLinkage() &&
    1146          16 :       ((isa<Function>(GV) && TM.getFunctionSections()) ||
    1147         318 :        (isa<GlobalVariable>(GV) && TM.getDataSections())))
    1148             :     CannotUsePrivateLabel = true;
    1149             : 
    1150         334 :   getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel);
    1151         334 : }
    1152             : 
    1153           9 : MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable(
    1154             :     const Function &F, const TargetMachine &TM) const {
    1155             :   // If the function can be removed, produce a unique section so that
    1156             :   // the table doesn't prevent the removal.
    1157           9 :   const Comdat *C = F.getComdat();
    1158           9 :   bool EmitUniqueSection = TM.getFunctionSections() || C;
    1159             :   if (!EmitUniqueSection)
    1160           5 :     return ReadOnlySection;
    1161             : 
    1162             :   // FIXME: we should produce a symbol for F instead.
    1163           4 :   if (F.hasPrivateLinkage())
    1164           0 :     return ReadOnlySection;
    1165             : 
    1166           4 :   MCSymbol *Sym = TM.getSymbol(&F);
    1167           4 :   StringRef COMDATSymName = Sym->getName();
    1168             : 
    1169           4 :   SectionKind Kind = SectionKind::getReadOnly();
    1170           4 :   StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind);
    1171           4 :   unsigned Characteristics = getCOFFSectionFlags(Kind, TM);
    1172           4 :   Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT;
    1173           4 :   unsigned UniqueID = NextUniqueID++;
    1174             : 
    1175           4 :   return getContext().getCOFFSection(
    1176             :       SecName, Characteristics, Kind, COMDATSymName,
    1177           4 :       COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID);
    1178             : }
    1179             : 
    1180         733 : void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer,
    1181             :                                                       Module &M) const {
    1182         733 :   if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
    1183             :     // Emit the linker options to the linker .drectve section.  According to the
    1184             :     // spec, this section is a space-separated string containing flags for
    1185             :     // linker.
    1186          24 :     MCSection *Sec = getDrectveSection();
    1187          24 :     Streamer.SwitchSection(Sec);
    1188          67 :     for (const auto &Option : LinkerOptions->operands()) {
    1189         131 :       for (const auto &Piece : cast<MDNode>(Option)->operands()) {
    1190             :         // Lead with a space for consistency with our dllexport implementation.
    1191          44 :         std::string Directive(" ");
    1192          88 :         Directive.append(cast<MDString>(Piece)->getString());
    1193          88 :         Streamer.EmitBytes(Directive);
    1194             :       }
    1195             :     }
    1196             :   }
    1197             : 
    1198         733 :   unsigned Version = 0;
    1199         733 :   unsigned Flags = 0;
    1200         733 :   StringRef Section;
    1201             : 
    1202         733 :   GetObjCImageInfo(M, Version, Flags, Section);
    1203         733 :   if (Section.empty())
    1204         730 :     return;
    1205             : 
    1206           3 :   auto &C = getContext();
    1207             :   auto *S = C.getCOFFSection(
    1208             :       Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ,
    1209           3 :       SectionKind::getReadOnly());
    1210           3 :   Streamer.SwitchSection(S);
    1211           6 :   Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
    1212           3 :   Streamer.EmitIntValue(Version, 4);
    1213           3 :   Streamer.EmitIntValue(Flags, 4);
    1214           3 :   Streamer.AddBlankLine();
    1215             : }
    1216             : 
    1217         736 : void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx,
    1218             :                                               const TargetMachine &TM) {
    1219         736 :   TargetLoweringObjectFile::Initialize(Ctx, TM);
    1220             :   const Triple &T = TM.getTargetTriple();
    1221             :   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
    1222         616 :     StaticCtorSection =
    1223        1232 :         Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
    1224             :                                            COFF::IMAGE_SCN_MEM_READ,
    1225             :                            SectionKind::getReadOnly());
    1226         616 :     StaticDtorSection =
    1227        1232 :         Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
    1228             :                                            COFF::IMAGE_SCN_MEM_READ,
    1229             :                            SectionKind::getReadOnly());
    1230             :   } else {
    1231         120 :     StaticCtorSection = Ctx.getCOFFSection(
    1232             :         ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
    1233             :                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
    1234             :         SectionKind::getData());
    1235         120 :     StaticDtorSection = Ctx.getCOFFSection(
    1236             :         ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
    1237             :                       COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE,
    1238             :         SectionKind::getData());
    1239             :   }
    1240         736 : }
    1241             : 
    1242          27 : static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx,
    1243             :                                                    const Triple &T, bool IsCtor,
    1244             :                                                    unsigned Priority,
    1245             :                                                    const MCSymbol *KeySym,
    1246             :                                                    MCSectionCOFF *Default) {
    1247             :   if (T.isKnownWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment())
    1248          16 :     return Ctx.getAssociativeCOFFSection(Default, KeySym, 0);
    1249             : 
    1250          22 :   std::string Name = IsCtor ? ".ctors" : ".dtors";
    1251          11 :   if (Priority != 65535)
    1252           4 :     raw_string_ostream(Name) << format(".%05u", 65535 - Priority);
    1253             : 
    1254          22 :   return Ctx.getAssociativeCOFFSection(
    1255             :       Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
    1256             :                                    COFF::IMAGE_SCN_MEM_READ |
    1257             :                                    COFF::IMAGE_SCN_MEM_WRITE,
    1258             :                          SectionKind::getData()),
    1259          11 :       KeySym, 0);
    1260             : }
    1261             : 
    1262          22 : MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection(
    1263             :     unsigned Priority, const MCSymbol *KeySym) const {
    1264          22 :   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true,
    1265             :                                       Priority, KeySym,
    1266          44 :                                       cast<MCSectionCOFF>(StaticCtorSection));
    1267             : }
    1268             : 
    1269           5 : MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection(
    1270             :     unsigned Priority, const MCSymbol *KeySym) const {
    1271           5 :   return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false,
    1272             :                                       Priority, KeySym,
    1273          10 :                                       cast<MCSectionCOFF>(StaticDtorSection));
    1274             : }
    1275             : 
    1276        5613 : void TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal(
    1277             :     raw_ostream &OS, const GlobalValue *GV) const {
    1278       11226 :   emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler());
    1279        5613 : }
    1280             : 
    1281           8 : void TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed(
    1282             :     raw_ostream &OS, const GlobalValue *GV) const {
    1283          16 :   emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler());
    1284           8 : }
    1285             : 
    1286          91 : const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference(
    1287             :     const GlobalValue *LHS, const GlobalValue *RHS,
    1288             :     const TargetMachine &TM) const {
    1289             :   const Triple &T = TM.getTargetTriple();
    1290             :   if (!T.isKnownWindowsMSVCEnvironment() &&
    1291             :       !T.isWindowsItaniumEnvironment() &&
    1292             :       !T.isWindowsCoreCLREnvironment())
    1293             :     return nullptr;
    1294             : 
    1295             :   // Our symbols should exist in address space zero, cowardly no-op if
    1296             :   // otherwise.
    1297         273 :   if (LHS->getType()->getPointerAddressSpace() != 0 ||
    1298          91 :       RHS->getType()->getPointerAddressSpace() != 0)
    1299             :     return nullptr;
    1300             : 
    1301             :   // Both ptrtoint instructions must wrap global objects:
    1302             :   // - Only global variables are eligible for image relative relocations.
    1303             :   // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable.
    1304             :   // We expect __ImageBase to be a global variable without a section, externally
    1305             :   // defined.
    1306             :   //
    1307             :   // It should look something like this: @__ImageBase = external constant i8
    1308         182 :   if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) ||
    1309          91 :       LHS->isThreadLocal() || RHS->isThreadLocal() ||
    1310         263 :       RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() ||
    1311          86 :       cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection())
    1312             :     return nullptr;
    1313             : 
    1314         172 :   return MCSymbolRefExpr::create(TM.getSymbol(LHS),
    1315             :                                  MCSymbolRefExpr::VK_COFF_IMGREL32,
    1316         172 :                                  getContext());
    1317             : }
    1318             : 
    1319         527 : static std::string APIntToHexString(const APInt &AI) {
    1320         527 :   unsigned Width = (AI.getBitWidth() / 8) * 2;
    1321         527 :   std::string HexString = utohexstr(AI.getLimitedValue(), /*LowerCase=*/true);
    1322         527 :   unsigned Size = HexString.size();
    1323             :   assert(Width >= Size && "hex string is too large!");
    1324         527 :   HexString.insert(HexString.begin(), Width - Size, '0');
    1325             : 
    1326         527 :   return HexString;
    1327             : }
    1328             : 
    1329         585 : static std::string scalarConstantToHexString(const Constant *C) {
    1330         585 :   Type *Ty = C->getType();
    1331         585 :   if (isa<UndefValue>(C)) {
    1332          12 :     return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits()));
    1333             :   } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) {
    1334         430 :     return APIntToHexString(CFP->getValueAPF().bitcastToAPInt());
    1335             :   } else if (const auto *CI = dyn_cast<ConstantInt>(C)) {
    1336         306 :     return APIntToHexString(CI->getValue());
    1337             :   } else {
    1338             :     unsigned NumElements;
    1339          58 :     if (isa<VectorType>(Ty))
    1340             :       NumElements = Ty->getVectorNumElements();
    1341             :     else
    1342           3 :       NumElements = Ty->getArrayNumElements();
    1343             :     std::string HexString;
    1344         402 :     for (int I = NumElements - 1, E = -1; I != E; --I)
    1345         688 :       HexString += scalarConstantToHexString(C->getAggregateElement(I));
    1346             :     return HexString;
    1347             :   }
    1348             : }
    1349             : 
    1350         261 : MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant(
    1351             :     const DataLayout &DL, SectionKind Kind, const Constant *C,
    1352             :     unsigned &Align) const {
    1353         519 :   if (Kind.isMergeableConst() && C &&
    1354         258 :       getContext().getAsmInfo()->hasCOFFAssociativeComdats()) {
    1355             :     // GNU binutils doesn't support the kind of symbol with a null
    1356             :     // storage class that this generates.
    1357             :     const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA |
    1358             :                                      COFF::IMAGE_SCN_MEM_READ |
    1359             :                                      COFF::IMAGE_SCN_LNK_COMDAT;
    1360             :     std::string COMDATSymName;
    1361         241 :     if (Kind.isMergeableConst4()) {
    1362         102 :       if (Align <= 4) {
    1363         306 :         COMDATSymName = "__real@" + scalarConstantToHexString(C);
    1364         102 :         Align = 4;
    1365             :       }
    1366         139 :     } else if (Kind.isMergeableConst8()) {
    1367          84 :       if (Align <= 8) {
    1368         252 :         COMDATSymName = "__real@" + scalarConstantToHexString(C);
    1369          84 :         Align = 8;
    1370             :       }
    1371          55 :     } else if (Kind.isMergeableConst16()) {
    1372             :       // FIXME: These may not be appropriate for non-x86 architectures.
    1373          51 :       if (Align <= 16) {
    1374         153 :         COMDATSymName = "__xmm@" + scalarConstantToHexString(C);
    1375          51 :         Align = 16;
    1376             :       }
    1377           4 :     } else if (Kind.isMergeableConst32()) {
    1378           4 :       if (Align <= 32) {
    1379          12 :         COMDATSymName = "__ymm@" + scalarConstantToHexString(C);
    1380           4 :         Align = 32;
    1381             :       }
    1382             :     }
    1383             : 
    1384         241 :     if (!COMDATSymName.empty())
    1385         482 :       return getContext().getCOFFSection(".rdata", Characteristics, Kind,
    1386             :                                          COMDATSymName,
    1387         241 :                                          COFF::IMAGE_COMDAT_SELECT_ANY);
    1388             :   }
    1389             : 
    1390          20 :   return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align);
    1391             : }
    1392             : 
    1393             : 
    1394             : //===----------------------------------------------------------------------===//
    1395             : //                                  Wasm
    1396             : //===----------------------------------------------------------------------===//
    1397             : 
    1398        1578 : static const Comdat *getWasmComdat(const GlobalValue *GV) {
    1399        1578 :   const Comdat *C = GV->getComdat();
    1400        1578 :   if (!C)
    1401             :     return nullptr;
    1402             : 
    1403           9 :   if (C->getSelectionKind() != Comdat::Any)
    1404           0 :     report_fatal_error("WebAssembly COMDATs only support "
    1405           0 :                        "SelectionKind::Any, '" + C->getName() + "' cannot be "
    1406             :                        "lowered.");
    1407             : 
    1408             :   return C;
    1409             : }
    1410             : 
    1411             : static SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) {
    1412             :   // If we're told we have function data, then use that.
    1413           3 :   if (K.isText())
    1414             :     return SectionKind::getText();
    1415             : 
    1416             :   // Otherwise, ignore whatever section type the generic impl detected and use
    1417             :   // a plain data section.
    1418             :   return SectionKind::getData();
    1419             : }
    1420             : 
    1421           6 : MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal(
    1422             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
    1423             :   // We don't support explict section names for functions in the wasm object
    1424             :   // format.  Each function has to be in its own unique section.
    1425           6 :   if (isa<Function>(GO)) {
    1426           3 :     return SelectSectionForGlobal(GO, Kind, TM);
    1427             :   }
    1428             : 
    1429           3 :   StringRef Name = GO->getSection();
    1430             : 
    1431             :   Kind = getWasmKindForNamedSection(Name, Kind);
    1432             : 
    1433             :   StringRef Group = "";
    1434           3 :   if (const Comdat *C = getWasmComdat(GO)) {
    1435           0 :     Group = C->getName();
    1436             :   }
    1437             : 
    1438           6 :   return getContext().getWasmSection(Name, Kind, Group,
    1439             :                                      MCContext::GenericSectionID);
    1440             : }
    1441             : 
    1442        1575 : static MCSectionWasm *selectWasmSectionForGlobal(
    1443             :     MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
    1444             :     const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) {
    1445             :   StringRef Group = "";
    1446        1575 :   if (const Comdat *C = getWasmComdat(GO)) {
    1447           9 :     Group = C->getName();
    1448             :   }
    1449             : 
    1450             :   bool UniqueSectionNames = TM.getUniqueSectionNames();
    1451        1575 :   SmallString<128> Name = getSectionPrefixForGlobal(Kind);
    1452             : 
    1453             :   if (const auto *F = dyn_cast<Function>(GO)) {
    1454        1407 :     const auto &OptionalPrefix = F->getSectionPrefix();
    1455        1407 :     if (OptionalPrefix)
    1456             :       Name += *OptionalPrefix;
    1457             :   }
    1458             : 
    1459        1575 :   if (EmitUniqueSection && UniqueSectionNames) {
    1460        1575 :     Name.push_back('.');
    1461        1575 :     TM.getNameWithPrefix(Name, GO, Mang, true);
    1462             :   }
    1463             :   unsigned UniqueID = MCContext::GenericSectionID;
    1464        1575 :   if (EmitUniqueSection && !UniqueSectionNames) {
    1465           0 :     UniqueID = *NextUniqueID;
    1466           0 :     (*NextUniqueID)++;
    1467             :   }
    1468        3150 :   return Ctx.getWasmSection(Name, Kind, Group, UniqueID);
    1469             : }
    1470             : 
    1471        1575 : MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal(
    1472             :     const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
    1473             : 
    1474        1575 :   if (Kind.isCommon())
    1475           0 :     report_fatal_error("mergable sections not supported yet on wasm");
    1476             : 
    1477             :   // If we have -ffunction-section or -fdata-section then we should emit the
    1478             :   // global value to a uniqued section specifically for it.
    1479             :   bool EmitUniqueSection = false;
    1480        1575 :   if (Kind.isText())
    1481             :     EmitUniqueSection = TM.getFunctionSections();
    1482             :   else
    1483             :     EmitUniqueSection = TM.getDataSections();
    1484        1575 :   EmitUniqueSection |= GO->hasComdat();
    1485             : 
    1486        1575 :   return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
    1487        1575 :                                     EmitUniqueSection, &NextUniqueID);
    1488             : }
    1489             : 
    1490           0 : bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection(
    1491             :     bool UsesLabelDifference, const Function &F) const {
    1492             :   // We can always create relative relocations, so use another section
    1493             :   // that can be marked non-executable.
    1494           0 :   return false;
    1495             : }
    1496             : 
    1497           0 : const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference(
    1498             :     const GlobalValue *LHS, const GlobalValue *RHS,
    1499             :     const TargetMachine &TM) const {
    1500             :   // We may only use a PLT-relative relocation to refer to unnamed_addr
    1501             :   // functions.
    1502           0 :   if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy())
    1503             :     return nullptr;
    1504             : 
    1505             :   // Basic sanity checks.
    1506           0 :   if (LHS->getType()->getPointerAddressSpace() != 0 ||
    1507           0 :       RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() ||
    1508             :       RHS->isThreadLocal())
    1509             :     return nullptr;
    1510             : 
    1511           0 :   return MCBinaryExpr::createSub(
    1512           0 :       MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None,
    1513           0 :                               getContext()),
    1514           0 :       MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext());
    1515             : }
    1516             : 
    1517         263 : void TargetLoweringObjectFileWasm::InitializeWasm() {
    1518         263 :   StaticCtorSection =
    1519         526 :       getContext().getWasmSection(".init_array", SectionKind::getData());
    1520         263 : }
    1521             : 
    1522          21 : MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection(
    1523             :     unsigned Priority, const MCSymbol *KeySym) const {
    1524          21 :   return Priority == UINT16_MAX ?
    1525             :          StaticCtorSection :
    1526          81 :          getContext().getWasmSection(".init_array." + utostr(Priority),
    1527          21 :                                      SectionKind::getData());
    1528             : }
    1529             : 
    1530           0 : MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection(
    1531             :     unsigned Priority, const MCSymbol *KeySym) const {
    1532           0 :   llvm_unreachable("@llvm.global_dtors should have been lowered already");
    1533             :   return nullptr;
    1534             : }

Generated by: LCOV version 1.13