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