1 //===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements classes used to handle lowerings specific to common 10 // object file formats. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h" 15 #include "llvm/ADT/SmallString.h" 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/ADT/StringRef.h" 19 #include "llvm/ADT/Triple.h" 20 #include "llvm/BinaryFormat/COFF.h" 21 #include "llvm/BinaryFormat/Dwarf.h" 22 #include "llvm/BinaryFormat/ELF.h" 23 #include "llvm/BinaryFormat/MachO.h" 24 #include "llvm/CodeGen/BasicBlockSectionUtils.h" 25 #include "llvm/CodeGen/MachineBasicBlock.h" 26 #include "llvm/CodeGen/MachineFunction.h" 27 #include "llvm/CodeGen/MachineModuleInfo.h" 28 #include "llvm/CodeGen/MachineModuleInfoImpls.h" 29 #include "llvm/IR/Comdat.h" 30 #include "llvm/IR/Constants.h" 31 #include "llvm/IR/DataLayout.h" 32 #include "llvm/IR/DerivedTypes.h" 33 #include "llvm/IR/DiagnosticInfo.h" 34 #include "llvm/IR/DiagnosticPrinter.h" 35 #include "llvm/IR/Function.h" 36 #include "llvm/IR/GlobalAlias.h" 37 #include "llvm/IR/GlobalObject.h" 38 #include "llvm/IR/GlobalValue.h" 39 #include "llvm/IR/GlobalVariable.h" 40 #include "llvm/IR/Mangler.h" 41 #include "llvm/IR/Metadata.h" 42 #include "llvm/IR/Module.h" 43 #include "llvm/IR/PseudoProbe.h" 44 #include "llvm/IR/Type.h" 45 #include "llvm/MC/MCAsmInfo.h" 46 #include "llvm/MC/MCContext.h" 47 #include "llvm/MC/MCExpr.h" 48 #include "llvm/MC/MCSectionCOFF.h" 49 #include "llvm/MC/MCSectionELF.h" 50 #include "llvm/MC/MCSectionMachO.h" 51 #include "llvm/MC/MCSectionWasm.h" 52 #include "llvm/MC/MCSectionXCOFF.h" 53 #include "llvm/MC/MCStreamer.h" 54 #include "llvm/MC/MCSymbol.h" 55 #include "llvm/MC/MCSymbolELF.h" 56 #include "llvm/MC/MCValue.h" 57 #include "llvm/MC/SectionKind.h" 58 #include "llvm/ProfileData/InstrProf.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CodeGen.h" 61 #include "llvm/Support/ErrorHandling.h" 62 #include "llvm/Support/Format.h" 63 #include "llvm/Support/raw_ostream.h" 64 #include "llvm/Target/TargetMachine.h" 65 #include <cassert> 66 #include <string> 67 68 using namespace llvm; 69 using namespace dwarf; 70 71 static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags, 72 StringRef &Section) { 73 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 74 M.getModuleFlagsMetadata(ModuleFlags); 75 76 for (const auto &MFE: ModuleFlags) { 77 // Ignore flags with 'Require' behaviour. 78 if (MFE.Behavior == Module::Require) 79 continue; 80 81 StringRef Key = MFE.Key->getString(); 82 if (Key == "Objective-C Image Info Version") { 83 Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 84 } else if (Key == "Objective-C Garbage Collection" || 85 Key == "Objective-C GC Only" || 86 Key == "Objective-C Is Simulated" || 87 Key == "Objective-C Class Properties" || 88 Key == "Objective-C Image Swift Version") { 89 Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue(); 90 } else if (Key == "Objective-C Image Info Section") { 91 Section = cast<MDString>(MFE.Val)->getString(); 92 } 93 // Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor + 94 // "Objective-C Garbage Collection". 95 else if (Key == "Swift ABI Version") { 96 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8; 97 } else if (Key == "Swift Major Version") { 98 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24; 99 } else if (Key == "Swift Minor Version") { 100 Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16; 101 } 102 } 103 } 104 105 //===----------------------------------------------------------------------===// 106 // ELF 107 //===----------------------------------------------------------------------===// 108 109 TargetLoweringObjectFileELF::TargetLoweringObjectFileELF() 110 : TargetLoweringObjectFile() { 111 SupportDSOLocalEquivalentLowering = true; 112 } 113 114 void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx, 115 const TargetMachine &TgtM) { 116 TargetLoweringObjectFile::Initialize(Ctx, TgtM); 117 TM = &TgtM; 118 119 CodeModel::Model CM = TgtM.getCodeModel(); 120 InitializeELF(TgtM.Options.UseInitArray); 121 122 switch (TgtM.getTargetTriple().getArch()) { 123 case Triple::arm: 124 case Triple::armeb: 125 case Triple::thumb: 126 case Triple::thumbeb: 127 if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM) 128 break; 129 // Fallthrough if not using EHABI 130 LLVM_FALLTHROUGH; 131 case Triple::ppc: 132 case Triple::x86: 133 PersonalityEncoding = isPositionIndependent() 134 ? dwarf::DW_EH_PE_indirect | 135 dwarf::DW_EH_PE_pcrel | 136 dwarf::DW_EH_PE_sdata4 137 : dwarf::DW_EH_PE_absptr; 138 LSDAEncoding = isPositionIndependent() 139 ? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4 140 : dwarf::DW_EH_PE_absptr; 141 TTypeEncoding = isPositionIndependent() 142 ? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 143 dwarf::DW_EH_PE_sdata4 144 : dwarf::DW_EH_PE_absptr; 145 break; 146 case Triple::x86_64: 147 if (isPositionIndependent()) { 148 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 149 ((CM == CodeModel::Small || CM == CodeModel::Medium) 150 ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 151 LSDAEncoding = dwarf::DW_EH_PE_pcrel | 152 (CM == CodeModel::Small 153 ? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8); 154 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 155 ((CM == CodeModel::Small || CM == CodeModel::Medium) 156 ? dwarf::DW_EH_PE_sdata8 : dwarf::DW_EH_PE_sdata4); 157 } else { 158 PersonalityEncoding = 159 (CM == CodeModel::Small || CM == CodeModel::Medium) 160 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 161 LSDAEncoding = (CM == CodeModel::Small) 162 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 163 TTypeEncoding = (CM == CodeModel::Small) 164 ? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr; 165 } 166 break; 167 case Triple::hexagon: 168 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 169 LSDAEncoding = dwarf::DW_EH_PE_absptr; 170 TTypeEncoding = dwarf::DW_EH_PE_absptr; 171 if (isPositionIndependent()) { 172 PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; 173 LSDAEncoding |= dwarf::DW_EH_PE_pcrel; 174 TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel; 175 } 176 break; 177 case Triple::aarch64: 178 case Triple::aarch64_be: 179 case Triple::aarch64_32: 180 // The small model guarantees static code/data size < 4GB, but not where it 181 // will be in memory. Most of these could end up >2GB away so even a signed 182 // pc-relative 32-bit address is insufficient, theoretically. 183 if (isPositionIndependent()) { 184 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 185 dwarf::DW_EH_PE_sdata8; 186 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata8; 187 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 188 dwarf::DW_EH_PE_sdata8; 189 } else { 190 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 191 LSDAEncoding = dwarf::DW_EH_PE_absptr; 192 TTypeEncoding = dwarf::DW_EH_PE_absptr; 193 } 194 break; 195 case Triple::lanai: 196 LSDAEncoding = dwarf::DW_EH_PE_absptr; 197 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 198 TTypeEncoding = dwarf::DW_EH_PE_absptr; 199 break; 200 case Triple::mips: 201 case Triple::mipsel: 202 case Triple::mips64: 203 case Triple::mips64el: 204 // MIPS uses indirect pointer to refer personality functions and types, so 205 // that the eh_frame section can be read-only. DW.ref.personality will be 206 // generated for relocation. 207 PersonalityEncoding = dwarf::DW_EH_PE_indirect; 208 // FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't 209 // identify N64 from just a triple. 210 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 211 dwarf::DW_EH_PE_sdata4; 212 // We don't support PC-relative LSDA references in GAS so we use the default 213 // DW_EH_PE_absptr for those. 214 215 // FreeBSD must be explicit about the data size and using pcrel since it's 216 // assembler/linker won't do the automatic conversion that the Linux tools 217 // do. 218 if (TgtM.getTargetTriple().isOSFreeBSD()) { 219 PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 220 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 221 } 222 break; 223 case Triple::ppc64: 224 case Triple::ppc64le: 225 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 226 dwarf::DW_EH_PE_udata8; 227 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8; 228 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 229 dwarf::DW_EH_PE_udata8; 230 break; 231 case Triple::sparcel: 232 case Triple::sparc: 233 if (isPositionIndependent()) { 234 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 235 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 236 dwarf::DW_EH_PE_sdata4; 237 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 238 dwarf::DW_EH_PE_sdata4; 239 } else { 240 LSDAEncoding = dwarf::DW_EH_PE_absptr; 241 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 242 TTypeEncoding = dwarf::DW_EH_PE_absptr; 243 } 244 CallSiteEncoding = dwarf::DW_EH_PE_udata4; 245 break; 246 case Triple::riscv32: 247 case Triple::riscv64: 248 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 249 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 250 dwarf::DW_EH_PE_sdata4; 251 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 252 dwarf::DW_EH_PE_sdata4; 253 CallSiteEncoding = dwarf::DW_EH_PE_udata4; 254 break; 255 case Triple::sparcv9: 256 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 257 if (isPositionIndependent()) { 258 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 259 dwarf::DW_EH_PE_sdata4; 260 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 261 dwarf::DW_EH_PE_sdata4; 262 } else { 263 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 264 TTypeEncoding = dwarf::DW_EH_PE_absptr; 265 } 266 break; 267 case Triple::systemz: 268 // All currently-defined code models guarantee that 4-byte PC-relative 269 // values will be in range. 270 if (isPositionIndependent()) { 271 PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 272 dwarf::DW_EH_PE_sdata4; 273 LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 274 TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | 275 dwarf::DW_EH_PE_sdata4; 276 } else { 277 PersonalityEncoding = dwarf::DW_EH_PE_absptr; 278 LSDAEncoding = dwarf::DW_EH_PE_absptr; 279 TTypeEncoding = dwarf::DW_EH_PE_absptr; 280 } 281 break; 282 default: 283 break; 284 } 285 } 286 287 void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer, 288 Module &M) const { 289 auto &C = getContext(); 290 291 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 292 auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS, 293 ELF::SHF_EXCLUDE); 294 295 Streamer.SwitchSection(S); 296 297 for (const auto *Operand : LinkerOptions->operands()) { 298 if (cast<MDNode>(Operand)->getNumOperands() != 2) 299 report_fatal_error("invalid llvm.linker.options"); 300 for (const auto &Option : cast<MDNode>(Operand)->operands()) { 301 Streamer.emitBytes(cast<MDString>(Option)->getString()); 302 Streamer.emitInt8(0); 303 } 304 } 305 } 306 307 if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) { 308 auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES, 309 ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, ""); 310 311 Streamer.SwitchSection(S); 312 313 for (const auto *Operand : DependentLibraries->operands()) { 314 Streamer.emitBytes( 315 cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString()); 316 Streamer.emitInt8(0); 317 } 318 } 319 320 if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) { 321 // Emit a descriptor for every function including functions that have an 322 // available external linkage. We may not want this for imported functions 323 // that has code in another thinLTO module but we don't have a good way to 324 // tell them apart from inline functions defined in header files. Therefore 325 // we put each descriptor in a separate comdat section and rely on the 326 // linker to deduplicate. 327 for (const auto *Operand : FuncInfo->operands()) { 328 const auto *MD = cast<MDNode>(Operand); 329 auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0)); 330 auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1)); 331 auto *Name = cast<MDString>(MD->getOperand(2)); 332 auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection( 333 TM->getFunctionSections() ? Name->getString() : StringRef()); 334 335 Streamer.SwitchSection(S); 336 Streamer.emitInt64(GUID->getZExtValue()); 337 Streamer.emitInt64(Hash->getZExtValue()); 338 Streamer.emitULEB128IntValue(Name->getString().size()); 339 Streamer.emitBytes(Name->getString()); 340 } 341 } 342 343 unsigned Version = 0; 344 unsigned Flags = 0; 345 StringRef Section; 346 347 GetObjCImageInfo(M, Version, Flags, Section); 348 if (!Section.empty()) { 349 auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC); 350 Streamer.SwitchSection(S); 351 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 352 Streamer.emitInt32(Version); 353 Streamer.emitInt32(Flags); 354 Streamer.AddBlankLine(); 355 } 356 357 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 358 M.getModuleFlagsMetadata(ModuleFlags); 359 360 MDNode *CFGProfile = nullptr; 361 362 for (const auto &MFE : ModuleFlags) { 363 StringRef Key = MFE.Key->getString(); 364 if (Key == "CG Profile") { 365 CFGProfile = cast<MDNode>(MFE.Val); 366 break; 367 } 368 } 369 370 if (!CFGProfile) 371 return; 372 373 auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * { 374 if (!MDO) 375 return nullptr; 376 auto V = cast<ValueAsMetadata>(MDO); 377 const Function *F = cast<Function>(V->getValue()->stripPointerCasts()); 378 return TM->getSymbol(F); 379 }; 380 381 for (const auto &Edge : CFGProfile->operands()) { 382 MDNode *E = cast<MDNode>(Edge); 383 const MCSymbol *From = GetSym(E->getOperand(0)); 384 const MCSymbol *To = GetSym(E->getOperand(1)); 385 // Skip null functions. This can happen if functions are dead stripped after 386 // the CGProfile pass has been run. 387 if (!From || !To) 388 continue; 389 uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2)) 390 ->getValue() 391 ->getUniqueInteger() 392 .getZExtValue(); 393 Streamer.emitCGProfileEntry( 394 MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C), 395 MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count); 396 } 397 } 398 399 MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol( 400 const GlobalValue *GV, const TargetMachine &TM, 401 MachineModuleInfo *MMI) const { 402 unsigned Encoding = getPersonalityEncoding(); 403 if ((Encoding & 0x80) == DW_EH_PE_indirect) 404 return getContext().getOrCreateSymbol(StringRef("DW.ref.") + 405 TM.getSymbol(GV)->getName()); 406 if ((Encoding & 0x70) == DW_EH_PE_absptr) 407 return TM.getSymbol(GV); 408 report_fatal_error("We do not support this DWARF encoding yet!"); 409 } 410 411 void TargetLoweringObjectFileELF::emitPersonalityValue( 412 MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const { 413 SmallString<64> NameData("DW.ref."); 414 NameData += Sym->getName(); 415 MCSymbolELF *Label = 416 cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData)); 417 Streamer.emitSymbolAttribute(Label, MCSA_Hidden); 418 Streamer.emitSymbolAttribute(Label, MCSA_Weak); 419 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP; 420 MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(), 421 ELF::SHT_PROGBITS, Flags, 0); 422 unsigned Size = DL.getPointerSize(); 423 Streamer.SwitchSection(Sec); 424 Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0).value()); 425 Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject); 426 const MCExpr *E = MCConstantExpr::create(Size, getContext()); 427 Streamer.emitELFSize(Label, E); 428 Streamer.emitLabel(Label); 429 430 Streamer.emitSymbolValue(Sym, Size); 431 } 432 433 const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference( 434 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 435 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 436 if (Encoding & DW_EH_PE_indirect) { 437 MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>(); 438 439 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM); 440 441 // Add information about the stub reference to ELFMMI so that the stub 442 // gets emitted by the asmprinter. 443 MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym); 444 if (!StubSym.getPointer()) { 445 MCSymbol *Sym = TM.getSymbol(GV); 446 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 447 } 448 449 return TargetLoweringObjectFile:: 450 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 451 Encoding & ~DW_EH_PE_indirect, Streamer); 452 } 453 454 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 455 MMI, Streamer); 456 } 457 458 static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) { 459 // N.B.: The defaults used in here are not the same ones used in MC. 460 // We follow gcc, MC follows gas. For example, given ".section .eh_frame", 461 // both gas and MC will produce a section with no flags. Given 462 // section(".eh_frame") gcc will produce: 463 // 464 // .section .eh_frame,"a",@progbits 465 466 if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF, 467 /*AddSegmentInfo=*/false) || 468 Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF, 469 /*AddSegmentInfo=*/false) || 470 Name == ".llvmbc" || Name == ".llvmcmd") 471 return SectionKind::getMetadata(); 472 473 if (Name.empty() || Name[0] != '.') return K; 474 475 // Default implementation based on some magic section names. 476 if (Name == ".bss" || 477 Name.startswith(".bss.") || 478 Name.startswith(".gnu.linkonce.b.") || 479 Name.startswith(".llvm.linkonce.b.") || 480 Name == ".sbss" || 481 Name.startswith(".sbss.") || 482 Name.startswith(".gnu.linkonce.sb.") || 483 Name.startswith(".llvm.linkonce.sb.")) 484 return SectionKind::getBSS(); 485 486 if (Name == ".tdata" || 487 Name.startswith(".tdata.") || 488 Name.startswith(".gnu.linkonce.td.") || 489 Name.startswith(".llvm.linkonce.td.")) 490 return SectionKind::getThreadData(); 491 492 if (Name == ".tbss" || 493 Name.startswith(".tbss.") || 494 Name.startswith(".gnu.linkonce.tb.") || 495 Name.startswith(".llvm.linkonce.tb.")) 496 return SectionKind::getThreadBSS(); 497 498 return K; 499 } 500 501 static unsigned getELFSectionType(StringRef Name, SectionKind K) { 502 // Use SHT_NOTE for section whose name starts with ".note" to allow 503 // emitting ELF notes from C variable declaration. 504 // See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609 505 if (Name.startswith(".note")) 506 return ELF::SHT_NOTE; 507 508 if (Name == ".init_array") 509 return ELF::SHT_INIT_ARRAY; 510 511 if (Name == ".fini_array") 512 return ELF::SHT_FINI_ARRAY; 513 514 if (Name == ".preinit_array") 515 return ELF::SHT_PREINIT_ARRAY; 516 517 if (K.isBSS() || K.isThreadBSS()) 518 return ELF::SHT_NOBITS; 519 520 return ELF::SHT_PROGBITS; 521 } 522 523 static unsigned getELFSectionFlags(SectionKind K) { 524 unsigned Flags = 0; 525 526 if (!K.isMetadata()) 527 Flags |= ELF::SHF_ALLOC; 528 529 if (K.isText()) 530 Flags |= ELF::SHF_EXECINSTR; 531 532 if (K.isExecuteOnly()) 533 Flags |= ELF::SHF_ARM_PURECODE; 534 535 if (K.isWriteable()) 536 Flags |= ELF::SHF_WRITE; 537 538 if (K.isThreadLocal()) 539 Flags |= ELF::SHF_TLS; 540 541 if (K.isMergeableCString() || K.isMergeableConst()) 542 Flags |= ELF::SHF_MERGE; 543 544 if (K.isMergeableCString()) 545 Flags |= ELF::SHF_STRINGS; 546 547 return Flags; 548 } 549 550 static const Comdat *getELFComdat(const GlobalValue *GV) { 551 const Comdat *C = GV->getComdat(); 552 if (!C) 553 return nullptr; 554 555 if (C->getSelectionKind() != Comdat::Any) 556 report_fatal_error("ELF COMDATs only support SelectionKind::Any, '" + 557 C->getName() + "' cannot be lowered."); 558 559 return C; 560 } 561 562 static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO, 563 const TargetMachine &TM) { 564 MDNode *MD = GO->getMetadata(LLVMContext::MD_associated); 565 if (!MD) 566 return nullptr; 567 568 const MDOperand &Op = MD->getOperand(0); 569 if (!Op.get()) 570 return nullptr; 571 572 auto *VM = dyn_cast<ValueAsMetadata>(Op); 573 if (!VM) 574 report_fatal_error("MD_associated operand is not ValueAsMetadata"); 575 576 auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue()); 577 return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr; 578 } 579 580 static unsigned getEntrySizeForKind(SectionKind Kind) { 581 if (Kind.isMergeable1ByteCString()) 582 return 1; 583 else if (Kind.isMergeable2ByteCString()) 584 return 2; 585 else if (Kind.isMergeable4ByteCString()) 586 return 4; 587 else if (Kind.isMergeableConst4()) 588 return 4; 589 else if (Kind.isMergeableConst8()) 590 return 8; 591 else if (Kind.isMergeableConst16()) 592 return 16; 593 else if (Kind.isMergeableConst32()) 594 return 32; 595 else { 596 // We shouldn't have mergeable C strings or mergeable constants that we 597 // didn't handle above. 598 assert(!Kind.isMergeableCString() && "unknown string width"); 599 assert(!Kind.isMergeableConst() && "unknown data width"); 600 return 0; 601 } 602 } 603 604 /// Return the section prefix name used by options FunctionsSections and 605 /// DataSections. 606 static StringRef getSectionPrefixForGlobal(SectionKind Kind) { 607 if (Kind.isText()) 608 return ".text"; 609 if (Kind.isReadOnly()) 610 return ".rodata"; 611 if (Kind.isBSS()) 612 return ".bss"; 613 if (Kind.isThreadData()) 614 return ".tdata"; 615 if (Kind.isThreadBSS()) 616 return ".tbss"; 617 if (Kind.isData()) 618 return ".data"; 619 if (Kind.isReadOnlyWithRel()) 620 return ".data.rel.ro"; 621 llvm_unreachable("Unknown section kind"); 622 } 623 624 static SmallString<128> 625 getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind, 626 Mangler &Mang, const TargetMachine &TM, 627 unsigned EntrySize, bool UniqueSectionName) { 628 SmallString<128> Name; 629 if (Kind.isMergeableCString()) { 630 // We also need alignment here. 631 // FIXME: this is getting the alignment of the character, not the 632 // alignment of the global! 633 Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign( 634 cast<GlobalVariable>(GO)); 635 636 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; 637 Name = SizeSpec + utostr(Alignment.value()); 638 } else if (Kind.isMergeableConst()) { 639 Name = ".rodata.cst"; 640 Name += utostr(EntrySize); 641 } else { 642 Name = getSectionPrefixForGlobal(Kind); 643 } 644 645 bool HasPrefix = false; 646 if (const auto *F = dyn_cast<Function>(GO)) { 647 if (Optional<StringRef> Prefix = F->getSectionPrefix()) { 648 raw_svector_ostream(Name) << '.' << *Prefix; 649 HasPrefix = true; 650 } 651 } 652 653 if (UniqueSectionName) { 654 Name.push_back('.'); 655 TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true); 656 } else if (HasPrefix) 657 Name.push_back('.'); 658 return Name; 659 } 660 661 namespace { 662 class LoweringDiagnosticInfo : public DiagnosticInfo { 663 const Twine &Msg; 664 665 public: 666 LoweringDiagnosticInfo(const Twine &DiagMsg, 667 DiagnosticSeverity Severity = DS_Error) 668 : DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {} 669 void print(DiagnosticPrinter &DP) const override { DP << Msg; } 670 }; 671 } 672 673 MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal( 674 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 675 StringRef SectionName = GO->getSection(); 676 677 // Check if '#pragma clang section' name is applicable. 678 // Note that pragma directive overrides -ffunction-section, -fdata-section 679 // and so section name is exactly as user specified and not uniqued. 680 const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO); 681 if (GV && GV->hasImplicitSection()) { 682 auto Attrs = GV->getAttributes(); 683 if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) { 684 SectionName = Attrs.getAttribute("bss-section").getValueAsString(); 685 } else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) { 686 SectionName = Attrs.getAttribute("rodata-section").getValueAsString(); 687 } else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) { 688 SectionName = Attrs.getAttribute("relro-section").getValueAsString(); 689 } else if (Attrs.hasAttribute("data-section") && Kind.isData()) { 690 SectionName = Attrs.getAttribute("data-section").getValueAsString(); 691 } 692 } 693 const Function *F = dyn_cast<Function>(GO); 694 if (F && F->hasFnAttribute("implicit-section-name")) { 695 SectionName = F->getFnAttribute("implicit-section-name").getValueAsString(); 696 } 697 698 // Infer section flags from the section name if we can. 699 Kind = getELFKindForNamedSection(SectionName, Kind); 700 701 StringRef Group = ""; 702 unsigned Flags = getELFSectionFlags(Kind); 703 if (const Comdat *C = getELFComdat(GO)) { 704 Group = C->getName(); 705 Flags |= ELF::SHF_GROUP; 706 } 707 708 unsigned EntrySize = getEntrySizeForKind(Kind); 709 710 // A section can have at most one associated section. Put each global with 711 // MD_associated in a unique section. 712 unsigned UniqueID = MCContext::GenericSectionID; 713 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM); 714 if (GO->getMetadata(LLVMContext::MD_associated)) { 715 UniqueID = NextUniqueID++; 716 Flags |= ELF::SHF_LINK_ORDER; 717 } else { 718 if (getContext().getAsmInfo()->useIntegratedAssembler()) { 719 // Symbols must be placed into sections with compatible entry 720 // sizes. Generate unique sections for symbols that have not 721 // been assigned to compatible sections. 722 if (Flags & ELF::SHF_MERGE) { 723 auto maybeID = getContext().getELFUniqueIDForEntsize(SectionName, Flags, 724 EntrySize); 725 if (maybeID) 726 UniqueID = *maybeID; 727 else { 728 // If the user has specified the same section name as would be created 729 // implicitly for this symbol e.g. .rodata.str1.1, then we don't need 730 // to unique the section as the entry size for this symbol will be 731 // compatible with implicitly created sections. 732 SmallString<128> ImplicitSectionNameStem = getELFSectionNameForGlobal( 733 GO, Kind, getMangler(), TM, EntrySize, false); 734 if (!(getContext().isELFImplicitMergeableSectionNamePrefix( 735 SectionName) && 736 SectionName.startswith(ImplicitSectionNameStem))) 737 UniqueID = NextUniqueID++; 738 } 739 } else { 740 // We need to unique the section if the user has explicity 741 // assigned a non-mergeable symbol to a section name for 742 // a generic mergeable section. 743 if (getContext().isELFGenericMergeableSection(SectionName)) { 744 auto maybeID = getContext().getELFUniqueIDForEntsize( 745 SectionName, Flags, EntrySize); 746 UniqueID = maybeID ? *maybeID : NextUniqueID++; 747 } 748 } 749 } else { 750 // If two symbols with differing sizes end up in the same mergeable 751 // section that section can be assigned an incorrect entry size. To avoid 752 // this we usually put symbols of the same size into distinct mergeable 753 // sections with the same name. Doing so relies on the ",unique ," 754 // assembly feature. This feature is not avalible until bintuils 755 // version 2.35 (https://sourceware.org/bugzilla/show_bug.cgi?id=25380). 756 Flags &= ~ELF::SHF_MERGE; 757 EntrySize = 0; 758 } 759 } 760 761 MCSectionELF *Section = getContext().getELFSection( 762 SectionName, getELFSectionType(SectionName, Kind), Flags, 763 EntrySize, Group, UniqueID, LinkedToSym); 764 // Make sure that we did not get some other section with incompatible sh_link. 765 // This should not be possible due to UniqueID code above. 766 assert(Section->getLinkedToSymbol() == LinkedToSym && 767 "Associated symbol mismatch between sections"); 768 769 if (!getContext().getAsmInfo()->useIntegratedAssembler()) { 770 // If we are not using the integrated assembler then this symbol might have 771 // been placed in an incompatible mergeable section. Emit an error if this 772 // is the case to avoid creating broken output. 773 if ((Section->getFlags() & ELF::SHF_MERGE) && 774 (Section->getEntrySize() != getEntrySizeForKind(Kind))) 775 GO->getContext().diagnose(LoweringDiagnosticInfo( 776 "Symbol '" + GO->getName() + "' from module '" + 777 (GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") + 778 "' required a section with entry-size=" + 779 Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" + 780 SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) + 781 ": Explicit assignment by pragma or attribute of an incompatible " 782 "symbol to this section?")); 783 } 784 785 return Section; 786 } 787 788 static MCSectionELF *selectELFSectionForGlobal( 789 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 790 const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags, 791 unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) { 792 793 StringRef Group = ""; 794 if (const Comdat *C = getELFComdat(GO)) { 795 Flags |= ELF::SHF_GROUP; 796 Group = C->getName(); 797 } 798 799 // Get the section entry size based on the kind. 800 unsigned EntrySize = getEntrySizeForKind(Kind); 801 802 bool UniqueSectionName = false; 803 unsigned UniqueID = MCContext::GenericSectionID; 804 if (EmitUniqueSection) { 805 if (TM.getUniqueSectionNames()) { 806 UniqueSectionName = true; 807 } else { 808 UniqueID = *NextUniqueID; 809 (*NextUniqueID)++; 810 } 811 } 812 SmallString<128> Name = getELFSectionNameForGlobal( 813 GO, Kind, Mang, TM, EntrySize, UniqueSectionName); 814 815 // Use 0 as the unique ID for execute-only text. 816 if (Kind.isExecuteOnly()) 817 UniqueID = 0; 818 return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags, 819 EntrySize, Group, UniqueID, AssociatedSymbol); 820 } 821 822 MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal( 823 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 824 unsigned Flags = getELFSectionFlags(Kind); 825 826 // If we have -ffunction-section or -fdata-section then we should emit the 827 // global value to a uniqued section specifically for it. 828 bool EmitUniqueSection = false; 829 if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) { 830 if (Kind.isText()) 831 EmitUniqueSection = TM.getFunctionSections(); 832 else 833 EmitUniqueSection = TM.getDataSections(); 834 } 835 EmitUniqueSection |= GO->hasComdat(); 836 837 const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM); 838 if (LinkedToSym) { 839 EmitUniqueSection = true; 840 Flags |= ELF::SHF_LINK_ORDER; 841 } 842 843 MCSectionELF *Section = selectELFSectionForGlobal( 844 getContext(), GO, Kind, getMangler(), TM, EmitUniqueSection, Flags, 845 &NextUniqueID, LinkedToSym); 846 assert(Section->getLinkedToSymbol() == LinkedToSym); 847 return Section; 848 } 849 850 MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable( 851 const Function &F, const TargetMachine &TM) const { 852 // If the function can be removed, produce a unique section so that 853 // the table doesn't prevent the removal. 854 const Comdat *C = F.getComdat(); 855 bool EmitUniqueSection = TM.getFunctionSections() || C; 856 if (!EmitUniqueSection) 857 return ReadOnlySection; 858 859 return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(), 860 getMangler(), TM, EmitUniqueSection, 861 ELF::SHF_ALLOC, &NextUniqueID, 862 /* AssociatedSymbol */ nullptr); 863 } 864 865 MCSection * 866 TargetLoweringObjectFileELF::getSectionForLSDA(const Function &F, 867 const TargetMachine &TM) const { 868 // If neither COMDAT nor function sections, use the monolithic LSDA section. 869 // Re-use this path if LSDASection is null as in the Arm EHABI. 870 if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections())) 871 return LSDASection; 872 873 const auto *LSDA = cast<MCSectionELF>(LSDASection); 874 unsigned Flags = LSDA->getFlags(); 875 StringRef Group; 876 if (F.hasComdat()) { 877 Group = F.getComdat()->getName(); 878 Flags |= ELF::SHF_GROUP; 879 } 880 881 // Append the function name as the suffix like GCC, assuming 882 // -funique-section-names applies to .gcc_except_table sections. 883 if (TM.getUniqueSectionNames()) 884 return getContext().getELFSection(LSDA->getName() + "." + F.getName(), 885 LSDA->getType(), Flags, 0, Group, 886 MCSection::NonUniqueID, nullptr); 887 888 // Allocate a unique ID if function sections && (integrated assembler or GNU 889 // as>=2.35). Note we could use SHF_LINK_ORDER to facilitate --gc-sections but 890 // that would require that we know the linker is a modern LLD (12.0 or later). 891 // GNU ld as of 2.35 does not support mixed SHF_LINK_ORDER & 892 // non-SHF_LINK_ORDER components in an output section 893 // https://sourceware.org/bugzilla/show_bug.cgi?id=26256 894 unsigned ID = TM.getFunctionSections() && 895 getContext().getAsmInfo()->useIntegratedAssembler() 896 ? NextUniqueID++ 897 : MCSection::NonUniqueID; 898 return getContext().getELFSection(LSDA->getName(), LSDA->getType(), Flags, 0, 899 Group, ID, nullptr); 900 } 901 902 bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection( 903 bool UsesLabelDifference, const Function &F) const { 904 // We can always create relative relocations, so use another section 905 // that can be marked non-executable. 906 return false; 907 } 908 909 /// Given a mergeable constant with the specified size and relocation 910 /// information, return a section that it should be placed in. 911 MCSection *TargetLoweringObjectFileELF::getSectionForConstant( 912 const DataLayout &DL, SectionKind Kind, const Constant *C, 913 Align &Alignment) const { 914 if (Kind.isMergeableConst4() && MergeableConst4Section) 915 return MergeableConst4Section; 916 if (Kind.isMergeableConst8() && MergeableConst8Section) 917 return MergeableConst8Section; 918 if (Kind.isMergeableConst16() && MergeableConst16Section) 919 return MergeableConst16Section; 920 if (Kind.isMergeableConst32() && MergeableConst32Section) 921 return MergeableConst32Section; 922 if (Kind.isReadOnly()) 923 return ReadOnlySection; 924 925 assert(Kind.isReadOnlyWithRel() && "Unknown section kind"); 926 return DataRelROSection; 927 } 928 929 /// Returns a unique section for the given machine basic block. 930 MCSection *TargetLoweringObjectFileELF::getSectionForMachineBasicBlock( 931 const Function &F, const MachineBasicBlock &MBB, 932 const TargetMachine &TM) const { 933 assert(MBB.isBeginSection() && "Basic block does not start a section!"); 934 unsigned UniqueID = MCContext::GenericSectionID; 935 936 // For cold sections use the .text.split. prefix along with the parent 937 // function name. All cold blocks for the same function go to the same 938 // section. Similarly all exception blocks are grouped by symbol name 939 // under the .text.eh prefix. For regular sections, we either use a unique 940 // name, or a unique ID for the section. 941 SmallString<128> Name; 942 if (MBB.getSectionID() == MBBSectionID::ColdSectionID) { 943 Name += BBSectionsColdTextPrefix; 944 Name += MBB.getParent()->getName(); 945 } else if (MBB.getSectionID() == MBBSectionID::ExceptionSectionID) { 946 Name += ".text.eh."; 947 Name += MBB.getParent()->getName(); 948 } else { 949 Name += MBB.getParent()->getSection()->getName(); 950 if (TM.getUniqueBasicBlockSectionNames()) { 951 Name += "."; 952 Name += MBB.getSymbol()->getName(); 953 } else { 954 UniqueID = NextUniqueID++; 955 } 956 } 957 958 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_EXECINSTR; 959 std::string GroupName = ""; 960 if (F.hasComdat()) { 961 Flags |= ELF::SHF_GROUP; 962 GroupName = F.getComdat()->getName().str(); 963 } 964 return getContext().getELFSection(Name, ELF::SHT_PROGBITS, Flags, 965 0 /* Entry Size */, GroupName, UniqueID, 966 nullptr); 967 } 968 969 static MCSectionELF *getStaticStructorSection(MCContext &Ctx, bool UseInitArray, 970 bool IsCtor, unsigned Priority, 971 const MCSymbol *KeySym) { 972 std::string Name; 973 unsigned Type; 974 unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE; 975 StringRef COMDAT = KeySym ? KeySym->getName() : ""; 976 977 if (KeySym) 978 Flags |= ELF::SHF_GROUP; 979 980 if (UseInitArray) { 981 if (IsCtor) { 982 Type = ELF::SHT_INIT_ARRAY; 983 Name = ".init_array"; 984 } else { 985 Type = ELF::SHT_FINI_ARRAY; 986 Name = ".fini_array"; 987 } 988 if (Priority != 65535) { 989 Name += '.'; 990 Name += utostr(Priority); 991 } 992 } else { 993 // The default scheme is .ctor / .dtor, so we have to invert the priority 994 // numbering. 995 if (IsCtor) 996 Name = ".ctors"; 997 else 998 Name = ".dtors"; 999 if (Priority != 65535) 1000 raw_string_ostream(Name) << format(".%05u", 65535 - Priority); 1001 Type = ELF::SHT_PROGBITS; 1002 } 1003 1004 return Ctx.getELFSection(Name, Type, Flags, 0, COMDAT); 1005 } 1006 1007 MCSection *TargetLoweringObjectFileELF::getStaticCtorSection( 1008 unsigned Priority, const MCSymbol *KeySym) const { 1009 return getStaticStructorSection(getContext(), UseInitArray, true, Priority, 1010 KeySym); 1011 } 1012 1013 MCSection *TargetLoweringObjectFileELF::getStaticDtorSection( 1014 unsigned Priority, const MCSymbol *KeySym) const { 1015 return getStaticStructorSection(getContext(), UseInitArray, false, Priority, 1016 KeySym); 1017 } 1018 1019 const MCExpr *TargetLoweringObjectFileELF::lowerRelativeReference( 1020 const GlobalValue *LHS, const GlobalValue *RHS, 1021 const TargetMachine &TM) const { 1022 // We may only use a PLT-relative relocation to refer to unnamed_addr 1023 // functions. 1024 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 1025 return nullptr; 1026 1027 // Basic sanity checks. 1028 if (LHS->getType()->getPointerAddressSpace() != 0 || 1029 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 1030 RHS->isThreadLocal()) 1031 return nullptr; 1032 1033 return MCBinaryExpr::createSub( 1034 MCSymbolRefExpr::create(TM.getSymbol(LHS), PLTRelativeVariantKind, 1035 getContext()), 1036 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 1037 } 1038 1039 const MCExpr *TargetLoweringObjectFileELF::lowerDSOLocalEquivalent( 1040 const DSOLocalEquivalent *Equiv, const TargetMachine &TM) const { 1041 assert(supportDSOLocalEquivalentLowering()); 1042 1043 const auto *GV = Equiv->getGlobalValue(); 1044 1045 // A PLT entry is not needed for dso_local globals. 1046 if (GV->isDSOLocal() || GV->isImplicitDSOLocal()) 1047 return MCSymbolRefExpr::create(TM.getSymbol(GV), getContext()); 1048 1049 return MCSymbolRefExpr::create(TM.getSymbol(GV), PLTRelativeVariantKind, 1050 getContext()); 1051 } 1052 1053 MCSection *TargetLoweringObjectFileELF::getSectionForCommandLines() const { 1054 // Use ".GCC.command.line" since this feature is to support clang's 1055 // -frecord-gcc-switches which in turn attempts to mimic GCC's switch of the 1056 // same name. 1057 return getContext().getELFSection(".GCC.command.line", ELF::SHT_PROGBITS, 1058 ELF::SHF_MERGE | ELF::SHF_STRINGS, 1, ""); 1059 } 1060 1061 void 1062 TargetLoweringObjectFileELF::InitializeELF(bool UseInitArray_) { 1063 UseInitArray = UseInitArray_; 1064 MCContext &Ctx = getContext(); 1065 if (!UseInitArray) { 1066 StaticCtorSection = Ctx.getELFSection(".ctors", ELF::SHT_PROGBITS, 1067 ELF::SHF_ALLOC | ELF::SHF_WRITE); 1068 1069 StaticDtorSection = Ctx.getELFSection(".dtors", ELF::SHT_PROGBITS, 1070 ELF::SHF_ALLOC | ELF::SHF_WRITE); 1071 return; 1072 } 1073 1074 StaticCtorSection = Ctx.getELFSection(".init_array", ELF::SHT_INIT_ARRAY, 1075 ELF::SHF_WRITE | ELF::SHF_ALLOC); 1076 StaticDtorSection = Ctx.getELFSection(".fini_array", ELF::SHT_FINI_ARRAY, 1077 ELF::SHF_WRITE | ELF::SHF_ALLOC); 1078 } 1079 1080 //===----------------------------------------------------------------------===// 1081 // MachO 1082 //===----------------------------------------------------------------------===// 1083 1084 TargetLoweringObjectFileMachO::TargetLoweringObjectFileMachO() 1085 : TargetLoweringObjectFile() { 1086 SupportIndirectSymViaGOTPCRel = true; 1087 } 1088 1089 void TargetLoweringObjectFileMachO::Initialize(MCContext &Ctx, 1090 const TargetMachine &TM) { 1091 TargetLoweringObjectFile::Initialize(Ctx, TM); 1092 if (TM.getRelocationModel() == Reloc::Static) { 1093 StaticCtorSection = Ctx.getMachOSection("__TEXT", "__constructor", 0, 1094 SectionKind::getData()); 1095 StaticDtorSection = Ctx.getMachOSection("__TEXT", "__destructor", 0, 1096 SectionKind::getData()); 1097 } else { 1098 StaticCtorSection = Ctx.getMachOSection("__DATA", "__mod_init_func", 1099 MachO::S_MOD_INIT_FUNC_POINTERS, 1100 SectionKind::getData()); 1101 StaticDtorSection = Ctx.getMachOSection("__DATA", "__mod_term_func", 1102 MachO::S_MOD_TERM_FUNC_POINTERS, 1103 SectionKind::getData()); 1104 } 1105 1106 PersonalityEncoding = 1107 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 1108 LSDAEncoding = dwarf::DW_EH_PE_pcrel; 1109 TTypeEncoding = 1110 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4; 1111 } 1112 1113 void TargetLoweringObjectFileMachO::emitModuleMetadata(MCStreamer &Streamer, 1114 Module &M) const { 1115 // Emit the linker options if present. 1116 if (auto *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 1117 for (const auto *Option : LinkerOptions->operands()) { 1118 SmallVector<std::string, 4> StrOptions; 1119 for (const auto &Piece : cast<MDNode>(Option)->operands()) 1120 StrOptions.push_back(std::string(cast<MDString>(Piece)->getString())); 1121 Streamer.emitLinkerOptions(StrOptions); 1122 } 1123 } 1124 1125 unsigned VersionVal = 0; 1126 unsigned ImageInfoFlags = 0; 1127 StringRef SectionVal; 1128 1129 GetObjCImageInfo(M, VersionVal, ImageInfoFlags, SectionVal); 1130 1131 // The section is mandatory. If we don't have it, then we don't have GC info. 1132 if (SectionVal.empty()) 1133 return; 1134 1135 StringRef Segment, Section; 1136 unsigned TAA = 0, StubSize = 0; 1137 bool TAAParsed; 1138 std::string ErrorCode = 1139 MCSectionMachO::ParseSectionSpecifier(SectionVal, Segment, Section, 1140 TAA, TAAParsed, StubSize); 1141 if (!ErrorCode.empty()) 1142 // If invalid, report the error with report_fatal_error. 1143 report_fatal_error("Invalid section specifier '" + Section + "': " + 1144 ErrorCode + "."); 1145 1146 // Get the section. 1147 MCSectionMachO *S = getContext().getMachOSection( 1148 Segment, Section, TAA, StubSize, SectionKind::getData()); 1149 Streamer.SwitchSection(S); 1150 Streamer.emitLabel(getContext(). 1151 getOrCreateSymbol(StringRef("L_OBJC_IMAGE_INFO"))); 1152 Streamer.emitInt32(VersionVal); 1153 Streamer.emitInt32(ImageInfoFlags); 1154 Streamer.AddBlankLine(); 1155 } 1156 1157 static void checkMachOComdat(const GlobalValue *GV) { 1158 const Comdat *C = GV->getComdat(); 1159 if (!C) 1160 return; 1161 1162 report_fatal_error("MachO doesn't support COMDATs, '" + C->getName() + 1163 "' cannot be lowered."); 1164 } 1165 1166 MCSection *TargetLoweringObjectFileMachO::getExplicitSectionGlobal( 1167 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1168 // Parse the section specifier and create it if valid. 1169 StringRef Segment, Section; 1170 unsigned TAA = 0, StubSize = 0; 1171 bool TAAParsed; 1172 1173 checkMachOComdat(GO); 1174 1175 std::string ErrorCode = 1176 MCSectionMachO::ParseSectionSpecifier(GO->getSection(), Segment, Section, 1177 TAA, TAAParsed, StubSize); 1178 if (!ErrorCode.empty()) { 1179 // If invalid, report the error with report_fatal_error. 1180 report_fatal_error("Global variable '" + GO->getName() + 1181 "' has an invalid section specifier '" + 1182 GO->getSection() + "': " + ErrorCode + "."); 1183 } 1184 1185 // Get the section. 1186 MCSectionMachO *S = 1187 getContext().getMachOSection(Segment, Section, TAA, StubSize, Kind); 1188 1189 // If TAA wasn't set by ParseSectionSpecifier() above, 1190 // use the value returned by getMachOSection() as a default. 1191 if (!TAAParsed) 1192 TAA = S->getTypeAndAttributes(); 1193 1194 // Okay, now that we got the section, verify that the TAA & StubSize agree. 1195 // If the user declared multiple globals with different section flags, we need 1196 // to reject it here. 1197 if (S->getTypeAndAttributes() != TAA || S->getStubSize() != StubSize) { 1198 // If invalid, report the error with report_fatal_error. 1199 report_fatal_error("Global variable '" + GO->getName() + 1200 "' section type or attributes does not match previous" 1201 " section specifier"); 1202 } 1203 1204 return S; 1205 } 1206 1207 MCSection *TargetLoweringObjectFileMachO::SelectSectionForGlobal( 1208 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1209 checkMachOComdat(GO); 1210 1211 // Handle thread local data. 1212 if (Kind.isThreadBSS()) return TLSBSSSection; 1213 if (Kind.isThreadData()) return TLSDataSection; 1214 1215 if (Kind.isText()) 1216 return GO->isWeakForLinker() ? TextCoalSection : TextSection; 1217 1218 // If this is weak/linkonce, put this in a coalescable section, either in text 1219 // or data depending on if it is writable. 1220 if (GO->isWeakForLinker()) { 1221 if (Kind.isReadOnly()) 1222 return ConstTextCoalSection; 1223 if (Kind.isReadOnlyWithRel()) 1224 return ConstDataCoalSection; 1225 return DataCoalSection; 1226 } 1227 1228 // FIXME: Alignment check should be handled by section classifier. 1229 if (Kind.isMergeable1ByteCString() && 1230 GO->getParent()->getDataLayout().getPreferredAlign( 1231 cast<GlobalVariable>(GO)) < Align(32)) 1232 return CStringSection; 1233 1234 // Do not put 16-bit arrays in the UString section if they have an 1235 // externally visible label, this runs into issues with certain linker 1236 // versions. 1237 if (Kind.isMergeable2ByteCString() && !GO->hasExternalLinkage() && 1238 GO->getParent()->getDataLayout().getPreferredAlign( 1239 cast<GlobalVariable>(GO)) < Align(32)) 1240 return UStringSection; 1241 1242 // With MachO only variables whose corresponding symbol starts with 'l' or 1243 // 'L' can be merged, so we only try merging GVs with private linkage. 1244 if (GO->hasPrivateLinkage() && Kind.isMergeableConst()) { 1245 if (Kind.isMergeableConst4()) 1246 return FourByteConstantSection; 1247 if (Kind.isMergeableConst8()) 1248 return EightByteConstantSection; 1249 if (Kind.isMergeableConst16()) 1250 return SixteenByteConstantSection; 1251 } 1252 1253 // Otherwise, if it is readonly, but not something we can specially optimize, 1254 // just drop it in .const. 1255 if (Kind.isReadOnly()) 1256 return ReadOnlySection; 1257 1258 // If this is marked const, put it into a const section. But if the dynamic 1259 // linker needs to write to it, put it in the data segment. 1260 if (Kind.isReadOnlyWithRel()) 1261 return ConstDataSection; 1262 1263 // Put zero initialized globals with strong external linkage in the 1264 // DATA, __common section with the .zerofill directive. 1265 if (Kind.isBSSExtern()) 1266 return DataCommonSection; 1267 1268 // Put zero initialized globals with local linkage in __DATA,__bss directive 1269 // with the .zerofill directive (aka .lcomm). 1270 if (Kind.isBSSLocal()) 1271 return DataBSSSection; 1272 1273 // Otherwise, just drop the variable in the normal data section. 1274 return DataSection; 1275 } 1276 1277 MCSection *TargetLoweringObjectFileMachO::getSectionForConstant( 1278 const DataLayout &DL, SectionKind Kind, const Constant *C, 1279 Align &Alignment) const { 1280 // If this constant requires a relocation, we have to put it in the data 1281 // segment, not in the text segment. 1282 if (Kind.isData() || Kind.isReadOnlyWithRel()) 1283 return ConstDataSection; 1284 1285 if (Kind.isMergeableConst4()) 1286 return FourByteConstantSection; 1287 if (Kind.isMergeableConst8()) 1288 return EightByteConstantSection; 1289 if (Kind.isMergeableConst16()) 1290 return SixteenByteConstantSection; 1291 return ReadOnlySection; // .const 1292 } 1293 1294 const MCExpr *TargetLoweringObjectFileMachO::getTTypeGlobalReference( 1295 const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM, 1296 MachineModuleInfo *MMI, MCStreamer &Streamer) const { 1297 // The mach-o version of this method defaults to returning a stub reference. 1298 1299 if (Encoding & DW_EH_PE_indirect) { 1300 MachineModuleInfoMachO &MachOMMI = 1301 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1302 1303 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 1304 1305 // Add information about the stub reference to MachOMMI so that the stub 1306 // gets emitted by the asmprinter. 1307 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 1308 if (!StubSym.getPointer()) { 1309 MCSymbol *Sym = TM.getSymbol(GV); 1310 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 1311 } 1312 1313 return TargetLoweringObjectFile:: 1314 getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()), 1315 Encoding & ~DW_EH_PE_indirect, Streamer); 1316 } 1317 1318 return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM, 1319 MMI, Streamer); 1320 } 1321 1322 MCSymbol *TargetLoweringObjectFileMachO::getCFIPersonalitySymbol( 1323 const GlobalValue *GV, const TargetMachine &TM, 1324 MachineModuleInfo *MMI) const { 1325 // The mach-o version of this method defaults to returning a stub reference. 1326 MachineModuleInfoMachO &MachOMMI = 1327 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1328 1329 MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, "$non_lazy_ptr", TM); 1330 1331 // Add information about the stub reference to MachOMMI so that the stub 1332 // gets emitted by the asmprinter. 1333 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(SSym); 1334 if (!StubSym.getPointer()) { 1335 MCSymbol *Sym = TM.getSymbol(GV); 1336 StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage()); 1337 } 1338 1339 return SSym; 1340 } 1341 1342 const MCExpr *TargetLoweringObjectFileMachO::getIndirectSymViaGOTPCRel( 1343 const GlobalValue *GV, const MCSymbol *Sym, const MCValue &MV, 1344 int64_t Offset, MachineModuleInfo *MMI, MCStreamer &Streamer) const { 1345 // Although MachO 32-bit targets do not explicitly have a GOTPCREL relocation 1346 // as 64-bit do, we replace the GOT equivalent by accessing the final symbol 1347 // through a non_lazy_ptr stub instead. One advantage is that it allows the 1348 // computation of deltas to final external symbols. Example: 1349 // 1350 // _extgotequiv: 1351 // .long _extfoo 1352 // 1353 // _delta: 1354 // .long _extgotequiv-_delta 1355 // 1356 // is transformed to: 1357 // 1358 // _delta: 1359 // .long L_extfoo$non_lazy_ptr-(_delta+0) 1360 // 1361 // .section __IMPORT,__pointers,non_lazy_symbol_pointers 1362 // L_extfoo$non_lazy_ptr: 1363 // .indirect_symbol _extfoo 1364 // .long 0 1365 // 1366 // The indirect symbol table (and sections of non_lazy_symbol_pointers type) 1367 // may point to both local (same translation unit) and global (other 1368 // translation units) symbols. Example: 1369 // 1370 // .section __DATA,__pointers,non_lazy_symbol_pointers 1371 // L1: 1372 // .indirect_symbol _myGlobal 1373 // .long 0 1374 // L2: 1375 // .indirect_symbol _myLocal 1376 // .long _myLocal 1377 // 1378 // If the symbol is local, instead of the symbol's index, the assembler 1379 // places the constant INDIRECT_SYMBOL_LOCAL into the indirect symbol table. 1380 // Then the linker will notice the constant in the table and will look at the 1381 // content of the symbol. 1382 MachineModuleInfoMachO &MachOMMI = 1383 MMI->getObjFileInfo<MachineModuleInfoMachO>(); 1384 MCContext &Ctx = getContext(); 1385 1386 // The offset must consider the original displacement from the base symbol 1387 // since 32-bit targets don't have a GOTPCREL to fold the PC displacement. 1388 Offset = -MV.getConstant(); 1389 const MCSymbol *BaseSym = &MV.getSymB()->getSymbol(); 1390 1391 // Access the final symbol via sym$non_lazy_ptr and generate the appropriated 1392 // non_lazy_ptr stubs. 1393 SmallString<128> Name; 1394 StringRef Suffix = "$non_lazy_ptr"; 1395 Name += MMI->getModule()->getDataLayout().getPrivateGlobalPrefix(); 1396 Name += Sym->getName(); 1397 Name += Suffix; 1398 MCSymbol *Stub = Ctx.getOrCreateSymbol(Name); 1399 1400 MachineModuleInfoImpl::StubValueTy &StubSym = MachOMMI.getGVStubEntry(Stub); 1401 1402 if (!StubSym.getPointer()) 1403 StubSym = MachineModuleInfoImpl::StubValueTy(const_cast<MCSymbol *>(Sym), 1404 !GV->hasLocalLinkage()); 1405 1406 const MCExpr *BSymExpr = 1407 MCSymbolRefExpr::create(BaseSym, MCSymbolRefExpr::VK_None, Ctx); 1408 const MCExpr *LHS = 1409 MCSymbolRefExpr::create(Stub, MCSymbolRefExpr::VK_None, Ctx); 1410 1411 if (!Offset) 1412 return MCBinaryExpr::createSub(LHS, BSymExpr, Ctx); 1413 1414 const MCExpr *RHS = 1415 MCBinaryExpr::createAdd(BSymExpr, MCConstantExpr::create(Offset, Ctx), Ctx); 1416 return MCBinaryExpr::createSub(LHS, RHS, Ctx); 1417 } 1418 1419 static bool canUsePrivateLabel(const MCAsmInfo &AsmInfo, 1420 const MCSection &Section) { 1421 if (!AsmInfo.isSectionAtomizableBySymbols(Section)) 1422 return true; 1423 1424 // If it is not dead stripped, it is safe to use private labels. 1425 const MCSectionMachO &SMO = cast<MCSectionMachO>(Section); 1426 if (SMO.hasAttribute(MachO::S_ATTR_NO_DEAD_STRIP)) 1427 return true; 1428 1429 return false; 1430 } 1431 1432 void TargetLoweringObjectFileMachO::getNameWithPrefix( 1433 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1434 const TargetMachine &TM) const { 1435 bool CannotUsePrivateLabel = true; 1436 if (auto *GO = GV->getBaseObject()) { 1437 SectionKind GOKind = TargetLoweringObjectFile::getKindForGlobal(GO, TM); 1438 const MCSection *TheSection = SectionForGlobal(GO, GOKind, TM); 1439 CannotUsePrivateLabel = 1440 !canUsePrivateLabel(*TM.getMCAsmInfo(), *TheSection); 1441 } 1442 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1443 } 1444 1445 //===----------------------------------------------------------------------===// 1446 // COFF 1447 //===----------------------------------------------------------------------===// 1448 1449 static unsigned 1450 getCOFFSectionFlags(SectionKind K, const TargetMachine &TM) { 1451 unsigned Flags = 0; 1452 bool isThumb = TM.getTargetTriple().getArch() == Triple::thumb; 1453 1454 if (K.isMetadata()) 1455 Flags |= 1456 COFF::IMAGE_SCN_MEM_DISCARDABLE; 1457 else if (K.isText()) 1458 Flags |= 1459 COFF::IMAGE_SCN_MEM_EXECUTE | 1460 COFF::IMAGE_SCN_MEM_READ | 1461 COFF::IMAGE_SCN_CNT_CODE | 1462 (isThumb ? COFF::IMAGE_SCN_MEM_16BIT : (COFF::SectionCharacteristics)0); 1463 else if (K.isBSS()) 1464 Flags |= 1465 COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA | 1466 COFF::IMAGE_SCN_MEM_READ | 1467 COFF::IMAGE_SCN_MEM_WRITE; 1468 else if (K.isThreadLocal()) 1469 Flags |= 1470 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1471 COFF::IMAGE_SCN_MEM_READ | 1472 COFF::IMAGE_SCN_MEM_WRITE; 1473 else if (K.isReadOnly() || K.isReadOnlyWithRel()) 1474 Flags |= 1475 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1476 COFF::IMAGE_SCN_MEM_READ; 1477 else if (K.isWriteable()) 1478 Flags |= 1479 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1480 COFF::IMAGE_SCN_MEM_READ | 1481 COFF::IMAGE_SCN_MEM_WRITE; 1482 1483 return Flags; 1484 } 1485 1486 static const GlobalValue *getComdatGVForCOFF(const GlobalValue *GV) { 1487 const Comdat *C = GV->getComdat(); 1488 assert(C && "expected GV to have a Comdat!"); 1489 1490 StringRef ComdatGVName = C->getName(); 1491 const GlobalValue *ComdatGV = GV->getParent()->getNamedValue(ComdatGVName); 1492 if (!ComdatGV) 1493 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 1494 "' does not exist."); 1495 1496 if (ComdatGV->getComdat() != C) 1497 report_fatal_error("Associative COMDAT symbol '" + ComdatGVName + 1498 "' is not a key for its COMDAT."); 1499 1500 return ComdatGV; 1501 } 1502 1503 static int getSelectionForCOFF(const GlobalValue *GV) { 1504 if (const Comdat *C = GV->getComdat()) { 1505 const GlobalValue *ComdatKey = getComdatGVForCOFF(GV); 1506 if (const auto *GA = dyn_cast<GlobalAlias>(ComdatKey)) 1507 ComdatKey = GA->getBaseObject(); 1508 if (ComdatKey == GV) { 1509 switch (C->getSelectionKind()) { 1510 case Comdat::Any: 1511 return COFF::IMAGE_COMDAT_SELECT_ANY; 1512 case Comdat::ExactMatch: 1513 return COFF::IMAGE_COMDAT_SELECT_EXACT_MATCH; 1514 case Comdat::Largest: 1515 return COFF::IMAGE_COMDAT_SELECT_LARGEST; 1516 case Comdat::NoDuplicates: 1517 return COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1518 case Comdat::SameSize: 1519 return COFF::IMAGE_COMDAT_SELECT_SAME_SIZE; 1520 } 1521 } else { 1522 return COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE; 1523 } 1524 } 1525 return 0; 1526 } 1527 1528 MCSection *TargetLoweringObjectFileCOFF::getExplicitSectionGlobal( 1529 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1530 int Selection = 0; 1531 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1532 StringRef Name = GO->getSection(); 1533 StringRef COMDATSymName = ""; 1534 if (GO->hasComdat()) { 1535 Selection = getSelectionForCOFF(GO); 1536 const GlobalValue *ComdatGV; 1537 if (Selection == COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE) 1538 ComdatGV = getComdatGVForCOFF(GO); 1539 else 1540 ComdatGV = GO; 1541 1542 if (!ComdatGV->hasPrivateLinkage()) { 1543 MCSymbol *Sym = TM.getSymbol(ComdatGV); 1544 COMDATSymName = Sym->getName(); 1545 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1546 } else { 1547 Selection = 0; 1548 } 1549 } 1550 1551 return getContext().getCOFFSection(Name, Characteristics, Kind, COMDATSymName, 1552 Selection); 1553 } 1554 1555 static StringRef getCOFFSectionNameForUniqueGlobal(SectionKind Kind) { 1556 if (Kind.isText()) 1557 return ".text"; 1558 if (Kind.isBSS()) 1559 return ".bss"; 1560 if (Kind.isThreadLocal()) 1561 return ".tls$"; 1562 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1563 return ".rdata"; 1564 return ".data"; 1565 } 1566 1567 MCSection *TargetLoweringObjectFileCOFF::SelectSectionForGlobal( 1568 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 1569 // If we have -ffunction-sections then we should emit the global value to a 1570 // uniqued section specifically for it. 1571 bool EmitUniquedSection; 1572 if (Kind.isText()) 1573 EmitUniquedSection = TM.getFunctionSections(); 1574 else 1575 EmitUniquedSection = TM.getDataSections(); 1576 1577 if ((EmitUniquedSection && !Kind.isCommon()) || GO->hasComdat()) { 1578 SmallString<256> Name = getCOFFSectionNameForUniqueGlobal(Kind); 1579 1580 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1581 1582 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1583 int Selection = getSelectionForCOFF(GO); 1584 if (!Selection) 1585 Selection = COFF::IMAGE_COMDAT_SELECT_NODUPLICATES; 1586 const GlobalValue *ComdatGV; 1587 if (GO->hasComdat()) 1588 ComdatGV = getComdatGVForCOFF(GO); 1589 else 1590 ComdatGV = GO; 1591 1592 unsigned UniqueID = MCContext::GenericSectionID; 1593 if (EmitUniquedSection) 1594 UniqueID = NextUniqueID++; 1595 1596 if (!ComdatGV->hasPrivateLinkage()) { 1597 MCSymbol *Sym = TM.getSymbol(ComdatGV); 1598 StringRef COMDATSymName = Sym->getName(); 1599 1600 if (const auto *F = dyn_cast<Function>(GO)) 1601 if (Optional<StringRef> Prefix = F->getSectionPrefix()) 1602 raw_svector_ostream(Name) << '$' << *Prefix; 1603 1604 // Append "$symbol" to the section name *before* IR-level mangling is 1605 // applied when targetting mingw. This is what GCC does, and the ld.bfd 1606 // COFF linker will not properly handle comdats otherwise. 1607 if (getTargetTriple().isWindowsGNUEnvironment()) 1608 raw_svector_ostream(Name) << '$' << ComdatGV->getName(); 1609 1610 return getContext().getCOFFSection(Name, Characteristics, Kind, 1611 COMDATSymName, Selection, UniqueID); 1612 } else { 1613 SmallString<256> TmpData; 1614 getMangler().getNameWithPrefix(TmpData, GO, /*CannotUsePrivateLabel=*/true); 1615 return getContext().getCOFFSection(Name, Characteristics, Kind, TmpData, 1616 Selection, UniqueID); 1617 } 1618 } 1619 1620 if (Kind.isText()) 1621 return TextSection; 1622 1623 if (Kind.isThreadLocal()) 1624 return TLSDataSection; 1625 1626 if (Kind.isReadOnly() || Kind.isReadOnlyWithRel()) 1627 return ReadOnlySection; 1628 1629 // Note: we claim that common symbols are put in BSSSection, but they are 1630 // really emitted with the magic .comm directive, which creates a symbol table 1631 // entry but not a section. 1632 if (Kind.isBSS() || Kind.isCommon()) 1633 return BSSSection; 1634 1635 return DataSection; 1636 } 1637 1638 void TargetLoweringObjectFileCOFF::getNameWithPrefix( 1639 SmallVectorImpl<char> &OutName, const GlobalValue *GV, 1640 const TargetMachine &TM) const { 1641 bool CannotUsePrivateLabel = false; 1642 if (GV->hasPrivateLinkage() && 1643 ((isa<Function>(GV) && TM.getFunctionSections()) || 1644 (isa<GlobalVariable>(GV) && TM.getDataSections()))) 1645 CannotUsePrivateLabel = true; 1646 1647 getMangler().getNameWithPrefix(OutName, GV, CannotUsePrivateLabel); 1648 } 1649 1650 MCSection *TargetLoweringObjectFileCOFF::getSectionForJumpTable( 1651 const Function &F, const TargetMachine &TM) const { 1652 // If the function can be removed, produce a unique section so that 1653 // the table doesn't prevent the removal. 1654 const Comdat *C = F.getComdat(); 1655 bool EmitUniqueSection = TM.getFunctionSections() || C; 1656 if (!EmitUniqueSection) 1657 return ReadOnlySection; 1658 1659 // FIXME: we should produce a symbol for F instead. 1660 if (F.hasPrivateLinkage()) 1661 return ReadOnlySection; 1662 1663 MCSymbol *Sym = TM.getSymbol(&F); 1664 StringRef COMDATSymName = Sym->getName(); 1665 1666 SectionKind Kind = SectionKind::getReadOnly(); 1667 StringRef SecName = getCOFFSectionNameForUniqueGlobal(Kind); 1668 unsigned Characteristics = getCOFFSectionFlags(Kind, TM); 1669 Characteristics |= COFF::IMAGE_SCN_LNK_COMDAT; 1670 unsigned UniqueID = NextUniqueID++; 1671 1672 return getContext().getCOFFSection( 1673 SecName, Characteristics, Kind, COMDATSymName, 1674 COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE, UniqueID); 1675 } 1676 1677 void TargetLoweringObjectFileCOFF::emitModuleMetadata(MCStreamer &Streamer, 1678 Module &M) const { 1679 emitLinkerDirectives(Streamer, M); 1680 1681 unsigned Version = 0; 1682 unsigned Flags = 0; 1683 StringRef Section; 1684 1685 GetObjCImageInfo(M, Version, Flags, Section); 1686 if (!Section.empty()) { 1687 auto &C = getContext(); 1688 auto *S = C.getCOFFSection(Section, 1689 COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1690 COFF::IMAGE_SCN_MEM_READ, 1691 SectionKind::getReadOnly()); 1692 Streamer.SwitchSection(S); 1693 Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO"))); 1694 Streamer.emitInt32(Version); 1695 Streamer.emitInt32(Flags); 1696 Streamer.AddBlankLine(); 1697 } 1698 1699 auto &C = getContext(); 1700 SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags; 1701 M.getModuleFlagsMetadata(ModuleFlags); 1702 1703 MDNode *CFGProfile = nullptr; 1704 1705 for (const auto &MFE : ModuleFlags) { 1706 StringRef Key = MFE.Key->getString(); 1707 if (Key == "CG Profile") { 1708 CFGProfile = cast<MDNode>(MFE.Val); 1709 break; 1710 } 1711 } 1712 1713 if (!CFGProfile) 1714 return; 1715 1716 auto GetSym = [this](const MDOperand &MDO) -> MCSymbol * { 1717 if (!MDO) 1718 return nullptr; 1719 auto V = cast<ValueAsMetadata>(MDO); 1720 const Function *F = cast<Function>(V->getValue()); 1721 if (F->hasDLLImportStorageClass()) 1722 return nullptr; 1723 return TM->getSymbol(F); 1724 }; 1725 1726 for (const auto &Edge : CFGProfile->operands()) { 1727 MDNode *E = cast<MDNode>(Edge); 1728 const MCSymbol *From = GetSym(E->getOperand(0)); 1729 const MCSymbol *To = GetSym(E->getOperand(1)); 1730 // Skip null functions. This can happen if functions are dead stripped after 1731 // the CGProfile pass has been run. 1732 if (!From || !To) 1733 continue; 1734 uint64_t Count = cast<ConstantAsMetadata>(E->getOperand(2)) 1735 ->getValue() 1736 ->getUniqueInteger() 1737 .getZExtValue(); 1738 Streamer.emitCGProfileEntry( 1739 MCSymbolRefExpr::create(From, MCSymbolRefExpr::VK_None, C), 1740 MCSymbolRefExpr::create(To, MCSymbolRefExpr::VK_None, C), Count); 1741 } 1742 } 1743 1744 void TargetLoweringObjectFileCOFF::emitLinkerDirectives( 1745 MCStreamer &Streamer, Module &M) const { 1746 if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) { 1747 // Emit the linker options to the linker .drectve section. According to the 1748 // spec, this section is a space-separated string containing flags for 1749 // linker. 1750 MCSection *Sec = getDrectveSection(); 1751 Streamer.SwitchSection(Sec); 1752 for (const auto *Option : LinkerOptions->operands()) { 1753 for (const auto &Piece : cast<MDNode>(Option)->operands()) { 1754 // Lead with a space for consistency with our dllexport implementation. 1755 std::string Directive(" "); 1756 Directive.append(std::string(cast<MDString>(Piece)->getString())); 1757 Streamer.emitBytes(Directive); 1758 } 1759 } 1760 } 1761 1762 // Emit /EXPORT: flags for each exported global as necessary. 1763 std::string Flags; 1764 for (const GlobalValue &GV : M.global_values()) { 1765 raw_string_ostream OS(Flags); 1766 emitLinkerFlagsForGlobalCOFF(OS, &GV, getTargetTriple(), getMangler()); 1767 OS.flush(); 1768 if (!Flags.empty()) { 1769 Streamer.SwitchSection(getDrectveSection()); 1770 Streamer.emitBytes(Flags); 1771 } 1772 Flags.clear(); 1773 } 1774 1775 // Emit /INCLUDE: flags for each used global as necessary. 1776 if (const auto *LU = M.getNamedGlobal("llvm.used")) { 1777 assert(LU->hasInitializer() && "expected llvm.used to have an initializer"); 1778 assert(isa<ArrayType>(LU->getValueType()) && 1779 "expected llvm.used to be an array type"); 1780 if (const auto *A = cast<ConstantArray>(LU->getInitializer())) { 1781 for (const Value *Op : A->operands()) { 1782 const auto *GV = cast<GlobalValue>(Op->stripPointerCasts()); 1783 // Global symbols with internal or private linkage are not visible to 1784 // the linker, and thus would cause an error when the linker tried to 1785 // preserve the symbol due to the `/include:` directive. 1786 if (GV->hasLocalLinkage()) 1787 continue; 1788 1789 raw_string_ostream OS(Flags); 1790 emitLinkerFlagsForUsedCOFF(OS, GV, getTargetTriple(), getMangler()); 1791 OS.flush(); 1792 1793 if (!Flags.empty()) { 1794 Streamer.SwitchSection(getDrectveSection()); 1795 Streamer.emitBytes(Flags); 1796 } 1797 Flags.clear(); 1798 } 1799 } 1800 } 1801 } 1802 1803 void TargetLoweringObjectFileCOFF::Initialize(MCContext &Ctx, 1804 const TargetMachine &TM) { 1805 TargetLoweringObjectFile::Initialize(Ctx, TM); 1806 this->TM = &TM; 1807 const Triple &T = TM.getTargetTriple(); 1808 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { 1809 StaticCtorSection = 1810 Ctx.getCOFFSection(".CRT$XCU", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1811 COFF::IMAGE_SCN_MEM_READ, 1812 SectionKind::getReadOnly()); 1813 StaticDtorSection = 1814 Ctx.getCOFFSection(".CRT$XTX", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1815 COFF::IMAGE_SCN_MEM_READ, 1816 SectionKind::getReadOnly()); 1817 } else { 1818 StaticCtorSection = Ctx.getCOFFSection( 1819 ".ctors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1820 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, 1821 SectionKind::getData()); 1822 StaticDtorSection = Ctx.getCOFFSection( 1823 ".dtors", COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1824 COFF::IMAGE_SCN_MEM_READ | COFF::IMAGE_SCN_MEM_WRITE, 1825 SectionKind::getData()); 1826 } 1827 } 1828 1829 static MCSectionCOFF *getCOFFStaticStructorSection(MCContext &Ctx, 1830 const Triple &T, bool IsCtor, 1831 unsigned Priority, 1832 const MCSymbol *KeySym, 1833 MCSectionCOFF *Default) { 1834 if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) { 1835 // If the priority is the default, use .CRT$XCU, possibly associative. 1836 if (Priority == 65535) 1837 return Ctx.getAssociativeCOFFSection(Default, KeySym, 0); 1838 1839 // Otherwise, we need to compute a new section name. Low priorities should 1840 // run earlier. The linker will sort sections ASCII-betically, and we need a 1841 // string that sorts between .CRT$XCA and .CRT$XCU. In the general case, we 1842 // make a name like ".CRT$XCT12345", since that runs before .CRT$XCU. Really 1843 // low priorities need to sort before 'L', since the CRT uses that 1844 // internally, so we use ".CRT$XCA00001" for them. 1845 SmallString<24> Name; 1846 raw_svector_ostream OS(Name); 1847 OS << ".CRT$X" << (IsCtor ? "C" : "T") << 1848 (Priority < 200 ? 'A' : 'T') << format("%05u", Priority); 1849 MCSectionCOFF *Sec = Ctx.getCOFFSection( 1850 Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | COFF::IMAGE_SCN_MEM_READ, 1851 SectionKind::getReadOnly()); 1852 return Ctx.getAssociativeCOFFSection(Sec, KeySym, 0); 1853 } 1854 1855 std::string Name = IsCtor ? ".ctors" : ".dtors"; 1856 if (Priority != 65535) 1857 raw_string_ostream(Name) << format(".%05u", 65535 - Priority); 1858 1859 return Ctx.getAssociativeCOFFSection( 1860 Ctx.getCOFFSection(Name, COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1861 COFF::IMAGE_SCN_MEM_READ | 1862 COFF::IMAGE_SCN_MEM_WRITE, 1863 SectionKind::getData()), 1864 KeySym, 0); 1865 } 1866 1867 MCSection *TargetLoweringObjectFileCOFF::getStaticCtorSection( 1868 unsigned Priority, const MCSymbol *KeySym) const { 1869 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), true, 1870 Priority, KeySym, 1871 cast<MCSectionCOFF>(StaticCtorSection)); 1872 } 1873 1874 MCSection *TargetLoweringObjectFileCOFF::getStaticDtorSection( 1875 unsigned Priority, const MCSymbol *KeySym) const { 1876 return getCOFFStaticStructorSection(getContext(), getTargetTriple(), false, 1877 Priority, KeySym, 1878 cast<MCSectionCOFF>(StaticDtorSection)); 1879 } 1880 1881 const MCExpr *TargetLoweringObjectFileCOFF::lowerRelativeReference( 1882 const GlobalValue *LHS, const GlobalValue *RHS, 1883 const TargetMachine &TM) const { 1884 const Triple &T = TM.getTargetTriple(); 1885 if (T.isOSCygMing()) 1886 return nullptr; 1887 1888 // Our symbols should exist in address space zero, cowardly no-op if 1889 // otherwise. 1890 if (LHS->getType()->getPointerAddressSpace() != 0 || 1891 RHS->getType()->getPointerAddressSpace() != 0) 1892 return nullptr; 1893 1894 // Both ptrtoint instructions must wrap global objects: 1895 // - Only global variables are eligible for image relative relocations. 1896 // - The subtrahend refers to the special symbol __ImageBase, a GlobalVariable. 1897 // We expect __ImageBase to be a global variable without a section, externally 1898 // defined. 1899 // 1900 // It should look something like this: @__ImageBase = external constant i8 1901 if (!isa<GlobalObject>(LHS) || !isa<GlobalVariable>(RHS) || 1902 LHS->isThreadLocal() || RHS->isThreadLocal() || 1903 RHS->getName() != "__ImageBase" || !RHS->hasExternalLinkage() || 1904 cast<GlobalVariable>(RHS)->hasInitializer() || RHS->hasSection()) 1905 return nullptr; 1906 1907 return MCSymbolRefExpr::create(TM.getSymbol(LHS), 1908 MCSymbolRefExpr::VK_COFF_IMGREL32, 1909 getContext()); 1910 } 1911 1912 static std::string APIntToHexString(const APInt &AI) { 1913 unsigned Width = (AI.getBitWidth() / 8) * 2; 1914 std::string HexString = AI.toString(16, /*Signed=*/false); 1915 llvm::transform(HexString, HexString.begin(), tolower); 1916 unsigned Size = HexString.size(); 1917 assert(Width >= Size && "hex string is too large!"); 1918 HexString.insert(HexString.begin(), Width - Size, '0'); 1919 1920 return HexString; 1921 } 1922 1923 static std::string scalarConstantToHexString(const Constant *C) { 1924 Type *Ty = C->getType(); 1925 if (isa<UndefValue>(C)) { 1926 return APIntToHexString(APInt::getNullValue(Ty->getPrimitiveSizeInBits())); 1927 } else if (const auto *CFP = dyn_cast<ConstantFP>(C)) { 1928 return APIntToHexString(CFP->getValueAPF().bitcastToAPInt()); 1929 } else if (const auto *CI = dyn_cast<ConstantInt>(C)) { 1930 return APIntToHexString(CI->getValue()); 1931 } else { 1932 unsigned NumElements; 1933 if (auto *VTy = dyn_cast<VectorType>(Ty)) 1934 NumElements = cast<FixedVectorType>(VTy)->getNumElements(); 1935 else 1936 NumElements = Ty->getArrayNumElements(); 1937 std::string HexString; 1938 for (int I = NumElements - 1, E = -1; I != E; --I) 1939 HexString += scalarConstantToHexString(C->getAggregateElement(I)); 1940 return HexString; 1941 } 1942 } 1943 1944 MCSection *TargetLoweringObjectFileCOFF::getSectionForConstant( 1945 const DataLayout &DL, SectionKind Kind, const Constant *C, 1946 Align &Alignment) const { 1947 if (Kind.isMergeableConst() && C && 1948 getContext().getAsmInfo()->hasCOFFComdatConstants()) { 1949 // This creates comdat sections with the given symbol name, but unless 1950 // AsmPrinter::GetCPISymbol actually makes the symbol global, the symbol 1951 // will be created with a null storage class, which makes GNU binutils 1952 // error out. 1953 const unsigned Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA | 1954 COFF::IMAGE_SCN_MEM_READ | 1955 COFF::IMAGE_SCN_LNK_COMDAT; 1956 std::string COMDATSymName; 1957 if (Kind.isMergeableConst4()) { 1958 if (Alignment <= 4) { 1959 COMDATSymName = "__real@" + scalarConstantToHexString(C); 1960 Alignment = Align(4); 1961 } 1962 } else if (Kind.isMergeableConst8()) { 1963 if (Alignment <= 8) { 1964 COMDATSymName = "__real@" + scalarConstantToHexString(C); 1965 Alignment = Align(8); 1966 } 1967 } else if (Kind.isMergeableConst16()) { 1968 // FIXME: These may not be appropriate for non-x86 architectures. 1969 if (Alignment <= 16) { 1970 COMDATSymName = "__xmm@" + scalarConstantToHexString(C); 1971 Alignment = Align(16); 1972 } 1973 } else if (Kind.isMergeableConst32()) { 1974 if (Alignment <= 32) { 1975 COMDATSymName = "__ymm@" + scalarConstantToHexString(C); 1976 Alignment = Align(32); 1977 } 1978 } 1979 1980 if (!COMDATSymName.empty()) 1981 return getContext().getCOFFSection(".rdata", Characteristics, Kind, 1982 COMDATSymName, 1983 COFF::IMAGE_COMDAT_SELECT_ANY); 1984 } 1985 1986 return TargetLoweringObjectFile::getSectionForConstant(DL, Kind, C, 1987 Alignment); 1988 } 1989 1990 //===----------------------------------------------------------------------===// 1991 // Wasm 1992 //===----------------------------------------------------------------------===// 1993 1994 static const Comdat *getWasmComdat(const GlobalValue *GV) { 1995 const Comdat *C = GV->getComdat(); 1996 if (!C) 1997 return nullptr; 1998 1999 if (C->getSelectionKind() != Comdat::Any) 2000 report_fatal_error("WebAssembly COMDATs only support " 2001 "SelectionKind::Any, '" + C->getName() + "' cannot be " 2002 "lowered."); 2003 2004 return C; 2005 } 2006 2007 MCSection *TargetLoweringObjectFileWasm::getExplicitSectionGlobal( 2008 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2009 // We don't support explict section names for functions in the wasm object 2010 // format. Each function has to be in its own unique section. 2011 if (isa<Function>(GO)) { 2012 return SelectSectionForGlobal(GO, Kind, TM); 2013 } 2014 2015 StringRef Name = GO->getSection(); 2016 2017 // Certain data sections we treat as named custom sections rather than 2018 // segments within the data section. 2019 // This could be avoided if all data segements (the wasm sense) were 2020 // represented as their own sections (in the llvm sense). 2021 // TODO(sbc): https://github.com/WebAssembly/tool-conventions/issues/138 2022 if (Name == ".llvmcmd" || Name == ".llvmbc") 2023 Kind = SectionKind::getMetadata(); 2024 2025 StringRef Group = ""; 2026 if (const Comdat *C = getWasmComdat(GO)) { 2027 Group = C->getName(); 2028 } 2029 2030 MCSectionWasm* Section = 2031 getContext().getWasmSection(Name, Kind, Group, 2032 MCContext::GenericSectionID); 2033 2034 return Section; 2035 } 2036 2037 static MCSectionWasm *selectWasmSectionForGlobal( 2038 MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang, 2039 const TargetMachine &TM, bool EmitUniqueSection, unsigned *NextUniqueID) { 2040 StringRef Group = ""; 2041 if (const Comdat *C = getWasmComdat(GO)) { 2042 Group = C->getName(); 2043 } 2044 2045 bool UniqueSectionNames = TM.getUniqueSectionNames(); 2046 SmallString<128> Name = getSectionPrefixForGlobal(Kind); 2047 2048 if (const auto *F = dyn_cast<Function>(GO)) { 2049 const auto &OptionalPrefix = F->getSectionPrefix(); 2050 if (OptionalPrefix) 2051 raw_svector_ostream(Name) << '.' << *OptionalPrefix; 2052 } 2053 2054 if (EmitUniqueSection && UniqueSectionNames) { 2055 Name.push_back('.'); 2056 TM.getNameWithPrefix(Name, GO, Mang, true); 2057 } 2058 unsigned UniqueID = MCContext::GenericSectionID; 2059 if (EmitUniqueSection && !UniqueSectionNames) { 2060 UniqueID = *NextUniqueID; 2061 (*NextUniqueID)++; 2062 } 2063 2064 return Ctx.getWasmSection(Name, Kind, Group, UniqueID); 2065 } 2066 2067 MCSection *TargetLoweringObjectFileWasm::SelectSectionForGlobal( 2068 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2069 2070 if (Kind.isCommon()) 2071 report_fatal_error("mergable sections not supported yet on wasm"); 2072 2073 // If we have -ffunction-section or -fdata-section then we should emit the 2074 // global value to a uniqued section specifically for it. 2075 bool EmitUniqueSection = false; 2076 if (Kind.isText()) 2077 EmitUniqueSection = TM.getFunctionSections(); 2078 else 2079 EmitUniqueSection = TM.getDataSections(); 2080 EmitUniqueSection |= GO->hasComdat(); 2081 2082 return selectWasmSectionForGlobal(getContext(), GO, Kind, getMangler(), TM, 2083 EmitUniqueSection, &NextUniqueID); 2084 } 2085 2086 bool TargetLoweringObjectFileWasm::shouldPutJumpTableInFunctionSection( 2087 bool UsesLabelDifference, const Function &F) const { 2088 // We can always create relative relocations, so use another section 2089 // that can be marked non-executable. 2090 return false; 2091 } 2092 2093 const MCExpr *TargetLoweringObjectFileWasm::lowerRelativeReference( 2094 const GlobalValue *LHS, const GlobalValue *RHS, 2095 const TargetMachine &TM) const { 2096 // We may only use a PLT-relative relocation to refer to unnamed_addr 2097 // functions. 2098 if (!LHS->hasGlobalUnnamedAddr() || !LHS->getValueType()->isFunctionTy()) 2099 return nullptr; 2100 2101 // Basic sanity checks. 2102 if (LHS->getType()->getPointerAddressSpace() != 0 || 2103 RHS->getType()->getPointerAddressSpace() != 0 || LHS->isThreadLocal() || 2104 RHS->isThreadLocal()) 2105 return nullptr; 2106 2107 return MCBinaryExpr::createSub( 2108 MCSymbolRefExpr::create(TM.getSymbol(LHS), MCSymbolRefExpr::VK_None, 2109 getContext()), 2110 MCSymbolRefExpr::create(TM.getSymbol(RHS), getContext()), getContext()); 2111 } 2112 2113 void TargetLoweringObjectFileWasm::InitializeWasm() { 2114 StaticCtorSection = 2115 getContext().getWasmSection(".init_array", SectionKind::getData()); 2116 2117 // We don't use PersonalityEncoding and LSDAEncoding because we don't emit 2118 // .cfi directives. We use TTypeEncoding to encode typeinfo global variables. 2119 TTypeEncoding = dwarf::DW_EH_PE_absptr; 2120 } 2121 2122 MCSection *TargetLoweringObjectFileWasm::getStaticCtorSection( 2123 unsigned Priority, const MCSymbol *KeySym) const { 2124 return Priority == UINT16_MAX ? 2125 StaticCtorSection : 2126 getContext().getWasmSection(".init_array." + utostr(Priority), 2127 SectionKind::getData()); 2128 } 2129 2130 MCSection *TargetLoweringObjectFileWasm::getStaticDtorSection( 2131 unsigned Priority, const MCSymbol *KeySym) const { 2132 llvm_unreachable("@llvm.global_dtors should have been lowered already"); 2133 return nullptr; 2134 } 2135 2136 //===----------------------------------------------------------------------===// 2137 // XCOFF 2138 //===----------------------------------------------------------------------===// 2139 MCSymbol * 2140 TargetLoweringObjectFileXCOFF::getTargetSymbol(const GlobalValue *GV, 2141 const TargetMachine &TM) const { 2142 // We always use a qualname symbol for a GV that represents 2143 // a declaration, a function descriptor, or a common symbol. 2144 // If a GV represents a GlobalVariable and -fdata-sections is enabled, we 2145 // also return a qualname so that a label symbol could be avoided. 2146 // It is inherently ambiguous when the GO represents the address of a 2147 // function, as the GO could either represent a function descriptor or a 2148 // function entry point. We choose to always return a function descriptor 2149 // here. 2150 if (const GlobalObject *GO = dyn_cast<GlobalObject>(GV)) { 2151 if (GO->isDeclarationForLinker()) 2152 return cast<MCSectionXCOFF>(getSectionForExternalReference(GO, TM)) 2153 ->getQualNameSymbol(); 2154 2155 SectionKind GOKind = getKindForGlobal(GO, TM); 2156 if (GOKind.isText()) 2157 return cast<MCSectionXCOFF>( 2158 getSectionForFunctionDescriptor(cast<Function>(GO), TM)) 2159 ->getQualNameSymbol(); 2160 if ((TM.getDataSections() && !GO->hasSection()) || GOKind.isCommon() || 2161 GOKind.isBSSLocal()) 2162 return cast<MCSectionXCOFF>(SectionForGlobal(GO, GOKind, TM)) 2163 ->getQualNameSymbol(); 2164 } 2165 2166 // For all other cases, fall back to getSymbol to return the unqualified name. 2167 return nullptr; 2168 } 2169 2170 MCSection *TargetLoweringObjectFileXCOFF::getExplicitSectionGlobal( 2171 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2172 if (!GO->hasSection()) 2173 report_fatal_error("#pragma clang section is not yet supported"); 2174 2175 StringRef SectionName = GO->getSection(); 2176 XCOFF::StorageMappingClass MappingClass; 2177 if (Kind.isText()) 2178 MappingClass = XCOFF::XMC_PR; 2179 else if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) 2180 MappingClass = XCOFF::XMC_RW; 2181 else if (Kind.isReadOnly()) 2182 MappingClass = XCOFF::XMC_RO; 2183 else 2184 report_fatal_error("XCOFF other section types not yet implemented."); 2185 2186 return getContext().getXCOFFSection(SectionName, MappingClass, XCOFF::XTY_SD, 2187 Kind, /* MultiSymbolsAllowed*/ true); 2188 } 2189 2190 MCSection *TargetLoweringObjectFileXCOFF::getSectionForExternalReference( 2191 const GlobalObject *GO, const TargetMachine &TM) const { 2192 assert(GO->isDeclarationForLinker() && 2193 "Tried to get ER section for a defined global."); 2194 2195 SmallString<128> Name; 2196 getNameWithPrefix(Name, GO, TM); 2197 2198 // Externals go into a csect of type ER. 2199 return getContext().getXCOFFSection( 2200 Name, isa<Function>(GO) ? XCOFF::XMC_DS : XCOFF::XMC_UA, XCOFF::XTY_ER, 2201 SectionKind::getMetadata()); 2202 } 2203 2204 MCSection *TargetLoweringObjectFileXCOFF::SelectSectionForGlobal( 2205 const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { 2206 // Common symbols go into a csect with matching name which will get mapped 2207 // into the .bss section. 2208 if (Kind.isBSSLocal() || Kind.isCommon()) { 2209 SmallString<128> Name; 2210 getNameWithPrefix(Name, GO, TM); 2211 return getContext().getXCOFFSection( 2212 Name, Kind.isBSSLocal() ? XCOFF::XMC_BS : XCOFF::XMC_RW, XCOFF::XTY_CM, 2213 Kind); 2214 } 2215 2216 if (Kind.isMergeableCString()) { 2217 Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign( 2218 cast<GlobalVariable>(GO)); 2219 2220 unsigned EntrySize = getEntrySizeForKind(Kind); 2221 std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + "."; 2222 SmallString<128> Name; 2223 Name = SizeSpec + utostr(Alignment.value()); 2224 2225 if (TM.getDataSections()) 2226 getNameWithPrefix(Name, GO, TM); 2227 2228 return getContext().getXCOFFSection( 2229 Name, XCOFF::XMC_RO, XCOFF::XTY_SD, Kind, 2230 /* MultiSymbolsAllowed*/ !TM.getDataSections()); 2231 } 2232 2233 if (Kind.isText()) { 2234 if (TM.getFunctionSections()) { 2235 return cast<MCSymbolXCOFF>(getFunctionEntryPointSymbol(GO, TM)) 2236 ->getRepresentedCsect(); 2237 } 2238 return TextSection; 2239 } 2240 2241 // TODO: We may put Kind.isReadOnlyWithRel() under option control, because 2242 // user may want to have read-only data with relocations placed into a 2243 // read-only section by the compiler. 2244 // For BSS kind, zero initialized data must be emitted to the .data section 2245 // because external linkage control sections that get mapped to the .bss 2246 // section will be linked as tentative defintions, which is only appropriate 2247 // for SectionKind::Common. 2248 if (Kind.isData() || Kind.isReadOnlyWithRel() || Kind.isBSS()) { 2249 if (TM.getDataSections()) { 2250 SmallString<128> Name; 2251 getNameWithPrefix(Name, GO, TM); 2252 return getContext().getXCOFFSection(Name, XCOFF::XMC_RW, XCOFF::XTY_SD, 2253 SectionKind::getData()); 2254 } 2255 return DataSection; 2256 } 2257 2258 if (Kind.isReadOnly()) { 2259 if (TM.getDataSections()) { 2260 SmallString<128> Name; 2261 getNameWithPrefix(Name, GO, TM); 2262 return getContext().getXCOFFSection(Name, XCOFF::XMC_RO, XCOFF::XTY_SD, 2263 SectionKind::getReadOnly()); 2264 } 2265 return ReadOnlySection; 2266 } 2267 2268 report_fatal_error("XCOFF other section types not yet implemented."); 2269 } 2270 2271 MCSection *TargetLoweringObjectFileXCOFF::getSectionForJumpTable( 2272 const Function &F, const TargetMachine &TM) const { 2273 assert (!F.getComdat() && "Comdat not supported on XCOFF."); 2274 2275 if (!TM.getFunctionSections()) 2276 return ReadOnlySection; 2277 2278 // If the function can be removed, produce a unique section so that 2279 // the table doesn't prevent the removal. 2280 SmallString<128> NameStr(".rodata.jmp.."); 2281 getNameWithPrefix(NameStr, &F, TM); 2282 return getContext().getXCOFFSection(NameStr, XCOFF::XMC_RO, XCOFF::XTY_SD, 2283 SectionKind::getReadOnly()); 2284 } 2285 2286 bool TargetLoweringObjectFileXCOFF::shouldPutJumpTableInFunctionSection( 2287 bool UsesLabelDifference, const Function &F) const { 2288 return false; 2289 } 2290 2291 /// Given a mergeable constant with the specified size and relocation 2292 /// information, return a section that it should be placed in. 2293 MCSection *TargetLoweringObjectFileXCOFF::getSectionForConstant( 2294 const DataLayout &DL, SectionKind Kind, const Constant *C, 2295 Align &Alignment) const { 2296 //TODO: Enable emiting constant pool to unique sections when we support it. 2297 return ReadOnlySection; 2298 } 2299 2300 void TargetLoweringObjectFileXCOFF::Initialize(MCContext &Ctx, 2301 const TargetMachine &TgtM) { 2302 TargetLoweringObjectFile::Initialize(Ctx, TgtM); 2303 TTypeEncoding = 2304 dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_datarel | 2305 (TgtM.getTargetTriple().isArch32Bit() ? dwarf::DW_EH_PE_sdata4 2306 : dwarf::DW_EH_PE_sdata8); 2307 PersonalityEncoding = 0; 2308 LSDAEncoding = 0; 2309 CallSiteEncoding = dwarf::DW_EH_PE_udata4; 2310 } 2311 2312 MCSection *TargetLoweringObjectFileXCOFF::getStaticCtorSection( 2313 unsigned Priority, const MCSymbol *KeySym) const { 2314 report_fatal_error("no static constructor section on AIX"); 2315 } 2316 2317 MCSection *TargetLoweringObjectFileXCOFF::getStaticDtorSection( 2318 unsigned Priority, const MCSymbol *KeySym) const { 2319 report_fatal_error("no static destructor section on AIX"); 2320 } 2321 2322 const MCExpr *TargetLoweringObjectFileXCOFF::lowerRelativeReference( 2323 const GlobalValue *LHS, const GlobalValue *RHS, 2324 const TargetMachine &TM) const { 2325 report_fatal_error("XCOFF not yet implemented."); 2326 } 2327 2328 XCOFF::StorageClass 2329 TargetLoweringObjectFileXCOFF::getStorageClassForGlobal(const GlobalValue *GV) { 2330 assert(!isa<GlobalIFunc>(GV) && "GlobalIFunc is not supported on AIX."); 2331 2332 switch (GV->getLinkage()) { 2333 case GlobalValue::InternalLinkage: 2334 case GlobalValue::PrivateLinkage: 2335 return XCOFF::C_HIDEXT; 2336 case GlobalValue::ExternalLinkage: 2337 case GlobalValue::CommonLinkage: 2338 case GlobalValue::AvailableExternallyLinkage: 2339 return XCOFF::C_EXT; 2340 case GlobalValue::ExternalWeakLinkage: 2341 case GlobalValue::LinkOnceAnyLinkage: 2342 case GlobalValue::LinkOnceODRLinkage: 2343 case GlobalValue::WeakAnyLinkage: 2344 case GlobalValue::WeakODRLinkage: 2345 return XCOFF::C_WEAKEXT; 2346 case GlobalValue::AppendingLinkage: 2347 report_fatal_error( 2348 "There is no mapping that implements AppendingLinkage for XCOFF."); 2349 } 2350 llvm_unreachable("Unknown linkage type!"); 2351 } 2352 2353 MCSymbol *TargetLoweringObjectFileXCOFF::getFunctionEntryPointSymbol( 2354 const GlobalValue *Func, const TargetMachine &TM) const { 2355 assert( 2356 (isa<Function>(Func) || 2357 (isa<GlobalAlias>(Func) && 2358 isa_and_nonnull<Function>(cast<GlobalAlias>(Func)->getBaseObject()))) && 2359 "Func must be a function or an alias which has a function as base " 2360 "object."); 2361 2362 SmallString<128> NameStr; 2363 NameStr.push_back('.'); 2364 getNameWithPrefix(NameStr, Func, TM); 2365 2366 // When -function-sections is enabled and explicit section is not specified, 2367 // it's not necessary to emit function entry point label any more. We will use 2368 // function entry point csect instead. And for function delcarations, the 2369 // undefined symbols gets treated as csect with XTY_ER property. 2370 if (((TM.getFunctionSections() && !Func->hasSection()) || 2371 Func->isDeclaration()) && 2372 isa<Function>(Func)) { 2373 return getContext() 2374 .getXCOFFSection(NameStr, XCOFF::XMC_PR, 2375 Func->isDeclaration() ? XCOFF::XTY_ER : XCOFF::XTY_SD, 2376 SectionKind::getText()) 2377 ->getQualNameSymbol(); 2378 } 2379 2380 return getContext().getOrCreateSymbol(NameStr); 2381 } 2382 2383 MCSection *TargetLoweringObjectFileXCOFF::getSectionForFunctionDescriptor( 2384 const Function *F, const TargetMachine &TM) const { 2385 SmallString<128> NameStr; 2386 getNameWithPrefix(NameStr, F, TM); 2387 return getContext().getXCOFFSection(NameStr, XCOFF::XMC_DS, XCOFF::XTY_SD, 2388 SectionKind::getData()); 2389 } 2390 2391 MCSection *TargetLoweringObjectFileXCOFF::getSectionForTOCEntry( 2392 const MCSymbol *Sym, const TargetMachine &TM) const { 2393 // Use TE storage-mapping class when large code model is enabled so that 2394 // the chance of needing -bbigtoc is decreased. 2395 return getContext().getXCOFFSection( 2396 cast<MCSymbolXCOFF>(Sym)->getSymbolTableName(), 2397 TM.getCodeModel() == CodeModel::Large ? XCOFF::XMC_TE : XCOFF::XMC_TC, 2398 XCOFF::XTY_SD, SectionKind::getData()); 2399 } 2400