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