1321369Sdim//===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===// 2203954Srdivacky// 3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4353358Sdim// See https://llvm.org/LICENSE.txt for license information. 5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6203954Srdivacky// 7203954Srdivacky//===----------------------------------------------------------------------===// 8203954Srdivacky// 9203954Srdivacky// This file implements classes used to handle lowerings specific to common 10203954Srdivacky// object file formats. 11203954Srdivacky// 12203954Srdivacky//===----------------------------------------------------------------------===// 13203954Srdivacky 14203954Srdivacky#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 15249423Sdim#include "llvm/ADT/SmallString.h" 16321369Sdim#include "llvm/ADT/SmallVector.h" 17249423Sdim#include "llvm/ADT/StringExtras.h" 18321369Sdim#include "llvm/ADT/StringRef.h" 19249423Sdim#include "llvm/ADT/Triple.h" 20321369Sdim#include "llvm/BinaryFormat/COFF.h" 21321369Sdim#include "llvm/BinaryFormat/Dwarf.h" 22321369Sdim#include "llvm/BinaryFormat/ELF.h" 23321369Sdim#include "llvm/BinaryFormat/MachO.h" 24321369Sdim#include "llvm/CodeGen/MachineModuleInfo.h" 25203954Srdivacky#include "llvm/CodeGen/MachineModuleInfoImpls.h" 26321369Sdim#include "llvm/IR/Comdat.h" 27249423Sdim#include "llvm/IR/Constants.h" 28249423Sdim#include "llvm/IR/DataLayout.h" 29249423Sdim#include "llvm/IR/DerivedTypes.h" 30249423Sdim#include "llvm/IR/Function.h" 31321369Sdim#include "llvm/IR/GlobalAlias.h" 32321369Sdim#include "llvm/IR/GlobalObject.h" 33321369Sdim#include "llvm/IR/GlobalValue.h" 34249423Sdim#include "llvm/IR/GlobalVariable.h" 35276479Sdim#include "llvm/IR/Mangler.h" 36321369Sdim#include "llvm/IR/Metadata.h" 37249423Sdim#include "llvm/IR/Module.h" 38321369Sdim#include "llvm/IR/Type.h" 39296417Sdim#include "llvm/MC/MCAsmInfo.h" 40203954Srdivacky#include "llvm/MC/MCContext.h" 41203954Srdivacky#include "llvm/MC/MCExpr.h" 42249423Sdim#include "llvm/MC/MCSectionCOFF.h" 43249423Sdim#include "llvm/MC/MCSectionELF.h" 44203954Srdivacky#include "llvm/MC/MCSectionMachO.h" 45321369Sdim#include "llvm/MC/MCSectionWasm.h" 46360784Sdim#include "llvm/MC/MCSectionXCOFF.h" 47221345Sdim#include "llvm/MC/MCStreamer.h" 48321369Sdim#include "llvm/MC/MCSymbol.h" 49288943Sdim#include "llvm/MC/MCSymbolELF.h" 50288943Sdim#include "llvm/MC/MCValue.h" 51321369Sdim#include "llvm/MC/SectionKind.h" 52309124Sdim#include "llvm/ProfileData/InstrProf.h" 53321369Sdim#include "llvm/Support/Casting.h" 54321369Sdim#include "llvm/Support/CodeGen.h" 55327952Sdim#include "llvm/Support/Format.h" 56203954Srdivacky#include "llvm/Support/ErrorHandling.h" 57203954Srdivacky#include "llvm/Support/raw_ostream.h" 58249423Sdim#include "llvm/Target/TargetMachine.h" 59321369Sdim#include <cassert> 60321369Sdim#include <string> 61321369Sdim 62203954Srdivackyusing namespace llvm; 63204642Srdivackyusing namespace dwarf; 64203954Srdivacky 65321369Sdimstatic void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, 66321369Sdim StringRef &Section) { 67321369Sdim SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 68321369Sdim M.getModuleFlagsMetadata(ModuleFlags); 69321369Sdim 70321369Sdim for (const auto &MFE: ModuleFlags) { 71321369Sdim // Ignore flags with 'Require' behaviour. 72321369Sdim if (MFE.Behavior == Module::Require) 73321369Sdim continue; 74321369Sdim 75321369Sdim StringRef Key = MFE.Key->getString(); 76321369Sdim if (Key == "Objective-C Image Info Version") { 77321369Sdim Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 78321369Sdim } else if (Key == "Objective-C Garbage Collection" || 79321369Sdim Key == "Objective-C GC Only" || 80321369Sdim Key == "Objective-C Is Simulated" || 81321369Sdim Key == "Objective-C Class Properties" || 82321369Sdim Key == "Objective-C Image Swift Version") { 83321369Sdim Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 84321369Sdim } else if (Key == "Objective-C Image Info Section") { 85321369Sdim Section = cast<MDString>(MFE.Val)->getString(); 86321369Sdim } 87321369Sdim } 88321369Sdim} 89321369Sdim 90203954Srdivacky//===----------------------------------------------------------------------===// 91203954Srdivacky// ELF 92203954Srdivacky//===----------------------------------------------------------------------===// 93203954Srdivacky 94341825Sdimvoid TargetLoweringObjectFileELF::Initialize(MCContext &Ctx, 95341825Sdim const TargetMachine &TgtM) { 96341825Sdim TargetLoweringObjectFile::Initialize(Ctx, TgtM); 97341825Sdim TM = &TgtM; 98344779Sdim 99344779Sdim CodeModel::Model CM = TgtM.getCodeModel(); 100344779Sdim 101344779Sdim switch (TgtM.getTargetTriple().getArch()) { 102344779Sdim case Triple::arm: 103344779Sdim case Triple::armeb: 104344779Sdim case Triple::thumb: 105344779Sdim case Triple::thumbeb: 106344779Sdim if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM) 107344779Sdim break; 108344779Sdim // Fallthrough if not using EHABI 109344779Sdim LLVM_FALLTHROUGH; 110344779Sdim case Triple::ppc: 111344779Sdim case Triple::x86: 112344779Sdim PersonalityEncoding = isPositionIndependent() 113344779Sdim ? dwarf::DW_EH_PE_indirect | 114344779Sdim dwarf::DW_EH_PE_pcrel | 115344779Sdim dwarf::DW_EH_PE_sdata4 116344779Sdim : dwarf::DW_EH_PE_absptr; 117344779Sdim LSDAEncoding = isPositionIndependent() 118344779Sdim ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 119344779Sdim : dwarf::DW_EH_PE_absptr; 120344779Sdim TTypeEncoding = isPositionIndependent() 121344779Sdim ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 122344779Sdim dwarf::DW_EH_PE_sdata4 123344779Sdim : dwarf::DW_EH_PE_absptr; 124344779Sdim break; 125344779Sdim case Triple::x86_64: 126344779Sdim if (isPositionIndependent()) { 127344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 128344779Sdim ((CM == CodeModel::Small || CM == CodeModel::Medium) 129344779Sdim ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 130344779Sdim LSDAEncoding = dwarf::DW_EH_PE_pcrel | 131344779Sdim (CM == CodeModel::Small 132344779Sdim ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 133344779Sdim TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 134344779Sdim ((CM == CodeModel::Small || CM == CodeModel::Medium) 135344779Sdim ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4); 136344779Sdim } else { 137344779Sdim PersonalityEncoding = 138344779Sdim (CM == CodeModel::Small || CM == CodeModel::Medium) 139344779Sdim ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 140344779Sdim LSDAEncoding = (CM == CodeModel::Small) 141344779Sdim ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 142344779Sdim TTypeEncoding = (CM == CodeModel::Small) 143344779Sdim ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 144344779Sdim } 145344779Sdim break; 146344779Sdim case Triple::hexagon: 147344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_absptr; 148344779Sdim LSDAEncoding = dwarf::DW_EH_PE_absptr; 149344779Sdim TTypeEncoding = dwarf::DW_EH_PE_absptr; 150344779Sdim if (isPositionIndependent()) { 151344779Sdim PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; 152344779Sdim LSDAEncoding |= dwarf::DW_EH_PE_pcrel; 153344779Sdim TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; 154344779Sdim } 155344779Sdim break; 156344779Sdim case Triple::aarch64: 157344779Sdim case Triple::aarch64_be: 158360784Sdim case Triple::aarch64_32: 159344779Sdim // The small model guarantees static code/data size < 4GB, but not where it 160344779Sdim // will be in memory. Most of these could end up >2GB away so even a signed 161344779Sdim // pc-relative 32-bit address is insufficient, theoretically. 162344779Sdim if (isPositionIndependent()) { 163344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 164344779Sdim dwarf::DW_EH_PE_sdata8; 165344779Sdim LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8; 166344779Sdim TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 167344779Sdim dwarf::DW_EH_PE_sdata8; 168344779Sdim } else { 169344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_absptr; 170344779Sdim LSDAEncoding = dwarf::DW_EH_PE_absptr; 171344779Sdim TTypeEncoding = dwarf::DW_EH_PE_absptr; 172344779Sdim } 173344779Sdim break; 174344779Sdim case Triple::lanai: 175344779Sdim LSDAEncoding = dwarf::DW_EH_PE_absptr; 176344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_absptr; 177344779Sdim TTypeEncoding = dwarf::DW_EH_PE_absptr; 178344779Sdim break; 179344779Sdim case Triple::mips: 180344779Sdim case Triple::mipsel: 181344779Sdim case Triple::mips64: 182344779Sdim case Triple::mips64el: 183344779Sdim // MIPS uses indirect pointer to refer personality functions and types, so 184344779Sdim // that the eh_frame section can be read-only. DW.ref.personality will be 185344779Sdim // generated for relocation. 186344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_indirect; 187344779Sdim // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't 188344779Sdim // identify N64 from just a triple. 189344779Sdim TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 190344779Sdim dwarf::DW_EH_PE_sdata4; 191344779Sdim // We don't support PC-relative LSDA references in GAS so we use the default 192344779Sdim // DW_EH_PE_absptr for those. 193344779Sdim 194344779Sdim // FreeBSD must be explicit about the data size and using pcrel since it's 195344779Sdim // assembler/linker won't do the automatic conversion that the Linux tools 196344779Sdim // do. 197344779Sdim if (TgtM.getTargetTriple().isOSFreeBSD()) { 198344779Sdim PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 199344779Sdim LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 200344779Sdim } 201344779Sdim break; 202344779Sdim case Triple::ppc64: 203344779Sdim case Triple::ppc64le: 204344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 205344779Sdim dwarf::DW_EH_PE_udata8; 206344779Sdim LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8; 207344779Sdim TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 208344779Sdim dwarf::DW_EH_PE_udata8; 209344779Sdim break; 210344779Sdim case Triple::sparcel: 211344779Sdim case Triple::sparc: 212344779Sdim if (isPositionIndependent()) { 213344779Sdim LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 214344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 215344779Sdim dwarf::DW_EH_PE_sdata4; 216344779Sdim TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 217344779Sdim dwarf::DW_EH_PE_sdata4; 218344779Sdim } else { 219344779Sdim LSDAEncoding = dwarf::DW_EH_PE_absptr; 220344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_absptr; 221344779Sdim TTypeEncoding = dwarf::DW_EH_PE_absptr; 222344779Sdim } 223353358Sdim CallSiteEncoding = dwarf::DW_EH_PE_udata4; 224344779Sdim break; 225353358Sdim case Triple::riscv32: 226353358Sdim case Triple::riscv64: 227353358Sdim LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 228353358Sdim PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 229353358Sdim dwarf::DW_EH_PE_sdata4; 230353358Sdim TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 231353358Sdim dwarf::DW_EH_PE_sdata4; 232353358Sdim CallSiteEncoding = dwarf::DW_EH_PE_udata4; 233353358Sdim break; 234344779Sdim case Triple::sparcv9: 235344779Sdim LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 236344779Sdim if (isPositionIndependent()) { 237344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 238344779Sdim dwarf::DW_EH_PE_sdata4; 239344779Sdim TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 240344779Sdim dwarf::DW_EH_PE_sdata4; 241344779Sdim } else { 242344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_absptr; 243344779Sdim TTypeEncoding = dwarf::DW_EH_PE_absptr; 244344779Sdim } 245344779Sdim break; 246344779Sdim case Triple::systemz: 247344779Sdim // All currently-defined code models guarantee that 4-byte PC-relative 248344779Sdim // values will be in range. 249344779Sdim if (isPositionIndependent()) { 250344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 251344779Sdim dwarf::DW_EH_PE_sdata4; 252344779Sdim LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 253344779Sdim TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 254344779Sdim dwarf::DW_EH_PE_sdata4; 255344779Sdim } else { 256344779Sdim PersonalityEncoding = dwarf::DW_EH_PE_absptr; 257344779Sdim LSDAEncoding = dwarf::DW_EH_PE_absptr; 258344779Sdim TTypeEncoding = dwarf::DW_EH_PE_absptr; 259344779Sdim } 260344779Sdim break; 261344779Sdim default: 262344779Sdim break; 263344779Sdim } 264341825Sdim} 265341825Sdim 266341825Sdimvoid TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer, 267341825Sdim Module &M) const { 268341825Sdim auto &C = getContext(); 269341825Sdim 270341825Sdim if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 271341825Sdim auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS, 272341825Sdim ELF::SHF_EXCLUDE); 273341825Sdim 274341825Sdim Streamer.SwitchSection(S); 275341825Sdim 276360784Sdim for (const auto *Operand : LinkerOptions->operands()) { 277341825Sdim if (cast<MDNode>(Operand)->getNumOperands() != 2) 278341825Sdim report_fatal_error("invalid llvm.linker.options"); 279341825Sdim for (const auto &Option : cast<MDNode>(Operand)->operands()) { 280341825Sdim Streamer.EmitBytes(cast<MDString>(Option)->getString()); 281341825Sdim Streamer.EmitIntValue(0, 1); 282341825Sdim } 283341825Sdim } 284341825Sdim } 285341825Sdim 286353358Sdim if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) { 287353358Sdim auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES, 288353358Sdim ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, ""); 289353358Sdim 290353358Sdim Streamer.SwitchSection(S); 291353358Sdim 292360784Sdim for (const auto *Operand : DependentLibraries->operands()) { 293353358Sdim Streamer.EmitBytes( 294353358Sdim cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString()); 295353358Sdim Streamer.EmitIntValue(0, 1); 296353358Sdim } 297353358Sdim } 298353358Sdim 299321369Sdim unsigned Version = 0; 300321369Sdim unsigned Flags = 0; 301321369Sdim StringRef Section; 302321369Sdim 303321369Sdim GetObjCImageInfo(M, Version, Flags, Section); 304341825Sdim if (!Section.empty()) { 305341825Sdim auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC); 306341825Sdim Streamer.SwitchSection(S); 307341825Sdim Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 308341825Sdim Streamer.EmitIntValue(Version, 4); 309341825Sdim Streamer.EmitIntValue(Flags, 4); 310341825Sdim Streamer.AddBlankLine(); 311341825Sdim } 312341825Sdim 313341825Sdim SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 314341825Sdim M.getModuleFlagsMetadata(ModuleFlags); 315341825Sdim 316341825Sdim MDNode *CFGProfile = nullptr; 317341825Sdim 318341825Sdim for (const auto &MFE : ModuleFlags) { 319341825Sdim StringRef Key = MFE.Key->getString(); 320341825Sdim if (Key == "CG Profile") { 321341825Sdim CFGProfile = cast<MDNode>(MFE.Val); 322341825Sdim break; 323341825Sdim } 324341825Sdim } 325341825Sdim 326341825Sdim if (!CFGProfile) 327321369Sdim return; 328321369Sdim 329341825Sdim auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * { 330341825Sdim if (!MDO) 331341825Sdim return nullptr; 332341825Sdim auto V = cast<ValueAsMetadata>(MDO); 333341825Sdim const Function *F = cast<Function>(V->getValue()); 334341825Sdim return TM->getSymbol(F); 335341825Sdim }; 336341825Sdim 337341825Sdim for (const auto &Edge : CFGProfile->operands()) { 338341825Sdim MDNode *E = cast<MDNode>(Edge); 339341825Sdim const MCSymbol *From = GetSym(E->getOperand(0)); 340341825Sdim const MCSymbol *To = GetSym(E->getOperand(1)); 341341825Sdim // Skip null functions. This can happen if functions are dead stripped after 342341825Sdim // the CGProfile pass has been run. 343341825Sdim if (!From || !To) 344341825Sdim continue; 345341825Sdim uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2)) 346341825Sdim ->getValue() 347341825Sdim ->getUniqueInteger() 348341825Sdim .getZExtValue(); 349341825Sdim Streamer.emitCGProfileEntry( 350341825Sdim MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C), 351341825Sdim MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count); 352341825Sdim } 353321369Sdim} 354321369Sdim 355276479SdimMCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol( 356314564Sdim const GlobalValue *GV, const TargetMachine &TM, 357276479Sdim MachineModuleInfo *MMI) const { 358221345Sdim unsigned Encoding = getPersonalityEncoding(); 359321369Sdim if ((Encoding & 0x80) == DW_EH_PE_indirect) 360288943Sdim return getContext().getOrCreateSymbol(StringRef("DW.ref.") + 361314564Sdim TM.getSymbol(GV)->getName()); 362321369Sdim if ((Encoding & 0x70) == DW_EH_PE_absptr) 363314564Sdim return TM.getSymbol(GV); 364276479Sdim report_fatal_error("We do not support this DWARF encoding yet!"); 365221345Sdim} 366221345Sdim 367296417Sdimvoid TargetLoweringObjectFileELF::emitPersonalityValue( 368296417Sdim MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const { 369224145Sdim SmallString<64> NameData("DW.ref."); 370224145Sdim NameData += Sym->getName(); 371288943Sdim MCSymbolELF *Label = 372288943Sdim cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData)); 373221345Sdim Streamer.EmitSymbolAttribute(Label, MCSA_Hidden); 374221345Sdim Streamer.EmitSymbolAttribute(Label, MCSA_Weak); 375221345Sdim unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; 376309124Sdim MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(), 377309124Sdim ELF::SHT_PROGBITS, Flags, 0); 378296417Sdim unsigned Size = DL.getPointerSize(); 379221345Sdim Streamer.SwitchSection(Sec); 380360784Sdim Streamer.EmitValueToAlignment(DL.getPointerABIAlignment(0).value()); 381221345Sdim Streamer.EmitSymbolAttribute(Label, MCSA_ELF_TypeObject); 382288943Sdim const MCExpr *E = MCConstantExpr::create(Size, getContext()); 383288943Sdim Streamer.emitELFSize(Label, E); 384221345Sdim Streamer.EmitLabel(Label); 385221345Sdim 386221345Sdim Streamer.EmitSymbolValue(Sym, Size); 387221345Sdim} 388221345Sdim 389276479Sdimconst MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference( 390314564Sdim const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 391314564Sdim MachineModuleInfo *MMI, MCStreamer &Streamer) const { 392321369Sdim if (Encoding & DW_EH_PE_indirect) { 393249423Sdim MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>(); 394249423Sdim 395314564Sdim MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM); 396249423Sdim 397249423Sdim // Add information about the stub reference to ELFMMI so that the stub 398249423Sdim // gets emitted by the asmprinter. 399249423Sdim MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym); 400276479Sdim if (!StubSym.getPointer()) { 401314564Sdim MCSymbol *Sym = TM.getSymbol(GV); 402249423Sdim StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 403249423Sdim } 404249423Sdim 405249423Sdim return TargetLoweringObjectFile:: 406288943Sdim getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 407321369Sdim Encoding & ~DW_EH_PE_indirect, Streamer); 408249423Sdim } 409249423Sdim 410314564Sdim return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 411314564Sdim MMI, Streamer); 412249423Sdim} 413249423Sdim 414327952Sdimstatic SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) { 415341825Sdim // N.B.: The defaults used in here are not the same ones used in MC. 416223017Sdim // We follow gcc, MC follows gas. For example, given ".section .eh_frame", 417223017Sdim // both gas and MC will produce a section with no flags. Given 418239462Sdim // section(".eh_frame") gcc will produce: 419239462Sdim // 420239462Sdim // .section .eh_frame,"a",@progbits 421321369Sdim 422321369Sdim if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF, 423321369Sdim /*AddSegmentInfo=*/false)) 424309124Sdim return SectionKind::getMetadata(); 425309124Sdim 426203954Srdivacky if (Name.empty() || Name[0] != '.') return K; 427203954Srdivacky 428341825Sdim // Default implementation based on some magic section names. 429203954Srdivacky if (Name == ".bss" || 430203954Srdivacky Name.startswith(".bss.") || 431203954Srdivacky Name.startswith(".gnu.linkonce.b.") || 432203954Srdivacky Name.startswith(".llvm.linkonce.b.") || 433203954Srdivacky Name == ".sbss" || 434203954Srdivacky Name.startswith(".sbss.") || 435203954Srdivacky Name.startswith(".gnu.linkonce.sb.") || 436203954Srdivacky Name.startswith(".llvm.linkonce.sb.")) 437203954Srdivacky return SectionKind::getBSS(); 438203954Srdivacky 439203954Srdivacky if (Name == ".tdata" || 440203954Srdivacky Name.startswith(".tdata.") || 441203954Srdivacky Name.startswith(".gnu.linkonce.td.") || 442203954Srdivacky Name.startswith(".llvm.linkonce.td.")) 443203954Srdivacky return SectionKind::getThreadData(); 444203954Srdivacky 445203954Srdivacky if (Name == ".tbss" || 446203954Srdivacky Name.startswith(".tbss.") || 447203954Srdivacky Name.startswith(".gnu.linkonce.tb.") || 448203954Srdivacky Name.startswith(".llvm.linkonce.tb.")) 449203954Srdivacky return SectionKind::getThreadBSS(); 450203954Srdivacky 451203954Srdivacky return K; 452203954Srdivacky} 453203954Srdivacky 454203954Srdivackystatic unsigned getELFSectionType(StringRef Name, SectionKind K) { 455314564Sdim // Use SHT_NOTE for section whose name starts with ".note" to allow 456314564Sdim // emitting ELF notes from C variable declaration. 457314564Sdim // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609 458314564Sdim if (Name.startswith(".note")) 459314564Sdim return ELF::SHT_NOTE; 460203954Srdivacky 461203954Srdivacky if (Name == ".init_array") 462218893Sdim return ELF::SHT_INIT_ARRAY; 463203954Srdivacky 464203954Srdivacky if (Name == ".fini_array") 465218893Sdim return ELF::SHT_FINI_ARRAY; 466203954Srdivacky 467203954Srdivacky if (Name == ".preinit_array") 468218893Sdim return ELF::SHT_PREINIT_ARRAY; 469203954Srdivacky 470203954Srdivacky if (K.isBSS() || K.isThreadBSS()) 471218893Sdim return ELF::SHT_NOBITS; 472203954Srdivacky 473218893Sdim return ELF::SHT_PROGBITS; 474203954Srdivacky} 475203954Srdivacky 476288943Sdimstatic unsigned getELFSectionFlags(SectionKind K) { 477203954Srdivacky unsigned Flags = 0; 478203954Srdivacky 479203954Srdivacky if (!K.isMetadata()) 480218893Sdim Flags |= ELF::SHF_ALLOC; 481203954Srdivacky 482203954Srdivacky if (K.isText()) 483218893Sdim Flags |= ELF::SHF_EXECINSTR; 484203954Srdivacky 485314564Sdim if (K.isExecuteOnly()) 486314564Sdim Flags |= ELF::SHF_ARM_PURECODE; 487314564Sdim 488203954Srdivacky if (K.isWriteable()) 489218893Sdim Flags |= ELF::SHF_WRITE; 490203954Srdivacky 491203954Srdivacky if (K.isThreadLocal()) 492218893Sdim Flags |= ELF::SHF_TLS; 493203954Srdivacky 494288943Sdim if (K.isMergeableCString() || K.isMergeableConst()) 495218893Sdim Flags |= ELF::SHF_MERGE; 496203954Srdivacky 497203954Srdivacky if (K.isMergeableCString()) 498218893Sdim Flags |= ELF::SHF_STRINGS; 499203954Srdivacky 500203954Srdivacky return Flags; 501203954Srdivacky} 502203954Srdivacky 503276479Sdimstatic const Comdat *getELFComdat(const GlobalValue *GV) { 504276479Sdim const Comdat *C = GV->getComdat(); 505276479Sdim if (!C) 506276479Sdim return nullptr; 507203954Srdivacky 508276479Sdim if (C->getSelectionKind() != Comdat::Any) 509276479Sdim report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" + 510276479Sdim C->getName() + "' cannot be lowered."); 511276479Sdim 512276479Sdim return C; 513276479Sdim} 514276479Sdim 515321369Sdimstatic const MCSymbolELF *getAssociatedSymbol(const GlobalObject *GO, 516321369Sdim const TargetMachine &TM) { 517321369Sdim MDNode *MD = GO->getMetadata(LLVMContext::MD_associated); 518321369Sdim if (!MD) 519321369Sdim return nullptr; 520321369Sdim 521321369Sdim const MDOperand &Op = MD->getOperand(0); 522321369Sdim if (!Op.get()) 523321369Sdim return nullptr; 524321369Sdim 525321369Sdim auto *VM = dyn_cast<ValueAsMetadata>(Op); 526321369Sdim if (!VM) 527321369Sdim report_fatal_error("MD_associated operand is not ValueAsMetadata"); 528321369Sdim 529360784Sdim auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue()); 530360784Sdim return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr; 531321369Sdim} 532321369Sdim 533344779Sdimstatic unsigned getEntrySizeForKind(SectionKind Kind) { 534344779Sdim if (Kind.isMergeable1ByteCString()) 535344779Sdim return 1; 536344779Sdim else if (Kind.isMergeable2ByteCString()) 537344779Sdim return 2; 538344779Sdim else if (Kind.isMergeable4ByteCString()) 539344779Sdim return 4; 540344779Sdim else if (Kind.isMergeableConst4()) 541344779Sdim return 4; 542344779Sdim else if (Kind.isMergeableConst8()) 543344779Sdim return 8; 544344779Sdim else if (Kind.isMergeableConst16()) 545344779Sdim return 16; 546344779Sdim else if (Kind.isMergeableConst32()) 547344779Sdim return 32; 548344779Sdim else { 549344779Sdim // We shouldn't have mergeable C strings or mergeable constants that we 550344779Sdim // didn't handle above. 551344779Sdim assert(!Kind.isMergeableCString() && "unknown string width"); 552344779Sdim assert(!Kind.isMergeableConst() && "unknown data width"); 553344779Sdim return 0; 554344779Sdim } 555344779Sdim} 556344779Sdim 557288943SdimMCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal( 558314564Sdim const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 559314564Sdim StringRef SectionName = GO->getSection(); 560203954Srdivacky 561321369Sdim // Check if '#pragma clang section' name is applicable. 562321369Sdim // Note that pragma directive overrides -ffunction-section, -fdata-section 563321369Sdim // and so section name is exactly as user specified and not uniqued. 564321369Sdim const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO); 565321369Sdim if (GV && GV->hasImplicitSection()) { 566321369Sdim auto Attrs = GV->getAttributes(); 567321369Sdim if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) { 568321369Sdim SectionName = Attrs.getAttribute("bss-section").getValueAsString(); 569321369Sdim } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) { 570321369Sdim SectionName = Attrs.getAttribute("rodata-section").getValueAsString(); 571360784Sdim } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) { 572360784Sdim SectionName = Attrs.getAttribute("relro-section").getValueAsString(); 573321369Sdim } else if (Attrs.hasAttribute("data-section") && Kind.isData()) { 574321369Sdim SectionName = Attrs.getAttribute("data-section").getValueAsString(); 575321369Sdim } 576321369Sdim } 577321369Sdim const Function *F = dyn_cast<Function>(GO); 578321369Sdim if (F && F->hasFnAttribute("implicit-section-name")) { 579321369Sdim SectionName = F->getFnAttribute("implicit-section-name").getValueAsString(); 580321369Sdim } 581321369Sdim 582203954Srdivacky // Infer section flags from the section name if we can. 583203954Srdivacky Kind = getELFKindForNamedSection(SectionName, Kind); 584203954Srdivacky 585276479Sdim StringRef Group = ""; 586276479Sdim unsigned Flags = getELFSectionFlags(Kind); 587314564Sdim if (const Comdat *C = getELFComdat(GO)) { 588276479Sdim Group = C->getName(); 589276479Sdim Flags |= ELF::SHF_GROUP; 590276479Sdim } 591321369Sdim 592321369Sdim // A section can have at most one associated section. Put each global with 593321369Sdim // MD_associated in a unique section. 594321369Sdim unsigned UniqueID = MCContext::GenericSectionID; 595321369Sdim const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM); 596321369Sdim if (AssociatedSymbol) { 597321369Sdim UniqueID = NextUniqueID++; 598321369Sdim Flags |= ELF::SHF_LINK_ORDER; 599321369Sdim } 600321369Sdim 601321369Sdim MCSectionELF *Section = getContext().getELFSection( 602321369Sdim SectionName, getELFSectionType(SectionName, Kind), Flags, 603344779Sdim getEntrySizeForKind(Kind), Group, UniqueID, AssociatedSymbol); 604321369Sdim // Make sure that we did not get some other section with incompatible sh_link. 605321369Sdim // This should not be possible due to UniqueID code above. 606341825Sdim assert(Section->getAssociatedSymbol() == AssociatedSymbol && 607341825Sdim "Associated symbol mismatch between sections"); 608321369Sdim return Section; 609203954Srdivacky} 610203954Srdivacky 611288943Sdim/// Return the section prefix name used by options FunctionsSections and 612288943Sdim/// DataSections. 613276479Sdimstatic StringRef getSectionPrefixForGlobal(SectionKind Kind) { 614288943Sdim if (Kind.isText()) 615288943Sdim return ".text"; 616288943Sdim if (Kind.isReadOnly()) 617288943Sdim return ".rodata"; 618288943Sdim if (Kind.isBSS()) 619288943Sdim return ".bss"; 620288943Sdim if (Kind.isThreadData()) 621288943Sdim return ".tdata"; 622288943Sdim if (Kind.isThreadBSS()) 623288943Sdim return ".tbss"; 624296417Sdim if (Kind.isData()) 625288943Sdim return ".data"; 626207618Srdivacky assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 627288943Sdim return ".data.rel.ro"; 628207618Srdivacky} 629207618Srdivacky 630321369Sdimstatic MCSectionELF *selectELFSectionForGlobal( 631321369Sdim MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 632321369Sdim const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, 633321369Sdim unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) { 634218893Sdim 635288943Sdim StringRef Group = ""; 636314564Sdim if (const Comdat *C = getELFComdat(GO)) { 637288943Sdim Flags |= ELF::SHF_GROUP; 638288943Sdim Group = C->getName(); 639203954Srdivacky } 640203954Srdivacky 641341825Sdim // Get the section entry size based on the kind. 642341825Sdim unsigned EntrySize = getEntrySizeForKind(Kind); 643341825Sdim 644288943Sdim SmallString<128> Name; 645288943Sdim if (Kind.isMergeableCString()) { 646203954Srdivacky // We also need alignment here. 647203954Srdivacky // FIXME: this is getting the alignment of the character, not the 648203954Srdivacky // alignment of the global! 649314564Sdim unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment( 650314564Sdim cast<GlobalVariable>(GO)); 651203954Srdivacky 652288943Sdim std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; 653288943Sdim Name = SizeSpec + utostr(Align); 654288943Sdim } else if (Kind.isMergeableConst()) { 655288943Sdim Name = ".rodata.cst"; 656288943Sdim Name += utostr(EntrySize); 657288943Sdim } else { 658288943Sdim Name = getSectionPrefixForGlobal(Kind); 659203954Srdivacky } 660203954Srdivacky 661314564Sdim if (const auto *F = dyn_cast<Function>(GO)) { 662314564Sdim const auto &OptionalPrefix = F->getSectionPrefix(); 663314564Sdim if (OptionalPrefix) 664314564Sdim Name += *OptionalPrefix; 665314564Sdim } 666314564Sdim 667309124Sdim unsigned UniqueID = MCContext::GenericSectionID; 668341825Sdim if (EmitUniqueSection) { 669341825Sdim if (TM.getUniqueSectionNames()) { 670341825Sdim Name.push_back('.'); 671341825Sdim TM.getNameWithPrefix(Name, GO, Mang, true /*MayAlwaysUsePrivate*/); 672341825Sdim } else { 673341825Sdim UniqueID = *NextUniqueID; 674341825Sdim (*NextUniqueID)++; 675341825Sdim } 676288943Sdim } 677341825Sdim // Use 0 as the unique ID for execute-only text. 678314564Sdim if (Kind.isExecuteOnly()) 679314564Sdim UniqueID = 0; 680288943Sdim return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, 681321369Sdim EntrySize, Group, UniqueID, AssociatedSymbol); 682288943Sdim} 683203954Srdivacky 684288943SdimMCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal( 685314564Sdim const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 686288943Sdim unsigned Flags = getELFSectionFlags(Kind); 687203954Srdivacky 688288943Sdim // If we have -ffunction-section or -fdata-section then we should emit the 689288943Sdim // global value to a uniqued section specifically for it. 690288943Sdim bool EmitUniqueSection = false; 691288943Sdim if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) { 692288943Sdim if (Kind.isText()) 693288943Sdim EmitUniqueSection = TM.getFunctionSections(); 694288943Sdim else 695288943Sdim EmitUniqueSection = TM.getDataSections(); 696288943Sdim } 697314564Sdim EmitUniqueSection |= GO->hasComdat(); 698203954Srdivacky 699321369Sdim const MCSymbolELF *AssociatedSymbol = getAssociatedSymbol(GO, TM); 700321369Sdim if (AssociatedSymbol) { 701321369Sdim EmitUniqueSection = true; 702321369Sdim Flags |= ELF::SHF_LINK_ORDER; 703321369Sdim } 704321369Sdim 705321369Sdim MCSectionELF *Section = selectELFSectionForGlobal( 706321369Sdim getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags, 707321369Sdim &NextUniqueID, AssociatedSymbol); 708321369Sdim assert(Section->getAssociatedSymbol() == AssociatedSymbol); 709321369Sdim return Section; 710288943Sdim} 711203954Srdivacky 712288943SdimMCSection *TargetLoweringObjectFileELF::getSectionForJumpTable( 713314564Sdim const Function &F, const TargetMachine &TM) const { 714288943Sdim // If the function can be removed, produce a unique section so that 715288943Sdim // the table doesn't prevent the removal. 716288943Sdim const Comdat *C = F.getComdat(); 717288943Sdim bool EmitUniqueSection = TM.getFunctionSections() || C; 718288943Sdim if (!EmitUniqueSection) 719288943Sdim return ReadOnlySection; 720203954Srdivacky 721288943Sdim return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(), 722321369Sdim getMangler(), TM, EmitUniqueSection, 723321369Sdim ELF::SHF_ALLOC, &NextUniqueID, 724321369Sdim /* AssociatedSymbol */ nullptr); 725203954Srdivacky} 726203954Srdivacky 727288943Sdimbool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection( 728288943Sdim bool UsesLabelDifference, const Function &F) const { 729288943Sdim // We can always create relative relocations, so use another section 730288943Sdim // that can be marked non-executable. 731288943Sdim return false; 732288943Sdim} 733288943Sdim 734288943Sdim/// Given a mergeable constant with the specified size and relocation 735288943Sdim/// information, return a section that it should be placed in. 736296417SdimMCSection *TargetLoweringObjectFileELF::getSectionForConstant( 737309124Sdim const DataLayout &DL, SectionKind Kind, const Constant *C, 738309124Sdim unsigned &Align) const { 739203954Srdivacky if (Kind.isMergeableConst4() && MergeableConst4Section) 740203954Srdivacky return MergeableConst4Section; 741203954Srdivacky if (Kind.isMergeableConst8() && MergeableConst8Section) 742203954Srdivacky return MergeableConst8Section; 743203954Srdivacky if (Kind.isMergeableConst16() && MergeableConst16Section) 744203954Srdivacky return MergeableConst16Section; 745309124Sdim if (Kind.isMergeableConst32() && MergeableConst32Section) 746309124Sdim return MergeableConst32Section; 747203954Srdivacky if (Kind.isReadOnly()) 748203954Srdivacky return ReadOnlySection; 749203954Srdivacky 750203954Srdivacky assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 751203954Srdivacky return DataRelROSection; 752203954Srdivacky} 753203954Srdivacky 754288943Sdimstatic MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray, 755288943Sdim bool IsCtor, unsigned Priority, 756288943Sdim const MCSymbol *KeySym) { 757280031Sdim std::string Name; 758280031Sdim unsigned Type; 759280031Sdim unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 760280031Sdim StringRef COMDAT = KeySym ? KeySym->getName() : ""; 761234353Sdim 762280031Sdim if (KeySym) 763280031Sdim Flags |= ELF::SHF_GROUP; 764280031Sdim 765239462Sdim if (UseInitArray) { 766280031Sdim if (IsCtor) { 767280031Sdim Type = ELF::SHT_INIT_ARRAY; 768280031Sdim Name = ".init_array"; 769280031Sdim } else { 770280031Sdim Type = ELF::SHT_FINI_ARRAY; 771280031Sdim Name = ".fini_array"; 772280031Sdim } 773280031Sdim if (Priority != 65535) { 774280031Sdim Name += '.'; 775280031Sdim Name += utostr(Priority); 776280031Sdim } 777239462Sdim } else { 778280031Sdim // The default scheme is .ctor / .dtor, so we have to invert the priority 779280031Sdim // numbering. 780280031Sdim if (IsCtor) 781280031Sdim Name = ".ctors"; 782280031Sdim else 783280031Sdim Name = ".dtors"; 784327952Sdim if (Priority != 65535) 785327952Sdim raw_string_ostream(Name) << format(".%05u", 65535 - Priority); 786280031Sdim Type = ELF::SHT_PROGBITS; 787239462Sdim } 788280031Sdim 789288943Sdim return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT); 790234353Sdim} 791234353Sdim 792288943SdimMCSection *TargetLoweringObjectFileELF::getStaticCtorSection( 793280031Sdim unsigned Priority, const MCSymbol *KeySym) const { 794280031Sdim return getStaticStructorSection(getContext(), UseInitArray, true, Priority, 795280031Sdim KeySym); 796280031Sdim} 797280031Sdim 798288943SdimMCSection *TargetLoweringObjectFileELF::getStaticDtorSection( 799276479Sdim unsigned Priority, const MCSymbol *KeySym) const { 800280031Sdim return getStaticStructorSection(getContext(), UseInitArray, false, Priority, 801280031Sdim KeySym); 802234353Sdim} 803234353Sdim 804309124Sdimconst MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference( 805314564Sdim const GlobalValue *LHS, const GlobalValue *RHS, 806309124Sdim const TargetMachine &TM) const { 807309124Sdim // We may only use a PLT-relative relocation to refer to unnamed_addr 808309124Sdim // functions. 809309124Sdim if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 810309124Sdim return nullptr; 811309124Sdim 812309124Sdim // Basic sanity checks. 813309124Sdim if (LHS->getType()->getPointerAddressSpace() != 0 || 814309124Sdim RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 815309124Sdim RHS->isThreadLocal()) 816309124Sdim return nullptr; 817309124Sdim 818309124Sdim return MCBinaryExpr::createSub( 819314564Sdim MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind, 820309124Sdim getContext()), 821314564Sdim MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 822309124Sdim} 823309124Sdim 824344779SdimMCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const { 825344779Sdim // Use ".GCC.command.line" since this feature is to support clang's 826344779Sdim // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the 827344779Sdim // same name. 828344779Sdim return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS, 829344779Sdim ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, ""); 830344779Sdim} 831344779Sdim 832239462Sdimvoid 833239462SdimTargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 834239462Sdim UseInitArray = UseInitArray_; 835314564Sdim MCContext &Ctx = getContext(); 836314564Sdim if (!UseInitArray) { 837314564Sdim StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS, 838314564Sdim ELF::SHF_ALLOC | ELF::SHF_WRITE); 839314564Sdim 840314564Sdim StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS, 841314564Sdim ELF::SHF_ALLOC | ELF::SHF_WRITE); 842239462Sdim return; 843314564Sdim } 844239462Sdim 845314564Sdim StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY, 846314564Sdim ELF::SHF_WRITE | ELF::SHF_ALLOC); 847314564Sdim StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, 848314564Sdim ELF::SHF_WRITE | ELF::SHF_ALLOC); 849239462Sdim} 850239462Sdim 851203954Srdivacky//===----------------------------------------------------------------------===// 852203954Srdivacky// MachO 853203954Srdivacky//===----------------------------------------------------------------------===// 854203954Srdivacky 855288943SdimTargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() 856288943Sdim : TargetLoweringObjectFile() { 857288943Sdim SupportIndirectSymViaGOTPCRel = true; 858276479Sdim} 859276479Sdim 860314564Sdimvoid TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx, 861314564Sdim const TargetMachine &TM) { 862314564Sdim TargetLoweringObjectFile::Initialize(Ctx, TM); 863314564Sdim if (TM.getRelocationModel() == Reloc::Static) { 864314564Sdim StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0, 865314564Sdim SectionKind::getData()); 866314564Sdim StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0, 867314564Sdim SectionKind::getData()); 868314564Sdim } else { 869314564Sdim StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func", 870314564Sdim MachO::S_MOD_INIT_FUNC_POINTERS, 871314564Sdim SectionKind::getData()); 872314564Sdim StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func", 873314564Sdim MachO::S_MOD_TERM_FUNC_POINTERS, 874314564Sdim SectionKind::getData()); 875314564Sdim } 876344779Sdim 877344779Sdim PersonalityEncoding = 878344779Sdim dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 879344779Sdim LSDAEncoding = dwarf::DW_EH_PE_pcrel; 880344779Sdim TTypeEncoding = 881344779Sdim dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 882314564Sdim} 883314564Sdim 884341825Sdimvoid TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer, 885341825Sdim Module &M) const { 886249423Sdim // Emit the linker options if present. 887321369Sdim if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 888360784Sdim for (const auto *Option : LinkerOptions->operands()) { 889249423Sdim SmallVector<std::string, 4> StrOptions; 890309124Sdim for (const auto &Piece : cast<MDNode>(Option)->operands()) 891309124Sdim StrOptions.push_back(cast<MDString>(Piece)->getString()); 892249423Sdim Streamer.EmitLinkerOptions(StrOptions); 893249423Sdim } 894249423Sdim } 895249423Sdim 896321369Sdim unsigned VersionVal = 0; 897321369Sdim unsigned ImageInfoFlags = 0; 898321369Sdim StringRef SectionVal; 899321369Sdim 900321369Sdim GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal); 901321369Sdim 902234353Sdim // The section is mandatory. If we don't have it, then we don't have GC info. 903321369Sdim if (SectionVal.empty()) 904321369Sdim return; 905234353Sdim 906234353Sdim StringRef Segment, Section; 907234353Sdim unsigned TAA = 0, StubSize = 0; 908234353Sdim bool TAAParsed; 909234353Sdim std::string ErrorCode = 910234353Sdim MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, 911234353Sdim TAA, TAAParsed, StubSize); 912234353Sdim if (!ErrorCode.empty()) 913234353Sdim // If invalid, report the error with report_fatal_error. 914234353Sdim report_fatal_error("Invalid section specifier '" + Section + "': " + 915234353Sdim ErrorCode + "."); 916234353Sdim 917234353Sdim // Get the section. 918288943Sdim MCSectionMachO *S = getContext().getMachOSection( 919296417Sdim Segment, Section, TAA, StubSize, SectionKind::getData()); 920234353Sdim Streamer.SwitchSection(S); 921234353Sdim Streamer.EmitLabel(getContext(). 922288943Sdim getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 923234353Sdim Streamer.EmitIntValue(VersionVal, 4); 924239462Sdim Streamer.EmitIntValue(ImageInfoFlags, 4); 925234353Sdim Streamer.AddBlankLine(); 926234353Sdim} 927234353Sdim 928276479Sdimstatic void checkMachOComdat(const GlobalValue *GV) { 929276479Sdim const Comdat *C = GV->getComdat(); 930276479Sdim if (!C) 931276479Sdim return; 932276479Sdim 933276479Sdim report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() + 934276479Sdim "' cannot be lowered."); 935276479Sdim} 936276479Sdim 937288943SdimMCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( 938314564Sdim const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 939203954Srdivacky // Parse the section specifier and create it if valid. 940203954Srdivacky StringRef Segment, Section; 941221345Sdim unsigned TAA = 0, StubSize = 0; 942221345Sdim bool TAAParsed; 943276479Sdim 944314564Sdim checkMachOComdat(GO); 945276479Sdim 946203954Srdivacky std::string ErrorCode = 947314564Sdim MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section, 948221345Sdim TAA, TAAParsed, StubSize); 949203954Srdivacky if (!ErrorCode.empty()) { 950207618Srdivacky // If invalid, report the error with report_fatal_error. 951314564Sdim report_fatal_error("Global variable '" + GO->getName() + 952234353Sdim "' has an invalid section specifier '" + 953314564Sdim GO->getSection() + "': " + ErrorCode + "."); 954203954Srdivacky } 955203954Srdivacky 956203954Srdivacky // Get the section. 957288943Sdim MCSectionMachO *S = 958288943Sdim getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 959203954Srdivacky 960219077Sdim // If TAA wasn't set by ParseSectionSpecifier() above, 961219077Sdim // use the value returned by getMachOSection() as a default. 962221345Sdim if (!TAAParsed) 963219077Sdim TAA = S->getTypeAndAttributes(); 964219077Sdim 965203954Srdivacky // Okay, now that we got the section, verify that the TAA & StubSize agree. 966203954Srdivacky // If the user declared multiple globals with different section flags, we need 967203954Srdivacky // to reject it here. 968203954Srdivacky if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 969207618Srdivacky // If invalid, report the error with report_fatal_error. 970314564Sdim report_fatal_error("Global variable '" + GO->getName() + 971234353Sdim "' section type or attributes does not match previous" 972234353Sdim " section specifier"); 973203954Srdivacky } 974203954Srdivacky 975203954Srdivacky return S; 976203954Srdivacky} 977203954Srdivacky 978288943SdimMCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal( 979314564Sdim const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 980314564Sdim checkMachOComdat(GO); 981261991Sdim 982261991Sdim // Handle thread local data. 983261991Sdim if (Kind.isThreadBSS()) return TLSBSSSection; 984261991Sdim if (Kind.isThreadData()) return TLSDataSection; 985261991Sdim 986203954Srdivacky if (Kind.isText()) 987314564Sdim return GO->isWeakForLinker() ? TextCoalSection : TextSection; 988203954Srdivacky 989203954Srdivacky // If this is weak/linkonce, put this in a coalescable section, either in text 990203954Srdivacky // or data depending on if it is writable. 991314564Sdim if (GO->isWeakForLinker()) { 992203954Srdivacky if (Kind.isReadOnly()) 993203954Srdivacky return ConstTextCoalSection; 994341825Sdim if (Kind.isReadOnlyWithRel()) 995341825Sdim return ConstDataCoalSection; 996203954Srdivacky return DataCoalSection; 997203954Srdivacky } 998203954Srdivacky 999203954Srdivacky // FIXME: Alignment check should be handled by section classifier. 1000204961Srdivacky if (Kind.isMergeable1ByteCString() && 1001314564Sdim GO->getParent()->getDataLayout().getPreferredAlignment( 1002314564Sdim cast<GlobalVariable>(GO)) < 32) 1003204961Srdivacky return CStringSection; 1004218893Sdim 1005204961Srdivacky // Do not put 16-bit arrays in the UString section if they have an 1006204961Srdivacky // externally visible label, this runs into issues with certain linker 1007204961Srdivacky // versions. 1008314564Sdim if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() && 1009314564Sdim GO->getParent()->getDataLayout().getPreferredAlignment( 1010314564Sdim cast<GlobalVariable>(GO)) < 32) 1011204961Srdivacky return UStringSection; 1012203954Srdivacky 1013280031Sdim // With MachO only variables whose corresponding symbol starts with 'l' or 1014280031Sdim // 'L' can be merged, so we only try merging GVs with private linkage. 1015314564Sdim if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) { 1016203954Srdivacky if (Kind.isMergeableConst4()) 1017203954Srdivacky return FourByteConstantSection; 1018203954Srdivacky if (Kind.isMergeableConst8()) 1019203954Srdivacky return EightByteConstantSection; 1020276479Sdim if (Kind.isMergeableConst16()) 1021203954Srdivacky return SixteenByteConstantSection; 1022203954Srdivacky } 1023203954Srdivacky 1024203954Srdivacky // Otherwise, if it is readonly, but not something we can specially optimize, 1025203954Srdivacky // just drop it in .const. 1026203954Srdivacky if (Kind.isReadOnly()) 1027203954Srdivacky return ReadOnlySection; 1028203954Srdivacky 1029203954Srdivacky // If this is marked const, put it into a const section. But if the dynamic 1030203954Srdivacky // linker needs to write to it, put it in the data segment. 1031203954Srdivacky if (Kind.isReadOnlyWithRel()) 1032203954Srdivacky return ConstDataSection; 1033203954Srdivacky 1034203954Srdivacky // Put zero initialized globals with strong external linkage in the 1035203954Srdivacky // DATA, __common section with the .zerofill directive. 1036203954Srdivacky if (Kind.isBSSExtern()) 1037203954Srdivacky return DataCommonSection; 1038203954Srdivacky 1039203954Srdivacky // Put zero initialized globals with local linkage in __DATA,__bss directive 1040203954Srdivacky // with the .zerofill directive (aka .lcomm). 1041203954Srdivacky if (Kind.isBSSLocal()) 1042203954Srdivacky return DataBSSSection; 1043218893Sdim 1044203954Srdivacky // Otherwise, just drop the variable in the normal data section. 1045203954Srdivacky return DataSection; 1046203954Srdivacky} 1047203954Srdivacky 1048296417SdimMCSection *TargetLoweringObjectFileMachO::getSectionForConstant( 1049309124Sdim const DataLayout &DL, SectionKind Kind, const Constant *C, 1050309124Sdim unsigned &Align) const { 1051203954Srdivacky // If this constant requires a relocation, we have to put it in the data 1052203954Srdivacky // segment, not in the text segment. 1053296417Sdim if (Kind.isData() || Kind.isReadOnlyWithRel()) 1054203954Srdivacky return ConstDataSection; 1055203954Srdivacky 1056203954Srdivacky if (Kind.isMergeableConst4()) 1057203954Srdivacky return FourByteConstantSection; 1058203954Srdivacky if (Kind.isMergeableConst8()) 1059203954Srdivacky return EightByteConstantSection; 1060276479Sdim if (Kind.isMergeableConst16()) 1061203954Srdivacky return SixteenByteConstantSection; 1062203954Srdivacky return ReadOnlySection; // .const 1063203954Srdivacky} 1064203954Srdivacky 1065276479Sdimconst MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference( 1066314564Sdim const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 1067314564Sdim MachineModuleInfo *MMI, MCStreamer &Streamer) const { 1068203954Srdivacky // The mach-o version of this method defaults to returning a stub reference. 1069203954Srdivacky 1070204642Srdivacky if (Encoding & DW_EH_PE_indirect) { 1071204642Srdivacky MachineModuleInfoMachO &MachOMMI = 1072204642Srdivacky MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1073204642Srdivacky 1074314564Sdim MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 1075204642Srdivacky 1076204642Srdivacky // Add information about the stub reference to MachOMMI so that the stub 1077204642Srdivacky // gets emitted by the asmprinter. 1078309124Sdim MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 1079276479Sdim if (!StubSym.getPointer()) { 1080314564Sdim MCSymbol *Sym = TM.getSymbol(GV); 1081205218Srdivacky StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 1082204642Srdivacky } 1083203954Srdivacky 1084203954Srdivacky return TargetLoweringObjectFile:: 1085288943Sdim getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 1086321369Sdim Encoding & ~DW_EH_PE_indirect, Streamer); 1087203954Srdivacky } 1088203954Srdivacky 1089314564Sdim return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 1090314564Sdim MMI, Streamer); 1091203954Srdivacky} 1092203954Srdivacky 1093276479SdimMCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol( 1094314564Sdim const GlobalValue *GV, const TargetMachine &TM, 1095276479Sdim MachineModuleInfo *MMI) const { 1096221345Sdim // The mach-o version of this method defaults to returning a stub reference. 1097221345Sdim MachineModuleInfoMachO &MachOMMI = 1098221345Sdim MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1099221345Sdim 1100314564Sdim MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 1101221345Sdim 1102221345Sdim // Add information about the stub reference to MachOMMI so that the stub 1103221345Sdim // gets emitted by the asmprinter. 1104234353Sdim MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 1105276479Sdim if (!StubSym.getPointer()) { 1106314564Sdim MCSymbol *Sym = TM.getSymbol(GV); 1107221345Sdim StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 1108221345Sdim } 1109221345Sdim 1110221345Sdim return SSym; 1111221345Sdim} 1112221345Sdim 1113288943Sdimconst MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel( 1114360784Sdim const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, 1115360784Sdim int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const { 1116296417Sdim // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation 1117288943Sdim // as 64-bit do, we replace the GOT equivalent by accessing the final symbol 1118288943Sdim // through a non_lazy_ptr stub instead. One advantage is that it allows the 1119288943Sdim // computation of deltas to final external symbols. Example: 1120288943Sdim // 1121288943Sdim // _extgotequiv: 1122288943Sdim // .long _extfoo 1123288943Sdim // 1124288943Sdim // _delta: 1125288943Sdim // .long _extgotequiv-_delta 1126288943Sdim // 1127288943Sdim // is transformed to: 1128288943Sdim // 1129288943Sdim // _delta: 1130288943Sdim // .long L_extfoo$non_lazy_ptr-(_delta+0) 1131288943Sdim // 1132288943Sdim // .section __IMPORT,__pointers,non_lazy_symbol_pointers 1133288943Sdim // L_extfoo$non_lazy_ptr: 1134288943Sdim // .indirect_symbol _extfoo 1135288943Sdim // .long 0 1136288943Sdim // 1137344779Sdim // The indirect symbol table (and sections of non_lazy_symbol_pointers type) 1138344779Sdim // may point to both local (same translation unit) and global (other 1139344779Sdim // translation units) symbols. Example: 1140344779Sdim // 1141344779Sdim // .section __DATA,__pointers,non_lazy_symbol_pointers 1142344779Sdim // L1: 1143344779Sdim // .indirect_symbol _myGlobal 1144344779Sdim // .long 0 1145344779Sdim // L2: 1146344779Sdim // .indirect_symbol _myLocal 1147344779Sdim // .long _myLocal 1148344779Sdim // 1149344779Sdim // If the symbol is local, instead of the symbol's index, the assembler 1150344779Sdim // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table. 1151344779Sdim // Then the linker will notice the constant in the table and will look at the 1152344779Sdim // content of the symbol. 1153288943Sdim MachineModuleInfoMachO &MachOMMI = 1154288943Sdim MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1155288943Sdim MCContext &Ctx = getContext(); 1156288943Sdim 1157288943Sdim // The offset must consider the original displacement from the base symbol 1158288943Sdim // since 32-bit targets don't have a GOTPCREL to fold the PC displacement. 1159288943Sdim Offset = -MV.getConstant(); 1160288943Sdim const MCSymbol *BaseSym = &MV.getSymB()->getSymbol(); 1161288943Sdim 1162288943Sdim // Access the final symbol via sym$non_lazy_ptr and generate the appropriated 1163288943Sdim // non_lazy_ptr stubs. 1164288943Sdim SmallString<128> Name; 1165288943Sdim StringRef Suffix = "$non_lazy_ptr"; 1166296417Sdim Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix(); 1167288943Sdim Name += Sym->getName(); 1168288943Sdim Name += Suffix; 1169288943Sdim MCSymbol *Stub = Ctx.getOrCreateSymbol(Name); 1170288943Sdim 1171288943Sdim MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub); 1172360784Sdim 1173360784Sdim if (!StubSym.getPointer()) 1174344779Sdim StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym), 1175360784Sdim !GV->hasLocalLinkage()); 1176288943Sdim 1177288943Sdim const MCExpr *BSymExpr = 1178288943Sdim MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx); 1179288943Sdim const MCExpr *LHS = 1180288943Sdim MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx); 1181288943Sdim 1182288943Sdim if (!Offset) 1183288943Sdim return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx); 1184288943Sdim 1185288943Sdim const MCExpr *RHS = 1186288943Sdim MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx); 1187288943Sdim return MCBinaryExpr::createSub(LHS, RHS, Ctx); 1188288943Sdim} 1189288943Sdim 1190296417Sdimstatic bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, 1191296417Sdim const MCSection &Section) { 1192296417Sdim if (!AsmInfo.isSectionAtomizableBySymbols(Section)) 1193296417Sdim return true; 1194296417Sdim 1195296417Sdim // If it is not dead stripped, it is safe to use private labels. 1196296417Sdim const MCSectionMachO &SMO = cast<MCSectionMachO>(Section); 1197296417Sdim if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP)) 1198296417Sdim return true; 1199296417Sdim 1200296417Sdim return false; 1201296417Sdim} 1202296417Sdim 1203296417Sdimvoid TargetLoweringObjectFileMachO::getNameWithPrefix( 1204314564Sdim SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1205296417Sdim const TargetMachine &TM) const { 1206314564Sdim bool CannotUsePrivateLabel = true; 1207314564Sdim if (auto *GO = GV->getBaseObject()) { 1208314564Sdim SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM); 1209314564Sdim const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM); 1210314564Sdim CannotUsePrivateLabel = 1211314564Sdim !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection); 1212314564Sdim } 1213314564Sdim getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1214296417Sdim} 1215296417Sdim 1216203954Srdivacky//===----------------------------------------------------------------------===// 1217203954Srdivacky// COFF 1218203954Srdivacky//===----------------------------------------------------------------------===// 1219203954Srdivacky 1220208599Srdivackystatic unsigned 1221309124SdimgetCOFFSectionFlags(SectionKind K, const TargetMachine &TM) { 1222208599Srdivacky unsigned Flags = 0; 1223309124Sdim bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb; 1224208599Srdivacky 1225210299Sed if (K.isMetadata()) 1226208599Srdivacky Flags |= 1227210299Sed COFF::IMAGE_SCN_MEM_DISCARDABLE; 1228208599Srdivacky else if (K.isText()) 1229208599Srdivacky Flags |= 1230210299Sed COFF::IMAGE_SCN_MEM_EXECUTE | 1231218893Sdim COFF::IMAGE_SCN_MEM_READ | 1232309124Sdim COFF::IMAGE_SCN_CNT_CODE | 1233309124Sdim (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0); 1234280031Sdim else if (K.isBSS()) 1235208599Srdivacky Flags |= 1236210299Sed COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 1237210299Sed COFF::IMAGE_SCN_MEM_READ | 1238210299Sed COFF::IMAGE_SCN_MEM_WRITE; 1239234353Sdim else if (K.isThreadLocal()) 1240234353Sdim Flags |= 1241234353Sdim COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1242234353Sdim COFF::IMAGE_SCN_MEM_READ | 1243234353Sdim COFF::IMAGE_SCN_MEM_WRITE; 1244280031Sdim else if (K.isReadOnly() || K.isReadOnlyWithRel()) 1245208599Srdivacky Flags |= 1246210299Sed COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1247210299Sed COFF::IMAGE_SCN_MEM_READ; 1248208599Srdivacky else if (K.isWriteable()) 1249208599Srdivacky Flags |= 1250210299Sed COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1251210299Sed COFF::IMAGE_SCN_MEM_READ | 1252210299Sed COFF::IMAGE_SCN_MEM_WRITE; 1253208599Srdivacky 1254208599Srdivacky return Flags; 1255208599Srdivacky} 1256208599Srdivacky 1257276479Sdimstatic const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) { 1258276479Sdim const Comdat *C = GV->getComdat(); 1259276479Sdim assert(C && "expected GV to have a Comdat!"); 1260276479Sdim 1261276479Sdim StringRef ComdatGVName = C->getName(); 1262276479Sdim const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName); 1263276479Sdim if (!ComdatGV) 1264276479Sdim report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 1265276479Sdim "' does not exist."); 1266276479Sdim 1267276479Sdim if (ComdatGV->getComdat() != C) 1268276479Sdim report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 1269280031Sdim "' is not a key for its COMDAT."); 1270276479Sdim 1271276479Sdim return ComdatGV; 1272276479Sdim} 1273276479Sdim 1274276479Sdimstatic int getSelectionForCOFF(const GlobalValue *GV) { 1275276479Sdim if (const Comdat *C = GV->getComdat()) { 1276276479Sdim const GlobalValue *ComdatKey = getComdatGVForCOFF(GV); 1277276479Sdim if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey)) 1278276479Sdim ComdatKey = GA->getBaseObject(); 1279276479Sdim if (ComdatKey == GV) { 1280276479Sdim switch (C->getSelectionKind()) { 1281276479Sdim case Comdat::Any: 1282276479Sdim return COFF::IMAGE_COMDAT_SELECT_ANY; 1283276479Sdim case Comdat::ExactMatch: 1284276479Sdim return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH; 1285276479Sdim case Comdat::Largest: 1286276479Sdim return COFF::IMAGE_COMDAT_SELECT_LARGEST; 1287276479Sdim case Comdat::NoDuplicates: 1288276479Sdim return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1289276479Sdim case Comdat::SameSize: 1290276479Sdim return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE; 1291276479Sdim } 1292276479Sdim } else { 1293276479Sdim return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; 1294276479Sdim } 1295276479Sdim } 1296276479Sdim return 0; 1297276479Sdim} 1298276479Sdim 1299288943SdimMCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( 1300314564Sdim const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1301249423Sdim int Selection = 0; 1302309124Sdim unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1303314564Sdim StringRef Name = GO->getSection(); 1304276479Sdim StringRef COMDATSymName = ""; 1305314564Sdim if (GO->hasComdat()) { 1306314564Sdim Selection = getSelectionForCOFF(GO); 1307276479Sdim const GlobalValue *ComdatGV; 1308276479Sdim if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) 1309314564Sdim ComdatGV = getComdatGVForCOFF(GO); 1310276479Sdim else 1311314564Sdim ComdatGV = GO; 1312276479Sdim 1313276479Sdim if (!ComdatGV->hasPrivateLinkage()) { 1314314564Sdim MCSymbol *Sym = TM.getSymbol(ComdatGV); 1315276479Sdim COMDATSymName = Sym->getName(); 1316276479Sdim Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1317276479Sdim } else { 1318276479Sdim Selection = 0; 1319276479Sdim } 1320249423Sdim } 1321309124Sdim 1322309124Sdim return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName, 1323261991Sdim Selection); 1324203954Srdivacky} 1325203954Srdivacky 1326341825Sdimstatic StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 1327203954Srdivacky if (Kind.isText()) 1328276479Sdim return ".text"; 1329276479Sdim if (Kind.isBSS()) 1330276479Sdim return ".bss"; 1331276479Sdim if (Kind.isThreadLocal()) 1332276479Sdim return ".tls$"; 1333280031Sdim if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1334280031Sdim return ".rdata"; 1335280031Sdim return ".data"; 1336203954Srdivacky} 1337203954Srdivacky 1338288943SdimMCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal( 1339314564Sdim const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1340276479Sdim // If we have -ffunction-sections then we should emit the global value to a 1341276479Sdim // uniqued section specifically for it. 1342276479Sdim bool EmitUniquedSection; 1343276479Sdim if (Kind.isText()) 1344276479Sdim EmitUniquedSection = TM.getFunctionSections(); 1345276479Sdim else 1346276479Sdim EmitUniquedSection = TM.getDataSections(); 1347203954Srdivacky 1348314564Sdim if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) { 1349341825Sdim SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind); 1350341825Sdim 1351309124Sdim unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1352208599Srdivacky 1353210299Sed Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1354314564Sdim int Selection = getSelectionForCOFF(GO); 1355276479Sdim if (!Selection) 1356276479Sdim Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1357276479Sdim const GlobalValue *ComdatGV; 1358314564Sdim if (GO->hasComdat()) 1359314564Sdim ComdatGV = getComdatGVForCOFF(GO); 1360276479Sdim else 1361314564Sdim ComdatGV = GO; 1362208599Srdivacky 1363309124Sdim unsigned UniqueID = MCContext::GenericSectionID; 1364309124Sdim if (EmitUniquedSection) 1365309124Sdim UniqueID = NextUniqueID++; 1366309124Sdim 1367276479Sdim if (!ComdatGV->hasPrivateLinkage()) { 1368314564Sdim MCSymbol *Sym = TM.getSymbol(ComdatGV); 1369276479Sdim StringRef COMDATSymName = Sym->getName(); 1370341825Sdim 1371341825Sdim // Append "$symbol" to the section name *before* IR-level mangling is 1372341825Sdim // applied when targetting mingw. This is what GCC does, and the ld.bfd 1373341825Sdim // COFF linker will not properly handle comdats otherwise. 1374341825Sdim if (getTargetTriple().isWindowsGNUEnvironment()) 1375341825Sdim raw_svector_ostream(Name) << '$' << ComdatGV->getName(); 1376341825Sdim 1377276479Sdim return getContext().getCOFFSection(Name, Characteristics, Kind, 1378309124Sdim COMDATSymName, Selection, UniqueID); 1379288943Sdim } else { 1380288943Sdim SmallString<256> TmpData; 1381314564Sdim getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true); 1382288943Sdim return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData, 1383309124Sdim Selection, UniqueID); 1384276479Sdim } 1385203954Srdivacky } 1386203954Srdivacky 1387203954Srdivacky if (Kind.isText()) 1388261991Sdim return TextSection; 1389203954Srdivacky 1390234353Sdim if (Kind.isThreadLocal()) 1391261991Sdim return TLSDataSection; 1392234353Sdim 1393280031Sdim if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1394261991Sdim return ReadOnlySection; 1395261991Sdim 1396276479Sdim // Note: we claim that common symbols are put in BSSSection, but they are 1397276479Sdim // really emitted with the magic .comm directive, which creates a symbol table 1398276479Sdim // entry but not a section. 1399276479Sdim if (Kind.isBSS() || Kind.isCommon()) 1400261991Sdim return BSSSection; 1401261991Sdim 1402261991Sdim return DataSection; 1403203954Srdivacky} 1404203954Srdivacky 1405288943Sdimvoid TargetLoweringObjectFileCOFF::getNameWithPrefix( 1406314564Sdim SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1407296417Sdim const TargetMachine &TM) const { 1408296417Sdim bool CannotUsePrivateLabel = false; 1409288943Sdim if (GV->hasPrivateLinkage() && 1410288943Sdim ((isa<Function>(GV) && TM.getFunctionSections()) || 1411288943Sdim (isa<GlobalVariable>(GV) && TM.getDataSections()))) 1412288943Sdim CannotUsePrivateLabel = true; 1413288943Sdim 1414314564Sdim getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1415276479Sdim} 1416276479Sdim 1417288943SdimMCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable( 1418314564Sdim const Function &F, const TargetMachine &TM) const { 1419288943Sdim // If the function can be removed, produce a unique section so that 1420288943Sdim // the table doesn't prevent the removal. 1421288943Sdim const Comdat *C = F.getComdat(); 1422288943Sdim bool EmitUniqueSection = TM.getFunctionSections() || C; 1423288943Sdim if (!EmitUniqueSection) 1424288943Sdim return ReadOnlySection; 1425288943Sdim 1426288943Sdim // FIXME: we should produce a symbol for F instead. 1427288943Sdim if (F.hasPrivateLinkage()) 1428288943Sdim return ReadOnlySection; 1429288943Sdim 1430314564Sdim MCSymbol *Sym = TM.getSymbol(&F); 1431288943Sdim StringRef COMDATSymName = Sym->getName(); 1432288943Sdim 1433288943Sdim SectionKind Kind = SectionKind::getReadOnly(); 1434341825Sdim StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind); 1435309124Sdim unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1436288943Sdim Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1437309124Sdim unsigned UniqueID = NextUniqueID++; 1438288943Sdim 1439341825Sdim return getContext().getCOFFSection( 1440341825Sdim SecName, Characteristics, Kind, COMDATSymName, 1441341825Sdim COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); 1442288943Sdim} 1443288943Sdim 1444341825Sdimvoid TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer, 1445341825Sdim Module &M) const { 1446321369Sdim if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 1447309124Sdim // Emit the linker options to the linker .drectve section. According to the 1448309124Sdim // spec, this section is a space-separated string containing flags for 1449309124Sdim // linker. 1450309124Sdim MCSection *Sec = getDrectveSection(); 1451309124Sdim Streamer.SwitchSection(Sec); 1452360784Sdim for (const auto *Option : LinkerOptions->operands()) { 1453309124Sdim for (const auto &Piece : cast<MDNode>(Option)->operands()) { 1454309124Sdim // Lead with a space for consistency with our dllexport implementation. 1455309124Sdim std::string Directive(" "); 1456309124Sdim Directive.append(cast<MDString>(Piece)->getString()); 1457309124Sdim Streamer.EmitBytes(Directive); 1458309124Sdim } 1459251662Sdim } 1460251662Sdim } 1461321369Sdim 1462321369Sdim unsigned Version = 0; 1463321369Sdim unsigned Flags = 0; 1464321369Sdim StringRef Section; 1465321369Sdim 1466321369Sdim GetObjCImageInfo(M, Version, Flags, Section); 1467321369Sdim if (Section.empty()) 1468321369Sdim return; 1469321369Sdim 1470321369Sdim auto &C = getContext(); 1471321369Sdim auto *S = C.getCOFFSection( 1472321369Sdim Section, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, 1473321369Sdim SectionKind::getReadOnly()); 1474321369Sdim Streamer.SwitchSection(S); 1475321369Sdim Streamer.EmitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 1476321369Sdim Streamer.EmitIntValue(Version, 4); 1477321369Sdim Streamer.EmitIntValue(Flags, 4); 1478321369Sdim Streamer.AddBlankLine(); 1479251662Sdim} 1480276479Sdim 1481314564Sdimvoid TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx, 1482314564Sdim const TargetMachine &TM) { 1483314564Sdim TargetLoweringObjectFile::Initialize(Ctx, TM); 1484314564Sdim const Triple &T = TM.getTargetTriple(); 1485353358Sdim if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { 1486314564Sdim StaticCtorSection = 1487314564Sdim Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1488314564Sdim COFF::IMAGE_SCN_MEM_READ, 1489314564Sdim SectionKind::getReadOnly()); 1490314564Sdim StaticDtorSection = 1491314564Sdim Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1492314564Sdim COFF::IMAGE_SCN_MEM_READ, 1493314564Sdim SectionKind::getReadOnly()); 1494314564Sdim } else { 1495314564Sdim StaticCtorSection = Ctx.getCOFFSection( 1496314564Sdim ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1497314564Sdim COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, 1498314564Sdim SectionKind::getData()); 1499314564Sdim StaticDtorSection = Ctx.getCOFFSection( 1500314564Sdim ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1501314564Sdim COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, 1502314564Sdim SectionKind::getData()); 1503314564Sdim } 1504314564Sdim} 1505314564Sdim 1506327952Sdimstatic MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx, 1507327952Sdim const Triple &T, bool IsCtor, 1508327952Sdim unsigned Priority, 1509327952Sdim const MCSymbol *KeySym, 1510327952Sdim MCSectionCOFF *Default) { 1511353358Sdim if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { 1512344779Sdim // If the priority is the default, use .CRT$XCU, possibly associative. 1513344779Sdim if (Priority == 65535) 1514344779Sdim return Ctx.getAssociativeCOFFSection(Default, KeySym, 0); 1515327952Sdim 1516344779Sdim // Otherwise, we need to compute a new section name. Low priorities should 1517344779Sdim // run earlier. The linker will sort sections ASCII-betically, and we need a 1518344779Sdim // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we 1519344779Sdim // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really 1520344779Sdim // low priorities need to sort before 'L', since the CRT uses that 1521344779Sdim // internally, so we use ".CRT$XCA00001" for them. 1522344779Sdim SmallString<24> Name; 1523344779Sdim raw_svector_ostream OS(Name); 1524360784Sdim OS << ".CRT$X" << (IsCtor ? "C" : "T") << 1525360784Sdim (Priority < 200 ? 'A' : 'T') << format("%05u", Priority); 1526344779Sdim MCSectionCOFF *Sec = Ctx.getCOFFSection( 1527344779Sdim Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, 1528344779Sdim SectionKind::getReadOnly()); 1529344779Sdim return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0); 1530344779Sdim } 1531344779Sdim 1532327952Sdim std::string Name = IsCtor ? ".ctors" : ".dtors"; 1533327952Sdim if (Priority != 65535) 1534327952Sdim raw_string_ostream(Name) << format(".%05u", 65535 - Priority); 1535327952Sdim 1536327952Sdim return Ctx.getAssociativeCOFFSection( 1537327952Sdim Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1538327952Sdim COFF::IMAGE_SCN_MEM_READ | 1539327952Sdim COFF::IMAGE_SCN_MEM_WRITE, 1540327952Sdim SectionKind::getData()), 1541327952Sdim KeySym, 0); 1542327952Sdim} 1543327952Sdim 1544288943SdimMCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( 1545276479Sdim unsigned Priority, const MCSymbol *KeySym) const { 1546327952Sdim return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true, 1547327952Sdim Priority, KeySym, 1548327952Sdim cast<MCSectionCOFF>(StaticCtorSection)); 1549276479Sdim} 1550276479Sdim 1551288943SdimMCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( 1552276479Sdim unsigned Priority, const MCSymbol *KeySym) const { 1553327952Sdim return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false, 1554327952Sdim Priority, KeySym, 1555327952Sdim cast<MCSectionCOFF>(StaticDtorSection)); 1556276479Sdim} 1557288943Sdim 1558288943Sdimvoid TargetLoweringObjectFileCOFF::emitLinkerFlagsForGlobal( 1559314564Sdim raw_ostream &OS, const GlobalValue *GV) const { 1560321369Sdim emitLinkerFlagsForGlobalCOFF(OS, GV, getTargetTriple(), getMangler()); 1561321369Sdim} 1562288943Sdim 1563341825Sdimvoid TargetLoweringObjectFileCOFF::emitLinkerFlagsForUsed( 1564341825Sdim raw_ostream &OS, const GlobalValue *GV) const { 1565341825Sdim emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler()); 1566341825Sdim} 1567341825Sdim 1568341825Sdimconst MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference( 1569341825Sdim const GlobalValue *LHS, const GlobalValue *RHS, 1570341825Sdim const TargetMachine &TM) const { 1571341825Sdim const Triple &T = TM.getTargetTriple(); 1572353358Sdim if (T.isOSCygMing()) 1573341825Sdim return nullptr; 1574341825Sdim 1575341825Sdim // Our symbols should exist in address space zero, cowardly no-op if 1576341825Sdim // otherwise. 1577341825Sdim if (LHS->getType()->getPointerAddressSpace() != 0 || 1578341825Sdim RHS->getType()->getPointerAddressSpace() != 0) 1579341825Sdim return nullptr; 1580341825Sdim 1581341825Sdim // Both ptrtoint instructions must wrap global objects: 1582341825Sdim // - Only global variables are eligible for image relative relocations. 1583341825Sdim // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable. 1584341825Sdim // We expect __ImageBase to be a global variable without a section, externally 1585341825Sdim // defined. 1586341825Sdim // 1587341825Sdim // It should look something like this: @__ImageBase = external constant i8 1588341825Sdim if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) || 1589341825Sdim LHS->isThreadLocal() || RHS->isThreadLocal() || 1590341825Sdim RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() || 1591341825Sdim cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection()) 1592341825Sdim return nullptr; 1593341825Sdim 1594341825Sdim return MCSymbolRefExpr::create(TM.getSymbol(LHS), 1595341825Sdim MCSymbolRefExpr::VK_COFF_IMGREL32, 1596341825Sdim getContext()); 1597341825Sdim} 1598341825Sdim 1599341825Sdimstatic std::string APIntToHexString(const APInt &AI) { 1600341825Sdim unsigned Width = (AI.getBitWidth() / 8) * 2; 1601360784Sdim std::string HexString = AI.toString(16, /*Signed=*/false); 1602360784Sdim transform(HexString.begin(), HexString.end(), HexString.begin(), tolower); 1603341825Sdim unsigned Size = HexString.size(); 1604341825Sdim assert(Width >= Size && "hex string is too large!"); 1605341825Sdim HexString.insert(HexString.begin(), Width - Size, '0'); 1606341825Sdim 1607341825Sdim return HexString; 1608341825Sdim} 1609341825Sdim 1610341825Sdimstatic std::string scalarConstantToHexString(const Constant *C) { 1611341825Sdim Type *Ty = C->getType(); 1612341825Sdim if (isa<UndefValue>(C)) { 1613341825Sdim return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits())); 1614341825Sdim } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) { 1615341825Sdim return APIntToHexString(CFP->getValueAPF().bitcastToAPInt()); 1616341825Sdim } else if (const auto *CI = dyn_cast<ConstantInt>(C)) { 1617341825Sdim return APIntToHexString(CI->getValue()); 1618341825Sdim } else { 1619341825Sdim unsigned NumElements; 1620341825Sdim if (isa<VectorType>(Ty)) 1621341825Sdim NumElements = Ty->getVectorNumElements(); 1622341825Sdim else 1623341825Sdim NumElements = Ty->getArrayNumElements(); 1624341825Sdim std::string HexString; 1625341825Sdim for (int I = NumElements - 1, E = -1; I != E; --I) 1626341825Sdim HexString += scalarConstantToHexString(C->getAggregateElement(I)); 1627341825Sdim return HexString; 1628341825Sdim } 1629341825Sdim} 1630341825Sdim 1631341825SdimMCSection *TargetLoweringObjectFileCOFF::getSectionForConstant( 1632341825Sdim const DataLayout &DL, SectionKind Kind, const Constant *C, 1633341825Sdim unsigned &Align) const { 1634341825Sdim if (Kind.isMergeableConst() && C && 1635341825Sdim getContext().getAsmInfo()->hasCOFFComdatConstants()) { 1636341825Sdim // This creates comdat sections with the given symbol name, but unless 1637341825Sdim // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol 1638341825Sdim // will be created with a null storage class, which makes GNU binutils 1639341825Sdim // error out. 1640341825Sdim const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1641341825Sdim COFF::IMAGE_SCN_MEM_READ | 1642341825Sdim COFF::IMAGE_SCN_LNK_COMDAT; 1643341825Sdim std::string COMDATSymName; 1644341825Sdim if (Kind.isMergeableConst4()) { 1645341825Sdim if (Align <= 4) { 1646341825Sdim COMDATSymName = "__real@" + scalarConstantToHexString(C); 1647341825Sdim Align = 4; 1648341825Sdim } 1649341825Sdim } else if (Kind.isMergeableConst8()) { 1650341825Sdim if (Align <= 8) { 1651341825Sdim COMDATSymName = "__real@" + scalarConstantToHexString(C); 1652341825Sdim Align = 8; 1653341825Sdim } 1654341825Sdim } else if (Kind.isMergeableConst16()) { 1655341825Sdim // FIXME: These may not be appropriate for non-x86 architectures. 1656341825Sdim if (Align <= 16) { 1657341825Sdim COMDATSymName = "__xmm@" + scalarConstantToHexString(C); 1658341825Sdim Align = 16; 1659341825Sdim } 1660341825Sdim } else if (Kind.isMergeableConst32()) { 1661341825Sdim if (Align <= 32) { 1662341825Sdim COMDATSymName = "__ymm@" + scalarConstantToHexString(C); 1663341825Sdim Align = 32; 1664341825Sdim } 1665341825Sdim } 1666341825Sdim 1667341825Sdim if (!COMDATSymName.empty()) 1668341825Sdim return getContext().getCOFFSection(".rdata", Characteristics, Kind, 1669341825Sdim COMDATSymName, 1670341825Sdim COFF::IMAGE_COMDAT_SELECT_ANY); 1671341825Sdim } 1672341825Sdim 1673341825Sdim return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, Align); 1674341825Sdim} 1675341825Sdim 1676341825Sdim 1677321369Sdim//===----------------------------------------------------------------------===// 1678321369Sdim// Wasm 1679321369Sdim//===----------------------------------------------------------------------===// 1680288943Sdim 1681341825Sdimstatic const Comdat *getWasmComdat(const GlobalValue *GV) { 1682321369Sdim const Comdat *C = GV->getComdat(); 1683321369Sdim if (!C) 1684341825Sdim return nullptr; 1685288943Sdim 1686341825Sdim if (C->getSelectionKind() != Comdat::Any) 1687341825Sdim report_fatal_error("WebAssembly COMDATs only support " 1688341825Sdim "SelectionKind::Any, '" + C->getName() + "' cannot be " 1689341825Sdim "lowered."); 1690341825Sdim 1691341825Sdim return C; 1692327952Sdim} 1693321369Sdim 1694327952Sdimstatic SectionKind getWasmKindForNamedSection(StringRef Name, SectionKind K) { 1695327952Sdim // If we're told we have function data, then use that. 1696327952Sdim if (K.isText()) 1697327952Sdim return SectionKind::getText(); 1698327952Sdim 1699327952Sdim // Otherwise, ignore whatever section type the generic impl detected and use 1700327952Sdim // a plain data section. 1701327952Sdim return SectionKind::getData(); 1702321369Sdim} 1703321369Sdim 1704321369SdimMCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal( 1705321369Sdim const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1706341825Sdim // We don't support explict section names for functions in the wasm object 1707341825Sdim // format. Each function has to be in its own unique section. 1708341825Sdim if (isa<Function>(GO)) { 1709341825Sdim return SelectSectionForGlobal(GO, Kind, TM); 1710341825Sdim } 1711341825Sdim 1712327952Sdim StringRef Name = GO->getSection(); 1713341825Sdim 1714327952Sdim Kind = getWasmKindForNamedSection(Name, Kind); 1715341825Sdim 1716341825Sdim StringRef Group = ""; 1717341825Sdim if (const Comdat *C = getWasmComdat(GO)) { 1718341825Sdim Group = C->getName(); 1719341825Sdim } 1720341825Sdim 1721353358Sdim MCSectionWasm* Section = 1722353358Sdim getContext().getWasmSection(Name, Kind, Group, 1723353358Sdim MCContext::GenericSectionID); 1724353358Sdim 1725353358Sdim return Section; 1726321369Sdim} 1727321369Sdim 1728327952Sdimstatic MCSectionWasm *selectWasmSectionForGlobal( 1729327952Sdim MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 1730327952Sdim const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) { 1731321369Sdim StringRef Group = ""; 1732341825Sdim if (const Comdat *C = getWasmComdat(GO)) { 1733341825Sdim Group = C->getName(); 1734341825Sdim } 1735321369Sdim 1736321369Sdim bool UniqueSectionNames = TM.getUniqueSectionNames(); 1737321369Sdim SmallString<128> Name = getSectionPrefixForGlobal(Kind); 1738321369Sdim 1739321369Sdim if (const auto *F = dyn_cast<Function>(GO)) { 1740321369Sdim const auto &OptionalPrefix = F->getSectionPrefix(); 1741321369Sdim if (OptionalPrefix) 1742321369Sdim Name += *OptionalPrefix; 1743288943Sdim } 1744288943Sdim 1745321369Sdim if (EmitUniqueSection && UniqueSectionNames) { 1746321369Sdim Name.push_back('.'); 1747321369Sdim TM.getNameWithPrefix(Name, GO, Mang, true); 1748288943Sdim } 1749321369Sdim unsigned UniqueID = MCContext::GenericSectionID; 1750321369Sdim if (EmitUniqueSection && !UniqueSectionNames) { 1751321369Sdim UniqueID = *NextUniqueID; 1752321369Sdim (*NextUniqueID)++; 1753321369Sdim } 1754353358Sdim 1755327952Sdim return Ctx.getWasmSection(Name, Kind, Group, UniqueID); 1756288943Sdim} 1757321369Sdim 1758321369SdimMCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal( 1759321369Sdim const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1760321369Sdim 1761321369Sdim if (Kind.isCommon()) 1762321369Sdim report_fatal_error("mergable sections not supported yet on wasm"); 1763321369Sdim 1764321369Sdim // If we have -ffunction-section or -fdata-section then we should emit the 1765321369Sdim // global value to a uniqued section specifically for it. 1766321369Sdim bool EmitUniqueSection = false; 1767321369Sdim if (Kind.isText()) 1768321369Sdim EmitUniqueSection = TM.getFunctionSections(); 1769321369Sdim else 1770321369Sdim EmitUniqueSection = TM.getDataSections(); 1771321369Sdim EmitUniqueSection |= GO->hasComdat(); 1772321369Sdim 1773321369Sdim return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM, 1774327952Sdim EmitUniqueSection, &NextUniqueID); 1775321369Sdim} 1776321369Sdim 1777321369Sdimbool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection( 1778321369Sdim bool UsesLabelDifference, const Function &F) const { 1779321369Sdim // We can always create relative relocations, so use another section 1780321369Sdim // that can be marked non-executable. 1781321369Sdim return false; 1782321369Sdim} 1783321369Sdim 1784321369Sdimconst MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference( 1785321369Sdim const GlobalValue *LHS, const GlobalValue *RHS, 1786321369Sdim const TargetMachine &TM) const { 1787321369Sdim // We may only use a PLT-relative relocation to refer to unnamed_addr 1788321369Sdim // functions. 1789321369Sdim if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 1790321369Sdim return nullptr; 1791321369Sdim 1792321369Sdim // Basic sanity checks. 1793321369Sdim if (LHS->getType()->getPointerAddressSpace() != 0 || 1794321369Sdim RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 1795321369Sdim RHS->isThreadLocal()) 1796321369Sdim return nullptr; 1797321369Sdim 1798321369Sdim return MCBinaryExpr::createSub( 1799321369Sdim MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None, 1800321369Sdim getContext()), 1801321369Sdim MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 1802321369Sdim} 1803321369Sdim 1804327952Sdimvoid TargetLoweringObjectFileWasm::InitializeWasm() { 1805327952Sdim StaticCtorSection = 1806327952Sdim getContext().getWasmSection(".init_array", SectionKind::getData()); 1807344779Sdim 1808344779Sdim // We don't use PersonalityEncoding and LSDAEncoding because we don't emit 1809344779Sdim // .cfi directives. We use TTypeEncoding to encode typeinfo global variables. 1810344779Sdim TTypeEncoding = dwarf::DW_EH_PE_absptr; 1811321369Sdim} 1812327952Sdim 1813327952SdimMCSection *TargetLoweringObjectFileWasm::getStaticCtorSection( 1814327952Sdim unsigned Priority, const MCSymbol *KeySym) const { 1815327952Sdim return Priority == UINT16_MAX ? 1816327952Sdim StaticCtorSection : 1817327952Sdim getContext().getWasmSection(".init_array." + utostr(Priority), 1818327952Sdim SectionKind::getData()); 1819327952Sdim} 1820327952Sdim 1821327952SdimMCSection *TargetLoweringObjectFileWasm::getStaticDtorSection( 1822327952Sdim unsigned Priority, const MCSymbol *KeySym) const { 1823327952Sdim llvm_unreachable("@llvm.global_dtors should have been lowered already"); 1824327952Sdim return nullptr; 1825327952Sdim} 1826360784Sdim 1827360784Sdim//===----------------------------------------------------------------------===// 1828360784Sdim// XCOFF 1829360784Sdim//===----------------------------------------------------------------------===// 1830360784SdimMCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal( 1831360784Sdim const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1832360784Sdim report_fatal_error("XCOFF explicit sections not yet implemented."); 1833360784Sdim} 1834360784Sdim 1835360784SdimMCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal( 1836360784Sdim const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1837360784Sdim assert(!TM.getFunctionSections() && !TM.getDataSections() && 1838360784Sdim "XCOFF unique sections not yet implemented."); 1839360784Sdim 1840360784Sdim // Common symbols go into a csect with matching name which will get mapped 1841360784Sdim // into the .bss section. 1842360784Sdim if (Kind.isBSSLocal() || Kind.isCommon()) { 1843360784Sdim SmallString<128> Name; 1844360784Sdim getNameWithPrefix(Name, GO, TM); 1845360784Sdim XCOFF::StorageClass SC = 1846360784Sdim TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO); 1847360784Sdim return getContext().getXCOFFSection( 1848360784Sdim Name, Kind.isBSSLocal() ? XCOFF::XMC_BS : XCOFF::XMC_RW, XCOFF::XTY_CM, 1849360784Sdim SC, Kind, /* BeginSymbolName */ nullptr); 1850360784Sdim } 1851360784Sdim 1852360784Sdim if (Kind.isMergeableCString()) { 1853360784Sdim if (!Kind.isMergeable1ByteCString()) 1854360784Sdim report_fatal_error("Unhandled multi-byte mergeable string kind."); 1855360784Sdim 1856360784Sdim unsigned Align = GO->getParent()->getDataLayout().getPreferredAlignment( 1857360784Sdim cast<GlobalVariable>(GO)); 1858360784Sdim 1859360784Sdim unsigned EntrySize = getEntrySizeForKind(Kind); 1860360784Sdim std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; 1861360784Sdim SmallString<128> Name; 1862360784Sdim Name = SizeSpec + utostr(Align); 1863360784Sdim 1864360784Sdim return getContext().getXCOFFSection( 1865360784Sdim Name, XCOFF::XMC_RO, XCOFF::XTY_SD, 1866360784Sdim TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(GO), 1867360784Sdim Kind, /* BeginSymbolName */ nullptr); 1868360784Sdim } 1869360784Sdim 1870360784Sdim if (Kind.isText()) 1871360784Sdim return TextSection; 1872360784Sdim 1873360784Sdim if (Kind.isData() || Kind.isReadOnlyWithRel()) 1874360784Sdim // TODO: We may put this under option control, because user may want to 1875360784Sdim // have read-only data with relocations placed into a read-only section by 1876360784Sdim // the compiler. 1877360784Sdim return DataSection; 1878360784Sdim 1879360784Sdim // Zero initialized data must be emitted to the .data section because external 1880360784Sdim // linkage control sections that get mapped to the .bss section will be linked 1881360784Sdim // as tentative defintions, which is only appropriate for SectionKind::Common. 1882360784Sdim if (Kind.isBSS()) 1883360784Sdim return DataSection; 1884360784Sdim 1885360784Sdim if (Kind.isReadOnly()) 1886360784Sdim return ReadOnlySection; 1887360784Sdim 1888360784Sdim report_fatal_error("XCOFF other section types not yet implemented."); 1889360784Sdim} 1890360784Sdim 1891360784SdimMCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable( 1892360784Sdim const Function &F, const TargetMachine &TM) const { 1893360784Sdim assert (!TM.getFunctionSections() && "Unique sections not supported on XCOFF" 1894360784Sdim " yet."); 1895360784Sdim assert (!F.getComdat() && "Comdat not supported on XCOFF."); 1896360784Sdim //TODO: Enable emiting jump table to unique sections when we support it. 1897360784Sdim return ReadOnlySection; 1898360784Sdim} 1899360784Sdim 1900360784Sdimbool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection( 1901360784Sdim bool UsesLabelDifference, const Function &F) const { 1902360784Sdim return false; 1903360784Sdim} 1904360784Sdim 1905360784Sdim/// Given a mergeable constant with the specified size and relocation 1906360784Sdim/// information, return a section that it should be placed in. 1907360784SdimMCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant( 1908360784Sdim const DataLayout &DL, SectionKind Kind, const Constant *C, 1909360784Sdim unsigned &Align) const { 1910360784Sdim //TODO: Enable emiting constant pool to unique sections when we support it. 1911360784Sdim return ReadOnlySection; 1912360784Sdim} 1913360784Sdim 1914360784Sdimvoid TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx, 1915360784Sdim const TargetMachine &TgtM) { 1916360784Sdim TargetLoweringObjectFile::Initialize(Ctx, TgtM); 1917360784Sdim TTypeEncoding = 0; 1918360784Sdim PersonalityEncoding = 0; 1919360784Sdim LSDAEncoding = 0; 1920360784Sdim} 1921360784Sdim 1922360784SdimMCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection( 1923360784Sdim unsigned Priority, const MCSymbol *KeySym) const { 1924360784Sdim report_fatal_error("XCOFF ctor section not yet implemented."); 1925360784Sdim} 1926360784Sdim 1927360784SdimMCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection( 1928360784Sdim unsigned Priority, const MCSymbol *KeySym) const { 1929360784Sdim report_fatal_error("XCOFF dtor section not yet implemented."); 1930360784Sdim} 1931360784Sdim 1932360784Sdimconst MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference( 1933360784Sdim const GlobalValue *LHS, const GlobalValue *RHS, 1934360784Sdim const TargetMachine &TM) const { 1935360784Sdim report_fatal_error("XCOFF not yet implemented."); 1936360784Sdim} 1937360784Sdim 1938360784SdimXCOFF::StorageClass TargetLoweringObjectFileXCOFF::getStorageClassForGlobal( 1939360784Sdim const GlobalObject *GO) { 1940360784Sdim switch (GO->getLinkage()) { 1941360784Sdim case GlobalValue::InternalLinkage: 1942360784Sdim case GlobalValue::PrivateLinkage: 1943360784Sdim return XCOFF::C_HIDEXT; 1944360784Sdim case GlobalValue::ExternalLinkage: 1945360784Sdim case GlobalValue::CommonLinkage: 1946360784Sdim return XCOFF::C_EXT; 1947360784Sdim case GlobalValue::ExternalWeakLinkage: 1948360784Sdim return XCOFF::C_WEAKEXT; 1949360784Sdim default: 1950360784Sdim report_fatal_error( 1951360784Sdim "Unhandled linkage when mapping linkage to StorageClass."); 1952360784Sdim } 1953360784Sdim} 1954