1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 coordinates the per-module state used while generating code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenModule.h" 14 #include "ABIInfo.h" 15 #include "CGBlocks.h" 16 #include "CGCUDARuntime.h" 17 #include "CGCXXABI.h" 18 #include "CGCall.h" 19 #include "CGDebugInfo.h" 20 #include "CGHLSLRuntime.h" 21 #include "CGObjCRuntime.h" 22 #include "CGOpenCLRuntime.h" 23 #include "CGOpenMPRuntime.h" 24 #include "CGOpenMPRuntimeGPU.h" 25 #include "CodeGenFunction.h" 26 #include "CodeGenPGO.h" 27 #include "ConstantEmitter.h" 28 #include "CoverageMappingGen.h" 29 #include "TargetInfo.h" 30 #include "clang/AST/ASTContext.h" 31 #include "clang/AST/ASTLambda.h" 32 #include "clang/AST/CharUnits.h" 33 #include "clang/AST/Decl.h" 34 #include "clang/AST/DeclCXX.h" 35 #include "clang/AST/DeclObjC.h" 36 #include "clang/AST/DeclTemplate.h" 37 #include "clang/AST/Mangle.h" 38 #include "clang/AST/RecursiveASTVisitor.h" 39 #include "clang/AST/StmtVisitor.h" 40 #include "clang/Basic/Builtins.h" 41 #include "clang/Basic/CharInfo.h" 42 #include "clang/Basic/CodeGenOptions.h" 43 #include "clang/Basic/Diagnostic.h" 44 #include "clang/Basic/FileManager.h" 45 #include "clang/Basic/Module.h" 46 #include "clang/Basic/SourceManager.h" 47 #include "clang/Basic/TargetInfo.h" 48 #include "clang/Basic/Version.h" 49 #include "clang/CodeGen/BackendUtil.h" 50 #include "clang/CodeGen/ConstantInitBuilder.h" 51 #include "clang/Frontend/FrontendDiagnostic.h" 52 #include "llvm/ADT/STLExtras.h" 53 #include "llvm/ADT/StringExtras.h" 54 #include "llvm/ADT/StringSwitch.h" 55 #include "llvm/Analysis/TargetLibraryInfo.h" 56 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 57 #include "llvm/IR/AttributeMask.h" 58 #include "llvm/IR/CallingConv.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/Intrinsics.h" 61 #include "llvm/IR/LLVMContext.h" 62 #include "llvm/IR/Module.h" 63 #include "llvm/IR/ProfileSummary.h" 64 #include "llvm/ProfileData/InstrProfReader.h" 65 #include "llvm/ProfileData/SampleProf.h" 66 #include "llvm/Support/CRC.h" 67 #include "llvm/Support/CodeGen.h" 68 #include "llvm/Support/CommandLine.h" 69 #include "llvm/Support/ConvertUTF.h" 70 #include "llvm/Support/ErrorHandling.h" 71 #include "llvm/Support/RISCVISAInfo.h" 72 #include "llvm/Support/TimeProfiler.h" 73 #include "llvm/Support/xxhash.h" 74 #include "llvm/TargetParser/Triple.h" 75 #include "llvm/TargetParser/X86TargetParser.h" 76 #include <optional> 77 78 using namespace clang; 79 using namespace CodeGen; 80 81 static llvm::cl::opt<bool> LimitedCoverage( 82 "limited-coverage-experimental", llvm::cl::Hidden, 83 llvm::cl::desc("Emit limited coverage mapping information (experimental)")); 84 85 static const char AnnotationSection[] = "llvm.metadata"; 86 87 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 88 switch (CGM.getContext().getCXXABIKind()) { 89 case TargetCXXABI::AppleARM64: 90 case TargetCXXABI::Fuchsia: 91 case TargetCXXABI::GenericAArch64: 92 case TargetCXXABI::GenericARM: 93 case TargetCXXABI::iOS: 94 case TargetCXXABI::WatchOS: 95 case TargetCXXABI::GenericMIPS: 96 case TargetCXXABI::GenericItanium: 97 case TargetCXXABI::WebAssembly: 98 case TargetCXXABI::XL: 99 return CreateItaniumCXXABI(CGM); 100 case TargetCXXABI::Microsoft: 101 return CreateMicrosoftCXXABI(CGM); 102 } 103 104 llvm_unreachable("invalid C++ ABI kind"); 105 } 106 107 static std::unique_ptr<TargetCodeGenInfo> 108 createTargetCodeGenInfo(CodeGenModule &CGM) { 109 const TargetInfo &Target = CGM.getTarget(); 110 const llvm::Triple &Triple = Target.getTriple(); 111 const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts(); 112 113 switch (Triple.getArch()) { 114 default: 115 return createDefaultTargetCodeGenInfo(CGM); 116 117 case llvm::Triple::le32: 118 return createPNaClTargetCodeGenInfo(CGM); 119 case llvm::Triple::m68k: 120 return createM68kTargetCodeGenInfo(CGM); 121 case llvm::Triple::mips: 122 case llvm::Triple::mipsel: 123 if (Triple.getOS() == llvm::Triple::NaCl) 124 return createPNaClTargetCodeGenInfo(CGM); 125 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true); 126 127 case llvm::Triple::mips64: 128 case llvm::Triple::mips64el: 129 return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false); 130 131 case llvm::Triple::avr: { 132 // For passing parameters, R8~R25 are used on avr, and R18~R25 are used 133 // on avrtiny. For passing return value, R18~R25 are used on avr, and 134 // R22~R25 are used on avrtiny. 135 unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18; 136 unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8; 137 return createAVRTargetCodeGenInfo(CGM, NPR, NRR); 138 } 139 140 case llvm::Triple::aarch64: 141 case llvm::Triple::aarch64_32: 142 case llvm::Triple::aarch64_be: { 143 AArch64ABIKind Kind = AArch64ABIKind::AAPCS; 144 if (Target.getABI() == "darwinpcs") 145 Kind = AArch64ABIKind::DarwinPCS; 146 else if (Triple.isOSWindows()) 147 return createWindowsAArch64TargetCodeGenInfo(CGM, AArch64ABIKind::Win64); 148 149 return createAArch64TargetCodeGenInfo(CGM, Kind); 150 } 151 152 case llvm::Triple::wasm32: 153 case llvm::Triple::wasm64: { 154 WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP; 155 if (Target.getABI() == "experimental-mv") 156 Kind = WebAssemblyABIKind::ExperimentalMV; 157 return createWebAssemblyTargetCodeGenInfo(CGM, Kind); 158 } 159 160 case llvm::Triple::arm: 161 case llvm::Triple::armeb: 162 case llvm::Triple::thumb: 163 case llvm::Triple::thumbeb: { 164 if (Triple.getOS() == llvm::Triple::Win32) 165 return createWindowsARMTargetCodeGenInfo(CGM, ARMABIKind::AAPCS_VFP); 166 167 ARMABIKind Kind = ARMABIKind::AAPCS; 168 StringRef ABIStr = Target.getABI(); 169 if (ABIStr == "apcs-gnu") 170 Kind = ARMABIKind::APCS; 171 else if (ABIStr == "aapcs16") 172 Kind = ARMABIKind::AAPCS16_VFP; 173 else if (CodeGenOpts.FloatABI == "hard" || 174 (CodeGenOpts.FloatABI != "soft" && 175 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF || 176 Triple.getEnvironment() == llvm::Triple::MuslEABIHF || 177 Triple.getEnvironment() == llvm::Triple::EABIHF))) 178 Kind = ARMABIKind::AAPCS_VFP; 179 180 return createARMTargetCodeGenInfo(CGM, Kind); 181 } 182 183 case llvm::Triple::ppc: { 184 if (Triple.isOSAIX()) 185 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false); 186 187 bool IsSoftFloat = 188 CodeGenOpts.FloatABI == "soft" || Target.hasFeature("spe"); 189 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat); 190 } 191 case llvm::Triple::ppcle: { 192 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 193 return createPPC32TargetCodeGenInfo(CGM, IsSoftFloat); 194 } 195 case llvm::Triple::ppc64: 196 if (Triple.isOSAIX()) 197 return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true); 198 199 if (Triple.isOSBinFormatELF()) { 200 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1; 201 if (Target.getABI() == "elfv2") 202 Kind = PPC64_SVR4_ABIKind::ELFv2; 203 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 204 205 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat); 206 } 207 return createPPC64TargetCodeGenInfo(CGM); 208 case llvm::Triple::ppc64le: { 209 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!"); 210 PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2; 211 if (Target.getABI() == "elfv1") 212 Kind = PPC64_SVR4_ABIKind::ELFv1; 213 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft"; 214 215 return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, IsSoftFloat); 216 } 217 218 case llvm::Triple::nvptx: 219 case llvm::Triple::nvptx64: 220 return createNVPTXTargetCodeGenInfo(CGM); 221 222 case llvm::Triple::msp430: 223 return createMSP430TargetCodeGenInfo(CGM); 224 225 case llvm::Triple::riscv32: 226 case llvm::Triple::riscv64: { 227 StringRef ABIStr = Target.getABI(); 228 unsigned XLen = Target.getPointerWidth(LangAS::Default); 229 unsigned ABIFLen = 0; 230 if (ABIStr.ends_with("f")) 231 ABIFLen = 32; 232 else if (ABIStr.ends_with("d")) 233 ABIFLen = 64; 234 bool EABI = ABIStr.ends_with("e"); 235 return createRISCVTargetCodeGenInfo(CGM, XLen, ABIFLen, EABI); 236 } 237 238 case llvm::Triple::systemz: { 239 bool SoftFloat = CodeGenOpts.FloatABI == "soft"; 240 bool HasVector = !SoftFloat && Target.getABI() == "vector"; 241 return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloat); 242 } 243 244 case llvm::Triple::tce: 245 case llvm::Triple::tcele: 246 return createTCETargetCodeGenInfo(CGM); 247 248 case llvm::Triple::x86: { 249 bool IsDarwinVectorABI = Triple.isOSDarwin(); 250 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); 251 252 if (Triple.getOS() == llvm::Triple::Win32) { 253 return createWinX86_32TargetCodeGenInfo( 254 CGM, IsDarwinVectorABI, IsWin32FloatStructABI, 255 CodeGenOpts.NumRegisterParameters); 256 } 257 return createX86_32TargetCodeGenInfo( 258 CGM, IsDarwinVectorABI, IsWin32FloatStructABI, 259 CodeGenOpts.NumRegisterParameters, CodeGenOpts.FloatABI == "soft"); 260 } 261 262 case llvm::Triple::x86_64: { 263 StringRef ABI = Target.getABI(); 264 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 265 : ABI == "avx" ? X86AVXABILevel::AVX 266 : X86AVXABILevel::None); 267 268 switch (Triple.getOS()) { 269 case llvm::Triple::Win32: 270 return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel); 271 default: 272 return createX86_64TargetCodeGenInfo(CGM, AVXLevel); 273 } 274 } 275 case llvm::Triple::hexagon: 276 return createHexagonTargetCodeGenInfo(CGM); 277 case llvm::Triple::lanai: 278 return createLanaiTargetCodeGenInfo(CGM); 279 case llvm::Triple::r600: 280 return createAMDGPUTargetCodeGenInfo(CGM); 281 case llvm::Triple::amdgcn: 282 return createAMDGPUTargetCodeGenInfo(CGM); 283 case llvm::Triple::sparc: 284 return createSparcV8TargetCodeGenInfo(CGM); 285 case llvm::Triple::sparcv9: 286 return createSparcV9TargetCodeGenInfo(CGM); 287 case llvm::Triple::xcore: 288 return createXCoreTargetCodeGenInfo(CGM); 289 case llvm::Triple::arc: 290 return createARCTargetCodeGenInfo(CGM); 291 case llvm::Triple::spir: 292 case llvm::Triple::spir64: 293 return createCommonSPIRTargetCodeGenInfo(CGM); 294 case llvm::Triple::spirv32: 295 case llvm::Triple::spirv64: 296 return createSPIRVTargetCodeGenInfo(CGM); 297 case llvm::Triple::ve: 298 return createVETargetCodeGenInfo(CGM); 299 case llvm::Triple::csky: { 300 bool IsSoftFloat = !Target.hasFeature("hard-float-abi"); 301 bool hasFP64 = 302 Target.hasFeature("fpuv2_df") || Target.hasFeature("fpuv3_df"); 303 return createCSKYTargetCodeGenInfo(CGM, IsSoftFloat ? 0 304 : hasFP64 ? 64 305 : 32); 306 } 307 case llvm::Triple::bpfeb: 308 case llvm::Triple::bpfel: 309 return createBPFTargetCodeGenInfo(CGM); 310 case llvm::Triple::loongarch32: 311 case llvm::Triple::loongarch64: { 312 StringRef ABIStr = Target.getABI(); 313 unsigned ABIFRLen = 0; 314 if (ABIStr.ends_with("f")) 315 ABIFRLen = 32; 316 else if (ABIStr.ends_with("d")) 317 ABIFRLen = 64; 318 return createLoongArchTargetCodeGenInfo( 319 CGM, Target.getPointerWidth(LangAS::Default), ABIFRLen); 320 } 321 } 322 } 323 324 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { 325 if (!TheTargetCodeGenInfo) 326 TheTargetCodeGenInfo = createTargetCodeGenInfo(*this); 327 return *TheTargetCodeGenInfo; 328 } 329 330 CodeGenModule::CodeGenModule(ASTContext &C, 331 IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, 332 const HeaderSearchOptions &HSO, 333 const PreprocessorOptions &PPO, 334 const CodeGenOptions &CGO, llvm::Module &M, 335 DiagnosticsEngine &diags, 336 CoverageSourceInfo *CoverageInfo) 337 : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO), 338 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 339 Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 340 VMContext(M.getContext()), Types(*this), VTables(*this), 341 SanitizerMD(new SanitizerMetadata(*this)) { 342 343 // Initialize the type cache. 344 llvm::LLVMContext &LLVMContext = M.getContext(); 345 VoidTy = llvm::Type::getVoidTy(LLVMContext); 346 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 347 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 348 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 349 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 350 HalfTy = llvm::Type::getHalfTy(LLVMContext); 351 BFloatTy = llvm::Type::getBFloatTy(LLVMContext); 352 FloatTy = llvm::Type::getFloatTy(LLVMContext); 353 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 354 PointerWidthInBits = C.getTargetInfo().getPointerWidth(LangAS::Default); 355 PointerAlignInBytes = 356 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(LangAS::Default)) 357 .getQuantity(); 358 SizeSizeInBytes = 359 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 360 IntAlignInBytes = 361 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 362 CharTy = 363 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); 364 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 365 IntPtrTy = llvm::IntegerType::get(LLVMContext, 366 C.getTargetInfo().getMaxPointerWidth()); 367 Int8PtrTy = llvm::PointerType::get(LLVMContext, 0); 368 const llvm::DataLayout &DL = M.getDataLayout(); 369 AllocaInt8PtrTy = 370 llvm::PointerType::get(LLVMContext, DL.getAllocaAddrSpace()); 371 GlobalsInt8PtrTy = 372 llvm::PointerType::get(LLVMContext, DL.getDefaultGlobalsAddressSpace()); 373 ConstGlobalsPtrTy = llvm::PointerType::get( 374 LLVMContext, C.getTargetAddressSpace(GetGlobalConstantAddressSpace())); 375 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 376 377 // Build C++20 Module initializers. 378 // TODO: Add Microsoft here once we know the mangling required for the 379 // initializers. 380 CXX20ModuleInits = 381 LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() == 382 ItaniumMangleContext::MK_Itanium; 383 384 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 385 386 if (LangOpts.ObjC) 387 createObjCRuntime(); 388 if (LangOpts.OpenCL) 389 createOpenCLRuntime(); 390 if (LangOpts.OpenMP) 391 createOpenMPRuntime(); 392 if (LangOpts.CUDA) 393 createCUDARuntime(); 394 if (LangOpts.HLSL) 395 createHLSLRuntime(); 396 397 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 398 if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 399 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 400 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 401 getCXXABI().getMangleContext())); 402 403 // If debug info or coverage generation is enabled, create the CGDebugInfo 404 // object. 405 if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo || 406 CodeGenOpts.CoverageNotesFile.size() || 407 CodeGenOpts.CoverageDataFile.size()) 408 DebugInfo.reset(new CGDebugInfo(*this)); 409 410 Block.GlobalUniqueCount = 0; 411 412 if (C.getLangOpts().ObjC) 413 ObjCData.reset(new ObjCEntrypoints()); 414 415 if (CodeGenOpts.hasProfileClangUse()) { 416 auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 417 CodeGenOpts.ProfileInstrumentUsePath, *FS, 418 CodeGenOpts.ProfileRemappingFile); 419 // We're checking for profile read errors in CompilerInvocation, so if 420 // there was an error it should've already been caught. If it hasn't been 421 // somehow, trip an assertion. 422 assert(ReaderOrErr); 423 PGOReader = std::move(ReaderOrErr.get()); 424 } 425 426 // If coverage mapping generation is enabled, create the 427 // CoverageMappingModuleGen object. 428 if (CodeGenOpts.CoverageMapping) 429 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 430 431 // Generate the module name hash here if needed. 432 if (CodeGenOpts.UniqueInternalLinkageNames && 433 !getModule().getSourceFileName().empty()) { 434 std::string Path = getModule().getSourceFileName(); 435 // Check if a path substitution is needed from the MacroPrefixMap. 436 for (const auto &Entry : LangOpts.MacroPrefixMap) 437 if (Path.rfind(Entry.first, 0) != std::string::npos) { 438 Path = Entry.second + Path.substr(Entry.first.size()); 439 break; 440 } 441 ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(Path); 442 } 443 } 444 445 CodeGenModule::~CodeGenModule() {} 446 447 void CodeGenModule::createObjCRuntime() { 448 // This is just isGNUFamily(), but we want to force implementors of 449 // new ABIs to decide how best to do this. 450 switch (LangOpts.ObjCRuntime.getKind()) { 451 case ObjCRuntime::GNUstep: 452 case ObjCRuntime::GCC: 453 case ObjCRuntime::ObjFW: 454 ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 455 return; 456 457 case ObjCRuntime::FragileMacOSX: 458 case ObjCRuntime::MacOSX: 459 case ObjCRuntime::iOS: 460 case ObjCRuntime::WatchOS: 461 ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 462 return; 463 } 464 llvm_unreachable("bad runtime kind"); 465 } 466 467 void CodeGenModule::createOpenCLRuntime() { 468 OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 469 } 470 471 void CodeGenModule::createOpenMPRuntime() { 472 // Select a specialized code generation class based on the target, if any. 473 // If it does not exist use the default implementation. 474 switch (getTriple().getArch()) { 475 case llvm::Triple::nvptx: 476 case llvm::Triple::nvptx64: 477 case llvm::Triple::amdgcn: 478 assert(getLangOpts().OpenMPIsTargetDevice && 479 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 480 OpenMPRuntime.reset(new CGOpenMPRuntimeGPU(*this)); 481 break; 482 default: 483 if (LangOpts.OpenMPSimd) 484 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 485 else 486 OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 487 break; 488 } 489 } 490 491 void CodeGenModule::createCUDARuntime() { 492 CUDARuntime.reset(CreateNVCUDARuntime(*this)); 493 } 494 495 void CodeGenModule::createHLSLRuntime() { 496 HLSLRuntime.reset(new CGHLSLRuntime(*this)); 497 } 498 499 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 500 Replacements[Name] = C; 501 } 502 503 void CodeGenModule::applyReplacements() { 504 for (auto &I : Replacements) { 505 StringRef MangledName = I.first; 506 llvm::Constant *Replacement = I.second; 507 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 508 if (!Entry) 509 continue; 510 auto *OldF = cast<llvm::Function>(Entry); 511 auto *NewF = dyn_cast<llvm::Function>(Replacement); 512 if (!NewF) { 513 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 514 NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 515 } else { 516 auto *CE = cast<llvm::ConstantExpr>(Replacement); 517 assert(CE->getOpcode() == llvm::Instruction::BitCast || 518 CE->getOpcode() == llvm::Instruction::GetElementPtr); 519 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 520 } 521 } 522 523 // Replace old with new, but keep the old order. 524 OldF->replaceAllUsesWith(Replacement); 525 if (NewF) { 526 NewF->removeFromParent(); 527 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 528 NewF); 529 } 530 OldF->eraseFromParent(); 531 } 532 } 533 534 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 535 GlobalValReplacements.push_back(std::make_pair(GV, C)); 536 } 537 538 void CodeGenModule::applyGlobalValReplacements() { 539 for (auto &I : GlobalValReplacements) { 540 llvm::GlobalValue *GV = I.first; 541 llvm::Constant *C = I.second; 542 543 GV->replaceAllUsesWith(C); 544 GV->eraseFromParent(); 545 } 546 } 547 548 // This is only used in aliases that we created and we know they have a 549 // linear structure. 550 static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { 551 const llvm::Constant *C; 552 if (auto *GA = dyn_cast<llvm::GlobalAlias>(GV)) 553 C = GA->getAliasee(); 554 else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(GV)) 555 C = GI->getResolver(); 556 else 557 return GV; 558 559 const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(C->stripPointerCasts()); 560 if (!AliaseeGV) 561 return nullptr; 562 563 const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); 564 if (FinalGV == GV) 565 return nullptr; 566 567 return FinalGV; 568 } 569 570 static bool checkAliasedGlobal( 571 const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, 572 bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, 573 const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames, 574 SourceRange AliasRange) { 575 GV = getAliasedGlobal(Alias); 576 if (!GV) { 577 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 578 return false; 579 } 580 581 if (GV->hasCommonLinkage()) { 582 const llvm::Triple &Triple = Context.getTargetInfo().getTriple(); 583 if (Triple.getObjectFormat() == llvm::Triple::XCOFF) { 584 Diags.Report(Location, diag::err_alias_to_common); 585 return false; 586 } 587 } 588 589 if (GV->isDeclaration()) { 590 Diags.Report(Location, diag::err_alias_to_undefined) << IsIFunc << IsIFunc; 591 Diags.Report(Location, diag::note_alias_requires_mangled_name) 592 << IsIFunc << IsIFunc; 593 // Provide a note if the given function is not found and exists as a 594 // mangled name. 595 for (const auto &[Decl, Name] : MangledDeclNames) { 596 if (const auto *ND = dyn_cast<NamedDecl>(Decl.getDecl())) { 597 if (ND->getName() == GV->getName()) { 598 Diags.Report(Location, diag::note_alias_mangled_name_alternative) 599 << Name 600 << FixItHint::CreateReplacement( 601 AliasRange, 602 (Twine(IsIFunc ? "ifunc" : "alias") + "(\"" + Name + "\")") 603 .str()); 604 } 605 } 606 } 607 return false; 608 } 609 610 if (IsIFunc) { 611 // Check resolver function type. 612 const auto *F = dyn_cast<llvm::Function>(GV); 613 if (!F) { 614 Diags.Report(Location, diag::err_alias_to_undefined) 615 << IsIFunc << IsIFunc; 616 return false; 617 } 618 619 llvm::FunctionType *FTy = F->getFunctionType(); 620 if (!FTy->getReturnType()->isPointerTy()) { 621 Diags.Report(Location, diag::err_ifunc_resolver_return); 622 return false; 623 } 624 } 625 626 return true; 627 } 628 629 void CodeGenModule::checkAliases() { 630 // Check if the constructed aliases are well formed. It is really unfortunate 631 // that we have to do this in CodeGen, but we only construct mangled names 632 // and aliases during codegen. 633 bool Error = false; 634 DiagnosticsEngine &Diags = getDiags(); 635 for (const GlobalDecl &GD : Aliases) { 636 const auto *D = cast<ValueDecl>(GD.getDecl()); 637 SourceLocation Location; 638 SourceRange Range; 639 bool IsIFunc = D->hasAttr<IFuncAttr>(); 640 if (const Attr *A = D->getDefiningAttr()) { 641 Location = A->getLocation(); 642 Range = A->getRange(); 643 } else 644 llvm_unreachable("Not an alias or ifunc?"); 645 646 StringRef MangledName = getMangledName(GD); 647 llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 648 const llvm::GlobalValue *GV = nullptr; 649 if (!checkAliasedGlobal(getContext(), Diags, Location, IsIFunc, Alias, GV, 650 MangledDeclNames, Range)) { 651 Error = true; 652 continue; 653 } 654 655 llvm::Constant *Aliasee = 656 IsIFunc ? cast<llvm::GlobalIFunc>(Alias)->getResolver() 657 : cast<llvm::GlobalAlias>(Alias)->getAliasee(); 658 659 llvm::GlobalValue *AliaseeGV; 660 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 661 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 662 else 663 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 664 665 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 666 StringRef AliasSection = SA->getName(); 667 if (AliasSection != AliaseeGV->getSection()) 668 Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 669 << AliasSection << IsIFunc << IsIFunc; 670 } 671 672 // We have to handle alias to weak aliases in here. LLVM itself disallows 673 // this since the object semantics would not match the IL one. For 674 // compatibility with gcc we implement it by just pointing the alias 675 // to its aliasee's aliasee. We also warn, since the user is probably 676 // expecting the link to be weak. 677 if (auto *GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) { 678 if (GA->isInterposable()) { 679 Diags.Report(Location, diag::warn_alias_to_weak_alias) 680 << GV->getName() << GA->getName() << IsIFunc; 681 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 682 GA->getAliasee(), Alias->getType()); 683 684 if (IsIFunc) 685 cast<llvm::GlobalIFunc>(Alias)->setResolver(Aliasee); 686 else 687 cast<llvm::GlobalAlias>(Alias)->setAliasee(Aliasee); 688 } 689 } 690 } 691 if (!Error) 692 return; 693 694 for (const GlobalDecl &GD : Aliases) { 695 StringRef MangledName = getMangledName(GD); 696 llvm::GlobalValue *Alias = GetGlobalValue(MangledName); 697 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 698 Alias->eraseFromParent(); 699 } 700 } 701 702 void CodeGenModule::clear() { 703 DeferredDeclsToEmit.clear(); 704 EmittedDeferredDecls.clear(); 705 DeferredAnnotations.clear(); 706 if (OpenMPRuntime) 707 OpenMPRuntime->clear(); 708 } 709 710 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 711 StringRef MainFile) { 712 if (!hasDiagnostics()) 713 return; 714 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 715 if (MainFile.empty()) 716 MainFile = "<stdin>"; 717 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 718 } else { 719 if (Mismatched > 0) 720 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 721 722 if (Missing > 0) 723 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 724 } 725 } 726 727 static std::optional<llvm::GlobalValue::VisibilityTypes> 728 getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K) { 729 // Map to LLVM visibility. 730 switch (K) { 731 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Keep: 732 return std::nullopt; 733 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Default: 734 return llvm::GlobalValue::DefaultVisibility; 735 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Hidden: 736 return llvm::GlobalValue::HiddenVisibility; 737 case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Protected: 738 return llvm::GlobalValue::ProtectedVisibility; 739 } 740 llvm_unreachable("unknown option value!"); 741 } 742 743 void setLLVMVisibility(llvm::GlobalValue &GV, 744 std::optional<llvm::GlobalValue::VisibilityTypes> V) { 745 if (!V) 746 return; 747 748 // Reset DSO locality before setting the visibility. This removes 749 // any effects that visibility options and annotations may have 750 // had on the DSO locality. Setting the visibility will implicitly set 751 // appropriate globals to DSO Local; however, this will be pessimistic 752 // w.r.t. to the normal compiler IRGen. 753 GV.setDSOLocal(false); 754 GV.setVisibility(*V); 755 } 756 757 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, 758 llvm::Module &M) { 759 if (!LO.VisibilityFromDLLStorageClass) 760 return; 761 762 std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility = 763 getLLVMVisibility(LO.getDLLExportVisibility()); 764 765 std::optional<llvm::GlobalValue::VisibilityTypes> 766 NoDLLStorageClassVisibility = 767 getLLVMVisibility(LO.getNoDLLStorageClassVisibility()); 768 769 std::optional<llvm::GlobalValue::VisibilityTypes> 770 ExternDeclDLLImportVisibility = 771 getLLVMVisibility(LO.getExternDeclDLLImportVisibility()); 772 773 std::optional<llvm::GlobalValue::VisibilityTypes> 774 ExternDeclNoDLLStorageClassVisibility = 775 getLLVMVisibility(LO.getExternDeclNoDLLStorageClassVisibility()); 776 777 for (llvm::GlobalValue &GV : M.global_values()) { 778 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) 779 continue; 780 781 if (GV.isDeclarationForLinker()) 782 setLLVMVisibility(GV, GV.getDLLStorageClass() == 783 llvm::GlobalValue::DLLImportStorageClass 784 ? ExternDeclDLLImportVisibility 785 : ExternDeclNoDLLStorageClassVisibility); 786 else 787 setLLVMVisibility(GV, GV.getDLLStorageClass() == 788 llvm::GlobalValue::DLLExportStorageClass 789 ? DLLExportVisibility 790 : NoDLLStorageClassVisibility); 791 792 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 793 } 794 } 795 796 static bool isStackProtectorOn(const LangOptions &LangOpts, 797 const llvm::Triple &Triple, 798 clang::LangOptions::StackProtectorMode Mode) { 799 if (Triple.isAMDGPU() || Triple.isNVPTX()) 800 return false; 801 return LangOpts.getStackProtector() == Mode; 802 } 803 804 void CodeGenModule::Release() { 805 Module *Primary = getContext().getCurrentNamedModule(); 806 if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule()) 807 EmitModuleInitializers(Primary); 808 EmitDeferred(); 809 DeferredDecls.insert(EmittedDeferredDecls.begin(), 810 EmittedDeferredDecls.end()); 811 EmittedDeferredDecls.clear(); 812 EmitVTablesOpportunistically(); 813 applyGlobalValReplacements(); 814 applyReplacements(); 815 emitMultiVersionFunctions(); 816 817 if (Context.getLangOpts().IncrementalExtensions && 818 GlobalTopLevelStmtBlockInFlight.first) { 819 const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second; 820 GlobalTopLevelStmtBlockInFlight.first->FinishFunction(TLSD->getEndLoc()); 821 GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr}; 822 } 823 824 // Module implementations are initialized the same way as a regular TU that 825 // imports one or more modules. 826 if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition()) 827 EmitCXXModuleInitFunc(Primary); 828 else 829 EmitCXXGlobalInitFunc(); 830 EmitCXXGlobalCleanUpFunc(); 831 registerGlobalDtorsWithAtExit(); 832 EmitCXXThreadLocalInitFunc(); 833 if (ObjCRuntime) 834 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 835 AddGlobalCtor(ObjCInitFunction); 836 if (Context.getLangOpts().CUDA && CUDARuntime) { 837 if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) 838 AddGlobalCtor(CudaCtorFunction); 839 } 840 if (OpenMPRuntime) { 841 OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 842 OpenMPRuntime->clear(); 843 } 844 if (PGOReader) { 845 getModule().setProfileSummary( 846 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 847 llvm::ProfileSummary::PSK_Instr); 848 if (PGOStats.hasDiagnostics()) 849 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 850 } 851 llvm::stable_sort(GlobalCtors, [](const Structor &L, const Structor &R) { 852 return L.LexOrder < R.LexOrder; 853 }); 854 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 855 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 856 EmitGlobalAnnotations(); 857 EmitStaticExternCAliases(); 858 checkAliases(); 859 EmitDeferredUnusedCoverageMappings(); 860 CodeGenPGO(*this).setValueProfilingFlag(getModule()); 861 if (CoverageMapping) 862 CoverageMapping->emit(); 863 if (CodeGenOpts.SanitizeCfiCrossDso) { 864 CodeGenFunction(*this).EmitCfiCheckFail(); 865 CodeGenFunction(*this).EmitCfiCheckStub(); 866 } 867 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 868 finalizeKCFITypes(); 869 emitAtAvailableLinkGuard(); 870 if (Context.getTargetInfo().getTriple().isWasm()) 871 EmitMainVoidAlias(); 872 873 if (getTriple().isAMDGPU()) { 874 // Emit amdgpu_code_object_version module flag, which is code object version 875 // times 100. 876 if (getTarget().getTargetOpts().CodeObjectVersion != 877 llvm::CodeObjectVersionKind::COV_None) { 878 getModule().addModuleFlag(llvm::Module::Error, 879 "amdgpu_code_object_version", 880 getTarget().getTargetOpts().CodeObjectVersion); 881 } 882 883 // Currently, "-mprintf-kind" option is only supported for HIP 884 if (LangOpts.HIP) { 885 auto *MDStr = llvm::MDString::get( 886 getLLVMContext(), (getTarget().getTargetOpts().AMDGPUPrintfKindVal == 887 TargetOptions::AMDGPUPrintfKind::Hostcall) 888 ? "hostcall" 889 : "buffered"); 890 getModule().addModuleFlag(llvm::Module::Error, "amdgpu_printf_kind", 891 MDStr); 892 } 893 } 894 895 // Emit a global array containing all external kernels or device variables 896 // used by host functions and mark it as used for CUDA/HIP. This is necessary 897 // to get kernels or device variables in archives linked in even if these 898 // kernels or device variables are only used in host functions. 899 if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) { 900 SmallVector<llvm::Constant *, 8> UsedArray; 901 for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) { 902 GlobalDecl GD; 903 if (auto *FD = dyn_cast<FunctionDecl>(D)) 904 GD = GlobalDecl(FD, KernelReferenceKind::Kernel); 905 else 906 GD = GlobalDecl(D); 907 UsedArray.push_back(llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 908 GetAddrOfGlobal(GD), Int8PtrTy)); 909 } 910 911 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size()); 912 913 auto *GV = new llvm::GlobalVariable( 914 getModule(), ATy, false, llvm::GlobalValue::InternalLinkage, 915 llvm::ConstantArray::get(ATy, UsedArray), "__clang_gpu_used_external"); 916 addCompilerUsedGlobal(GV); 917 } 918 if (LangOpts.HIP) { 919 // Emit a unique ID so that host and device binaries from the same 920 // compilation unit can be associated. 921 auto *GV = new llvm::GlobalVariable( 922 getModule(), Int8Ty, false, llvm::GlobalValue::ExternalLinkage, 923 llvm::Constant::getNullValue(Int8Ty), 924 "__hip_cuid_" + getContext().getCUIDHash()); 925 addCompilerUsedGlobal(GV); 926 } 927 emitLLVMUsed(); 928 if (SanStats) 929 SanStats->finish(); 930 931 if (CodeGenOpts.Autolink && 932 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 933 EmitModuleLinkOptions(); 934 } 935 936 // On ELF we pass the dependent library specifiers directly to the linker 937 // without manipulating them. This is in contrast to other platforms where 938 // they are mapped to a specific linker option by the compiler. This 939 // difference is a result of the greater variety of ELF linkers and the fact 940 // that ELF linkers tend to handle libraries in a more complicated fashion 941 // than on other platforms. This forces us to defer handling the dependent 942 // libs to the linker. 943 // 944 // CUDA/HIP device and host libraries are different. Currently there is no 945 // way to differentiate dependent libraries for host or device. Existing 946 // usage of #pragma comment(lib, *) is intended for host libraries on 947 // Windows. Therefore emit llvm.dependent-libraries only for host. 948 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 949 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 950 for (auto *MD : ELFDependentLibraries) 951 NMD->addOperand(MD); 952 } 953 954 // Record mregparm value now so it is visible through rest of codegen. 955 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 956 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 957 CodeGenOpts.NumRegisterParameters); 958 959 if (CodeGenOpts.DwarfVersion) { 960 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 961 CodeGenOpts.DwarfVersion); 962 } 963 964 if (CodeGenOpts.Dwarf64) 965 getModule().addModuleFlag(llvm::Module::Max, "DWARF64", 1); 966 967 if (Context.getLangOpts().SemanticInterposition) 968 // Require various optimization to respect semantic interposition. 969 getModule().setSemanticInterposition(true); 970 971 if (CodeGenOpts.EmitCodeView) { 972 // Indicate that we want CodeView in the metadata. 973 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 974 } 975 if (CodeGenOpts.CodeViewGHash) { 976 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 977 } 978 if (CodeGenOpts.ControlFlowGuard) { 979 // Function ID tables and checks for Control Flow Guard (cfguard=2). 980 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 981 } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 982 // Function ID tables for Control Flow Guard (cfguard=1). 983 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 984 } 985 if (CodeGenOpts.EHContGuard) { 986 // Function ID tables for EH Continuation Guard. 987 getModule().addModuleFlag(llvm::Module::Warning, "ehcontguard", 1); 988 } 989 if (Context.getLangOpts().Kernel) { 990 // Note if we are compiling with /kernel. 991 getModule().addModuleFlag(llvm::Module::Warning, "ms-kernel", 1); 992 } 993 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 994 // We don't support LTO with 2 with different StrictVTablePointers 995 // FIXME: we could support it by stripping all the information introduced 996 // by StrictVTablePointers. 997 998 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 999 1000 llvm::Metadata *Ops[2] = { 1001 llvm::MDString::get(VMContext, "StrictVTablePointers"), 1002 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1003 llvm::Type::getInt32Ty(VMContext), 1))}; 1004 1005 getModule().addModuleFlag(llvm::Module::Require, 1006 "StrictVTablePointersRequirement", 1007 llvm::MDNode::get(VMContext, Ops)); 1008 } 1009 if (getModuleDebugInfo()) 1010 // We support a single version in the linked module. The LLVM 1011 // parser will drop debug info with a different version number 1012 // (and warn about it, too). 1013 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 1014 llvm::DEBUG_METADATA_VERSION); 1015 1016 // We need to record the widths of enums and wchar_t, so that we can generate 1017 // the correct build attributes in the ARM backend. wchar_size is also used by 1018 // TargetLibraryInfo. 1019 uint64_t WCharWidth = 1020 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 1021 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 1022 1023 if (getTriple().isOSzOS()) { 1024 getModule().addModuleFlag(llvm::Module::Warning, 1025 "zos_product_major_version", 1026 uint32_t(CLANG_VERSION_MAJOR)); 1027 getModule().addModuleFlag(llvm::Module::Warning, 1028 "zos_product_minor_version", 1029 uint32_t(CLANG_VERSION_MINOR)); 1030 getModule().addModuleFlag(llvm::Module::Warning, "zos_product_patchlevel", 1031 uint32_t(CLANG_VERSION_PATCHLEVEL)); 1032 std::string ProductId = getClangVendor() + "clang"; 1033 getModule().addModuleFlag(llvm::Module::Error, "zos_product_id", 1034 llvm::MDString::get(VMContext, ProductId)); 1035 1036 // Record the language because we need it for the PPA2. 1037 StringRef lang_str = languageToString( 1038 LangStandard::getLangStandardForKind(LangOpts.LangStd).Language); 1039 getModule().addModuleFlag(llvm::Module::Error, "zos_cu_language", 1040 llvm::MDString::get(VMContext, lang_str)); 1041 1042 time_t TT = PreprocessorOpts.SourceDateEpoch 1043 ? *PreprocessorOpts.SourceDateEpoch 1044 : std::time(nullptr); 1045 getModule().addModuleFlag(llvm::Module::Max, "zos_translation_time", 1046 static_cast<uint64_t>(TT)); 1047 1048 // Multiple modes will be supported here. 1049 getModule().addModuleFlag(llvm::Module::Error, "zos_le_char_mode", 1050 llvm::MDString::get(VMContext, "ascii")); 1051 } 1052 1053 llvm::Triple T = Context.getTargetInfo().getTriple(); 1054 if (T.isARM() || T.isThumb()) { 1055 // The minimum width of an enum in bytes 1056 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 1057 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 1058 } 1059 1060 if (T.isRISCV()) { 1061 StringRef ABIStr = Target.getABI(); 1062 llvm::LLVMContext &Ctx = TheModule.getContext(); 1063 getModule().addModuleFlag(llvm::Module::Error, "target-abi", 1064 llvm::MDString::get(Ctx, ABIStr)); 1065 1066 // Add the canonical ISA string as metadata so the backend can set the ELF 1067 // attributes correctly. We use AppendUnique so LTO will keep all of the 1068 // unique ISA strings that were linked together. 1069 const std::vector<std::string> &Features = 1070 getTarget().getTargetOpts().Features; 1071 auto ParseResult = 1072 llvm::RISCVISAInfo::parseFeatures(T.isRISCV64() ? 64 : 32, Features); 1073 if (!errorToBool(ParseResult.takeError())) 1074 getModule().addModuleFlag( 1075 llvm::Module::AppendUnique, "riscv-isa", 1076 llvm::MDNode::get( 1077 Ctx, llvm::MDString::get(Ctx, (*ParseResult)->toString()))); 1078 } 1079 1080 if (CodeGenOpts.SanitizeCfiCrossDso) { 1081 // Indicate that we want cross-DSO control flow integrity checks. 1082 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 1083 } 1084 1085 if (CodeGenOpts.WholeProgramVTables) { 1086 // Indicate whether VFE was enabled for this module, so that the 1087 // vcall_visibility metadata added under whole program vtables is handled 1088 // appropriately in the optimizer. 1089 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 1090 CodeGenOpts.VirtualFunctionElimination); 1091 } 1092 1093 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 1094 getModule().addModuleFlag(llvm::Module::Override, 1095 "CFI Canonical Jump Tables", 1096 CodeGenOpts.SanitizeCfiCanonicalJumpTables); 1097 } 1098 1099 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) { 1100 getModule().addModuleFlag(llvm::Module::Override, "kcfi", 1); 1101 // KCFI assumes patchable-function-prefix is the same for all indirectly 1102 // called functions. Store the expected offset for code generation. 1103 if (CodeGenOpts.PatchableFunctionEntryOffset) 1104 getModule().addModuleFlag(llvm::Module::Override, "kcfi-offset", 1105 CodeGenOpts.PatchableFunctionEntryOffset); 1106 } 1107 1108 if (CodeGenOpts.CFProtectionReturn && 1109 Target.checkCFProtectionReturnSupported(getDiags())) { 1110 // Indicate that we want to instrument return control flow protection. 1111 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-return", 1112 1); 1113 } 1114 1115 if (CodeGenOpts.CFProtectionBranch && 1116 Target.checkCFProtectionBranchSupported(getDiags())) { 1117 // Indicate that we want to instrument branch control flow protection. 1118 getModule().addModuleFlag(llvm::Module::Min, "cf-protection-branch", 1119 1); 1120 } 1121 1122 if (CodeGenOpts.FunctionReturnThunks) 1123 getModule().addModuleFlag(llvm::Module::Override, "function_return_thunk_extern", 1); 1124 1125 if (CodeGenOpts.IndirectBranchCSPrefix) 1126 getModule().addModuleFlag(llvm::Module::Override, "indirect_branch_cs_prefix", 1); 1127 1128 // Add module metadata for return address signing (ignoring 1129 // non-leaf/all) and stack tagging. These are actually turned on by function 1130 // attributes, but we use module metadata to emit build attributes. This is 1131 // needed for LTO, where the function attributes are inside bitcode 1132 // serialised into a global variable by the time build attributes are 1133 // emitted, so we can't access them. LTO objects could be compiled with 1134 // different flags therefore module flags are set to "Min" behavior to achieve 1135 // the same end result of the normal build where e.g BTI is off if any object 1136 // doesn't support it. 1137 if (Context.getTargetInfo().hasFeature("ptrauth") && 1138 LangOpts.getSignReturnAddressScope() != 1139 LangOptions::SignReturnAddressScopeKind::None) 1140 getModule().addModuleFlag(llvm::Module::Override, 1141 "sign-return-address-buildattr", 1); 1142 if (LangOpts.Sanitize.has(SanitizerKind::MemtagStack)) 1143 getModule().addModuleFlag(llvm::Module::Override, 1144 "tag-stack-memory-buildattr", 1); 1145 1146 if (T.isARM() || T.isThumb() || T.isAArch64()) { 1147 if (LangOpts.BranchTargetEnforcement) 1148 getModule().addModuleFlag(llvm::Module::Min, "branch-target-enforcement", 1149 1); 1150 if (LangOpts.BranchProtectionPAuthLR) 1151 getModule().addModuleFlag(llvm::Module::Min, "branch-protection-pauth-lr", 1152 1); 1153 if (LangOpts.GuardedControlStack) 1154 getModule().addModuleFlag(llvm::Module::Min, "guarded-control-stack", 1); 1155 if (LangOpts.hasSignReturnAddress()) 1156 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address", 1); 1157 if (LangOpts.isSignReturnAddressScopeAll()) 1158 getModule().addModuleFlag(llvm::Module::Min, "sign-return-address-all", 1159 1); 1160 if (!LangOpts.isSignReturnAddressWithAKey()) 1161 getModule().addModuleFlag(llvm::Module::Min, 1162 "sign-return-address-with-bkey", 1); 1163 } 1164 1165 if (CodeGenOpts.StackClashProtector) 1166 getModule().addModuleFlag( 1167 llvm::Module::Override, "probe-stack", 1168 llvm::MDString::get(TheModule.getContext(), "inline-asm")); 1169 1170 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) 1171 getModule().addModuleFlag(llvm::Module::Min, "stack-probe-size", 1172 CodeGenOpts.StackProbeSize); 1173 1174 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 1175 llvm::LLVMContext &Ctx = TheModule.getContext(); 1176 getModule().addModuleFlag( 1177 llvm::Module::Error, "MemProfProfileFilename", 1178 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); 1179 } 1180 1181 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 1182 // Indicate whether __nvvm_reflect should be configured to flush denormal 1183 // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 1184 // property.) 1185 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 1186 CodeGenOpts.FP32DenormalMode.Output != 1187 llvm::DenormalMode::IEEE); 1188 } 1189 1190 if (LangOpts.EHAsynch) 1191 getModule().addModuleFlag(llvm::Module::Warning, "eh-asynch", 1); 1192 1193 // Indicate whether this Module was compiled with -fopenmp 1194 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 1195 getModule().addModuleFlag(llvm::Module::Max, "openmp", LangOpts.OpenMP); 1196 if (getLangOpts().OpenMPIsTargetDevice) 1197 getModule().addModuleFlag(llvm::Module::Max, "openmp-device", 1198 LangOpts.OpenMP); 1199 1200 // Emit OpenCL specific module metadata: OpenCL/SPIR version. 1201 if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) { 1202 EmitOpenCLMetadata(); 1203 // Emit SPIR version. 1204 if (getTriple().isSPIR()) { 1205 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 1206 // opencl.spir.version named metadata. 1207 // C++ for OpenCL has a distinct mapping for version compatibility with 1208 // OpenCL. 1209 auto Version = LangOpts.getOpenCLCompatibleVersion(); 1210 llvm::Metadata *SPIRVerElts[] = { 1211 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1212 Int32Ty, Version / 100)), 1213 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1214 Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 1215 llvm::NamedMDNode *SPIRVerMD = 1216 TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 1217 llvm::LLVMContext &Ctx = TheModule.getContext(); 1218 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 1219 } 1220 } 1221 1222 // HLSL related end of code gen work items. 1223 if (LangOpts.HLSL) 1224 getHLSLRuntime().finishCodeGen(); 1225 1226 if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 1227 assert(PLevel < 3 && "Invalid PIC Level"); 1228 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 1229 if (Context.getLangOpts().PIE) 1230 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 1231 } 1232 1233 if (getCodeGenOpts().CodeModel.size() > 0) { 1234 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 1235 .Case("tiny", llvm::CodeModel::Tiny) 1236 .Case("small", llvm::CodeModel::Small) 1237 .Case("kernel", llvm::CodeModel::Kernel) 1238 .Case("medium", llvm::CodeModel::Medium) 1239 .Case("large", llvm::CodeModel::Large) 1240 .Default(~0u); 1241 if (CM != ~0u) { 1242 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 1243 getModule().setCodeModel(codeModel); 1244 1245 if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) && 1246 Context.getTargetInfo().getTriple().getArch() == 1247 llvm::Triple::x86_64) { 1248 getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold); 1249 } 1250 } 1251 } 1252 1253 if (CodeGenOpts.NoPLT) 1254 getModule().setRtLibUseGOT(); 1255 if (getTriple().isOSBinFormatELF() && 1256 CodeGenOpts.DirectAccessExternalData != 1257 getModule().getDirectAccessExternalData()) { 1258 getModule().setDirectAccessExternalData( 1259 CodeGenOpts.DirectAccessExternalData); 1260 } 1261 if (CodeGenOpts.UnwindTables) 1262 getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 1263 1264 switch (CodeGenOpts.getFramePointer()) { 1265 case CodeGenOptions::FramePointerKind::None: 1266 // 0 ("none") is the default. 1267 break; 1268 case CodeGenOptions::FramePointerKind::NonLeaf: 1269 getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); 1270 break; 1271 case CodeGenOptions::FramePointerKind::All: 1272 getModule().setFramePointer(llvm::FramePointerKind::All); 1273 break; 1274 } 1275 1276 SimplifyPersonality(); 1277 1278 if (getCodeGenOpts().EmitDeclMetadata) 1279 EmitDeclMetadata(); 1280 1281 if (getCodeGenOpts().CoverageNotesFile.size() || 1282 getCodeGenOpts().CoverageDataFile.size()) 1283 EmitCoverageFile(); 1284 1285 if (CGDebugInfo *DI = getModuleDebugInfo()) 1286 DI->finalize(); 1287 1288 if (getCodeGenOpts().EmitVersionIdentMetadata) 1289 EmitVersionIdentMetadata(); 1290 1291 if (!getCodeGenOpts().RecordCommandLine.empty()) 1292 EmitCommandLineMetadata(); 1293 1294 if (!getCodeGenOpts().StackProtectorGuard.empty()) 1295 getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); 1296 if (!getCodeGenOpts().StackProtectorGuardReg.empty()) 1297 getModule().setStackProtectorGuardReg( 1298 getCodeGenOpts().StackProtectorGuardReg); 1299 if (!getCodeGenOpts().StackProtectorGuardSymbol.empty()) 1300 getModule().setStackProtectorGuardSymbol( 1301 getCodeGenOpts().StackProtectorGuardSymbol); 1302 if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) 1303 getModule().setStackProtectorGuardOffset( 1304 getCodeGenOpts().StackProtectorGuardOffset); 1305 if (getCodeGenOpts().StackAlignment) 1306 getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); 1307 if (getCodeGenOpts().SkipRaxSetup) 1308 getModule().addModuleFlag(llvm::Module::Override, "SkipRaxSetup", 1); 1309 if (getLangOpts().RegCall4) 1310 getModule().addModuleFlag(llvm::Module::Override, "RegCallv4", 1); 1311 1312 if (getContext().getTargetInfo().getMaxTLSAlign()) 1313 getModule().addModuleFlag(llvm::Module::Error, "MaxTLSAlign", 1314 getContext().getTargetInfo().getMaxTLSAlign()); 1315 1316 getTargetCodeGenInfo().emitTargetGlobals(*this); 1317 1318 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); 1319 1320 EmitBackendOptionsMetadata(getCodeGenOpts()); 1321 1322 // If there is device offloading code embed it in the host now. 1323 EmbedObject(&getModule(), CodeGenOpts, getDiags()); 1324 1325 // Set visibility from DLL storage class 1326 // We do this at the end of LLVM IR generation; after any operation 1327 // that might affect the DLL storage class or the visibility, and 1328 // before anything that might act on these. 1329 setVisibilityFromDLLStorageClass(LangOpts, getModule()); 1330 } 1331 1332 void CodeGenModule::EmitOpenCLMetadata() { 1333 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 1334 // opencl.ocl.version named metadata node. 1335 // C++ for OpenCL has a distinct mapping for versions compatibile with OpenCL. 1336 auto Version = LangOpts.getOpenCLCompatibleVersion(); 1337 llvm::Metadata *OCLVerElts[] = { 1338 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1339 Int32Ty, Version / 100)), 1340 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 1341 Int32Ty, (Version % 100) / 10))}; 1342 llvm::NamedMDNode *OCLVerMD = 1343 TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 1344 llvm::LLVMContext &Ctx = TheModule.getContext(); 1345 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 1346 } 1347 1348 void CodeGenModule::EmitBackendOptionsMetadata( 1349 const CodeGenOptions &CodeGenOpts) { 1350 if (getTriple().isRISCV()) { 1351 getModule().addModuleFlag(llvm::Module::Min, "SmallDataLimit", 1352 CodeGenOpts.SmallDataLimit); 1353 } 1354 } 1355 1356 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 1357 // Make sure that this type is translated. 1358 Types.UpdateCompletedType(TD); 1359 } 1360 1361 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 1362 // Make sure that this type is translated. 1363 Types.RefreshTypeCacheForClass(RD); 1364 } 1365 1366 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 1367 if (!TBAA) 1368 return nullptr; 1369 return TBAA->getTypeInfo(QTy); 1370 } 1371 1372 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 1373 if (!TBAA) 1374 return TBAAAccessInfo(); 1375 if (getLangOpts().CUDAIsDevice) { 1376 // As CUDA builtin surface/texture types are replaced, skip generating TBAA 1377 // access info. 1378 if (AccessType->isCUDADeviceBuiltinSurfaceType()) { 1379 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != 1380 nullptr) 1381 return TBAAAccessInfo(); 1382 } else if (AccessType->isCUDADeviceBuiltinTextureType()) { 1383 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != 1384 nullptr) 1385 return TBAAAccessInfo(); 1386 } 1387 } 1388 return TBAA->getAccessInfo(AccessType); 1389 } 1390 1391 TBAAAccessInfo 1392 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 1393 if (!TBAA) 1394 return TBAAAccessInfo(); 1395 return TBAA->getVTablePtrAccessInfo(VTablePtrType); 1396 } 1397 1398 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 1399 if (!TBAA) 1400 return nullptr; 1401 return TBAA->getTBAAStructInfo(QTy); 1402 } 1403 1404 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 1405 if (!TBAA) 1406 return nullptr; 1407 return TBAA->getBaseTypeInfo(QTy); 1408 } 1409 1410 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 1411 if (!TBAA) 1412 return nullptr; 1413 return TBAA->getAccessTagInfo(Info); 1414 } 1415 1416 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 1417 TBAAAccessInfo TargetInfo) { 1418 if (!TBAA) 1419 return TBAAAccessInfo(); 1420 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 1421 } 1422 1423 TBAAAccessInfo 1424 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 1425 TBAAAccessInfo InfoB) { 1426 if (!TBAA) 1427 return TBAAAccessInfo(); 1428 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 1429 } 1430 1431 TBAAAccessInfo 1432 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 1433 TBAAAccessInfo SrcInfo) { 1434 if (!TBAA) 1435 return TBAAAccessInfo(); 1436 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 1437 } 1438 1439 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 1440 TBAAAccessInfo TBAAInfo) { 1441 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 1442 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 1443 } 1444 1445 void CodeGenModule::DecorateInstructionWithInvariantGroup( 1446 llvm::Instruction *I, const CXXRecordDecl *RD) { 1447 I->setMetadata(llvm::LLVMContext::MD_invariant_group, 1448 llvm::MDNode::get(getLLVMContext(), {})); 1449 } 1450 1451 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 1452 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 1453 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 1454 } 1455 1456 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1457 /// specified stmt yet. 1458 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 1459 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1460 "cannot compile this %0 yet"); 1461 std::string Msg = Type; 1462 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 1463 << Msg << S->getSourceRange(); 1464 } 1465 1466 /// ErrorUnsupported - Print out an error that codegen doesn't support the 1467 /// specified decl yet. 1468 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 1469 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 1470 "cannot compile this %0 yet"); 1471 std::string Msg = Type; 1472 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 1473 } 1474 1475 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 1476 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 1477 } 1478 1479 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 1480 const NamedDecl *D) const { 1481 // Internal definitions always have default visibility. 1482 if (GV->hasLocalLinkage()) { 1483 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1484 return; 1485 } 1486 if (!D) 1487 return; 1488 1489 // Set visibility for definitions, and for declarations if requested globally 1490 // or set explicitly. 1491 LinkageInfo LV = D->getLinkageAndVisibility(); 1492 1493 // OpenMP declare target variables must be visible to the host so they can 1494 // be registered. We require protected visibility unless the variable has 1495 // the DT_nohost modifier and does not need to be registered. 1496 if (Context.getLangOpts().OpenMP && 1497 Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(D) && 1498 D->hasAttr<OMPDeclareTargetDeclAttr>() && 1499 D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() != 1500 OMPDeclareTargetDeclAttr::DT_NoHost && 1501 LV.getVisibility() == HiddenVisibility) { 1502 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); 1503 return; 1504 } 1505 1506 if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) { 1507 // Reject incompatible dlllstorage and visibility annotations. 1508 if (!LV.isVisibilityExplicit()) 1509 return; 1510 if (GV->hasDLLExportStorageClass()) { 1511 if (LV.getVisibility() == HiddenVisibility) 1512 getDiags().Report(D->getLocation(), 1513 diag::err_hidden_visibility_dllexport); 1514 } else if (LV.getVisibility() != DefaultVisibility) { 1515 getDiags().Report(D->getLocation(), 1516 diag::err_non_default_visibility_dllimport); 1517 } 1518 return; 1519 } 1520 1521 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 1522 !GV->isDeclarationForLinker()) 1523 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 1524 } 1525 1526 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 1527 llvm::GlobalValue *GV) { 1528 if (GV->hasLocalLinkage()) 1529 return true; 1530 1531 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 1532 return true; 1533 1534 // DLLImport explicitly marks the GV as external. 1535 if (GV->hasDLLImportStorageClass()) 1536 return false; 1537 1538 const llvm::Triple &TT = CGM.getTriple(); 1539 const auto &CGOpts = CGM.getCodeGenOpts(); 1540 if (TT.isWindowsGNUEnvironment()) { 1541 // In MinGW, variables without DLLImport can still be automatically 1542 // imported from a DLL by the linker; don't mark variables that 1543 // potentially could come from another DLL as DSO local. 1544 1545 // With EmulatedTLS, TLS variables can be autoimported from other DLLs 1546 // (and this actually happens in the public interface of libstdc++), so 1547 // such variables can't be marked as DSO local. (Native TLS variables 1548 // can't be dllimported at all, though.) 1549 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 1550 (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) && 1551 CGOpts.AutoImport) 1552 return false; 1553 } 1554 1555 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 1556 // remain unresolved in the link, they can be resolved to zero, which is 1557 // outside the current DSO. 1558 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 1559 return false; 1560 1561 // Every other GV is local on COFF. 1562 // Make an exception for windows OS in the triple: Some firmware builds use 1563 // *-win32-macho triples. This (accidentally?) produced windows relocations 1564 // without GOT tables in older clang versions; Keep this behaviour. 1565 // FIXME: even thread local variables? 1566 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 1567 return true; 1568 1569 // Only handle COFF and ELF for now. 1570 if (!TT.isOSBinFormatELF()) 1571 return false; 1572 1573 // If this is not an executable, don't assume anything is local. 1574 llvm::Reloc::Model RM = CGOpts.RelocationModel; 1575 const auto &LOpts = CGM.getLangOpts(); 1576 if (RM != llvm::Reloc::Static && !LOpts.PIE) { 1577 // On ELF, if -fno-semantic-interposition is specified and the target 1578 // supports local aliases, there will be neither CC1 1579 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set 1580 // dso_local on the function if using a local alias is preferable (can avoid 1581 // PLT indirection). 1582 if (!(isa<llvm::Function>(GV) && GV->canBenefitFromLocalAlias())) 1583 return false; 1584 return !(CGM.getLangOpts().SemanticInterposition || 1585 CGM.getLangOpts().HalfNoSemanticInterposition); 1586 } 1587 1588 // A definition cannot be preempted from an executable. 1589 if (!GV->isDeclarationForLinker()) 1590 return true; 1591 1592 // Most PIC code sequences that assume that a symbol is local cannot produce a 1593 // 0 if it turns out the symbol is undefined. While this is ABI and relocation 1594 // depended, it seems worth it to handle it here. 1595 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 1596 return false; 1597 1598 // PowerPC64 prefers TOC indirection to avoid copy relocations. 1599 if (TT.isPPC64()) 1600 return false; 1601 1602 if (CGOpts.DirectAccessExternalData) { 1603 // If -fdirect-access-external-data (default for -fno-pic), set dso_local 1604 // for non-thread-local variables. If the symbol is not defined in the 1605 // executable, a copy relocation will be needed at link time. dso_local is 1606 // excluded for thread-local variables because they generally don't support 1607 // copy relocations. 1608 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 1609 if (!Var->isThreadLocal()) 1610 return true; 1611 1612 // -fno-pic sets dso_local on a function declaration to allow direct 1613 // accesses when taking its address (similar to a data symbol). If the 1614 // function is not defined in the executable, a canonical PLT entry will be 1615 // needed at link time. -fno-direct-access-external-data can avoid the 1616 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as 1617 // it could just cause trouble without providing perceptible benefits. 1618 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 1619 return true; 1620 } 1621 1622 // If we can use copy relocations we can assume it is local. 1623 1624 // Otherwise don't assume it is local. 1625 return false; 1626 } 1627 1628 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 1629 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 1630 } 1631 1632 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1633 GlobalDecl GD) const { 1634 const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 1635 // C++ destructors have a few C++ ABI specific special cases. 1636 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 1637 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 1638 return; 1639 } 1640 setDLLImportDLLExport(GV, D); 1641 } 1642 1643 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1644 const NamedDecl *D) const { 1645 if (D && D->isExternallyVisible()) { 1646 if (D->hasAttr<DLLImportAttr>()) 1647 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1648 else if ((D->hasAttr<DLLExportAttr>() || 1649 shouldMapVisibilityToDLLExport(D)) && 1650 !GV->isDeclarationForLinker()) 1651 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1652 } 1653 } 1654 1655 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1656 GlobalDecl GD) const { 1657 setDLLImportDLLExport(GV, GD); 1658 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 1659 } 1660 1661 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1662 const NamedDecl *D) const { 1663 setDLLImportDLLExport(GV, D); 1664 setGVPropertiesAux(GV, D); 1665 } 1666 1667 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 1668 const NamedDecl *D) const { 1669 setGlobalVisibility(GV, D); 1670 setDSOLocal(GV); 1671 GV->setPartition(CodeGenOpts.SymbolPartition); 1672 } 1673 1674 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 1675 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 1676 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 1677 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 1678 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 1679 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 1680 } 1681 1682 llvm::GlobalVariable::ThreadLocalMode 1683 CodeGenModule::GetDefaultLLVMTLSModel() const { 1684 switch (CodeGenOpts.getDefaultTLSModel()) { 1685 case CodeGenOptions::GeneralDynamicTLSModel: 1686 return llvm::GlobalVariable::GeneralDynamicTLSModel; 1687 case CodeGenOptions::LocalDynamicTLSModel: 1688 return llvm::GlobalVariable::LocalDynamicTLSModel; 1689 case CodeGenOptions::InitialExecTLSModel: 1690 return llvm::GlobalVariable::InitialExecTLSModel; 1691 case CodeGenOptions::LocalExecTLSModel: 1692 return llvm::GlobalVariable::LocalExecTLSModel; 1693 } 1694 llvm_unreachable("Invalid TLS model!"); 1695 } 1696 1697 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 1698 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 1699 1700 llvm::GlobalValue::ThreadLocalMode TLM; 1701 TLM = GetDefaultLLVMTLSModel(); 1702 1703 // Override the TLS model if it is explicitly specified. 1704 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 1705 TLM = GetLLVMTLSModel(Attr->getModel()); 1706 } 1707 1708 GV->setThreadLocalMode(TLM); 1709 } 1710 1711 static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 1712 StringRef Name) { 1713 const TargetInfo &Target = CGM.getTarget(); 1714 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 1715 } 1716 1717 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 1718 const CPUSpecificAttr *Attr, 1719 unsigned CPUIndex, 1720 raw_ostream &Out) { 1721 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 1722 // supported. 1723 if (Attr) 1724 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 1725 else if (CGM.getTarget().supportsIFunc()) 1726 Out << ".resolver"; 1727 } 1728 1729 static void AppendTargetVersionMangling(const CodeGenModule &CGM, 1730 const TargetVersionAttr *Attr, 1731 raw_ostream &Out) { 1732 if (Attr->isDefaultVersion()) { 1733 Out << ".default"; 1734 return; 1735 } 1736 Out << "._"; 1737 const TargetInfo &TI = CGM.getTarget(); 1738 llvm::SmallVector<StringRef, 8> Feats; 1739 Attr->getFeatures(Feats); 1740 llvm::stable_sort(Feats, [&TI](const StringRef FeatL, const StringRef FeatR) { 1741 return TI.multiVersionSortPriority(FeatL) < 1742 TI.multiVersionSortPriority(FeatR); 1743 }); 1744 for (const auto &Feat : Feats) { 1745 Out << 'M'; 1746 Out << Feat; 1747 } 1748 } 1749 1750 static void AppendTargetMangling(const CodeGenModule &CGM, 1751 const TargetAttr *Attr, raw_ostream &Out) { 1752 if (Attr->isDefaultVersion()) 1753 return; 1754 1755 Out << '.'; 1756 const TargetInfo &Target = CGM.getTarget(); 1757 ParsedTargetAttr Info = Target.parseTargetAttr(Attr->getFeaturesStr()); 1758 llvm::sort(Info.Features, [&Target](StringRef LHS, StringRef RHS) { 1759 // Multiversioning doesn't allow "no-${feature}", so we can 1760 // only have "+" prefixes here. 1761 assert(LHS.starts_with("+") && RHS.starts_with("+") && 1762 "Features should always have a prefix."); 1763 return Target.multiVersionSortPriority(LHS.substr(1)) > 1764 Target.multiVersionSortPriority(RHS.substr(1)); 1765 }); 1766 1767 bool IsFirst = true; 1768 1769 if (!Info.CPU.empty()) { 1770 IsFirst = false; 1771 Out << "arch_" << Info.CPU; 1772 } 1773 1774 for (StringRef Feat : Info.Features) { 1775 if (!IsFirst) 1776 Out << '_'; 1777 IsFirst = false; 1778 Out << Feat.substr(1); 1779 } 1780 } 1781 1782 // Returns true if GD is a function decl with internal linkage and 1783 // needs a unique suffix after the mangled name. 1784 static bool isUniqueInternalLinkageDecl(GlobalDecl GD, 1785 CodeGenModule &CGM) { 1786 const Decl *D = GD.getDecl(); 1787 return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(D) && 1788 (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); 1789 } 1790 1791 static void AppendTargetClonesMangling(const CodeGenModule &CGM, 1792 const TargetClonesAttr *Attr, 1793 unsigned VersionIndex, 1794 raw_ostream &Out) { 1795 const TargetInfo &TI = CGM.getTarget(); 1796 if (TI.getTriple().isAArch64()) { 1797 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1798 if (FeatureStr == "default") { 1799 Out << ".default"; 1800 return; 1801 } 1802 Out << "._"; 1803 SmallVector<StringRef, 8> Features; 1804 FeatureStr.split(Features, "+"); 1805 llvm::stable_sort(Features, 1806 [&TI](const StringRef FeatL, const StringRef FeatR) { 1807 return TI.multiVersionSortPriority(FeatL) < 1808 TI.multiVersionSortPriority(FeatR); 1809 }); 1810 for (auto &Feat : Features) { 1811 Out << 'M'; 1812 Out << Feat; 1813 } 1814 } else { 1815 Out << '.'; 1816 StringRef FeatureStr = Attr->getFeatureStr(VersionIndex); 1817 if (FeatureStr.starts_with("arch=")) 1818 Out << "arch_" << FeatureStr.substr(sizeof("arch=") - 1); 1819 else 1820 Out << FeatureStr; 1821 1822 Out << '.' << Attr->getMangledIndex(VersionIndex); 1823 } 1824 } 1825 1826 static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, 1827 const NamedDecl *ND, 1828 bool OmitMultiVersionMangling = false) { 1829 SmallString<256> Buffer; 1830 llvm::raw_svector_ostream Out(Buffer); 1831 MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1832 if (!CGM.getModuleNameHash().empty()) 1833 MC.needsUniqueInternalLinkageNames(); 1834 bool ShouldMangle = MC.shouldMangleDeclName(ND); 1835 if (ShouldMangle) 1836 MC.mangleName(GD.getWithDecl(ND), Out); 1837 else { 1838 IdentifierInfo *II = ND->getIdentifier(); 1839 assert(II && "Attempt to mangle unnamed decl."); 1840 const auto *FD = dyn_cast<FunctionDecl>(ND); 1841 1842 if (FD && 1843 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1844 if (CGM.getLangOpts().RegCall4) 1845 Out << "__regcall4__" << II->getName(); 1846 else 1847 Out << "__regcall3__" << II->getName(); 1848 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 1849 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 1850 Out << "__device_stub__" << II->getName(); 1851 } else { 1852 Out << II->getName(); 1853 } 1854 } 1855 1856 // Check if the module name hash should be appended for internal linkage 1857 // symbols. This should come before multi-version target suffixes are 1858 // appended. This is to keep the name and module hash suffix of the 1859 // internal linkage function together. The unique suffix should only be 1860 // added when name mangling is done to make sure that the final name can 1861 // be properly demangled. For example, for C functions without prototypes, 1862 // name mangling is not done and the unique suffix should not be appeneded 1863 // then. 1864 if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { 1865 assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && 1866 "Hash computed when not explicitly requested"); 1867 Out << CGM.getModuleNameHash(); 1868 } 1869 1870 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 1871 if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 1872 switch (FD->getMultiVersionKind()) { 1873 case MultiVersionKind::CPUDispatch: 1874 case MultiVersionKind::CPUSpecific: 1875 AppendCPUSpecificCPUDispatchMangling(CGM, 1876 FD->getAttr<CPUSpecificAttr>(), 1877 GD.getMultiVersionIndex(), Out); 1878 break; 1879 case MultiVersionKind::Target: 1880 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 1881 break; 1882 case MultiVersionKind::TargetVersion: 1883 AppendTargetVersionMangling(CGM, FD->getAttr<TargetVersionAttr>(), Out); 1884 break; 1885 case MultiVersionKind::TargetClones: 1886 AppendTargetClonesMangling(CGM, FD->getAttr<TargetClonesAttr>(), 1887 GD.getMultiVersionIndex(), Out); 1888 break; 1889 case MultiVersionKind::None: 1890 llvm_unreachable("None multiversion type isn't valid here"); 1891 } 1892 } 1893 1894 // Make unique name for device side static file-scope variable for HIP. 1895 if (CGM.getContext().shouldExternalize(ND) && 1896 CGM.getLangOpts().GPURelocatableDeviceCode && 1897 CGM.getLangOpts().CUDAIsDevice) 1898 CGM.printPostfixForExternalizedDecl(Out, ND); 1899 1900 return std::string(Out.str()); 1901 } 1902 1903 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 1904 const FunctionDecl *FD, 1905 StringRef &CurName) { 1906 if (!FD->isMultiVersion()) 1907 return; 1908 1909 // Get the name of what this would be without the 'target' attribute. This 1910 // allows us to lookup the version that was emitted when this wasn't a 1911 // multiversion function. 1912 std::string NonTargetName = 1913 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 1914 GlobalDecl OtherGD; 1915 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 1916 assert(OtherGD.getCanonicalDecl() 1917 .getDecl() 1918 ->getAsFunction() 1919 ->isMultiVersion() && 1920 "Other GD should now be a multiversioned function"); 1921 // OtherFD is the version of this function that was mangled BEFORE 1922 // becoming a MultiVersion function. It potentially needs to be updated. 1923 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 1924 .getDecl() 1925 ->getAsFunction() 1926 ->getMostRecentDecl(); 1927 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 1928 // This is so that if the initial version was already the 'default' 1929 // version, we don't try to update it. 1930 if (OtherName != NonTargetName) { 1931 // Remove instead of erase, since others may have stored the StringRef 1932 // to this. 1933 const auto ExistingRecord = Manglings.find(NonTargetName); 1934 if (ExistingRecord != std::end(Manglings)) 1935 Manglings.remove(&(*ExistingRecord)); 1936 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 1937 StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = 1938 Result.first->first(); 1939 // If this is the current decl is being created, make sure we update the name. 1940 if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) 1941 CurName = OtherNameRef; 1942 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 1943 Entry->setName(OtherName); 1944 } 1945 } 1946 } 1947 1948 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 1949 GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 1950 1951 // Some ABIs don't have constructor variants. Make sure that base and 1952 // complete constructors get mangled the same. 1953 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 1954 if (!getTarget().getCXXABI().hasConstructorVariants()) { 1955 CXXCtorType OrigCtorType = GD.getCtorType(); 1956 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 1957 if (OrigCtorType == Ctor_Base) 1958 CanonicalGD = GlobalDecl(CD, Ctor_Complete); 1959 } 1960 } 1961 1962 // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a 1963 // static device variable depends on whether the variable is referenced by 1964 // a host or device host function. Therefore the mangled name cannot be 1965 // cached. 1966 if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(GD.getDecl())) { 1967 auto FoundName = MangledDeclNames.find(CanonicalGD); 1968 if (FoundName != MangledDeclNames.end()) 1969 return FoundName->second; 1970 } 1971 1972 // Keep the first result in the case of a mangling collision. 1973 const auto *ND = cast<NamedDecl>(GD.getDecl()); 1974 std::string MangledName = getMangledNameImpl(*this, GD, ND); 1975 1976 // Ensure either we have different ABIs between host and device compilations, 1977 // says host compilation following MSVC ABI but device compilation follows 1978 // Itanium C++ ABI or, if they follow the same ABI, kernel names after 1979 // mangling should be the same after name stubbing. The later checking is 1980 // very important as the device kernel name being mangled in host-compilation 1981 // is used to resolve the device binaries to be executed. Inconsistent naming 1982 // result in undefined behavior. Even though we cannot check that naming 1983 // directly between host- and device-compilations, the host- and 1984 // device-mangling in host compilation could help catching certain ones. 1985 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 1986 getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice || 1987 (getContext().getAuxTargetInfo() && 1988 (getContext().getAuxTargetInfo()->getCXXABI() != 1989 getContext().getTargetInfo().getCXXABI())) || 1990 getCUDARuntime().getDeviceSideName(ND) == 1991 getMangledNameImpl( 1992 *this, 1993 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 1994 ND)); 1995 1996 auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 1997 return MangledDeclNames[CanonicalGD] = Result.first->first(); 1998 } 1999 2000 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 2001 const BlockDecl *BD) { 2002 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 2003 const Decl *D = GD.getDecl(); 2004 2005 SmallString<256> Buffer; 2006 llvm::raw_svector_ostream Out(Buffer); 2007 if (!D) 2008 MangleCtx.mangleGlobalBlock(BD, 2009 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 2010 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 2011 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 2012 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 2013 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 2014 else 2015 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 2016 2017 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 2018 return Result.first->first(); 2019 } 2020 2021 const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) { 2022 auto it = MangledDeclNames.begin(); 2023 while (it != MangledDeclNames.end()) { 2024 if (it->second == Name) 2025 return it->first; 2026 it++; 2027 } 2028 return GlobalDecl(); 2029 } 2030 2031 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 2032 return getModule().getNamedValue(Name); 2033 } 2034 2035 /// AddGlobalCtor - Add a function to the list that will be called before 2036 /// main() runs. 2037 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 2038 unsigned LexOrder, 2039 llvm::Constant *AssociatedData) { 2040 // FIXME: Type coercion of void()* types. 2041 GlobalCtors.push_back(Structor(Priority, LexOrder, Ctor, AssociatedData)); 2042 } 2043 2044 /// AddGlobalDtor - Add a function to the list that will be called 2045 /// when the module is unloaded. 2046 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 2047 bool IsDtorAttrFunc) { 2048 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 2049 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 2050 DtorsUsingAtExit[Priority].push_back(Dtor); 2051 return; 2052 } 2053 2054 // FIXME: Type coercion of void()* types. 2055 GlobalDtors.push_back(Structor(Priority, ~0U, Dtor, nullptr)); 2056 } 2057 2058 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 2059 if (Fns.empty()) return; 2060 2061 // Ctor function type is void()*. 2062 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 2063 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 2064 TheModule.getDataLayout().getProgramAddressSpace()); 2065 2066 // Get the type of a ctor entry, { i32, void ()*, i8* }. 2067 llvm::StructType *CtorStructTy = llvm::StructType::get( 2068 Int32Ty, CtorPFTy, VoidPtrTy); 2069 2070 // Construct the constructor and destructor arrays. 2071 ConstantInitBuilder builder(*this); 2072 auto ctors = builder.beginArray(CtorStructTy); 2073 for (const auto &I : Fns) { 2074 auto ctor = ctors.beginStruct(CtorStructTy); 2075 ctor.addInt(Int32Ty, I.Priority); 2076 ctor.add(I.Initializer); 2077 if (I.AssociatedData) 2078 ctor.add(I.AssociatedData); 2079 else 2080 ctor.addNullPointer(VoidPtrTy); 2081 ctor.finishAndAddTo(ctors); 2082 } 2083 2084 auto list = 2085 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 2086 /*constant*/ false, 2087 llvm::GlobalValue::AppendingLinkage); 2088 2089 // The LTO linker doesn't seem to like it when we set an alignment 2090 // on appending variables. Take it off as a workaround. 2091 list->setAlignment(std::nullopt); 2092 2093 Fns.clear(); 2094 } 2095 2096 llvm::GlobalValue::LinkageTypes 2097 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 2098 const auto *D = cast<FunctionDecl>(GD.getDecl()); 2099 2100 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 2101 2102 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 2103 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 2104 2105 return getLLVMLinkageForDeclarator(D, Linkage); 2106 } 2107 2108 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 2109 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 2110 if (!MDS) return nullptr; 2111 2112 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 2113 } 2114 2115 llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T) { 2116 if (auto *FnType = T->getAs<FunctionProtoType>()) 2117 T = getContext().getFunctionType( 2118 FnType->getReturnType(), FnType->getParamTypes(), 2119 FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 2120 2121 std::string OutName; 2122 llvm::raw_string_ostream Out(OutName); 2123 getCXXABI().getMangleContext().mangleCanonicalTypeName( 2124 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); 2125 2126 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) 2127 Out << ".normalized"; 2128 2129 return llvm::ConstantInt::get(Int32Ty, 2130 static_cast<uint32_t>(llvm::xxHash64(OutName))); 2131 } 2132 2133 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 2134 const CGFunctionInfo &Info, 2135 llvm::Function *F, bool IsThunk) { 2136 unsigned CallingConv; 2137 llvm::AttributeList PAL; 2138 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, 2139 /*AttrOnCallSite=*/false, IsThunk); 2140 F->setAttributes(PAL); 2141 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 2142 } 2143 2144 static void removeImageAccessQualifier(std::string& TyName) { 2145 std::string ReadOnlyQual("__read_only"); 2146 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 2147 if (ReadOnlyPos != std::string::npos) 2148 // "+ 1" for the space after access qualifier. 2149 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 2150 else { 2151 std::string WriteOnlyQual("__write_only"); 2152 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 2153 if (WriteOnlyPos != std::string::npos) 2154 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 2155 else { 2156 std::string ReadWriteQual("__read_write"); 2157 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 2158 if (ReadWritePos != std::string::npos) 2159 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 2160 } 2161 } 2162 } 2163 2164 // Returns the address space id that should be produced to the 2165 // kernel_arg_addr_space metadata. This is always fixed to the ids 2166 // as specified in the SPIR 2.0 specification in order to differentiate 2167 // for example in clGetKernelArgInfo() implementation between the address 2168 // spaces with targets without unique mapping to the OpenCL address spaces 2169 // (basically all single AS CPUs). 2170 static unsigned ArgInfoAddressSpace(LangAS AS) { 2171 switch (AS) { 2172 case LangAS::opencl_global: 2173 return 1; 2174 case LangAS::opencl_constant: 2175 return 2; 2176 case LangAS::opencl_local: 2177 return 3; 2178 case LangAS::opencl_generic: 2179 return 4; // Not in SPIR 2.0 specs. 2180 case LangAS::opencl_global_device: 2181 return 5; 2182 case LangAS::opencl_global_host: 2183 return 6; 2184 default: 2185 return 0; // Assume private. 2186 } 2187 } 2188 2189 void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn, 2190 const FunctionDecl *FD, 2191 CodeGenFunction *CGF) { 2192 assert(((FD && CGF) || (!FD && !CGF)) && 2193 "Incorrect use - FD and CGF should either be both null or not!"); 2194 // Create MDNodes that represent the kernel arg metadata. 2195 // Each MDNode is a list in the form of "key", N number of values which is 2196 // the same number of values as their are kernel arguments. 2197 2198 const PrintingPolicy &Policy = Context.getPrintingPolicy(); 2199 2200 // MDNode for the kernel argument address space qualifiers. 2201 SmallVector<llvm::Metadata *, 8> addressQuals; 2202 2203 // MDNode for the kernel argument access qualifiers (images only). 2204 SmallVector<llvm::Metadata *, 8> accessQuals; 2205 2206 // MDNode for the kernel argument type names. 2207 SmallVector<llvm::Metadata *, 8> argTypeNames; 2208 2209 // MDNode for the kernel argument base type names. 2210 SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 2211 2212 // MDNode for the kernel argument type qualifiers. 2213 SmallVector<llvm::Metadata *, 8> argTypeQuals; 2214 2215 // MDNode for the kernel argument names. 2216 SmallVector<llvm::Metadata *, 8> argNames; 2217 2218 if (FD && CGF) 2219 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 2220 const ParmVarDecl *parm = FD->getParamDecl(i); 2221 // Get argument name. 2222 argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 2223 2224 if (!getLangOpts().OpenCL) 2225 continue; 2226 QualType ty = parm->getType(); 2227 std::string typeQuals; 2228 2229 // Get image and pipe access qualifier: 2230 if (ty->isImageType() || ty->isPipeType()) { 2231 const Decl *PDecl = parm; 2232 if (const auto *TD = ty->getAs<TypedefType>()) 2233 PDecl = TD->getDecl(); 2234 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 2235 if (A && A->isWriteOnly()) 2236 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 2237 else if (A && A->isReadWrite()) 2238 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 2239 else 2240 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 2241 } else 2242 accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 2243 2244 auto getTypeSpelling = [&](QualType Ty) { 2245 auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 2246 2247 if (Ty.isCanonical()) { 2248 StringRef typeNameRef = typeName; 2249 // Turn "unsigned type" to "utype" 2250 if (typeNameRef.consume_front("unsigned ")) 2251 return std::string("u") + typeNameRef.str(); 2252 if (typeNameRef.consume_front("signed ")) 2253 return typeNameRef.str(); 2254 } 2255 2256 return typeName; 2257 }; 2258 2259 if (ty->isPointerType()) { 2260 QualType pointeeTy = ty->getPointeeType(); 2261 2262 // Get address qualifier. 2263 addressQuals.push_back( 2264 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 2265 ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 2266 2267 // Get argument type name. 2268 std::string typeName = getTypeSpelling(pointeeTy) + "*"; 2269 std::string baseTypeName = 2270 getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 2271 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 2272 argBaseTypeNames.push_back( 2273 llvm::MDString::get(VMContext, baseTypeName)); 2274 2275 // Get argument type qualifiers: 2276 if (ty.isRestrictQualified()) 2277 typeQuals = "restrict"; 2278 if (pointeeTy.isConstQualified() || 2279 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 2280 typeQuals += typeQuals.empty() ? "const" : " const"; 2281 if (pointeeTy.isVolatileQualified()) 2282 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 2283 } else { 2284 uint32_t AddrSpc = 0; 2285 bool isPipe = ty->isPipeType(); 2286 if (ty->isImageType() || isPipe) 2287 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 2288 2289 addressQuals.push_back( 2290 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 2291 2292 // Get argument type name. 2293 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 2294 std::string typeName = getTypeSpelling(ty); 2295 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 2296 2297 // Remove access qualifiers on images 2298 // (as they are inseparable from type in clang implementation, 2299 // but OpenCL spec provides a special query to get access qualifier 2300 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 2301 if (ty->isImageType()) { 2302 removeImageAccessQualifier(typeName); 2303 removeImageAccessQualifier(baseTypeName); 2304 } 2305 2306 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 2307 argBaseTypeNames.push_back( 2308 llvm::MDString::get(VMContext, baseTypeName)); 2309 2310 if (isPipe) 2311 typeQuals = "pipe"; 2312 } 2313 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 2314 } 2315 2316 if (getLangOpts().OpenCL) { 2317 Fn->setMetadata("kernel_arg_addr_space", 2318 llvm::MDNode::get(VMContext, addressQuals)); 2319 Fn->setMetadata("kernel_arg_access_qual", 2320 llvm::MDNode::get(VMContext, accessQuals)); 2321 Fn->setMetadata("kernel_arg_type", 2322 llvm::MDNode::get(VMContext, argTypeNames)); 2323 Fn->setMetadata("kernel_arg_base_type", 2324 llvm::MDNode::get(VMContext, argBaseTypeNames)); 2325 Fn->setMetadata("kernel_arg_type_qual", 2326 llvm::MDNode::get(VMContext, argTypeQuals)); 2327 } 2328 if (getCodeGenOpts().EmitOpenCLArgMetadata || 2329 getCodeGenOpts().HIPSaveKernelArgName) 2330 Fn->setMetadata("kernel_arg_name", 2331 llvm::MDNode::get(VMContext, argNames)); 2332 } 2333 2334 /// Determines whether the language options require us to model 2335 /// unwind exceptions. We treat -fexceptions as mandating this 2336 /// except under the fragile ObjC ABI with only ObjC exceptions 2337 /// enabled. This means, for example, that C with -fexceptions 2338 /// enables this. 2339 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 2340 // If exceptions are completely disabled, obviously this is false. 2341 if (!LangOpts.Exceptions) return false; 2342 2343 // If C++ exceptions are enabled, this is true. 2344 if (LangOpts.CXXExceptions) return true; 2345 2346 // If ObjC exceptions are enabled, this depends on the ABI. 2347 if (LangOpts.ObjCExceptions) { 2348 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 2349 } 2350 2351 return true; 2352 } 2353 2354 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 2355 const CXXMethodDecl *MD) { 2356 // Check that the type metadata can ever actually be used by a call. 2357 if (!CGM.getCodeGenOpts().LTOUnit || 2358 !CGM.HasHiddenLTOVisibility(MD->getParent())) 2359 return false; 2360 2361 // Only functions whose address can be taken with a member function pointer 2362 // need this sort of type metadata. 2363 return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() && 2364 !isa<CXXConstructorDecl, CXXDestructorDecl>(MD); 2365 } 2366 2367 SmallVector<const CXXRecordDecl *, 0> 2368 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 2369 llvm::SetVector<const CXXRecordDecl *> MostBases; 2370 2371 std::function<void (const CXXRecordDecl *)> CollectMostBases; 2372 CollectMostBases = [&](const CXXRecordDecl *RD) { 2373 if (RD->getNumBases() == 0) 2374 MostBases.insert(RD); 2375 for (const CXXBaseSpecifier &B : RD->bases()) 2376 CollectMostBases(B.getType()->getAsCXXRecordDecl()); 2377 }; 2378 CollectMostBases(RD); 2379 return MostBases.takeVector(); 2380 } 2381 2382 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 2383 llvm::Function *F) { 2384 llvm::AttrBuilder B(F->getContext()); 2385 2386 if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables) 2387 B.addUWTableAttr(llvm::UWTableKind(CodeGenOpts.UnwindTables)); 2388 2389 if (CodeGenOpts.StackClashProtector) 2390 B.addAttribute("probe-stack", "inline-asm"); 2391 2392 if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) 2393 B.addAttribute("stack-probe-size", 2394 std::to_string(CodeGenOpts.StackProbeSize)); 2395 2396 if (!hasUnwindExceptions(LangOpts)) 2397 B.addAttribute(llvm::Attribute::NoUnwind); 2398 2399 if (D && D->hasAttr<NoStackProtectorAttr>()) 2400 ; // Do nothing. 2401 else if (D && D->hasAttr<StrictGuardStackCheckAttr>() && 2402 isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn)) 2403 B.addAttribute(llvm::Attribute::StackProtectStrong); 2404 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPOn)) 2405 B.addAttribute(llvm::Attribute::StackProtect); 2406 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPStrong)) 2407 B.addAttribute(llvm::Attribute::StackProtectStrong); 2408 else if (isStackProtectorOn(LangOpts, getTriple(), LangOptions::SSPReq)) 2409 B.addAttribute(llvm::Attribute::StackProtectReq); 2410 2411 if (!D) { 2412 // If we don't have a declaration to control inlining, the function isn't 2413 // explicitly marked as alwaysinline for semantic reasons, and inlining is 2414 // disabled, mark the function as noinline. 2415 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 2416 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 2417 B.addAttribute(llvm::Attribute::NoInline); 2418 2419 F->addFnAttrs(B); 2420 return; 2421 } 2422 2423 // Handle SME attributes that apply to function definitions, 2424 // rather than to function prototypes. 2425 if (D->hasAttr<ArmLocallyStreamingAttr>()) 2426 B.addAttribute("aarch64_pstate_sm_body"); 2427 2428 if (auto *Attr = D->getAttr<ArmNewAttr>()) { 2429 if (Attr->isNewZA()) 2430 B.addAttribute("aarch64_new_za"); 2431 if (Attr->isNewZT0()) 2432 B.addAttribute("aarch64_new_zt0"); 2433 } 2434 2435 // Track whether we need to add the optnone LLVM attribute, 2436 // starting with the default for this optimization level. 2437 bool ShouldAddOptNone = 2438 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 2439 // We can't add optnone in the following cases, it won't pass the verifier. 2440 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 2441 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 2442 2443 // Add optnone, but do so only if the function isn't always_inline. 2444 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 2445 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 2446 B.addAttribute(llvm::Attribute::OptimizeNone); 2447 2448 // OptimizeNone implies noinline; we should not be inlining such functions. 2449 B.addAttribute(llvm::Attribute::NoInline); 2450 2451 // We still need to handle naked functions even though optnone subsumes 2452 // much of their semantics. 2453 if (D->hasAttr<NakedAttr>()) 2454 B.addAttribute(llvm::Attribute::Naked); 2455 2456 // OptimizeNone wins over OptimizeForSize and MinSize. 2457 F->removeFnAttr(llvm::Attribute::OptimizeForSize); 2458 F->removeFnAttr(llvm::Attribute::MinSize); 2459 } else if (D->hasAttr<NakedAttr>()) { 2460 // Naked implies noinline: we should not be inlining such functions. 2461 B.addAttribute(llvm::Attribute::Naked); 2462 B.addAttribute(llvm::Attribute::NoInline); 2463 } else if (D->hasAttr<NoDuplicateAttr>()) { 2464 B.addAttribute(llvm::Attribute::NoDuplicate); 2465 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 2466 // Add noinline if the function isn't always_inline. 2467 B.addAttribute(llvm::Attribute::NoInline); 2468 } else if (D->hasAttr<AlwaysInlineAttr>() && 2469 !F->hasFnAttribute(llvm::Attribute::NoInline)) { 2470 // (noinline wins over always_inline, and we can't specify both in IR) 2471 B.addAttribute(llvm::Attribute::AlwaysInline); 2472 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 2473 // If we're not inlining, then force everything that isn't always_inline to 2474 // carry an explicit noinline attribute. 2475 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 2476 B.addAttribute(llvm::Attribute::NoInline); 2477 } else { 2478 // Otherwise, propagate the inline hint attribute and potentially use its 2479 // absence to mark things as noinline. 2480 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 2481 // Search function and template pattern redeclarations for inline. 2482 auto CheckForInline = [](const FunctionDecl *FD) { 2483 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 2484 return Redecl->isInlineSpecified(); 2485 }; 2486 if (any_of(FD->redecls(), CheckRedeclForInline)) 2487 return true; 2488 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 2489 if (!Pattern) 2490 return false; 2491 return any_of(Pattern->redecls(), CheckRedeclForInline); 2492 }; 2493 if (CheckForInline(FD)) { 2494 B.addAttribute(llvm::Attribute::InlineHint); 2495 } else if (CodeGenOpts.getInlining() == 2496 CodeGenOptions::OnlyHintInlining && 2497 !FD->isInlined() && 2498 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 2499 B.addAttribute(llvm::Attribute::NoInline); 2500 } 2501 } 2502 } 2503 2504 // Add other optimization related attributes if we are optimizing this 2505 // function. 2506 if (!D->hasAttr<OptimizeNoneAttr>()) { 2507 if (D->hasAttr<ColdAttr>()) { 2508 if (!ShouldAddOptNone) 2509 B.addAttribute(llvm::Attribute::OptimizeForSize); 2510 B.addAttribute(llvm::Attribute::Cold); 2511 } 2512 if (D->hasAttr<HotAttr>()) 2513 B.addAttribute(llvm::Attribute::Hot); 2514 if (D->hasAttr<MinSizeAttr>()) 2515 B.addAttribute(llvm::Attribute::MinSize); 2516 } 2517 2518 F->addFnAttrs(B); 2519 2520 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 2521 if (alignment) 2522 F->setAlignment(llvm::Align(alignment)); 2523 2524 if (!D->hasAttr<AlignedAttr>()) 2525 if (LangOpts.FunctionAlignment) 2526 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 2527 2528 // Some C++ ABIs require 2-byte alignment for member functions, in order to 2529 // reserve a bit for differentiating between virtual and non-virtual member 2530 // functions. If the current target's C++ ABI requires this and this is a 2531 // member function, set its alignment accordingly. 2532 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 2533 if (isa<CXXMethodDecl>(D) && F->getPointerAlignment(getDataLayout()) < 2) 2534 F->setAlignment(std::max(llvm::Align(2), F->getAlign().valueOrOne())); 2535 } 2536 2537 // In the cross-dso CFI mode with canonical jump tables, we want !type 2538 // attributes on definitions only. 2539 if (CodeGenOpts.SanitizeCfiCrossDso && 2540 CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 2541 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 2542 // Skip available_externally functions. They won't be codegen'ed in the 2543 // current module anyway. 2544 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 2545 CreateFunctionTypeMetadataForIcall(FD, F); 2546 } 2547 } 2548 2549 // Emit type metadata on member functions for member function pointer checks. 2550 // These are only ever necessary on definitions; we're guaranteed that the 2551 // definition will be present in the LTO unit as a result of LTO visibility. 2552 auto *MD = dyn_cast<CXXMethodDecl>(D); 2553 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 2554 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 2555 llvm::Metadata *Id = 2556 CreateMetadataIdentifierForType(Context.getMemberPointerType( 2557 MD->getType(), Context.getRecordType(Base).getTypePtr())); 2558 F->addTypeMetadata(0, Id); 2559 } 2560 } 2561 } 2562 2563 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 2564 const Decl *D = GD.getDecl(); 2565 if (isa_and_nonnull<NamedDecl>(D)) 2566 setGVProperties(GV, GD); 2567 else 2568 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 2569 2570 if (D && D->hasAttr<UsedAttr>()) 2571 addUsedOrCompilerUsedGlobal(GV); 2572 2573 if (const auto *VD = dyn_cast_if_present<VarDecl>(D); 2574 VD && 2575 ((CodeGenOpts.KeepPersistentStorageVariables && 2576 (VD->getStorageDuration() == SD_Static || 2577 VD->getStorageDuration() == SD_Thread)) || 2578 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && 2579 VD->getType().isConstQualified()))) 2580 addUsedOrCompilerUsedGlobal(GV); 2581 } 2582 2583 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 2584 llvm::AttrBuilder &Attrs, 2585 bool SetTargetFeatures) { 2586 // Add target-cpu and target-features attributes to functions. If 2587 // we have a decl for the function and it has a target attribute then 2588 // parse that and add it to the feature set. 2589 StringRef TargetCPU = getTarget().getTargetOpts().CPU; 2590 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 2591 std::vector<std::string> Features; 2592 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 2593 FD = FD ? FD->getMostRecentDecl() : FD; 2594 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 2595 const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr; 2596 assert((!TD || !TV) && "both target_version and target specified"); 2597 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 2598 const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; 2599 bool AddedAttr = false; 2600 if (TD || TV || SD || TC) { 2601 llvm::StringMap<bool> FeatureMap; 2602 getContext().getFunctionFeatureMap(FeatureMap, GD); 2603 2604 // Produce the canonical string for this set of features. 2605 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 2606 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 2607 2608 // Now add the target-cpu and target-features to the function. 2609 // While we populated the feature map above, we still need to 2610 // get and parse the target attribute so we can get the cpu for 2611 // the function. 2612 if (TD) { 2613 ParsedTargetAttr ParsedAttr = 2614 Target.parseTargetAttr(TD->getFeaturesStr()); 2615 if (!ParsedAttr.CPU.empty() && 2616 getTarget().isValidCPUName(ParsedAttr.CPU)) { 2617 TargetCPU = ParsedAttr.CPU; 2618 TuneCPU = ""; // Clear the tune CPU. 2619 } 2620 if (!ParsedAttr.Tune.empty() && 2621 getTarget().isValidCPUName(ParsedAttr.Tune)) 2622 TuneCPU = ParsedAttr.Tune; 2623 } 2624 2625 if (SD) { 2626 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can 2627 // favor this processor. 2628 TuneCPU = SD->getCPUName(GD.getMultiVersionIndex())->getName(); 2629 } 2630 } else { 2631 // Otherwise just add the existing target cpu and target features to the 2632 // function. 2633 Features = getTarget().getTargetOpts().Features; 2634 } 2635 2636 if (!TargetCPU.empty()) { 2637 Attrs.addAttribute("target-cpu", TargetCPU); 2638 AddedAttr = true; 2639 } 2640 if (!TuneCPU.empty()) { 2641 Attrs.addAttribute("tune-cpu", TuneCPU); 2642 AddedAttr = true; 2643 } 2644 if (!Features.empty() && SetTargetFeatures) { 2645 llvm::erase_if(Features, [&](const std::string& F) { 2646 return getTarget().isReadOnlyFeature(F.substr(1)); 2647 }); 2648 llvm::sort(Features); 2649 Attrs.addAttribute("target-features", llvm::join(Features, ",")); 2650 AddedAttr = true; 2651 } 2652 2653 return AddedAttr; 2654 } 2655 2656 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 2657 llvm::GlobalObject *GO) { 2658 const Decl *D = GD.getDecl(); 2659 SetCommonAttributes(GD, GO); 2660 2661 if (D) { 2662 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2663 if (D->hasAttr<RetainAttr>()) 2664 addUsedGlobal(GV); 2665 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 2666 GV->addAttribute("bss-section", SA->getName()); 2667 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 2668 GV->addAttribute("data-section", SA->getName()); 2669 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 2670 GV->addAttribute("rodata-section", SA->getName()); 2671 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2672 GV->addAttribute("relro-section", SA->getName()); 2673 } 2674 2675 if (auto *F = dyn_cast<llvm::Function>(GO)) { 2676 if (D->hasAttr<RetainAttr>()) 2677 addUsedGlobal(F); 2678 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 2679 if (!D->getAttr<SectionAttr>()) 2680 F->addFnAttr("implicit-section-name", SA->getName()); 2681 2682 llvm::AttrBuilder Attrs(F->getContext()); 2683 if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 2684 // We know that GetCPUAndFeaturesAttributes will always have the 2685 // newest set, since it has the newest possible FunctionDecl, so the 2686 // new ones should replace the old. 2687 llvm::AttributeMask RemoveAttrs; 2688 RemoveAttrs.addAttribute("target-cpu"); 2689 RemoveAttrs.addAttribute("target-features"); 2690 RemoveAttrs.addAttribute("tune-cpu"); 2691 F->removeFnAttrs(RemoveAttrs); 2692 F->addFnAttrs(Attrs); 2693 } 2694 } 2695 2696 if (const auto *CSA = D->getAttr<CodeSegAttr>()) 2697 GO->setSection(CSA->getName()); 2698 else if (const auto *SA = D->getAttr<SectionAttr>()) 2699 GO->setSection(SA->getName()); 2700 } 2701 2702 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 2703 } 2704 2705 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 2706 llvm::Function *F, 2707 const CGFunctionInfo &FI) { 2708 const Decl *D = GD.getDecl(); 2709 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 2710 SetLLVMFunctionAttributesForDefinition(D, F); 2711 2712 F->setLinkage(llvm::Function::InternalLinkage); 2713 2714 setNonAliasAttributes(GD, F); 2715 } 2716 2717 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 2718 // Set linkage and visibility in case we never see a definition. 2719 LinkageInfo LV = ND->getLinkageAndVisibility(); 2720 // Don't set internal linkage on declarations. 2721 // "extern_weak" is overloaded in LLVM; we probably should have 2722 // separate linkage types for this. 2723 if (isExternallyVisible(LV.getLinkage()) && 2724 (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 2725 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 2726 } 2727 2728 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 2729 llvm::Function *F) { 2730 // Only if we are checking indirect calls. 2731 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 2732 return; 2733 2734 // Non-static class methods are handled via vtable or member function pointer 2735 // checks elsewhere. 2736 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2737 return; 2738 2739 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 2740 F->addTypeMetadata(0, MD); 2741 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 2742 2743 // Emit a hash-based bit set entry for cross-DSO calls. 2744 if (CodeGenOpts.SanitizeCfiCrossDso) 2745 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 2746 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 2747 } 2748 2749 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) { 2750 llvm::LLVMContext &Ctx = F->getContext(); 2751 llvm::MDBuilder MDB(Ctx); 2752 F->setMetadata(llvm::LLVMContext::MD_kcfi_type, 2753 llvm::MDNode::get( 2754 Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType())))); 2755 } 2756 2757 static bool allowKCFIIdentifier(StringRef Name) { 2758 // KCFI type identifier constants are only necessary for external assembly 2759 // functions, which means it's safe to skip unusual names. Subset of 2760 // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar(). 2761 return llvm::all_of(Name, [](const char &C) { 2762 return llvm::isAlnum(C) || C == '_' || C == '.'; 2763 }); 2764 } 2765 2766 void CodeGenModule::finalizeKCFITypes() { 2767 llvm::Module &M = getModule(); 2768 for (auto &F : M.functions()) { 2769 // Remove KCFI type metadata from non-address-taken local functions. 2770 bool AddressTaken = F.hasAddressTaken(); 2771 if (!AddressTaken && F.hasLocalLinkage()) 2772 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type); 2773 2774 // Generate a constant with the expected KCFI type identifier for all 2775 // address-taken function declarations to support annotating indirectly 2776 // called assembly functions. 2777 if (!AddressTaken || !F.isDeclaration()) 2778 continue; 2779 2780 const llvm::ConstantInt *Type; 2781 if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type)) 2782 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0)); 2783 else 2784 continue; 2785 2786 StringRef Name = F.getName(); 2787 if (!allowKCFIIdentifier(Name)) 2788 continue; 2789 2790 std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" + 2791 Name + ", " + Twine(Type->getZExtValue()) + "\n") 2792 .str(); 2793 M.appendModuleInlineAsm(Asm); 2794 } 2795 } 2796 2797 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 2798 bool IsIncompleteFunction, 2799 bool IsThunk) { 2800 2801 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 2802 // If this is an intrinsic function, set the function's attributes 2803 // to the intrinsic's attributes. 2804 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 2805 return; 2806 } 2807 2808 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2809 2810 if (!IsIncompleteFunction) 2811 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2812 IsThunk); 2813 2814 // Add the Returned attribute for "this", except for iOS 5 and earlier 2815 // where substantial code, including the libstdc++ dylib, was compiled with 2816 // GCC and does not actually return "this". 2817 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 2818 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 2819 assert(!F->arg_empty() && 2820 F->arg_begin()->getType() 2821 ->canLosslesslyBitCastTo(F->getReturnType()) && 2822 "unexpected this return"); 2823 F->addParamAttr(0, llvm::Attribute::Returned); 2824 } 2825 2826 // Only a few attributes are set on declarations; these may later be 2827 // overridden by a definition. 2828 2829 setLinkageForGV(F, FD); 2830 setGVProperties(F, FD); 2831 2832 // Setup target-specific attributes. 2833 if (!IsIncompleteFunction && F->isDeclaration()) 2834 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 2835 2836 if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 2837 F->setSection(CSA->getName()); 2838 else if (const auto *SA = FD->getAttr<SectionAttr>()) 2839 F->setSection(SA->getName()); 2840 2841 if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2842 if (EA->isError()) 2843 F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2844 else if (EA->isWarning()) 2845 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2846 } 2847 2848 // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2849 if (FD->isInlineBuiltinDeclaration()) { 2850 const FunctionDecl *FDBody; 2851 bool HasBody = FD->hasBody(FDBody); 2852 (void)HasBody; 2853 assert(HasBody && "Inline builtin declarations should always have an " 2854 "available body!"); 2855 if (shouldEmitFunction(FDBody)) 2856 F->addFnAttr(llvm::Attribute::NoBuiltin); 2857 } 2858 2859 if (FD->isReplaceableGlobalAllocationFunction()) { 2860 // A replaceable global allocation function does not act like a builtin by 2861 // default, only if it is invoked by a new-expression or delete-expression. 2862 F->addFnAttr(llvm::Attribute::NoBuiltin); 2863 } 2864 2865 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 2866 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2867 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 2868 if (MD->isVirtual()) 2869 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2870 2871 // Don't emit entries for function declarations in the cross-DSO mode. This 2872 // is handled with better precision by the receiving DSO. But if jump tables 2873 // are non-canonical then we need type metadata in order to produce the local 2874 // jump table. 2875 if (!CodeGenOpts.SanitizeCfiCrossDso || 2876 !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 2877 CreateFunctionTypeMetadataForIcall(FD, F); 2878 2879 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 2880 setKCFIType(FD, F); 2881 2882 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 2883 getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 2884 2885 if (CodeGenOpts.InlineMaxStackSize != UINT_MAX) 2886 F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize)); 2887 2888 if (const auto *CB = FD->getAttr<CallbackAttr>()) { 2889 // Annotate the callback behavior as metadata: 2890 // - The callback callee (as argument number). 2891 // - The callback payloads (as argument numbers). 2892 llvm::LLVMContext &Ctx = F->getContext(); 2893 llvm::MDBuilder MDB(Ctx); 2894 2895 // The payload indices are all but the first one in the encoding. The first 2896 // identifies the callback callee. 2897 int CalleeIdx = *CB->encoding_begin(); 2898 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 2899 F->addMetadata(llvm::LLVMContext::MD_callback, 2900 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2901 CalleeIdx, PayloadIndices, 2902 /* VarArgsArePassed */ false)})); 2903 } 2904 } 2905 2906 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2907 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2908 "Only globals with definition can force usage."); 2909 LLVMUsed.emplace_back(GV); 2910 } 2911 2912 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 2913 assert(!GV->isDeclaration() && 2914 "Only globals with definition can force usage."); 2915 LLVMCompilerUsed.emplace_back(GV); 2916 } 2917 2918 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2919 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2920 "Only globals with definition can force usage."); 2921 if (getTriple().isOSBinFormatELF()) 2922 LLVMCompilerUsed.emplace_back(GV); 2923 else 2924 LLVMUsed.emplace_back(GV); 2925 } 2926 2927 static void emitUsed(CodeGenModule &CGM, StringRef Name, 2928 std::vector<llvm::WeakTrackingVH> &List) { 2929 // Don't create llvm.used if there is no need. 2930 if (List.empty()) 2931 return; 2932 2933 // Convert List to what ConstantArray needs. 2934 SmallVector<llvm::Constant*, 8> UsedArray; 2935 UsedArray.resize(List.size()); 2936 for (unsigned i = 0, e = List.size(); i != e; ++i) { 2937 UsedArray[i] = 2938 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2939 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2940 } 2941 2942 if (UsedArray.empty()) 2943 return; 2944 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2945 2946 auto *GV = new llvm::GlobalVariable( 2947 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2948 llvm::ConstantArray::get(ATy, UsedArray), Name); 2949 2950 GV->setSection("llvm.metadata"); 2951 } 2952 2953 void CodeGenModule::emitLLVMUsed() { 2954 emitUsed(*this, "llvm.used", LLVMUsed); 2955 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2956 } 2957 2958 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2959 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2960 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2961 } 2962 2963 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2964 llvm::SmallString<32> Opt; 2965 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2966 if (Opt.empty()) 2967 return; 2968 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2969 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2970 } 2971 2972 void CodeGenModule::AddDependentLib(StringRef Lib) { 2973 auto &C = getLLVMContext(); 2974 if (getTarget().getTriple().isOSBinFormatELF()) { 2975 ELFDependentLibraries.push_back( 2976 llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2977 return; 2978 } 2979 2980 llvm::SmallString<24> Opt; 2981 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2982 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2983 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2984 } 2985 2986 /// Add link options implied by the given module, including modules 2987 /// it depends on, using a postorder walk. 2988 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2989 SmallVectorImpl<llvm::MDNode *> &Metadata, 2990 llvm::SmallPtrSet<Module *, 16> &Visited) { 2991 // Import this module's parent. 2992 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2993 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2994 } 2995 2996 // Import this module's dependencies. 2997 for (Module *Import : llvm::reverse(Mod->Imports)) { 2998 if (Visited.insert(Import).second) 2999 addLinkOptionsPostorder(CGM, Import, Metadata, Visited); 3000 } 3001 3002 // Add linker options to link against the libraries/frameworks 3003 // described by this module. 3004 llvm::LLVMContext &Context = CGM.getLLVMContext(); 3005 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 3006 3007 // For modules that use export_as for linking, use that module 3008 // name instead. 3009 if (Mod->UseExportAsModuleLinkName) 3010 return; 3011 3012 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 3013 // Link against a framework. Frameworks are currently Darwin only, so we 3014 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 3015 if (LL.IsFramework) { 3016 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), 3017 llvm::MDString::get(Context, LL.Library)}; 3018 3019 Metadata.push_back(llvm::MDNode::get(Context, Args)); 3020 continue; 3021 } 3022 3023 // Link against a library. 3024 if (IsELF) { 3025 llvm::Metadata *Args[2] = { 3026 llvm::MDString::get(Context, "lib"), 3027 llvm::MDString::get(Context, LL.Library), 3028 }; 3029 Metadata.push_back(llvm::MDNode::get(Context, Args)); 3030 } else { 3031 llvm::SmallString<24> Opt; 3032 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 3033 auto *OptString = llvm::MDString::get(Context, Opt); 3034 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 3035 } 3036 } 3037 } 3038 3039 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) { 3040 assert(Primary->isNamedModuleUnit() && 3041 "We should only emit module initializers for named modules."); 3042 3043 // Emit the initializers in the order that sub-modules appear in the 3044 // source, first Global Module Fragments, if present. 3045 if (auto GMF = Primary->getGlobalModuleFragment()) { 3046 for (Decl *D : getContext().getModuleInitializers(GMF)) { 3047 if (isa<ImportDecl>(D)) 3048 continue; 3049 assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?"); 3050 EmitTopLevelDecl(D); 3051 } 3052 } 3053 // Second any associated with the module, itself. 3054 for (Decl *D : getContext().getModuleInitializers(Primary)) { 3055 // Skip import decls, the inits for those are called explicitly. 3056 if (isa<ImportDecl>(D)) 3057 continue; 3058 EmitTopLevelDecl(D); 3059 } 3060 // Third any associated with the Privat eMOdule Fragment, if present. 3061 if (auto PMF = Primary->getPrivateModuleFragment()) { 3062 for (Decl *D : getContext().getModuleInitializers(PMF)) { 3063 // Skip import decls, the inits for those are called explicitly. 3064 if (isa<ImportDecl>(D)) 3065 continue; 3066 assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?"); 3067 EmitTopLevelDecl(D); 3068 } 3069 } 3070 } 3071 3072 void CodeGenModule::EmitModuleLinkOptions() { 3073 // Collect the set of all of the modules we want to visit to emit link 3074 // options, which is essentially the imported modules and all of their 3075 // non-explicit child modules. 3076 llvm::SetVector<clang::Module *> LinkModules; 3077 llvm::SmallPtrSet<clang::Module *, 16> Visited; 3078 SmallVector<clang::Module *, 16> Stack; 3079 3080 // Seed the stack with imported modules. 3081 for (Module *M : ImportedModules) { 3082 // Do not add any link flags when an implementation TU of a module imports 3083 // a header of that same module. 3084 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 3085 !getLangOpts().isCompilingModule()) 3086 continue; 3087 if (Visited.insert(M).second) 3088 Stack.push_back(M); 3089 } 3090 3091 // Find all of the modules to import, making a little effort to prune 3092 // non-leaf modules. 3093 while (!Stack.empty()) { 3094 clang::Module *Mod = Stack.pop_back_val(); 3095 3096 bool AnyChildren = false; 3097 3098 // Visit the submodules of this module. 3099 for (const auto &SM : Mod->submodules()) { 3100 // Skip explicit children; they need to be explicitly imported to be 3101 // linked against. 3102 if (SM->IsExplicit) 3103 continue; 3104 3105 if (Visited.insert(SM).second) { 3106 Stack.push_back(SM); 3107 AnyChildren = true; 3108 } 3109 } 3110 3111 // We didn't find any children, so add this module to the list of 3112 // modules to link against. 3113 if (!AnyChildren) { 3114 LinkModules.insert(Mod); 3115 } 3116 } 3117 3118 // Add link options for all of the imported modules in reverse topological 3119 // order. We don't do anything to try to order import link flags with respect 3120 // to linker options inserted by things like #pragma comment(). 3121 SmallVector<llvm::MDNode *, 16> MetadataArgs; 3122 Visited.clear(); 3123 for (Module *M : LinkModules) 3124 if (Visited.insert(M).second) 3125 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 3126 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 3127 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 3128 3129 // Add the linker options metadata flag. 3130 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 3131 for (auto *MD : LinkerOptionsMetadata) 3132 NMD->addOperand(MD); 3133 } 3134 3135 void CodeGenModule::EmitDeferred() { 3136 // Emit deferred declare target declarations. 3137 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 3138 getOpenMPRuntime().emitDeferredTargetDecls(); 3139 3140 // Emit code for any potentially referenced deferred decls. Since a 3141 // previously unused static decl may become used during the generation of code 3142 // for a static function, iterate until no changes are made. 3143 3144 if (!DeferredVTables.empty()) { 3145 EmitDeferredVTables(); 3146 3147 // Emitting a vtable doesn't directly cause more vtables to 3148 // become deferred, although it can cause functions to be 3149 // emitted that then need those vtables. 3150 assert(DeferredVTables.empty()); 3151 } 3152 3153 // Emit CUDA/HIP static device variables referenced by host code only. 3154 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 3155 // needed for further handling. 3156 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 3157 llvm::append_range(DeferredDeclsToEmit, 3158 getContext().CUDADeviceVarODRUsedByHost); 3159 3160 // Stop if we're out of both deferred vtables and deferred declarations. 3161 if (DeferredDeclsToEmit.empty()) 3162 return; 3163 3164 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 3165 // work, it will not interfere with this. 3166 std::vector<GlobalDecl> CurDeclsToEmit; 3167 CurDeclsToEmit.swap(DeferredDeclsToEmit); 3168 3169 for (GlobalDecl &D : CurDeclsToEmit) { 3170 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 3171 // to get GlobalValue with exactly the type we need, not something that 3172 // might had been created for another decl with the same mangled name but 3173 // different type. 3174 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 3175 GetAddrOfGlobal(D, ForDefinition)); 3176 3177 // In case of different address spaces, we may still get a cast, even with 3178 // IsForDefinition equal to true. Query mangled names table to get 3179 // GlobalValue. 3180 if (!GV) 3181 GV = GetGlobalValue(getMangledName(D)); 3182 3183 // Make sure GetGlobalValue returned non-null. 3184 assert(GV); 3185 3186 // Check to see if we've already emitted this. This is necessary 3187 // for a couple of reasons: first, decls can end up in the 3188 // deferred-decls queue multiple times, and second, decls can end 3189 // up with definitions in unusual ways (e.g. by an extern inline 3190 // function acquiring a strong function redefinition). Just 3191 // ignore these cases. 3192 if (!GV->isDeclaration()) 3193 continue; 3194 3195 // If this is OpenMP, check if it is legal to emit this global normally. 3196 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 3197 continue; 3198 3199 // Otherwise, emit the definition and move on to the next one. 3200 EmitGlobalDefinition(D, GV); 3201 3202 // If we found out that we need to emit more decls, do that recursively. 3203 // This has the advantage that the decls are emitted in a DFS and related 3204 // ones are close together, which is convenient for testing. 3205 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 3206 EmitDeferred(); 3207 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 3208 } 3209 } 3210 } 3211 3212 void CodeGenModule::EmitVTablesOpportunistically() { 3213 // Try to emit external vtables as available_externally if they have emitted 3214 // all inlined virtual functions. It runs after EmitDeferred() and therefore 3215 // is not allowed to create new references to things that need to be emitted 3216 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 3217 3218 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 3219 && "Only emit opportunistic vtables with optimizations"); 3220 3221 for (const CXXRecordDecl *RD : OpportunisticVTables) { 3222 assert(getVTables().isVTableExternal(RD) && 3223 "This queue should only contain external vtables"); 3224 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 3225 VTables.GenerateClassData(RD); 3226 } 3227 OpportunisticVTables.clear(); 3228 } 3229 3230 void CodeGenModule::EmitGlobalAnnotations() { 3231 for (const auto& [MangledName, VD] : DeferredAnnotations) { 3232 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 3233 if (GV) 3234 AddGlobalAnnotations(VD, GV); 3235 } 3236 DeferredAnnotations.clear(); 3237 3238 if (Annotations.empty()) 3239 return; 3240 3241 // Create a new global variable for the ConstantStruct in the Module. 3242 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 3243 Annotations[0]->getType(), Annotations.size()), Annotations); 3244 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 3245 llvm::GlobalValue::AppendingLinkage, 3246 Array, "llvm.global.annotations"); 3247 gv->setSection(AnnotationSection); 3248 } 3249 3250 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 3251 llvm::Constant *&AStr = AnnotationStrings[Str]; 3252 if (AStr) 3253 return AStr; 3254 3255 // Not found yet, create a new global. 3256 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 3257 auto *gv = new llvm::GlobalVariable( 3258 getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s, 3259 ".str", nullptr, llvm::GlobalValue::NotThreadLocal, 3260 ConstGlobalsPtrTy->getAddressSpace()); 3261 gv->setSection(AnnotationSection); 3262 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3263 AStr = gv; 3264 return gv; 3265 } 3266 3267 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 3268 SourceManager &SM = getContext().getSourceManager(); 3269 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 3270 if (PLoc.isValid()) 3271 return EmitAnnotationString(PLoc.getFilename()); 3272 return EmitAnnotationString(SM.getBufferName(Loc)); 3273 } 3274 3275 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 3276 SourceManager &SM = getContext().getSourceManager(); 3277 PresumedLoc PLoc = SM.getPresumedLoc(L); 3278 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 3279 SM.getExpansionLineNumber(L); 3280 return llvm::ConstantInt::get(Int32Ty, LineNo); 3281 } 3282 3283 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 3284 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 3285 if (Exprs.empty()) 3286 return llvm::ConstantPointerNull::get(ConstGlobalsPtrTy); 3287 3288 llvm::FoldingSetNodeID ID; 3289 for (Expr *E : Exprs) { 3290 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 3291 } 3292 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 3293 if (Lookup) 3294 return Lookup; 3295 3296 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 3297 LLVMArgs.reserve(Exprs.size()); 3298 ConstantEmitter ConstEmiter(*this); 3299 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 3300 const auto *CE = cast<clang::ConstantExpr>(E); 3301 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 3302 CE->getType()); 3303 }); 3304 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 3305 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 3306 llvm::GlobalValue::PrivateLinkage, Struct, 3307 ".args"); 3308 GV->setSection(AnnotationSection); 3309 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3310 3311 Lookup = GV; 3312 return GV; 3313 } 3314 3315 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 3316 const AnnotateAttr *AA, 3317 SourceLocation L) { 3318 // Get the globals for file name, annotation, and the line number. 3319 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 3320 *UnitGV = EmitAnnotationUnit(L), 3321 *LineNoCst = EmitAnnotationLineNo(L), 3322 *Args = EmitAnnotationArgs(AA); 3323 3324 llvm::Constant *GVInGlobalsAS = GV; 3325 if (GV->getAddressSpace() != 3326 getDataLayout().getDefaultGlobalsAddressSpace()) { 3327 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 3328 GV, 3329 llvm::PointerType::get( 3330 GV->getContext(), getDataLayout().getDefaultGlobalsAddressSpace())); 3331 } 3332 3333 // Create the ConstantStruct for the global annotation. 3334 llvm::Constant *Fields[] = { 3335 GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args, 3336 }; 3337 return llvm::ConstantStruct::getAnon(Fields); 3338 } 3339 3340 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 3341 llvm::GlobalValue *GV) { 3342 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 3343 // Get the struct elements for these annotations. 3344 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 3345 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 3346 } 3347 3348 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 3349 SourceLocation Loc) const { 3350 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 3351 // NoSanitize by function name. 3352 if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 3353 return true; 3354 // NoSanitize by location. Check "mainfile" prefix. 3355 auto &SM = Context.getSourceManager(); 3356 FileEntryRef MainFile = *SM.getFileEntryRefForID(SM.getMainFileID()); 3357 if (NoSanitizeL.containsMainFile(Kind, MainFile.getName())) 3358 return true; 3359 3360 // Check "src" prefix. 3361 if (Loc.isValid()) 3362 return NoSanitizeL.containsLocation(Kind, Loc); 3363 // If location is unknown, this may be a compiler-generated function. Assume 3364 // it's located in the main file. 3365 return NoSanitizeL.containsFile(Kind, MainFile.getName()); 3366 } 3367 3368 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, 3369 llvm::GlobalVariable *GV, 3370 SourceLocation Loc, QualType Ty, 3371 StringRef Category) const { 3372 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 3373 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category)) 3374 return true; 3375 auto &SM = Context.getSourceManager(); 3376 if (NoSanitizeL.containsMainFile( 3377 Kind, SM.getFileEntryRefForID(SM.getMainFileID())->getName(), 3378 Category)) 3379 return true; 3380 if (NoSanitizeL.containsLocation(Kind, Loc, Category)) 3381 return true; 3382 3383 // Check global type. 3384 if (!Ty.isNull()) { 3385 // Drill down the array types: if global variable of a fixed type is 3386 // not sanitized, we also don't instrument arrays of them. 3387 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 3388 Ty = AT->getElementType(); 3389 Ty = Ty.getCanonicalType().getUnqualifiedType(); 3390 // Only record types (classes, structs etc.) are ignored. 3391 if (Ty->isRecordType()) { 3392 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 3393 if (NoSanitizeL.containsType(Kind, TypeStr, Category)) 3394 return true; 3395 } 3396 } 3397 return false; 3398 } 3399 3400 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 3401 StringRef Category) const { 3402 const auto &XRayFilter = getContext().getXRayFilter(); 3403 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 3404 auto Attr = ImbueAttr::NONE; 3405 if (Loc.isValid()) 3406 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 3407 if (Attr == ImbueAttr::NONE) 3408 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 3409 switch (Attr) { 3410 case ImbueAttr::NONE: 3411 return false; 3412 case ImbueAttr::ALWAYS: 3413 Fn->addFnAttr("function-instrument", "xray-always"); 3414 break; 3415 case ImbueAttr::ALWAYS_ARG1: 3416 Fn->addFnAttr("function-instrument", "xray-always"); 3417 Fn->addFnAttr("xray-log-args", "1"); 3418 break; 3419 case ImbueAttr::NEVER: 3420 Fn->addFnAttr("function-instrument", "xray-never"); 3421 break; 3422 } 3423 return true; 3424 } 3425 3426 ProfileList::ExclusionType 3427 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn, 3428 SourceLocation Loc) const { 3429 const auto &ProfileList = getContext().getProfileList(); 3430 // If the profile list is empty, then instrument everything. 3431 if (ProfileList.isEmpty()) 3432 return ProfileList::Allow; 3433 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 3434 // First, check the function name. 3435 if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind)) 3436 return *V; 3437 // Next, check the source location. 3438 if (Loc.isValid()) 3439 if (auto V = ProfileList.isLocationExcluded(Loc, Kind)) 3440 return *V; 3441 // If location is unknown, this may be a compiler-generated function. Assume 3442 // it's located in the main file. 3443 auto &SM = Context.getSourceManager(); 3444 if (auto MainFile = SM.getFileEntryRefForID(SM.getMainFileID())) 3445 if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind)) 3446 return *V; 3447 return ProfileList.getDefault(Kind); 3448 } 3449 3450 ProfileList::ExclusionType 3451 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn, 3452 SourceLocation Loc) const { 3453 auto V = isFunctionBlockedByProfileList(Fn, Loc); 3454 if (V != ProfileList::Allow) 3455 return V; 3456 3457 auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups; 3458 if (NumGroups > 1) { 3459 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups; 3460 if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup) 3461 return ProfileList::Skip; 3462 } 3463 return ProfileList::Allow; 3464 } 3465 3466 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 3467 // Never defer when EmitAllDecls is specified. 3468 if (LangOpts.EmitAllDecls) 3469 return true; 3470 3471 const auto *VD = dyn_cast<VarDecl>(Global); 3472 if (VD && 3473 ((CodeGenOpts.KeepPersistentStorageVariables && 3474 (VD->getStorageDuration() == SD_Static || 3475 VD->getStorageDuration() == SD_Thread)) || 3476 (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && 3477 VD->getType().isConstQualified()))) 3478 return true; 3479 3480 return getContext().DeclMustBeEmitted(Global); 3481 } 3482 3483 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 3484 // In OpenMP 5.0 variables and function may be marked as 3485 // device_type(host/nohost) and we should not emit them eagerly unless we sure 3486 // that they must be emitted on the host/device. To be sure we need to have 3487 // seen a declare target with an explicit mentioning of the function, we know 3488 // we have if the level of the declare target attribute is -1. Note that we 3489 // check somewhere else if we should emit this at all. 3490 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { 3491 std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 3492 OMPDeclareTargetDeclAttr::getActiveAttr(Global); 3493 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) 3494 return false; 3495 } 3496 3497 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3498 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 3499 // Implicit template instantiations may change linkage if they are later 3500 // explicitly instantiated, so they should not be emitted eagerly. 3501 return false; 3502 } 3503 if (const auto *VD = dyn_cast<VarDecl>(Global)) { 3504 if (Context.getInlineVariableDefinitionKind(VD) == 3505 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 3506 // A definition of an inline constexpr static data member may change 3507 // linkage later if it's redeclared outside the class. 3508 return false; 3509 if (CXX20ModuleInits && VD->getOwningModule() && 3510 !VD->getOwningModule()->isModuleMapModule()) { 3511 // For CXX20, module-owned initializers need to be deferred, since it is 3512 // not known at this point if they will be run for the current module or 3513 // as part of the initializer for an imported one. 3514 return false; 3515 } 3516 } 3517 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 3518 // codegen for global variables, because they may be marked as threadprivate. 3519 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 3520 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 3521 !Global->getType().isConstantStorage(getContext(), false, false) && 3522 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 3523 return false; 3524 3525 return true; 3526 } 3527 3528 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 3529 StringRef Name = getMangledName(GD); 3530 3531 // The UUID descriptor should be pointer aligned. 3532 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 3533 3534 // Look for an existing global. 3535 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 3536 return ConstantAddress(GV, GV->getValueType(), Alignment); 3537 3538 ConstantEmitter Emitter(*this); 3539 llvm::Constant *Init; 3540 3541 APValue &V = GD->getAsAPValue(); 3542 if (!V.isAbsent()) { 3543 // If possible, emit the APValue version of the initializer. In particular, 3544 // this gets the type of the constant right. 3545 Init = Emitter.emitForInitializer( 3546 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 3547 } else { 3548 // As a fallback, directly construct the constant. 3549 // FIXME: This may get padding wrong under esoteric struct layout rules. 3550 // MSVC appears to create a complete type 'struct __s_GUID' that it 3551 // presumably uses to represent these constants. 3552 MSGuidDecl::Parts Parts = GD->getParts(); 3553 llvm::Constant *Fields[4] = { 3554 llvm::ConstantInt::get(Int32Ty, Parts.Part1), 3555 llvm::ConstantInt::get(Int16Ty, Parts.Part2), 3556 llvm::ConstantInt::get(Int16Ty, Parts.Part3), 3557 llvm::ConstantDataArray::getRaw( 3558 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 3559 Int8Ty)}; 3560 Init = llvm::ConstantStruct::getAnon(Fields); 3561 } 3562 3563 auto *GV = new llvm::GlobalVariable( 3564 getModule(), Init->getType(), 3565 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 3566 if (supportsCOMDAT()) 3567 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3568 setDSOLocal(GV); 3569 3570 if (!V.isAbsent()) { 3571 Emitter.finalize(GV); 3572 return ConstantAddress(GV, GV->getValueType(), Alignment); 3573 } 3574 3575 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 3576 return ConstantAddress(GV, Ty, Alignment); 3577 } 3578 3579 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl( 3580 const UnnamedGlobalConstantDecl *GCD) { 3581 CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType()); 3582 3583 llvm::GlobalVariable **Entry = nullptr; 3584 Entry = &UnnamedGlobalConstantDeclMap[GCD]; 3585 if (*Entry) 3586 return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment); 3587 3588 ConstantEmitter Emitter(*this); 3589 llvm::Constant *Init; 3590 3591 const APValue &V = GCD->getValue(); 3592 3593 assert(!V.isAbsent()); 3594 Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(), 3595 GCD->getType()); 3596 3597 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), 3598 /*isConstant=*/true, 3599 llvm::GlobalValue::PrivateLinkage, Init, 3600 ".constant"); 3601 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3602 GV->setAlignment(Alignment.getAsAlign()); 3603 3604 Emitter.finalize(GV); 3605 3606 *Entry = GV; 3607 return ConstantAddress(GV, GV->getValueType(), Alignment); 3608 } 3609 3610 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 3611 const TemplateParamObjectDecl *TPO) { 3612 StringRef Name = getMangledName(TPO); 3613 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 3614 3615 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 3616 return ConstantAddress(GV, GV->getValueType(), Alignment); 3617 3618 ConstantEmitter Emitter(*this); 3619 llvm::Constant *Init = Emitter.emitForInitializer( 3620 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 3621 3622 if (!Init) { 3623 ErrorUnsupported(TPO, "template parameter object"); 3624 return ConstantAddress::invalid(); 3625 } 3626 3627 llvm::GlobalValue::LinkageTypes Linkage = 3628 isExternallyVisible(TPO->getLinkageAndVisibility().getLinkage()) 3629 ? llvm::GlobalValue::LinkOnceODRLinkage 3630 : llvm::GlobalValue::InternalLinkage; 3631 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), 3632 /*isConstant=*/true, Linkage, Init, Name); 3633 setGVProperties(GV, TPO); 3634 if (supportsCOMDAT()) 3635 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3636 Emitter.finalize(GV); 3637 3638 return ConstantAddress(GV, GV->getValueType(), Alignment); 3639 } 3640 3641 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 3642 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 3643 assert(AA && "No alias?"); 3644 3645 CharUnits Alignment = getContext().getDeclAlign(VD); 3646 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 3647 3648 // See if there is already something with the target's name in the module. 3649 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 3650 if (Entry) 3651 return ConstantAddress(Entry, DeclTy, Alignment); 3652 3653 llvm::Constant *Aliasee; 3654 if (isa<llvm::FunctionType>(DeclTy)) 3655 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 3656 GlobalDecl(cast<FunctionDecl>(VD)), 3657 /*ForVTable=*/false); 3658 else 3659 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 3660 nullptr); 3661 3662 auto *F = cast<llvm::GlobalValue>(Aliasee); 3663 F->setLinkage(llvm::Function::ExternalWeakLinkage); 3664 WeakRefReferences.insert(F); 3665 3666 return ConstantAddress(Aliasee, DeclTy, Alignment); 3667 } 3668 3669 template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) { 3670 if (!D) 3671 return false; 3672 if (auto *A = D->getAttr<AttrT>()) 3673 return A->isImplicit(); 3674 return D->isImplicit(); 3675 } 3676 3677 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 3678 const auto *Global = cast<ValueDecl>(GD.getDecl()); 3679 3680 // Weak references don't produce any output by themselves. 3681 if (Global->hasAttr<WeakRefAttr>()) 3682 return; 3683 3684 // If this is an alias definition (which otherwise looks like a declaration) 3685 // emit it now. 3686 if (Global->hasAttr<AliasAttr>()) 3687 return EmitAliasDefinition(GD); 3688 3689 // IFunc like an alias whose value is resolved at runtime by calling resolver. 3690 if (Global->hasAttr<IFuncAttr>()) 3691 return emitIFuncDefinition(GD); 3692 3693 // If this is a cpu_dispatch multiversion function, emit the resolver. 3694 if (Global->hasAttr<CPUDispatchAttr>()) 3695 return emitCPUDispatchDefinition(GD); 3696 3697 // If this is CUDA, be selective about which declarations we emit. 3698 // Non-constexpr non-lambda implicit host device functions are not emitted 3699 // unless they are used on device side. 3700 if (LangOpts.CUDA) { 3701 if (LangOpts.CUDAIsDevice) { 3702 const auto *FD = dyn_cast<FunctionDecl>(Global); 3703 if ((!Global->hasAttr<CUDADeviceAttr>() || 3704 (LangOpts.OffloadImplicitHostDeviceTemplates && FD && 3705 hasImplicitAttr<CUDAHostAttr>(FD) && 3706 hasImplicitAttr<CUDADeviceAttr>(FD) && !FD->isConstexpr() && 3707 !isLambdaCallOperator(FD) && 3708 !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(FD))) && 3709 !Global->hasAttr<CUDAGlobalAttr>() && 3710 !Global->hasAttr<CUDAConstantAttr>() && 3711 !Global->hasAttr<CUDASharedAttr>() && 3712 !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 3713 !Global->getType()->isCUDADeviceBuiltinTextureType() && 3714 !(LangOpts.HIPStdPar && isa<FunctionDecl>(Global) && 3715 !Global->hasAttr<CUDAHostAttr>())) 3716 return; 3717 } else { 3718 // We need to emit host-side 'shadows' for all global 3719 // device-side variables because the CUDA runtime needs their 3720 // size and host-side address in order to provide access to 3721 // their device-side incarnations. 3722 3723 // So device-only functions are the only things we skip. 3724 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 3725 Global->hasAttr<CUDADeviceAttr>()) 3726 return; 3727 3728 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 3729 "Expected Variable or Function"); 3730 } 3731 } 3732 3733 if (LangOpts.OpenMP) { 3734 // If this is OpenMP, check if it is legal to emit this global normally. 3735 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 3736 return; 3737 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 3738 if (MustBeEmitted(Global)) 3739 EmitOMPDeclareReduction(DRD); 3740 return; 3741 } 3742 if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 3743 if (MustBeEmitted(Global)) 3744 EmitOMPDeclareMapper(DMD); 3745 return; 3746 } 3747 } 3748 3749 // Ignore declarations, they will be emitted on their first use. 3750 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3751 // Update deferred annotations with the latest declaration if the function 3752 // function was already used or defined. 3753 if (FD->hasAttr<AnnotateAttr>()) { 3754 StringRef MangledName = getMangledName(GD); 3755 if (GetGlobalValue(MangledName)) 3756 DeferredAnnotations[MangledName] = FD; 3757 } 3758 3759 // Forward declarations are emitted lazily on first use. 3760 if (!FD->doesThisDeclarationHaveABody()) { 3761 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 3762 return; 3763 3764 StringRef MangledName = getMangledName(GD); 3765 3766 // Compute the function info and LLVM type. 3767 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3768 llvm::Type *Ty = getTypes().GetFunctionType(FI); 3769 3770 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 3771 /*DontDefer=*/false); 3772 return; 3773 } 3774 } else { 3775 const auto *VD = cast<VarDecl>(Global); 3776 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 3777 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 3778 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 3779 if (LangOpts.OpenMP) { 3780 // Emit declaration of the must-be-emitted declare target variable. 3781 if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3782 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 3783 3784 // If this variable has external storage and doesn't require special 3785 // link handling we defer to its canonical definition. 3786 if (VD->hasExternalStorage() && 3787 Res != OMPDeclareTargetDeclAttr::MT_Link) 3788 return; 3789 3790 bool UnifiedMemoryEnabled = 3791 getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 3792 if ((*Res == OMPDeclareTargetDeclAttr::MT_To || 3793 *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 3794 !UnifiedMemoryEnabled) { 3795 (void)GetAddrOfGlobalVar(VD); 3796 } else { 3797 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 3798 ((*Res == OMPDeclareTargetDeclAttr::MT_To || 3799 *Res == OMPDeclareTargetDeclAttr::MT_Enter) && 3800 UnifiedMemoryEnabled)) && 3801 "Link clause or to clause with unified memory expected."); 3802 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 3803 } 3804 3805 return; 3806 } 3807 } 3808 // If this declaration may have caused an inline variable definition to 3809 // change linkage, make sure that it's emitted. 3810 if (Context.getInlineVariableDefinitionKind(VD) == 3811 ASTContext::InlineVariableDefinitionKind::Strong) 3812 GetAddrOfGlobalVar(VD); 3813 return; 3814 } 3815 } 3816 3817 // Defer code generation to first use when possible, e.g. if this is an inline 3818 // function. If the global must always be emitted, do it eagerly if possible 3819 // to benefit from cache locality. 3820 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 3821 // Emit the definition if it can't be deferred. 3822 EmitGlobalDefinition(GD); 3823 addEmittedDeferredDecl(GD); 3824 return; 3825 } 3826 3827 // If we're deferring emission of a C++ variable with an 3828 // initializer, remember the order in which it appeared in the file. 3829 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 3830 cast<VarDecl>(Global)->hasInit()) { 3831 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 3832 CXXGlobalInits.push_back(nullptr); 3833 } 3834 3835 StringRef MangledName = getMangledName(GD); 3836 if (GetGlobalValue(MangledName) != nullptr) { 3837 // The value has already been used and should therefore be emitted. 3838 addDeferredDeclToEmit(GD); 3839 } else if (MustBeEmitted(Global)) { 3840 // The value must be emitted, but cannot be emitted eagerly. 3841 assert(!MayBeEmittedEagerly(Global)); 3842 addDeferredDeclToEmit(GD); 3843 } else { 3844 // Otherwise, remember that we saw a deferred decl with this name. The 3845 // first use of the mangled name will cause it to move into 3846 // DeferredDeclsToEmit. 3847 DeferredDecls[MangledName] = GD; 3848 } 3849 } 3850 3851 // Check if T is a class type with a destructor that's not dllimport. 3852 static bool HasNonDllImportDtor(QualType T) { 3853 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 3854 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 3855 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 3856 return true; 3857 3858 return false; 3859 } 3860 3861 namespace { 3862 struct FunctionIsDirectlyRecursive 3863 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 3864 const StringRef Name; 3865 const Builtin::Context &BI; 3866 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 3867 : Name(N), BI(C) {} 3868 3869 bool VisitCallExpr(const CallExpr *E) { 3870 const FunctionDecl *FD = E->getDirectCallee(); 3871 if (!FD) 3872 return false; 3873 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3874 if (Attr && Name == Attr->getLabel()) 3875 return true; 3876 unsigned BuiltinID = FD->getBuiltinID(); 3877 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 3878 return false; 3879 StringRef BuiltinName = BI.getName(BuiltinID); 3880 if (BuiltinName.starts_with("__builtin_") && 3881 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 3882 return true; 3883 } 3884 return false; 3885 } 3886 3887 bool VisitStmt(const Stmt *S) { 3888 for (const Stmt *Child : S->children()) 3889 if (Child && this->Visit(Child)) 3890 return true; 3891 return false; 3892 } 3893 }; 3894 3895 // Make sure we're not referencing non-imported vars or functions. 3896 struct DLLImportFunctionVisitor 3897 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 3898 bool SafeToInline = true; 3899 3900 bool shouldVisitImplicitCode() const { return true; } 3901 3902 bool VisitVarDecl(VarDecl *VD) { 3903 if (VD->getTLSKind()) { 3904 // A thread-local variable cannot be imported. 3905 SafeToInline = false; 3906 return SafeToInline; 3907 } 3908 3909 // A variable definition might imply a destructor call. 3910 if (VD->isThisDeclarationADefinition()) 3911 SafeToInline = !HasNonDllImportDtor(VD->getType()); 3912 3913 return SafeToInline; 3914 } 3915 3916 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 3917 if (const auto *D = E->getTemporary()->getDestructor()) 3918 SafeToInline = D->hasAttr<DLLImportAttr>(); 3919 return SafeToInline; 3920 } 3921 3922 bool VisitDeclRefExpr(DeclRefExpr *E) { 3923 ValueDecl *VD = E->getDecl(); 3924 if (isa<FunctionDecl>(VD)) 3925 SafeToInline = VD->hasAttr<DLLImportAttr>(); 3926 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 3927 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 3928 return SafeToInline; 3929 } 3930 3931 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 3932 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 3933 return SafeToInline; 3934 } 3935 3936 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3937 CXXMethodDecl *M = E->getMethodDecl(); 3938 if (!M) { 3939 // Call through a pointer to member function. This is safe to inline. 3940 SafeToInline = true; 3941 } else { 3942 SafeToInline = M->hasAttr<DLLImportAttr>(); 3943 } 3944 return SafeToInline; 3945 } 3946 3947 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 3948 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 3949 return SafeToInline; 3950 } 3951 3952 bool VisitCXXNewExpr(CXXNewExpr *E) { 3953 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 3954 return SafeToInline; 3955 } 3956 }; 3957 } 3958 3959 // isTriviallyRecursive - Check if this function calls another 3960 // decl that, because of the asm attribute or the other decl being a builtin, 3961 // ends up pointing to itself. 3962 bool 3963 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 3964 StringRef Name; 3965 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 3966 // asm labels are a special kind of mangling we have to support. 3967 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3968 if (!Attr) 3969 return false; 3970 Name = Attr->getLabel(); 3971 } else { 3972 Name = FD->getName(); 3973 } 3974 3975 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 3976 const Stmt *Body = FD->getBody(); 3977 return Body ? Walker.Visit(Body) : false; 3978 } 3979 3980 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 3981 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 3982 return true; 3983 3984 const auto *F = cast<FunctionDecl>(GD.getDecl()); 3985 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 3986 return false; 3987 3988 // We don't import function bodies from other named module units since that 3989 // behavior may break ABI compatibility of the current unit. 3990 if (const Module *M = F->getOwningModule(); 3991 M && M->getTopLevelModule()->isNamedModule() && 3992 getContext().getCurrentNamedModule() != M->getTopLevelModule()) 3993 return false; 3994 3995 if (F->hasAttr<NoInlineAttr>()) 3996 return false; 3997 3998 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 3999 // Check whether it would be safe to inline this dllimport function. 4000 DLLImportFunctionVisitor Visitor; 4001 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 4002 if (!Visitor.SafeToInline) 4003 return false; 4004 4005 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 4006 // Implicit destructor invocations aren't captured in the AST, so the 4007 // check above can't see them. Check for them manually here. 4008 for (const Decl *Member : Dtor->getParent()->decls()) 4009 if (isa<FieldDecl>(Member)) 4010 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 4011 return false; 4012 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 4013 if (HasNonDllImportDtor(B.getType())) 4014 return false; 4015 } 4016 } 4017 4018 // Inline builtins declaration must be emitted. They often are fortified 4019 // functions. 4020 if (F->isInlineBuiltinDeclaration()) 4021 return true; 4022 4023 // PR9614. Avoid cases where the source code is lying to us. An available 4024 // externally function should have an equivalent function somewhere else, 4025 // but a function that calls itself through asm label/`__builtin_` trickery is 4026 // clearly not equivalent to the real implementation. 4027 // This happens in glibc's btowc and in some configure checks. 4028 return !isTriviallyRecursive(F); 4029 } 4030 4031 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 4032 return CodeGenOpts.OptimizationLevel > 0; 4033 } 4034 4035 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 4036 llvm::GlobalValue *GV) { 4037 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4038 4039 if (FD->isCPUSpecificMultiVersion()) { 4040 auto *Spec = FD->getAttr<CPUSpecificAttr>(); 4041 for (unsigned I = 0; I < Spec->cpus_size(); ++I) 4042 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 4043 } else if (FD->isTargetClonesMultiVersion()) { 4044 auto *Clone = FD->getAttr<TargetClonesAttr>(); 4045 for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) 4046 if (Clone->isFirstOfVersion(I)) 4047 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 4048 // Ensure that the resolver function is also emitted. 4049 GetOrCreateMultiVersionResolver(GD); 4050 } else if (FD->hasAttr<TargetVersionAttr>()) { 4051 GetOrCreateMultiVersionResolver(GD); 4052 } else 4053 EmitGlobalFunctionDefinition(GD, GV); 4054 } 4055 4056 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 4057 const auto *D = cast<ValueDecl>(GD.getDecl()); 4058 4059 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 4060 Context.getSourceManager(), 4061 "Generating code for declaration"); 4062 4063 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 4064 // At -O0, don't generate IR for functions with available_externally 4065 // linkage. 4066 if (!shouldEmitFunction(GD)) 4067 return; 4068 4069 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 4070 std::string Name; 4071 llvm::raw_string_ostream OS(Name); 4072 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 4073 /*Qualified=*/true); 4074 return Name; 4075 }); 4076 4077 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 4078 // Make sure to emit the definition(s) before we emit the thunks. 4079 // This is necessary for the generation of certain thunks. 4080 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 4081 ABI->emitCXXStructor(GD); 4082 else if (FD->isMultiVersion()) 4083 EmitMultiVersionFunctionDefinition(GD, GV); 4084 else 4085 EmitGlobalFunctionDefinition(GD, GV); 4086 4087 if (Method->isVirtual()) 4088 getVTables().EmitThunks(GD); 4089 4090 return; 4091 } 4092 4093 if (FD->isMultiVersion()) 4094 return EmitMultiVersionFunctionDefinition(GD, GV); 4095 return EmitGlobalFunctionDefinition(GD, GV); 4096 } 4097 4098 if (const auto *VD = dyn_cast<VarDecl>(D)) 4099 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 4100 4101 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 4102 } 4103 4104 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 4105 llvm::Function *NewFn); 4106 4107 static unsigned 4108 TargetMVPriority(const TargetInfo &TI, 4109 const CodeGenFunction::MultiVersionResolverOption &RO) { 4110 unsigned Priority = 0; 4111 unsigned NumFeatures = 0; 4112 for (StringRef Feat : RO.Conditions.Features) { 4113 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 4114 NumFeatures++; 4115 } 4116 4117 if (!RO.Conditions.Architecture.empty()) 4118 Priority = std::max( 4119 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 4120 4121 Priority += TI.multiVersionFeatureCost() * NumFeatures; 4122 4123 return Priority; 4124 } 4125 4126 // Multiversion functions should be at most 'WeakODRLinkage' so that a different 4127 // TU can forward declare the function without causing problems. Particularly 4128 // in the cases of CPUDispatch, this causes issues. This also makes sure we 4129 // work with internal linkage functions, so that the same function name can be 4130 // used with internal linkage in multiple TUs. 4131 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, 4132 GlobalDecl GD) { 4133 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 4134 if (FD->getFormalLinkage() == Linkage::Internal) 4135 return llvm::GlobalValue::InternalLinkage; 4136 return llvm::GlobalValue::WeakODRLinkage; 4137 } 4138 4139 void CodeGenModule::emitMultiVersionFunctions() { 4140 std::vector<GlobalDecl> MVFuncsToEmit; 4141 MultiVersionFuncs.swap(MVFuncsToEmit); 4142 for (GlobalDecl GD : MVFuncsToEmit) { 4143 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4144 assert(FD && "Expected a FunctionDecl"); 4145 4146 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 4147 if (FD->isTargetMultiVersion()) { 4148 getContext().forEachMultiversionedFunctionVersion( 4149 FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 4150 GlobalDecl CurGD{ 4151 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 4152 StringRef MangledName = getMangledName(CurGD); 4153 llvm::Constant *Func = GetGlobalValue(MangledName); 4154 if (!Func) { 4155 if (CurFD->isDefined()) { 4156 EmitGlobalFunctionDefinition(CurGD, nullptr); 4157 Func = GetGlobalValue(MangledName); 4158 } else { 4159 const CGFunctionInfo &FI = 4160 getTypes().arrangeGlobalDeclaration(GD); 4161 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4162 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 4163 /*DontDefer=*/false, ForDefinition); 4164 } 4165 assert(Func && "This should have just been created"); 4166 } 4167 if (CurFD->getMultiVersionKind() == MultiVersionKind::Target) { 4168 const auto *TA = CurFD->getAttr<TargetAttr>(); 4169 llvm::SmallVector<StringRef, 8> Feats; 4170 TA->getAddedFeatures(Feats); 4171 Options.emplace_back(cast<llvm::Function>(Func), 4172 TA->getArchitecture(), Feats); 4173 } else { 4174 const auto *TVA = CurFD->getAttr<TargetVersionAttr>(); 4175 llvm::SmallVector<StringRef, 8> Feats; 4176 TVA->getFeatures(Feats); 4177 Options.emplace_back(cast<llvm::Function>(Func), 4178 /*Architecture*/ "", Feats); 4179 } 4180 }); 4181 } else if (FD->isTargetClonesMultiVersion()) { 4182 const auto *TC = FD->getAttr<TargetClonesAttr>(); 4183 for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); 4184 ++VersionIndex) { 4185 if (!TC->isFirstOfVersion(VersionIndex)) 4186 continue; 4187 GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD), 4188 VersionIndex}; 4189 StringRef Version = TC->getFeatureStr(VersionIndex); 4190 StringRef MangledName = getMangledName(CurGD); 4191 llvm::Constant *Func = GetGlobalValue(MangledName); 4192 if (!Func) { 4193 if (FD->isDefined()) { 4194 EmitGlobalFunctionDefinition(CurGD, nullptr); 4195 Func = GetGlobalValue(MangledName); 4196 } else { 4197 const CGFunctionInfo &FI = 4198 getTypes().arrangeGlobalDeclaration(CurGD); 4199 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4200 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 4201 /*DontDefer=*/false, ForDefinition); 4202 } 4203 assert(Func && "This should have just been created"); 4204 } 4205 4206 StringRef Architecture; 4207 llvm::SmallVector<StringRef, 1> Feature; 4208 4209 if (getTarget().getTriple().isAArch64()) { 4210 if (Version != "default") { 4211 llvm::SmallVector<StringRef, 8> VerFeats; 4212 Version.split(VerFeats, "+"); 4213 for (auto &CurFeat : VerFeats) 4214 Feature.push_back(CurFeat.trim()); 4215 } 4216 } else { 4217 if (Version.starts_with("arch=")) 4218 Architecture = Version.drop_front(sizeof("arch=") - 1); 4219 else if (Version != "default") 4220 Feature.push_back(Version); 4221 } 4222 4223 Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature); 4224 } 4225 } else { 4226 assert(0 && "Expected a target or target_clones multiversion function"); 4227 continue; 4228 } 4229 4230 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD); 4231 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) { 4232 ResolverConstant = IFunc->getResolver(); 4233 if (FD->isTargetClonesMultiVersion() || 4234 FD->isTargetVersionMultiVersion()) { 4235 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4236 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 4237 std::string MangledName = getMangledNameImpl( 4238 *this, GD, FD, /*OmitMultiVersionMangling=*/true); 4239 // In prior versions of Clang, the mangling for ifuncs incorrectly 4240 // included an .ifunc suffix. This alias is generated for backward 4241 // compatibility. It is deprecated, and may be removed in the future. 4242 auto *Alias = llvm::GlobalAlias::create( 4243 DeclTy, 0, getMultiversionLinkage(*this, GD), 4244 MangledName + ".ifunc", IFunc, &getModule()); 4245 SetCommonAttributes(FD, Alias); 4246 } 4247 } 4248 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant); 4249 4250 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 4251 4252 if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT()) 4253 ResolverFunc->setComdat( 4254 getModule().getOrInsertComdat(ResolverFunc->getName())); 4255 4256 const TargetInfo &TI = getTarget(); 4257 llvm::stable_sort( 4258 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 4259 const CodeGenFunction::MultiVersionResolverOption &RHS) { 4260 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 4261 }); 4262 CodeGenFunction CGF(*this); 4263 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 4264 } 4265 4266 // Ensure that any additions to the deferred decls list caused by emitting a 4267 // variant are emitted. This can happen when the variant itself is inline and 4268 // calls a function without linkage. 4269 if (!MVFuncsToEmit.empty()) 4270 EmitDeferred(); 4271 4272 // Ensure that any additions to the multiversion funcs list from either the 4273 // deferred decls or the multiversion functions themselves are emitted. 4274 if (!MultiVersionFuncs.empty()) 4275 emitMultiVersionFunctions(); 4276 } 4277 4278 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 4279 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4280 assert(FD && "Not a FunctionDecl?"); 4281 assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?"); 4282 const auto *DD = FD->getAttr<CPUDispatchAttr>(); 4283 assert(DD && "Not a cpu_dispatch Function?"); 4284 4285 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4286 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 4287 4288 StringRef ResolverName = getMangledName(GD); 4289 UpdateMultiVersionNames(GD, FD, ResolverName); 4290 4291 llvm::Type *ResolverType; 4292 GlobalDecl ResolverGD; 4293 if (getTarget().supportsIFunc()) { 4294 ResolverType = llvm::FunctionType::get( 4295 llvm::PointerType::get(DeclTy, 4296 getTypes().getTargetAddressSpace(FD->getType())), 4297 false); 4298 } 4299 else { 4300 ResolverType = DeclTy; 4301 ResolverGD = GD; 4302 } 4303 4304 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 4305 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 4306 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 4307 if (supportsCOMDAT()) 4308 ResolverFunc->setComdat( 4309 getModule().getOrInsertComdat(ResolverFunc->getName())); 4310 4311 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 4312 const TargetInfo &Target = getTarget(); 4313 unsigned Index = 0; 4314 for (const IdentifierInfo *II : DD->cpus()) { 4315 // Get the name of the target function so we can look it up/create it. 4316 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 4317 getCPUSpecificMangling(*this, II->getName()); 4318 4319 llvm::Constant *Func = GetGlobalValue(MangledName); 4320 4321 if (!Func) { 4322 GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 4323 if (ExistingDecl.getDecl() && 4324 ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 4325 EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 4326 Func = GetGlobalValue(MangledName); 4327 } else { 4328 if (!ExistingDecl.getDecl()) 4329 ExistingDecl = GD.getWithMultiVersionIndex(Index); 4330 4331 Func = GetOrCreateLLVMFunction( 4332 MangledName, DeclTy, ExistingDecl, 4333 /*ForVTable=*/false, /*DontDefer=*/true, 4334 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 4335 } 4336 } 4337 4338 llvm::SmallVector<StringRef, 32> Features; 4339 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 4340 llvm::transform(Features, Features.begin(), 4341 [](StringRef Str) { return Str.substr(1); }); 4342 llvm::erase_if(Features, [&Target](StringRef Feat) { 4343 return !Target.validateCpuSupports(Feat); 4344 }); 4345 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 4346 ++Index; 4347 } 4348 4349 llvm::stable_sort( 4350 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 4351 const CodeGenFunction::MultiVersionResolverOption &RHS) { 4352 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 4353 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 4354 }); 4355 4356 // If the list contains multiple 'default' versions, such as when it contains 4357 // 'pentium' and 'generic', don't emit the call to the generic one (since we 4358 // always run on at least a 'pentium'). We do this by deleting the 'least 4359 // advanced' (read, lowest mangling letter). 4360 while (Options.size() > 1 && 4361 llvm::all_of(llvm::X86::getCpuSupportsMask( 4362 (Options.end() - 2)->Conditions.Features), 4363 [](auto X) { return X == 0; })) { 4364 StringRef LHSName = (Options.end() - 2)->Function->getName(); 4365 StringRef RHSName = (Options.end() - 1)->Function->getName(); 4366 if (LHSName.compare(RHSName) < 0) 4367 Options.erase(Options.end() - 2); 4368 else 4369 Options.erase(Options.end() - 1); 4370 } 4371 4372 CodeGenFunction CGF(*this); 4373 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 4374 4375 if (getTarget().supportsIFunc()) { 4376 llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD); 4377 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD)); 4378 4379 // Fix up function declarations that were created for cpu_specific before 4380 // cpu_dispatch was known 4381 if (!isa<llvm::GlobalIFunc>(IFunc)) { 4382 assert(cast<llvm::Function>(IFunc)->isDeclaration()); 4383 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc, 4384 &getModule()); 4385 GI->takeName(IFunc); 4386 IFunc->replaceAllUsesWith(GI); 4387 IFunc->eraseFromParent(); 4388 IFunc = GI; 4389 } 4390 4391 std::string AliasName = getMangledNameImpl( 4392 *this, GD, FD, /*OmitMultiVersionMangling=*/true); 4393 llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 4394 if (!AliasFunc) { 4395 auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc, 4396 &getModule()); 4397 SetCommonAttributes(GD, GA); 4398 } 4399 } 4400 } 4401 4402 /// If a dispatcher for the specified mangled name is not in the module, create 4403 /// and return an llvm Function with the specified type. 4404 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) { 4405 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4406 assert(FD && "Not a FunctionDecl?"); 4407 4408 std::string MangledName = 4409 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 4410 4411 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 4412 // a separate resolver). 4413 std::string ResolverName = MangledName; 4414 if (getTarget().supportsIFunc()) { 4415 switch (FD->getMultiVersionKind()) { 4416 case MultiVersionKind::None: 4417 llvm_unreachable("unexpected MultiVersionKind::None for resolver"); 4418 case MultiVersionKind::Target: 4419 case MultiVersionKind::CPUSpecific: 4420 case MultiVersionKind::CPUDispatch: 4421 ResolverName += ".ifunc"; 4422 break; 4423 case MultiVersionKind::TargetClones: 4424 case MultiVersionKind::TargetVersion: 4425 break; 4426 } 4427 } else if (FD->isTargetMultiVersion()) { 4428 ResolverName += ".resolver"; 4429 } 4430 4431 // If the resolver has already been created, just return it. 4432 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 4433 return ResolverGV; 4434 4435 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4436 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 4437 4438 // The resolver needs to be created. For target and target_clones, defer 4439 // creation until the end of the TU. 4440 if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion()) 4441 MultiVersionFuncs.push_back(GD); 4442 4443 // For cpu_specific, don't create an ifunc yet because we don't know if the 4444 // cpu_dispatch will be emitted in this translation unit. 4445 if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) { 4446 llvm::Type *ResolverType = llvm::FunctionType::get( 4447 llvm::PointerType::get(DeclTy, 4448 getTypes().getTargetAddressSpace(FD->getType())), 4449 false); 4450 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 4451 MangledName + ".resolver", ResolverType, GlobalDecl{}, 4452 /*ForVTable=*/false); 4453 llvm::GlobalIFunc *GIF = 4454 llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 4455 "", Resolver, &getModule()); 4456 GIF->setName(ResolverName); 4457 SetCommonAttributes(FD, GIF); 4458 4459 return GIF; 4460 } 4461 4462 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 4463 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 4464 assert(isa<llvm::GlobalValue>(Resolver) && 4465 "Resolver should be created for the first time"); 4466 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 4467 return Resolver; 4468 } 4469 4470 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 4471 /// module, create and return an llvm Function with the specified type. If there 4472 /// is something in the module with the specified name, return it potentially 4473 /// bitcasted to the right type. 4474 /// 4475 /// If D is non-null, it specifies a decl that correspond to this. This is used 4476 /// to set the attributes on the function when it is first created. 4477 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 4478 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 4479 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 4480 ForDefinition_t IsForDefinition) { 4481 const Decl *D = GD.getDecl(); 4482 4483 // Any attempts to use a MultiVersion function should result in retrieving 4484 // the iFunc instead. Name Mangling will handle the rest of the changes. 4485 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 4486 // For the device mark the function as one that should be emitted. 4487 if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime && 4488 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 4489 !DontDefer && !IsForDefinition) { 4490 if (const FunctionDecl *FDDef = FD->getDefinition()) { 4491 GlobalDecl GDDef; 4492 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 4493 GDDef = GlobalDecl(CD, GD.getCtorType()); 4494 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 4495 GDDef = GlobalDecl(DD, GD.getDtorType()); 4496 else 4497 GDDef = GlobalDecl(FDDef); 4498 EmitGlobal(GDDef); 4499 } 4500 } 4501 4502 if (FD->isMultiVersion()) { 4503 UpdateMultiVersionNames(GD, FD, MangledName); 4504 if (!IsForDefinition) 4505 return GetOrCreateMultiVersionResolver(GD); 4506 } 4507 } 4508 4509 // Lookup the entry, lazily creating it if necessary. 4510 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4511 if (Entry) { 4512 if (WeakRefReferences.erase(Entry)) { 4513 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 4514 if (FD && !FD->hasAttr<WeakAttr>()) 4515 Entry->setLinkage(llvm::Function::ExternalLinkage); 4516 } 4517 4518 // Handle dropped DLL attributes. 4519 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 4520 !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) { 4521 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4522 setDSOLocal(Entry); 4523 } 4524 4525 // If there are two attempts to define the same mangled name, issue an 4526 // error. 4527 if (IsForDefinition && !Entry->isDeclaration()) { 4528 GlobalDecl OtherGD; 4529 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 4530 // to make sure that we issue an error only once. 4531 if (lookupRepresentativeDecl(MangledName, OtherGD) && 4532 (GD.getCanonicalDecl().getDecl() != 4533 OtherGD.getCanonicalDecl().getDecl()) && 4534 DiagnosedConflictingDefinitions.insert(GD).second) { 4535 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4536 << MangledName; 4537 getDiags().Report(OtherGD.getDecl()->getLocation(), 4538 diag::note_previous_definition); 4539 } 4540 } 4541 4542 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 4543 (Entry->getValueType() == Ty)) { 4544 return Entry; 4545 } 4546 4547 // Make sure the result is of the correct type. 4548 // (If function is requested for a definition, we always need to create a new 4549 // function, not just return a bitcast.) 4550 if (!IsForDefinition) 4551 return Entry; 4552 } 4553 4554 // This function doesn't have a complete type (for example, the return 4555 // type is an incomplete struct). Use a fake type instead, and make 4556 // sure not to try to set attributes. 4557 bool IsIncompleteFunction = false; 4558 4559 llvm::FunctionType *FTy; 4560 if (isa<llvm::FunctionType>(Ty)) { 4561 FTy = cast<llvm::FunctionType>(Ty); 4562 } else { 4563 FTy = llvm::FunctionType::get(VoidTy, false); 4564 IsIncompleteFunction = true; 4565 } 4566 4567 llvm::Function *F = 4568 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 4569 Entry ? StringRef() : MangledName, &getModule()); 4570 4571 // Store the declaration associated with this function so it is potentially 4572 // updated by further declarations or definitions and emitted at the end. 4573 if (D && D->hasAttr<AnnotateAttr>()) 4574 DeferredAnnotations[MangledName] = cast<ValueDecl>(D); 4575 4576 // If we already created a function with the same mangled name (but different 4577 // type) before, take its name and add it to the list of functions to be 4578 // replaced with F at the end of CodeGen. 4579 // 4580 // This happens if there is a prototype for a function (e.g. "int f()") and 4581 // then a definition of a different type (e.g. "int f(int x)"). 4582 if (Entry) { 4583 F->takeName(Entry); 4584 4585 // This might be an implementation of a function without a prototype, in 4586 // which case, try to do special replacement of calls which match the new 4587 // prototype. The really key thing here is that we also potentially drop 4588 // arguments from the call site so as to make a direct call, which makes the 4589 // inliner happier and suppresses a number of optimizer warnings (!) about 4590 // dropping arguments. 4591 if (!Entry->use_empty()) { 4592 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 4593 Entry->removeDeadConstantUsers(); 4594 } 4595 4596 addGlobalValReplacement(Entry, F); 4597 } 4598 4599 assert(F->getName() == MangledName && "name was uniqued!"); 4600 if (D) 4601 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 4602 if (ExtraAttrs.hasFnAttrs()) { 4603 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); 4604 F->addFnAttrs(B); 4605 } 4606 4607 if (!DontDefer) { 4608 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 4609 // each other bottoming out with the base dtor. Therefore we emit non-base 4610 // dtors on usage, even if there is no dtor definition in the TU. 4611 if (isa_and_nonnull<CXXDestructorDecl>(D) && 4612 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 4613 GD.getDtorType())) 4614 addDeferredDeclToEmit(GD); 4615 4616 // This is the first use or definition of a mangled name. If there is a 4617 // deferred decl with this name, remember that we need to emit it at the end 4618 // of the file. 4619 auto DDI = DeferredDecls.find(MangledName); 4620 if (DDI != DeferredDecls.end()) { 4621 // Move the potentially referenced deferred decl to the 4622 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 4623 // don't need it anymore). 4624 addDeferredDeclToEmit(DDI->second); 4625 DeferredDecls.erase(DDI); 4626 4627 // Otherwise, there are cases we have to worry about where we're 4628 // using a declaration for which we must emit a definition but where 4629 // we might not find a top-level definition: 4630 // - member functions defined inline in their classes 4631 // - friend functions defined inline in some class 4632 // - special member functions with implicit definitions 4633 // If we ever change our AST traversal to walk into class methods, 4634 // this will be unnecessary. 4635 // 4636 // We also don't emit a definition for a function if it's going to be an 4637 // entry in a vtable, unless it's already marked as used. 4638 } else if (getLangOpts().CPlusPlus && D) { 4639 // Look for a declaration that's lexically in a record. 4640 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 4641 FD = FD->getPreviousDecl()) { 4642 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 4643 if (FD->doesThisDeclarationHaveABody()) { 4644 addDeferredDeclToEmit(GD.getWithDecl(FD)); 4645 break; 4646 } 4647 } 4648 } 4649 } 4650 } 4651 4652 // Make sure the result is of the requested type. 4653 if (!IsIncompleteFunction) { 4654 assert(F->getFunctionType() == Ty); 4655 return F; 4656 } 4657 4658 return F; 4659 } 4660 4661 /// GetAddrOfFunction - Return the address of the given function. If Ty is 4662 /// non-null, then this function will use the specified type if it has to 4663 /// create it (this occurs when we see a definition of the function). 4664 llvm::Constant * 4665 CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable, 4666 bool DontDefer, 4667 ForDefinition_t IsForDefinition) { 4668 // If there was no specific requested type, just convert it now. 4669 if (!Ty) { 4670 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4671 Ty = getTypes().ConvertType(FD->getType()); 4672 } 4673 4674 // Devirtualized destructor calls may come through here instead of via 4675 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 4676 // of the complete destructor when necessary. 4677 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 4678 if (getTarget().getCXXABI().isMicrosoft() && 4679 GD.getDtorType() == Dtor_Complete && 4680 DD->getParent()->getNumVBases() == 0) 4681 GD = GlobalDecl(DD, Dtor_Base); 4682 } 4683 4684 StringRef MangledName = getMangledName(GD); 4685 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 4686 /*IsThunk=*/false, llvm::AttributeList(), 4687 IsForDefinition); 4688 // Returns kernel handle for HIP kernel stub function. 4689 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 4690 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 4691 auto *Handle = getCUDARuntime().getKernelHandle( 4692 cast<llvm::Function>(F->stripPointerCasts()), GD); 4693 if (IsForDefinition) 4694 return F; 4695 return Handle; 4696 } 4697 return F; 4698 } 4699 4700 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { 4701 llvm::GlobalValue *F = 4702 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); 4703 4704 return llvm::NoCFIValue::get(F); 4705 } 4706 4707 static const FunctionDecl * 4708 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 4709 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 4710 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 4711 4712 IdentifierInfo &CII = C.Idents.get(Name); 4713 for (const auto *Result : DC->lookup(&CII)) 4714 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4715 return FD; 4716 4717 if (!C.getLangOpts().CPlusPlus) 4718 return nullptr; 4719 4720 // Demangle the premangled name from getTerminateFn() 4721 IdentifierInfo &CXXII = 4722 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 4723 ? C.Idents.get("terminate") 4724 : C.Idents.get(Name); 4725 4726 for (const auto &N : {"__cxxabiv1", "std"}) { 4727 IdentifierInfo &NS = C.Idents.get(N); 4728 for (const auto *Result : DC->lookup(&NS)) { 4729 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 4730 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 4731 for (const auto *Result : LSD->lookup(&NS)) 4732 if ((ND = dyn_cast<NamespaceDecl>(Result))) 4733 break; 4734 4735 if (ND) 4736 for (const auto *Result : ND->lookup(&CXXII)) 4737 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4738 return FD; 4739 } 4740 } 4741 4742 return nullptr; 4743 } 4744 4745 /// CreateRuntimeFunction - Create a new runtime function with the specified 4746 /// type and name. 4747 llvm::FunctionCallee 4748 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 4749 llvm::AttributeList ExtraAttrs, bool Local, 4750 bool AssumeConvergent) { 4751 if (AssumeConvergent) { 4752 ExtraAttrs = 4753 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 4754 } 4755 4756 llvm::Constant *C = 4757 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 4758 /*DontDefer=*/false, /*IsThunk=*/false, 4759 ExtraAttrs); 4760 4761 if (auto *F = dyn_cast<llvm::Function>(C)) { 4762 if (F->empty()) { 4763 F->setCallingConv(getRuntimeCC()); 4764 4765 // In Windows Itanium environments, try to mark runtime functions 4766 // dllimport. For Mingw and MSVC, don't. We don't really know if the user 4767 // will link their standard library statically or dynamically. Marking 4768 // functions imported when they are not imported can cause linker errors 4769 // and warnings. 4770 if (!Local && getTriple().isWindowsItaniumEnvironment() && 4771 !getCodeGenOpts().LTOVisibilityPublicStd) { 4772 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 4773 if (!FD || FD->hasAttr<DLLImportAttr>()) { 4774 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4775 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 4776 } 4777 } 4778 setDSOLocal(F); 4779 } 4780 } 4781 4782 return {FTy, C}; 4783 } 4784 4785 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 4786 /// create and return an llvm GlobalVariable with the specified type and address 4787 /// space. If there is something in the module with the specified name, return 4788 /// it potentially bitcasted to the right type. 4789 /// 4790 /// If D is non-null, it specifies a decl that correspond to this. This is used 4791 /// to set the attributes on the global when it is first created. 4792 /// 4793 /// If IsForDefinition is true, it is guaranteed that an actual global with 4794 /// type Ty will be returned, not conversion of a variable with the same 4795 /// mangled name but some other type. 4796 llvm::Constant * 4797 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4798 LangAS AddrSpace, const VarDecl *D, 4799 ForDefinition_t IsForDefinition) { 4800 // Lookup the entry, lazily creating it if necessary. 4801 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4802 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 4803 if (Entry) { 4804 if (WeakRefReferences.erase(Entry)) { 4805 if (D && !D->hasAttr<WeakAttr>()) 4806 Entry->setLinkage(llvm::Function::ExternalLinkage); 4807 } 4808 4809 // Handle dropped DLL attributes. 4810 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 4811 !shouldMapVisibilityToDLLExport(D)) 4812 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4813 4814 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 4815 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 4816 4817 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 4818 return Entry; 4819 4820 // If there are two attempts to define the same mangled name, issue an 4821 // error. 4822 if (IsForDefinition && !Entry->isDeclaration()) { 4823 GlobalDecl OtherGD; 4824 const VarDecl *OtherD; 4825 4826 // Check that D is not yet in DiagnosedConflictingDefinitions is required 4827 // to make sure that we issue an error only once. 4828 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 4829 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 4830 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 4831 OtherD->hasInit() && 4832 DiagnosedConflictingDefinitions.insert(D).second) { 4833 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4834 << MangledName; 4835 getDiags().Report(OtherGD.getDecl()->getLocation(), 4836 diag::note_previous_definition); 4837 } 4838 } 4839 4840 // Make sure the result is of the correct type. 4841 if (Entry->getType()->getAddressSpace() != TargetAS) 4842 return llvm::ConstantExpr::getAddrSpaceCast( 4843 Entry, llvm::PointerType::get(Ty->getContext(), TargetAS)); 4844 4845 // (If global is requested for a definition, we always need to create a new 4846 // global, not just return a bitcast.) 4847 if (!IsForDefinition) 4848 return Entry; 4849 } 4850 4851 auto DAddrSpace = GetGlobalVarAddressSpace(D); 4852 4853 auto *GV = new llvm::GlobalVariable( 4854 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4855 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4856 getContext().getTargetAddressSpace(DAddrSpace)); 4857 4858 // If we already created a global with the same mangled name (but different 4859 // type) before, take its name and remove it from its parent. 4860 if (Entry) { 4861 GV->takeName(Entry); 4862 4863 if (!Entry->use_empty()) { 4864 Entry->replaceAllUsesWith(GV); 4865 } 4866 4867 Entry->eraseFromParent(); 4868 } 4869 4870 // This is the first use or definition of a mangled name. If there is a 4871 // deferred decl with this name, remember that we need to emit it at the end 4872 // of the file. 4873 auto DDI = DeferredDecls.find(MangledName); 4874 if (DDI != DeferredDecls.end()) { 4875 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 4876 // list, and remove it from DeferredDecls (since we don't need it anymore). 4877 addDeferredDeclToEmit(DDI->second); 4878 DeferredDecls.erase(DDI); 4879 } 4880 4881 // Handle things which are present even on external declarations. 4882 if (D) { 4883 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 4884 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 4885 4886 // FIXME: This code is overly simple and should be merged with other global 4887 // handling. 4888 GV->setConstant(D->getType().isConstantStorage(getContext(), false, false)); 4889 4890 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4891 4892 setLinkageForGV(GV, D); 4893 4894 if (D->getTLSKind()) { 4895 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4896 CXXThreadLocals.push_back(D); 4897 setTLSMode(GV, *D); 4898 } 4899 4900 setGVProperties(GV, D); 4901 4902 // If required by the ABI, treat declarations of static data members with 4903 // inline initializers as definitions. 4904 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 4905 EmitGlobalVarDefinition(D); 4906 } 4907 4908 // Emit section information for extern variables. 4909 if (D->hasExternalStorage()) { 4910 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 4911 GV->setSection(SA->getName()); 4912 } 4913 4914 // Handle XCore specific ABI requirements. 4915 if (getTriple().getArch() == llvm::Triple::xcore && 4916 D->getLanguageLinkage() == CLanguageLinkage && 4917 D->getType().isConstant(Context) && 4918 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 4919 GV->setSection(".cp.rodata"); 4920 4921 // Handle code model attribute 4922 if (const auto *CMA = D->getAttr<CodeModelAttr>()) 4923 GV->setCodeModel(CMA->getModel()); 4924 4925 // Check if we a have a const declaration with an initializer, we may be 4926 // able to emit it as available_externally to expose it's value to the 4927 // optimizer. 4928 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 4929 D->getType().isConstQualified() && !GV->hasInitializer() && 4930 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 4931 const auto *Record = 4932 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 4933 bool HasMutableFields = Record && Record->hasMutableFields(); 4934 if (!HasMutableFields) { 4935 const VarDecl *InitDecl; 4936 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4937 if (InitExpr) { 4938 ConstantEmitter emitter(*this); 4939 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 4940 if (Init) { 4941 auto *InitType = Init->getType(); 4942 if (GV->getValueType() != InitType) { 4943 // The type of the initializer does not match the definition. 4944 // This happens when an initializer has a different type from 4945 // the type of the global (because of padding at the end of a 4946 // structure for instance). 4947 GV->setName(StringRef()); 4948 // Make a new global with the correct type, this is now guaranteed 4949 // to work. 4950 auto *NewGV = cast<llvm::GlobalVariable>( 4951 GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4952 ->stripPointerCasts()); 4953 4954 // Erase the old global, since it is no longer used. 4955 GV->eraseFromParent(); 4956 GV = NewGV; 4957 } else { 4958 GV->setInitializer(Init); 4959 GV->setConstant(true); 4960 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 4961 } 4962 emitter.finalize(GV); 4963 } 4964 } 4965 } 4966 } 4967 } 4968 4969 if (D && 4970 D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) { 4971 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4972 // External HIP managed variables needed to be recorded for transformation 4973 // in both device and host compilations. 4974 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4975 D->hasExternalStorage()) 4976 getCUDARuntime().handleVarRegistration(D, *GV); 4977 } 4978 4979 if (D) 4980 SanitizerMD->reportGlobal(GV, *D); 4981 4982 LangAS ExpectedAS = 4983 D ? D->getType().getAddressSpace() 4984 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4985 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4986 if (DAddrSpace != ExpectedAS) { 4987 return getTargetCodeGenInfo().performAddrSpaceCast( 4988 *this, GV, DAddrSpace, ExpectedAS, 4989 llvm::PointerType::get(getLLVMContext(), TargetAS)); 4990 } 4991 4992 return GV; 4993 } 4994 4995 llvm::Constant * 4996 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 4997 const Decl *D = GD.getDecl(); 4998 4999 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 5000 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 5001 /*DontDefer=*/false, IsForDefinition); 5002 5003 if (isa<CXXMethodDecl>(D)) { 5004 auto FInfo = 5005 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 5006 auto Ty = getTypes().GetFunctionType(*FInfo); 5007 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 5008 IsForDefinition); 5009 } 5010 5011 if (isa<FunctionDecl>(D)) { 5012 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 5013 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 5014 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 5015 IsForDefinition); 5016 } 5017 5018 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 5019 } 5020 5021 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 5022 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 5023 llvm::Align Alignment) { 5024 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 5025 llvm::GlobalVariable *OldGV = nullptr; 5026 5027 if (GV) { 5028 // Check if the variable has the right type. 5029 if (GV->getValueType() == Ty) 5030 return GV; 5031 5032 // Because C++ name mangling, the only way we can end up with an already 5033 // existing global with the same name is if it has been declared extern "C". 5034 assert(GV->isDeclaration() && "Declaration has wrong type!"); 5035 OldGV = GV; 5036 } 5037 5038 // Create a new variable. 5039 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 5040 Linkage, nullptr, Name); 5041 5042 if (OldGV) { 5043 // Replace occurrences of the old variable if needed. 5044 GV->takeName(OldGV); 5045 5046 if (!OldGV->use_empty()) { 5047 OldGV->replaceAllUsesWith(GV); 5048 } 5049 5050 OldGV->eraseFromParent(); 5051 } 5052 5053 if (supportsCOMDAT() && GV->isWeakForLinker() && 5054 !GV->hasAvailableExternallyLinkage()) 5055 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 5056 5057 GV->setAlignment(Alignment); 5058 5059 return GV; 5060 } 5061 5062 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 5063 /// given global variable. If Ty is non-null and if the global doesn't exist, 5064 /// then it will be created with the specified type instead of whatever the 5065 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 5066 /// that an actual global with type Ty will be returned, not conversion of a 5067 /// variable with the same mangled name but some other type. 5068 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 5069 llvm::Type *Ty, 5070 ForDefinition_t IsForDefinition) { 5071 assert(D->hasGlobalStorage() && "Not a global variable"); 5072 QualType ASTTy = D->getType(); 5073 if (!Ty) 5074 Ty = getTypes().ConvertTypeForMem(ASTTy); 5075 5076 StringRef MangledName = getMangledName(D); 5077 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 5078 IsForDefinition); 5079 } 5080 5081 /// CreateRuntimeVariable - Create a new runtime global variable with the 5082 /// specified type and name. 5083 llvm::Constant * 5084 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 5085 StringRef Name) { 5086 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 5087 : LangAS::Default; 5088 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 5089 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 5090 return Ret; 5091 } 5092 5093 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 5094 assert(!D->getInit() && "Cannot emit definite definitions here!"); 5095 5096 StringRef MangledName = getMangledName(D); 5097 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 5098 5099 // We already have a definition, not declaration, with the same mangled name. 5100 // Emitting of declaration is not required (and actually overwrites emitted 5101 // definition). 5102 if (GV && !GV->isDeclaration()) 5103 return; 5104 5105 // If we have not seen a reference to this variable yet, place it into the 5106 // deferred declarations table to be emitted if needed later. 5107 if (!MustBeEmitted(D) && !GV) { 5108 DeferredDecls[MangledName] = D; 5109 return; 5110 } 5111 5112 // The tentative definition is the only definition. 5113 EmitGlobalVarDefinition(D); 5114 } 5115 5116 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 5117 EmitExternalVarDeclaration(D); 5118 } 5119 5120 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 5121 return Context.toCharUnitsFromBits( 5122 getDataLayout().getTypeStoreSizeInBits(Ty)); 5123 } 5124 5125 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 5126 if (LangOpts.OpenCL) { 5127 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 5128 assert(AS == LangAS::opencl_global || 5129 AS == LangAS::opencl_global_device || 5130 AS == LangAS::opencl_global_host || 5131 AS == LangAS::opencl_constant || 5132 AS == LangAS::opencl_local || 5133 AS >= LangAS::FirstTargetAddressSpace); 5134 return AS; 5135 } 5136 5137 if (LangOpts.SYCLIsDevice && 5138 (!D || D->getType().getAddressSpace() == LangAS::Default)) 5139 return LangAS::sycl_global; 5140 5141 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 5142 if (D) { 5143 if (D->hasAttr<CUDAConstantAttr>()) 5144 return LangAS::cuda_constant; 5145 if (D->hasAttr<CUDASharedAttr>()) 5146 return LangAS::cuda_shared; 5147 if (D->hasAttr<CUDADeviceAttr>()) 5148 return LangAS::cuda_device; 5149 if (D->getType().isConstQualified()) 5150 return LangAS::cuda_constant; 5151 } 5152 return LangAS::cuda_device; 5153 } 5154 5155 if (LangOpts.OpenMP) { 5156 LangAS AS; 5157 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 5158 return AS; 5159 } 5160 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 5161 } 5162 5163 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 5164 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 5165 if (LangOpts.OpenCL) 5166 return LangAS::opencl_constant; 5167 if (LangOpts.SYCLIsDevice) 5168 return LangAS::sycl_global; 5169 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) 5170 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) 5171 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up 5172 // with OpVariable instructions with Generic storage class which is not 5173 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V 5174 // UniformConstant storage class is not viable as pointers to it may not be 5175 // casted to Generic pointers which are used to model HIP's "flat" pointers. 5176 return LangAS::cuda_device; 5177 if (auto AS = getTarget().getConstantAddressSpace()) 5178 return *AS; 5179 return LangAS::Default; 5180 } 5181 5182 // In address space agnostic languages, string literals are in default address 5183 // space in AST. However, certain targets (e.g. amdgcn) request them to be 5184 // emitted in constant address space in LLVM IR. To be consistent with other 5185 // parts of AST, string literal global variables in constant address space 5186 // need to be casted to default address space before being put into address 5187 // map and referenced by other part of CodeGen. 5188 // In OpenCL, string literals are in constant address space in AST, therefore 5189 // they should not be casted to default address space. 5190 static llvm::Constant * 5191 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 5192 llvm::GlobalVariable *GV) { 5193 llvm::Constant *Cast = GV; 5194 if (!CGM.getLangOpts().OpenCL) { 5195 auto AS = CGM.GetGlobalConstantAddressSpace(); 5196 if (AS != LangAS::Default) 5197 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 5198 CGM, GV, AS, LangAS::Default, 5199 llvm::PointerType::get( 5200 CGM.getLLVMContext(), 5201 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 5202 } 5203 return Cast; 5204 } 5205 5206 template<typename SomeDecl> 5207 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 5208 llvm::GlobalValue *GV) { 5209 if (!getLangOpts().CPlusPlus) 5210 return; 5211 5212 // Must have 'used' attribute, or else inline assembly can't rely on 5213 // the name existing. 5214 if (!D->template hasAttr<UsedAttr>()) 5215 return; 5216 5217 // Must have internal linkage and an ordinary name. 5218 if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal) 5219 return; 5220 5221 // Must be in an extern "C" context. Entities declared directly within 5222 // a record are not extern "C" even if the record is in such a context. 5223 const SomeDecl *First = D->getFirstDecl(); 5224 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 5225 return; 5226 5227 // OK, this is an internal linkage entity inside an extern "C" linkage 5228 // specification. Make a note of that so we can give it the "expected" 5229 // mangled name if nothing else is using that name. 5230 std::pair<StaticExternCMap::iterator, bool> R = 5231 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 5232 5233 // If we have multiple internal linkage entities with the same name 5234 // in extern "C" regions, none of them gets that name. 5235 if (!R.second) 5236 R.first->second = nullptr; 5237 } 5238 5239 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 5240 if (!CGM.supportsCOMDAT()) 5241 return false; 5242 5243 if (D.hasAttr<SelectAnyAttr>()) 5244 return true; 5245 5246 GVALinkage Linkage; 5247 if (auto *VD = dyn_cast<VarDecl>(&D)) 5248 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 5249 else 5250 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 5251 5252 switch (Linkage) { 5253 case GVA_Internal: 5254 case GVA_AvailableExternally: 5255 case GVA_StrongExternal: 5256 return false; 5257 case GVA_DiscardableODR: 5258 case GVA_StrongODR: 5259 return true; 5260 } 5261 llvm_unreachable("No such linkage"); 5262 } 5263 5264 bool CodeGenModule::supportsCOMDAT() const { 5265 return getTriple().supportsCOMDAT(); 5266 } 5267 5268 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 5269 llvm::GlobalObject &GO) { 5270 if (!shouldBeInCOMDAT(*this, D)) 5271 return; 5272 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 5273 } 5274 5275 /// Pass IsTentative as true if you want to create a tentative definition. 5276 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 5277 bool IsTentative) { 5278 // OpenCL global variables of sampler type are translated to function calls, 5279 // therefore no need to be translated. 5280 QualType ASTTy = D->getType(); 5281 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 5282 return; 5283 5284 // If this is OpenMP device, check if it is legal to emit this global 5285 // normally. 5286 if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime && 5287 OpenMPRuntime->emitTargetGlobalVariable(D)) 5288 return; 5289 5290 llvm::TrackingVH<llvm::Constant> Init; 5291 bool NeedsGlobalCtor = false; 5292 // Whether the definition of the variable is available externally. 5293 // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable 5294 // since this is the job for its original source. 5295 bool IsDefinitionAvailableExternally = 5296 getContext().GetGVALinkageForVariable(D) == GVA_AvailableExternally; 5297 bool NeedsGlobalDtor = 5298 !IsDefinitionAvailableExternally && 5299 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 5300 5301 const VarDecl *InitDecl; 5302 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 5303 5304 std::optional<ConstantEmitter> emitter; 5305 5306 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 5307 // as part of their declaration." Sema has already checked for 5308 // error cases, so we just need to set Init to UndefValue. 5309 bool IsCUDASharedVar = 5310 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 5311 // Shadows of initialized device-side global variables are also left 5312 // undefined. 5313 // Managed Variables should be initialized on both host side and device side. 5314 bool IsCUDAShadowVar = 5315 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 5316 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 5317 D->hasAttr<CUDASharedAttr>()); 5318 bool IsCUDADeviceShadowVar = 5319 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 5320 (D->getType()->isCUDADeviceBuiltinSurfaceType() || 5321 D->getType()->isCUDADeviceBuiltinTextureType()); 5322 if (getLangOpts().CUDA && 5323 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 5324 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 5325 else if (D->hasAttr<LoaderUninitializedAttr>()) 5326 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 5327 else if (!InitExpr) { 5328 // This is a tentative definition; tentative definitions are 5329 // implicitly initialized with { 0 }. 5330 // 5331 // Note that tentative definitions are only emitted at the end of 5332 // a translation unit, so they should never have incomplete 5333 // type. In addition, EmitTentativeDefinition makes sure that we 5334 // never attempt to emit a tentative definition if a real one 5335 // exists. A use may still exists, however, so we still may need 5336 // to do a RAUW. 5337 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 5338 Init = EmitNullConstant(D->getType()); 5339 } else { 5340 initializedGlobalDecl = GlobalDecl(D); 5341 emitter.emplace(*this); 5342 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 5343 if (!Initializer) { 5344 QualType T = InitExpr->getType(); 5345 if (D->getType()->isReferenceType()) 5346 T = D->getType(); 5347 5348 if (getLangOpts().CPlusPlus) { 5349 if (InitDecl->hasFlexibleArrayInit(getContext())) 5350 ErrorUnsupported(D, "flexible array initializer"); 5351 Init = EmitNullConstant(T); 5352 5353 if (!IsDefinitionAvailableExternally) 5354 NeedsGlobalCtor = true; 5355 } else { 5356 ErrorUnsupported(D, "static initializer"); 5357 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 5358 } 5359 } else { 5360 Init = Initializer; 5361 // We don't need an initializer, so remove the entry for the delayed 5362 // initializer position (just in case this entry was delayed) if we 5363 // also don't need to register a destructor. 5364 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 5365 DelayedCXXInitPosition.erase(D); 5366 5367 #ifndef NDEBUG 5368 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) + 5369 InitDecl->getFlexibleArrayInitChars(getContext()); 5370 CharUnits CstSize = CharUnits::fromQuantity( 5371 getDataLayout().getTypeAllocSize(Init->getType())); 5372 assert(VarSize == CstSize && "Emitted constant has unexpected size"); 5373 #endif 5374 } 5375 } 5376 5377 llvm::Type* InitType = Init->getType(); 5378 llvm::Constant *Entry = 5379 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 5380 5381 // Strip off pointer casts if we got them. 5382 Entry = Entry->stripPointerCasts(); 5383 5384 // Entry is now either a Function or GlobalVariable. 5385 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 5386 5387 // We have a definition after a declaration with the wrong type. 5388 // We must make a new GlobalVariable* and update everything that used OldGV 5389 // (a declaration or tentative definition) with the new GlobalVariable* 5390 // (which will be a definition). 5391 // 5392 // This happens if there is a prototype for a global (e.g. 5393 // "extern int x[];") and then a definition of a different type (e.g. 5394 // "int x[10];"). This also happens when an initializer has a different type 5395 // from the type of the global (this happens with unions). 5396 if (!GV || GV->getValueType() != InitType || 5397 GV->getType()->getAddressSpace() != 5398 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 5399 5400 // Move the old entry aside so that we'll create a new one. 5401 Entry->setName(StringRef()); 5402 5403 // Make a new global with the correct type, this is now guaranteed to work. 5404 GV = cast<llvm::GlobalVariable>( 5405 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 5406 ->stripPointerCasts()); 5407 5408 // Replace all uses of the old global with the new global 5409 llvm::Constant *NewPtrForOldDecl = 5410 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 5411 Entry->getType()); 5412 Entry->replaceAllUsesWith(NewPtrForOldDecl); 5413 5414 // Erase the old global, since it is no longer used. 5415 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 5416 } 5417 5418 MaybeHandleStaticInExternC(D, GV); 5419 5420 if (D->hasAttr<AnnotateAttr>()) 5421 AddGlobalAnnotations(D, GV); 5422 5423 // Set the llvm linkage type as appropriate. 5424 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(D); 5425 5426 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 5427 // the device. [...]" 5428 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 5429 // __device__, declares a variable that: [...] 5430 // Is accessible from all the threads within the grid and from the host 5431 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 5432 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 5433 if (LangOpts.CUDA) { 5434 if (LangOpts.CUDAIsDevice) { 5435 if (Linkage != llvm::GlobalValue::InternalLinkage && 5436 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 5437 D->getType()->isCUDADeviceBuiltinSurfaceType() || 5438 D->getType()->isCUDADeviceBuiltinTextureType())) 5439 GV->setExternallyInitialized(true); 5440 } else { 5441 getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 5442 } 5443 getCUDARuntime().handleVarRegistration(D, *GV); 5444 } 5445 5446 GV->setInitializer(Init); 5447 if (emitter) 5448 emitter->finalize(GV); 5449 5450 // If it is safe to mark the global 'constant', do so now. 5451 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 5452 D->getType().isConstantStorage(getContext(), true, true)); 5453 5454 // If it is in a read-only section, mark it 'constant'. 5455 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 5456 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 5457 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 5458 GV->setConstant(true); 5459 } 5460 5461 CharUnits AlignVal = getContext().getDeclAlign(D); 5462 // Check for alignment specifed in an 'omp allocate' directive. 5463 if (std::optional<CharUnits> AlignValFromAllocate = 5464 getOMPAllocateAlignment(D)) 5465 AlignVal = *AlignValFromAllocate; 5466 GV->setAlignment(AlignVal.getAsAlign()); 5467 5468 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 5469 // function is only defined alongside the variable, not also alongside 5470 // callers. Normally, all accesses to a thread_local go through the 5471 // thread-wrapper in order to ensure initialization has occurred, underlying 5472 // variable will never be used other than the thread-wrapper, so it can be 5473 // converted to internal linkage. 5474 // 5475 // However, if the variable has the 'constinit' attribute, it _can_ be 5476 // referenced directly, without calling the thread-wrapper, so the linkage 5477 // must not be changed. 5478 // 5479 // Additionally, if the variable isn't plain external linkage, e.g. if it's 5480 // weak or linkonce, the de-duplication semantics are important to preserve, 5481 // so we don't change the linkage. 5482 if (D->getTLSKind() == VarDecl::TLS_Dynamic && 5483 Linkage == llvm::GlobalValue::ExternalLinkage && 5484 Context.getTargetInfo().getTriple().isOSDarwin() && 5485 !D->hasAttr<ConstInitAttr>()) 5486 Linkage = llvm::GlobalValue::InternalLinkage; 5487 5488 GV->setLinkage(Linkage); 5489 if (D->hasAttr<DLLImportAttr>()) 5490 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 5491 else if (D->hasAttr<DLLExportAttr>()) 5492 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 5493 else 5494 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 5495 5496 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 5497 // common vars aren't constant even if declared const. 5498 GV->setConstant(false); 5499 // Tentative definition of global variables may be initialized with 5500 // non-zero null pointers. In this case they should have weak linkage 5501 // since common linkage must have zero initializer and must not have 5502 // explicit section therefore cannot have non-zero initial value. 5503 if (!GV->getInitializer()->isNullValue()) 5504 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 5505 } 5506 5507 setNonAliasAttributes(D, GV); 5508 5509 if (D->getTLSKind() && !GV->isThreadLocal()) { 5510 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 5511 CXXThreadLocals.push_back(D); 5512 setTLSMode(GV, *D); 5513 } 5514 5515 maybeSetTrivialComdat(*D, *GV); 5516 5517 // Emit the initializer function if necessary. 5518 if (NeedsGlobalCtor || NeedsGlobalDtor) 5519 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 5520 5521 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor); 5522 5523 // Emit global variable debug information. 5524 if (CGDebugInfo *DI = getModuleDebugInfo()) 5525 if (getCodeGenOpts().hasReducedDebugInfo()) 5526 DI->EmitGlobalVariable(GV, D); 5527 } 5528 5529 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 5530 if (CGDebugInfo *DI = getModuleDebugInfo()) 5531 if (getCodeGenOpts().hasReducedDebugInfo()) { 5532 QualType ASTTy = D->getType(); 5533 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 5534 llvm::Constant *GV = 5535 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 5536 DI->EmitExternalVariable( 5537 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 5538 } 5539 } 5540 5541 static bool isVarDeclStrongDefinition(const ASTContext &Context, 5542 CodeGenModule &CGM, const VarDecl *D, 5543 bool NoCommon) { 5544 // Don't give variables common linkage if -fno-common was specified unless it 5545 // was overridden by a NoCommon attribute. 5546 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 5547 return true; 5548 5549 // C11 6.9.2/2: 5550 // A declaration of an identifier for an object that has file scope without 5551 // an initializer, and without a storage-class specifier or with the 5552 // storage-class specifier static, constitutes a tentative definition. 5553 if (D->getInit() || D->hasExternalStorage()) 5554 return true; 5555 5556 // A variable cannot be both common and exist in a section. 5557 if (D->hasAttr<SectionAttr>()) 5558 return true; 5559 5560 // A variable cannot be both common and exist in a section. 5561 // We don't try to determine which is the right section in the front-end. 5562 // If no specialized section name is applicable, it will resort to default. 5563 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 5564 D->hasAttr<PragmaClangDataSectionAttr>() || 5565 D->hasAttr<PragmaClangRelroSectionAttr>() || 5566 D->hasAttr<PragmaClangRodataSectionAttr>()) 5567 return true; 5568 5569 // Thread local vars aren't considered common linkage. 5570 if (D->getTLSKind()) 5571 return true; 5572 5573 // Tentative definitions marked with WeakImportAttr are true definitions. 5574 if (D->hasAttr<WeakImportAttr>()) 5575 return true; 5576 5577 // A variable cannot be both common and exist in a comdat. 5578 if (shouldBeInCOMDAT(CGM, *D)) 5579 return true; 5580 5581 // Declarations with a required alignment do not have common linkage in MSVC 5582 // mode. 5583 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5584 if (D->hasAttr<AlignedAttr>()) 5585 return true; 5586 QualType VarType = D->getType(); 5587 if (Context.isAlignmentRequired(VarType)) 5588 return true; 5589 5590 if (const auto *RT = VarType->getAs<RecordType>()) { 5591 const RecordDecl *RD = RT->getDecl(); 5592 for (const FieldDecl *FD : RD->fields()) { 5593 if (FD->isBitField()) 5594 continue; 5595 if (FD->hasAttr<AlignedAttr>()) 5596 return true; 5597 if (Context.isAlignmentRequired(FD->getType())) 5598 return true; 5599 } 5600 } 5601 } 5602 5603 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 5604 // common symbols, so symbols with greater alignment requirements cannot be 5605 // common. 5606 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 5607 // alignments for common symbols via the aligncomm directive, so this 5608 // restriction only applies to MSVC environments. 5609 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 5610 Context.getTypeAlignIfKnown(D->getType()) > 5611 Context.toBits(CharUnits::fromQuantity(32))) 5612 return true; 5613 5614 return false; 5615 } 5616 5617 llvm::GlobalValue::LinkageTypes 5618 CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D, 5619 GVALinkage Linkage) { 5620 if (Linkage == GVA_Internal) 5621 return llvm::Function::InternalLinkage; 5622 5623 if (D->hasAttr<WeakAttr>()) 5624 return llvm::GlobalVariable::WeakAnyLinkage; 5625 5626 if (const auto *FD = D->getAsFunction()) 5627 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 5628 return llvm::GlobalVariable::LinkOnceAnyLinkage; 5629 5630 // We are guaranteed to have a strong definition somewhere else, 5631 // so we can use available_externally linkage. 5632 if (Linkage == GVA_AvailableExternally) 5633 return llvm::GlobalValue::AvailableExternallyLinkage; 5634 5635 // Note that Apple's kernel linker doesn't support symbol 5636 // coalescing, so we need to avoid linkonce and weak linkages there. 5637 // Normally, this means we just map to internal, but for explicit 5638 // instantiations we'll map to external. 5639 5640 // In C++, the compiler has to emit a definition in every translation unit 5641 // that references the function. We should use linkonce_odr because 5642 // a) if all references in this translation unit are optimized away, we 5643 // don't need to codegen it. b) if the function persists, it needs to be 5644 // merged with other definitions. c) C++ has the ODR, so we know the 5645 // definition is dependable. 5646 if (Linkage == GVA_DiscardableODR) 5647 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 5648 : llvm::Function::InternalLinkage; 5649 5650 // An explicit instantiation of a template has weak linkage, since 5651 // explicit instantiations can occur in multiple translation units 5652 // and must all be equivalent. However, we are not allowed to 5653 // throw away these explicit instantiations. 5654 // 5655 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 5656 // so say that CUDA templates are either external (for kernels) or internal. 5657 // This lets llvm perform aggressive inter-procedural optimizations. For 5658 // -fgpu-rdc case, device function calls across multiple TU's are allowed, 5659 // therefore we need to follow the normal linkage paradigm. 5660 if (Linkage == GVA_StrongODR) { 5661 if (getLangOpts().AppleKext) 5662 return llvm::Function::ExternalLinkage; 5663 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 5664 !getLangOpts().GPURelocatableDeviceCode) 5665 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 5666 : llvm::Function::InternalLinkage; 5667 return llvm::Function::WeakODRLinkage; 5668 } 5669 5670 // C++ doesn't have tentative definitions and thus cannot have common 5671 // linkage. 5672 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 5673 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 5674 CodeGenOpts.NoCommon)) 5675 return llvm::GlobalVariable::CommonLinkage; 5676 5677 // selectany symbols are externally visible, so use weak instead of 5678 // linkonce. MSVC optimizes away references to const selectany globals, so 5679 // all definitions should be the same and ODR linkage should be used. 5680 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 5681 if (D->hasAttr<SelectAnyAttr>()) 5682 return llvm::GlobalVariable::WeakODRLinkage; 5683 5684 // Otherwise, we have strong external linkage. 5685 assert(Linkage == GVA_StrongExternal); 5686 return llvm::GlobalVariable::ExternalLinkage; 5687 } 5688 5689 llvm::GlobalValue::LinkageTypes 5690 CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) { 5691 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 5692 return getLLVMLinkageForDeclarator(VD, Linkage); 5693 } 5694 5695 /// Replace the uses of a function that was declared with a non-proto type. 5696 /// We want to silently drop extra arguments from call sites 5697 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 5698 llvm::Function *newFn) { 5699 // Fast path. 5700 if (old->use_empty()) return; 5701 5702 llvm::Type *newRetTy = newFn->getReturnType(); 5703 SmallVector<llvm::Value*, 4> newArgs; 5704 5705 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 5706 ui != ue; ) { 5707 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 5708 llvm::User *user = use->getUser(); 5709 5710 // Recognize and replace uses of bitcasts. Most calls to 5711 // unprototyped functions will use bitcasts. 5712 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 5713 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 5714 replaceUsesOfNonProtoConstant(bitcast, newFn); 5715 continue; 5716 } 5717 5718 // Recognize calls to the function. 5719 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 5720 if (!callSite) continue; 5721 if (!callSite->isCallee(&*use)) 5722 continue; 5723 5724 // If the return types don't match exactly, then we can't 5725 // transform this call unless it's dead. 5726 if (callSite->getType() != newRetTy && !callSite->use_empty()) 5727 continue; 5728 5729 // Get the call site's attribute list. 5730 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 5731 llvm::AttributeList oldAttrs = callSite->getAttributes(); 5732 5733 // If the function was passed too few arguments, don't transform. 5734 unsigned newNumArgs = newFn->arg_size(); 5735 if (callSite->arg_size() < newNumArgs) 5736 continue; 5737 5738 // If extra arguments were passed, we silently drop them. 5739 // If any of the types mismatch, we don't transform. 5740 unsigned argNo = 0; 5741 bool dontTransform = false; 5742 for (llvm::Argument &A : newFn->args()) { 5743 if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 5744 dontTransform = true; 5745 break; 5746 } 5747 5748 // Add any parameter attributes. 5749 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 5750 argNo++; 5751 } 5752 if (dontTransform) 5753 continue; 5754 5755 // Okay, we can transform this. Create the new call instruction and copy 5756 // over the required information. 5757 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 5758 5759 // Copy over any operand bundles. 5760 SmallVector<llvm::OperandBundleDef, 1> newBundles; 5761 callSite->getOperandBundlesAsDefs(newBundles); 5762 5763 llvm::CallBase *newCall; 5764 if (isa<llvm::CallInst>(callSite)) { 5765 newCall = 5766 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 5767 } else { 5768 auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 5769 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 5770 oldInvoke->getUnwindDest(), newArgs, 5771 newBundles, "", callSite); 5772 } 5773 newArgs.clear(); // for the next iteration 5774 5775 if (!newCall->getType()->isVoidTy()) 5776 newCall->takeName(callSite); 5777 newCall->setAttributes( 5778 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 5779 oldAttrs.getRetAttrs(), newArgAttrs)); 5780 newCall->setCallingConv(callSite->getCallingConv()); 5781 5782 // Finally, remove the old call, replacing any uses with the new one. 5783 if (!callSite->use_empty()) 5784 callSite->replaceAllUsesWith(newCall); 5785 5786 // Copy debug location attached to CI. 5787 if (callSite->getDebugLoc()) 5788 newCall->setDebugLoc(callSite->getDebugLoc()); 5789 5790 callSite->eraseFromParent(); 5791 } 5792 } 5793 5794 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 5795 /// implement a function with no prototype, e.g. "int foo() {}". If there are 5796 /// existing call uses of the old function in the module, this adjusts them to 5797 /// call the new function directly. 5798 /// 5799 /// This is not just a cleanup: the always_inline pass requires direct calls to 5800 /// functions to be able to inline them. If there is a bitcast in the way, it 5801 /// won't inline them. Instcombine normally deletes these calls, but it isn't 5802 /// run at -O0. 5803 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 5804 llvm::Function *NewFn) { 5805 // If we're redefining a global as a function, don't transform it. 5806 if (!isa<llvm::Function>(Old)) return; 5807 5808 replaceUsesOfNonProtoConstant(Old, NewFn); 5809 } 5810 5811 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 5812 auto DK = VD->isThisDeclarationADefinition(); 5813 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 5814 return; 5815 5816 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 5817 // If we have a definition, this might be a deferred decl. If the 5818 // instantiation is explicit, make sure we emit it at the end. 5819 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 5820 GetAddrOfGlobalVar(VD); 5821 5822 EmitTopLevelDecl(VD); 5823 } 5824 5825 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 5826 llvm::GlobalValue *GV) { 5827 const auto *D = cast<FunctionDecl>(GD.getDecl()); 5828 5829 // Compute the function info and LLVM type. 5830 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 5831 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 5832 5833 // Get or create the prototype for the function. 5834 if (!GV || (GV->getValueType() != Ty)) 5835 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 5836 /*DontDefer=*/true, 5837 ForDefinition)); 5838 5839 // Already emitted. 5840 if (!GV->isDeclaration()) 5841 return; 5842 5843 // We need to set linkage and visibility on the function before 5844 // generating code for it because various parts of IR generation 5845 // want to propagate this information down (e.g. to local static 5846 // declarations). 5847 auto *Fn = cast<llvm::Function>(GV); 5848 setFunctionLinkage(GD, Fn); 5849 5850 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 5851 setGVProperties(Fn, GD); 5852 5853 MaybeHandleStaticInExternC(D, Fn); 5854 5855 maybeSetTrivialComdat(*D, *Fn); 5856 5857 CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 5858 5859 setNonAliasAttributes(GD, Fn); 5860 SetLLVMFunctionAttributesForDefinition(D, Fn); 5861 5862 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 5863 AddGlobalCtor(Fn, CA->getPriority()); 5864 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5865 AddGlobalDtor(Fn, DA->getPriority(), true); 5866 if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>()) 5867 getOpenMPRuntime().emitDeclareTargetFunction(D, GV); 5868 } 5869 5870 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 5871 const auto *D = cast<ValueDecl>(GD.getDecl()); 5872 const AliasAttr *AA = D->getAttr<AliasAttr>(); 5873 assert(AA && "Not an alias?"); 5874 5875 StringRef MangledName = getMangledName(GD); 5876 5877 if (AA->getAliasee() == MangledName) { 5878 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5879 return; 5880 } 5881 5882 // If there is a definition in the module, then it wins over the alias. 5883 // This is dubious, but allow it to be safe. Just ignore the alias. 5884 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5885 if (Entry && !Entry->isDeclaration()) 5886 return; 5887 5888 Aliases.push_back(GD); 5889 5890 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5891 5892 // Create a reference to the named value. This ensures that it is emitted 5893 // if a deferred decl. 5894 llvm::Constant *Aliasee; 5895 llvm::GlobalValue::LinkageTypes LT; 5896 if (isa<llvm::FunctionType>(DeclTy)) { 5897 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 5898 /*ForVTable=*/false); 5899 LT = getFunctionLinkage(GD); 5900 } else { 5901 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 5902 /*D=*/nullptr); 5903 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5904 LT = getLLVMLinkageVarDefinition(VD); 5905 else 5906 LT = getFunctionLinkage(GD); 5907 } 5908 5909 // Create the new alias itself, but don't set a name yet. 5910 unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 5911 auto *GA = 5912 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 5913 5914 if (Entry) { 5915 if (GA->getAliasee() == Entry) { 5916 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5917 return; 5918 } 5919 5920 assert(Entry->isDeclaration()); 5921 5922 // If there is a declaration in the module, then we had an extern followed 5923 // by the alias, as in: 5924 // extern int test6(); 5925 // ... 5926 // int test6() __attribute__((alias("test7"))); 5927 // 5928 // Remove it and replace uses of it with the alias. 5929 GA->takeName(Entry); 5930 5931 Entry->replaceAllUsesWith(GA); 5932 Entry->eraseFromParent(); 5933 } else { 5934 GA->setName(MangledName); 5935 } 5936 5937 // Set attributes which are particular to an alias; this is a 5938 // specialization of the attributes which may be set on a global 5939 // variable/function. 5940 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 5941 D->isWeakImported()) { 5942 GA->setLinkage(llvm::Function::WeakAnyLinkage); 5943 } 5944 5945 if (const auto *VD = dyn_cast<VarDecl>(D)) 5946 if (VD->getTLSKind()) 5947 setTLSMode(GA, *VD); 5948 5949 SetCommonAttributes(GD, GA); 5950 5951 // Emit global alias debug information. 5952 if (isa<VarDecl>(D)) 5953 if (CGDebugInfo *DI = getModuleDebugInfo()) 5954 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD); 5955 } 5956 5957 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 5958 const auto *D = cast<ValueDecl>(GD.getDecl()); 5959 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 5960 assert(IFA && "Not an ifunc?"); 5961 5962 StringRef MangledName = getMangledName(GD); 5963 5964 if (IFA->getResolver() == MangledName) { 5965 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5966 return; 5967 } 5968 5969 // Report an error if some definition overrides ifunc. 5970 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5971 if (Entry && !Entry->isDeclaration()) { 5972 GlobalDecl OtherGD; 5973 if (lookupRepresentativeDecl(MangledName, OtherGD) && 5974 DiagnosedConflictingDefinitions.insert(GD).second) { 5975 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 5976 << MangledName; 5977 Diags.Report(OtherGD.getDecl()->getLocation(), 5978 diag::note_previous_definition); 5979 } 5980 return; 5981 } 5982 5983 Aliases.push_back(GD); 5984 5985 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5986 llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 5987 llvm::Constant *Resolver = 5988 GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 5989 /*ForVTable=*/false); 5990 llvm::GlobalIFunc *GIF = 5991 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 5992 "", Resolver, &getModule()); 5993 if (Entry) { 5994 if (GIF->getResolver() == Entry) { 5995 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5996 return; 5997 } 5998 assert(Entry->isDeclaration()); 5999 6000 // If there is a declaration in the module, then we had an extern followed 6001 // by the ifunc, as in: 6002 // extern int test(); 6003 // ... 6004 // int test() __attribute__((ifunc("resolver"))); 6005 // 6006 // Remove it and replace uses of it with the ifunc. 6007 GIF->takeName(Entry); 6008 6009 Entry->replaceAllUsesWith(GIF); 6010 Entry->eraseFromParent(); 6011 } else 6012 GIF->setName(MangledName); 6013 if (auto *F = dyn_cast<llvm::Function>(Resolver)) { 6014 F->addFnAttr(llvm::Attribute::DisableSanitizerInstrumentation); 6015 } 6016 SetCommonAttributes(GD, GIF); 6017 } 6018 6019 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 6020 ArrayRef<llvm::Type*> Tys) { 6021 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 6022 Tys); 6023 } 6024 6025 static llvm::StringMapEntry<llvm::GlobalVariable *> & 6026 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 6027 const StringLiteral *Literal, bool TargetIsLSB, 6028 bool &IsUTF16, unsigned &StringLength) { 6029 StringRef String = Literal->getString(); 6030 unsigned NumBytes = String.size(); 6031 6032 // Check for simple case. 6033 if (!Literal->containsNonAsciiOrNull()) { 6034 StringLength = NumBytes; 6035 return *Map.insert(std::make_pair(String, nullptr)).first; 6036 } 6037 6038 // Otherwise, convert the UTF8 literals into a string of shorts. 6039 IsUTF16 = true; 6040 6041 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 6042 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6043 llvm::UTF16 *ToPtr = &ToBuf[0]; 6044 6045 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6046 ToPtr + NumBytes, llvm::strictConversion); 6047 6048 // ConvertUTF8toUTF16 returns the length in ToPtr. 6049 StringLength = ToPtr - &ToBuf[0]; 6050 6051 // Add an explicit null. 6052 *ToPtr = 0; 6053 return *Map.insert(std::make_pair( 6054 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 6055 (StringLength + 1) * 2), 6056 nullptr)).first; 6057 } 6058 6059 ConstantAddress 6060 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 6061 unsigned StringLength = 0; 6062 bool isUTF16 = false; 6063 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 6064 GetConstantCFStringEntry(CFConstantStringMap, Literal, 6065 getDataLayout().isLittleEndian(), isUTF16, 6066 StringLength); 6067 6068 if (auto *C = Entry.second) 6069 return ConstantAddress( 6070 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 6071 6072 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 6073 llvm::Constant *Zeros[] = { Zero, Zero }; 6074 6075 const ASTContext &Context = getContext(); 6076 const llvm::Triple &Triple = getTriple(); 6077 6078 const auto CFRuntime = getLangOpts().CFRuntime; 6079 const bool IsSwiftABI = 6080 static_cast<unsigned>(CFRuntime) >= 6081 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 6082 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 6083 6084 // If we don't already have it, get __CFConstantStringClassReference. 6085 if (!CFConstantStringClassRef) { 6086 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 6087 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 6088 Ty = llvm::ArrayType::get(Ty, 0); 6089 6090 switch (CFRuntime) { 6091 default: break; 6092 case LangOptions::CoreFoundationABI::Swift: [[fallthrough]]; 6093 case LangOptions::CoreFoundationABI::Swift5_0: 6094 CFConstantStringClassName = 6095 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 6096 : "$s10Foundation19_NSCFConstantStringCN"; 6097 Ty = IntPtrTy; 6098 break; 6099 case LangOptions::CoreFoundationABI::Swift4_2: 6100 CFConstantStringClassName = 6101 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 6102 : "$S10Foundation19_NSCFConstantStringCN"; 6103 Ty = IntPtrTy; 6104 break; 6105 case LangOptions::CoreFoundationABI::Swift4_1: 6106 CFConstantStringClassName = 6107 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 6108 : "__T010Foundation19_NSCFConstantStringCN"; 6109 Ty = IntPtrTy; 6110 break; 6111 } 6112 6113 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 6114 6115 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 6116 llvm::GlobalValue *GV = nullptr; 6117 6118 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 6119 IdentifierInfo &II = Context.Idents.get(GV->getName()); 6120 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 6121 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 6122 6123 const VarDecl *VD = nullptr; 6124 for (const auto *Result : DC->lookup(&II)) 6125 if ((VD = dyn_cast<VarDecl>(Result))) 6126 break; 6127 6128 if (Triple.isOSBinFormatELF()) { 6129 if (!VD) 6130 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 6131 } else { 6132 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 6133 if (!VD || !VD->hasAttr<DLLExportAttr>()) 6134 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 6135 else 6136 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 6137 } 6138 6139 setDSOLocal(GV); 6140 } 6141 } 6142 6143 // Decay array -> ptr 6144 CFConstantStringClassRef = 6145 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 6146 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 6147 } 6148 6149 QualType CFTy = Context.getCFConstantStringType(); 6150 6151 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 6152 6153 ConstantInitBuilder Builder(*this); 6154 auto Fields = Builder.beginStruct(STy); 6155 6156 // Class pointer. 6157 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef)); 6158 6159 // Flags. 6160 if (IsSwiftABI) { 6161 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 6162 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 6163 } else { 6164 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 6165 } 6166 6167 // String pointer. 6168 llvm::Constant *C = nullptr; 6169 if (isUTF16) { 6170 auto Arr = llvm::ArrayRef( 6171 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 6172 Entry.first().size() / 2); 6173 C = llvm::ConstantDataArray::get(VMContext, Arr); 6174 } else { 6175 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 6176 } 6177 6178 // Note: -fwritable-strings doesn't make the backing store strings of 6179 // CFStrings writable. 6180 auto *GV = 6181 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 6182 llvm::GlobalValue::PrivateLinkage, C, ".str"); 6183 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 6184 // Don't enforce the target's minimum global alignment, since the only use 6185 // of the string is via this class initializer. 6186 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 6187 : Context.getTypeAlignInChars(Context.CharTy); 6188 GV->setAlignment(Align.getAsAlign()); 6189 6190 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 6191 // Without it LLVM can merge the string with a non unnamed_addr one during 6192 // LTO. Doing that changes the section it ends in, which surprises ld64. 6193 if (Triple.isOSBinFormatMachO()) 6194 GV->setSection(isUTF16 ? "__TEXT,__ustring" 6195 : "__TEXT,__cstring,cstring_literals"); 6196 // Make sure the literal ends up in .rodata to allow for safe ICF and for 6197 // the static linker to adjust permissions to read-only later on. 6198 else if (Triple.isOSBinFormatELF()) 6199 GV->setSection(".rodata"); 6200 6201 // String. 6202 llvm::Constant *Str = 6203 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 6204 6205 Fields.add(Str); 6206 6207 // String length. 6208 llvm::IntegerType *LengthTy = 6209 llvm::IntegerType::get(getModule().getContext(), 6210 Context.getTargetInfo().getLongWidth()); 6211 if (IsSwiftABI) { 6212 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 6213 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 6214 LengthTy = Int32Ty; 6215 else 6216 LengthTy = IntPtrTy; 6217 } 6218 Fields.addInt(LengthTy, StringLength); 6219 6220 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 6221 // properly aligned on 32-bit platforms. 6222 CharUnits Alignment = 6223 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 6224 6225 // The struct. 6226 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 6227 /*isConstant=*/false, 6228 llvm::GlobalVariable::PrivateLinkage); 6229 GV->addAttribute("objc_arc_inert"); 6230 switch (Triple.getObjectFormat()) { 6231 case llvm::Triple::UnknownObjectFormat: 6232 llvm_unreachable("unknown file format"); 6233 case llvm::Triple::DXContainer: 6234 case llvm::Triple::GOFF: 6235 case llvm::Triple::SPIRV: 6236 case llvm::Triple::XCOFF: 6237 llvm_unreachable("unimplemented"); 6238 case llvm::Triple::COFF: 6239 case llvm::Triple::ELF: 6240 case llvm::Triple::Wasm: 6241 GV->setSection("cfstring"); 6242 break; 6243 case llvm::Triple::MachO: 6244 GV->setSection("__DATA,__cfstring"); 6245 break; 6246 } 6247 Entry.second = GV; 6248 6249 return ConstantAddress(GV, GV->getValueType(), Alignment); 6250 } 6251 6252 bool CodeGenModule::getExpressionLocationsEnabled() const { 6253 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 6254 } 6255 6256 QualType CodeGenModule::getObjCFastEnumerationStateType() { 6257 if (ObjCFastEnumerationStateType.isNull()) { 6258 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 6259 D->startDefinition(); 6260 6261 QualType FieldTypes[] = { 6262 Context.UnsignedLongTy, Context.getPointerType(Context.getObjCIdType()), 6263 Context.getPointerType(Context.UnsignedLongTy), 6264 Context.getConstantArrayType(Context.UnsignedLongTy, llvm::APInt(32, 5), 6265 nullptr, ArraySizeModifier::Normal, 0)}; 6266 6267 for (size_t i = 0; i < 4; ++i) { 6268 FieldDecl *Field = FieldDecl::Create(Context, 6269 D, 6270 SourceLocation(), 6271 SourceLocation(), nullptr, 6272 FieldTypes[i], /*TInfo=*/nullptr, 6273 /*BitWidth=*/nullptr, 6274 /*Mutable=*/false, 6275 ICIS_NoInit); 6276 Field->setAccess(AS_public); 6277 D->addDecl(Field); 6278 } 6279 6280 D->completeDefinition(); 6281 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 6282 } 6283 6284 return ObjCFastEnumerationStateType; 6285 } 6286 6287 llvm::Constant * 6288 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 6289 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 6290 6291 // Don't emit it as the address of the string, emit the string data itself 6292 // as an inline array. 6293 if (E->getCharByteWidth() == 1) { 6294 SmallString<64> Str(E->getString()); 6295 6296 // Resize the string to the right size, which is indicated by its type. 6297 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 6298 assert(CAT && "String literal not of constant array type!"); 6299 Str.resize(CAT->getSize().getZExtValue()); 6300 return llvm::ConstantDataArray::getString(VMContext, Str, false); 6301 } 6302 6303 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 6304 llvm::Type *ElemTy = AType->getElementType(); 6305 unsigned NumElements = AType->getNumElements(); 6306 6307 // Wide strings have either 2-byte or 4-byte elements. 6308 if (ElemTy->getPrimitiveSizeInBits() == 16) { 6309 SmallVector<uint16_t, 32> Elements; 6310 Elements.reserve(NumElements); 6311 6312 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 6313 Elements.push_back(E->getCodeUnit(i)); 6314 Elements.resize(NumElements); 6315 return llvm::ConstantDataArray::get(VMContext, Elements); 6316 } 6317 6318 assert(ElemTy->getPrimitiveSizeInBits() == 32); 6319 SmallVector<uint32_t, 32> Elements; 6320 Elements.reserve(NumElements); 6321 6322 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 6323 Elements.push_back(E->getCodeUnit(i)); 6324 Elements.resize(NumElements); 6325 return llvm::ConstantDataArray::get(VMContext, Elements); 6326 } 6327 6328 static llvm::GlobalVariable * 6329 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 6330 CodeGenModule &CGM, StringRef GlobalName, 6331 CharUnits Alignment) { 6332 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 6333 CGM.GetGlobalConstantAddressSpace()); 6334 6335 llvm::Module &M = CGM.getModule(); 6336 // Create a global variable for this string 6337 auto *GV = new llvm::GlobalVariable( 6338 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 6339 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 6340 GV->setAlignment(Alignment.getAsAlign()); 6341 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 6342 if (GV->isWeakForLinker()) { 6343 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 6344 GV->setComdat(M.getOrInsertComdat(GV->getName())); 6345 } 6346 CGM.setDSOLocal(GV); 6347 6348 return GV; 6349 } 6350 6351 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 6352 /// constant array for the given string literal. 6353 ConstantAddress 6354 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 6355 StringRef Name) { 6356 CharUnits Alignment = 6357 getContext().getAlignOfGlobalVarInChars(S->getType(), /*VD=*/nullptr); 6358 6359 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 6360 llvm::GlobalVariable **Entry = nullptr; 6361 if (!LangOpts.WritableStrings) { 6362 Entry = &ConstantStringMap[C]; 6363 if (auto GV = *Entry) { 6364 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 6365 GV->setAlignment(Alignment.getAsAlign()); 6366 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 6367 GV->getValueType(), Alignment); 6368 } 6369 } 6370 6371 SmallString<256> MangledNameBuffer; 6372 StringRef GlobalVariableName; 6373 llvm::GlobalValue::LinkageTypes LT; 6374 6375 // Mangle the string literal if that's how the ABI merges duplicate strings. 6376 // Don't do it if they are writable, since we don't want writes in one TU to 6377 // affect strings in another. 6378 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 6379 !LangOpts.WritableStrings) { 6380 llvm::raw_svector_ostream Out(MangledNameBuffer); 6381 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 6382 LT = llvm::GlobalValue::LinkOnceODRLinkage; 6383 GlobalVariableName = MangledNameBuffer; 6384 } else { 6385 LT = llvm::GlobalValue::PrivateLinkage; 6386 GlobalVariableName = Name; 6387 } 6388 6389 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 6390 6391 CGDebugInfo *DI = getModuleDebugInfo(); 6392 if (DI && getCodeGenOpts().hasReducedDebugInfo()) 6393 DI->AddStringLiteralDebugInfo(GV, S); 6394 6395 if (Entry) 6396 *Entry = GV; 6397 6398 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>"); 6399 6400 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 6401 GV->getValueType(), Alignment); 6402 } 6403 6404 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 6405 /// array for the given ObjCEncodeExpr node. 6406 ConstantAddress 6407 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 6408 std::string Str; 6409 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 6410 6411 return GetAddrOfConstantCString(Str); 6412 } 6413 6414 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 6415 /// the literal and a terminating '\0' character. 6416 /// The result has pointer to array type. 6417 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 6418 const std::string &Str, const char *GlobalName) { 6419 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 6420 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars( 6421 getContext().CharTy, /*VD=*/nullptr); 6422 6423 llvm::Constant *C = 6424 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 6425 6426 // Don't share any string literals if strings aren't constant. 6427 llvm::GlobalVariable **Entry = nullptr; 6428 if (!LangOpts.WritableStrings) { 6429 Entry = &ConstantStringMap[C]; 6430 if (auto GV = *Entry) { 6431 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 6432 GV->setAlignment(Alignment.getAsAlign()); 6433 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 6434 GV->getValueType(), Alignment); 6435 } 6436 } 6437 6438 // Get the default prefix if a name wasn't specified. 6439 if (!GlobalName) 6440 GlobalName = ".str"; 6441 // Create a global variable for this. 6442 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 6443 GlobalName, Alignment); 6444 if (Entry) 6445 *Entry = GV; 6446 6447 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 6448 GV->getValueType(), Alignment); 6449 } 6450 6451 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 6452 const MaterializeTemporaryExpr *E, const Expr *Init) { 6453 assert((E->getStorageDuration() == SD_Static || 6454 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 6455 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 6456 6457 // If we're not materializing a subobject of the temporary, keep the 6458 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 6459 QualType MaterializedType = Init->getType(); 6460 if (Init == E->getSubExpr()) 6461 MaterializedType = E->getType(); 6462 6463 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 6464 6465 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 6466 if (!InsertResult.second) { 6467 // We've seen this before: either we already created it or we're in the 6468 // process of doing so. 6469 if (!InsertResult.first->second) { 6470 // We recursively re-entered this function, probably during emission of 6471 // the initializer. Create a placeholder. We'll clean this up in the 6472 // outer call, at the end of this function. 6473 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 6474 InsertResult.first->second = new llvm::GlobalVariable( 6475 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 6476 nullptr); 6477 } 6478 return ConstantAddress(InsertResult.first->second, 6479 llvm::cast<llvm::GlobalVariable>( 6480 InsertResult.first->second->stripPointerCasts()) 6481 ->getValueType(), 6482 Align); 6483 } 6484 6485 // FIXME: If an externally-visible declaration extends multiple temporaries, 6486 // we need to give each temporary the same name in every translation unit (and 6487 // we also need to make the temporaries externally-visible). 6488 SmallString<256> Name; 6489 llvm::raw_svector_ostream Out(Name); 6490 getCXXABI().getMangleContext().mangleReferenceTemporary( 6491 VD, E->getManglingNumber(), Out); 6492 6493 APValue *Value = nullptr; 6494 if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) { 6495 // If the initializer of the extending declaration is a constant 6496 // initializer, we should have a cached constant initializer for this 6497 // temporary. Note that this might have a different value from the value 6498 // computed by evaluating the initializer if the surrounding constant 6499 // expression modifies the temporary. 6500 Value = E->getOrCreateValue(false); 6501 } 6502 6503 // Try evaluating it now, it might have a constant initializer. 6504 Expr::EvalResult EvalResult; 6505 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 6506 !EvalResult.hasSideEffects()) 6507 Value = &EvalResult.Val; 6508 6509 LangAS AddrSpace = GetGlobalVarAddressSpace(VD); 6510 6511 std::optional<ConstantEmitter> emitter; 6512 llvm::Constant *InitialValue = nullptr; 6513 bool Constant = false; 6514 llvm::Type *Type; 6515 if (Value) { 6516 // The temporary has a constant initializer, use it. 6517 emitter.emplace(*this); 6518 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 6519 MaterializedType); 6520 Constant = 6521 MaterializedType.isConstantStorage(getContext(), /*ExcludeCtor*/ Value, 6522 /*ExcludeDtor*/ false); 6523 Type = InitialValue->getType(); 6524 } else { 6525 // No initializer, the initialization will be provided when we 6526 // initialize the declaration which performed lifetime extension. 6527 Type = getTypes().ConvertTypeForMem(MaterializedType); 6528 } 6529 6530 // Create a global variable for this lifetime-extended temporary. 6531 llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD); 6532 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 6533 const VarDecl *InitVD; 6534 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 6535 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 6536 // Temporaries defined inside a class get linkonce_odr linkage because the 6537 // class can be defined in multiple translation units. 6538 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 6539 } else { 6540 // There is no need for this temporary to have external linkage if the 6541 // VarDecl has external linkage. 6542 Linkage = llvm::GlobalVariable::InternalLinkage; 6543 } 6544 } 6545 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 6546 auto *GV = new llvm::GlobalVariable( 6547 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 6548 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 6549 if (emitter) emitter->finalize(GV); 6550 // Don't assign dllimport or dllexport to local linkage globals. 6551 if (!llvm::GlobalValue::isLocalLinkage(Linkage)) { 6552 setGVProperties(GV, VD); 6553 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) 6554 // The reference temporary should never be dllexport. 6555 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 6556 } 6557 GV->setAlignment(Align.getAsAlign()); 6558 if (supportsCOMDAT() && GV->isWeakForLinker()) 6559 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 6560 if (VD->getTLSKind()) 6561 setTLSMode(GV, *VD); 6562 llvm::Constant *CV = GV; 6563 if (AddrSpace != LangAS::Default) 6564 CV = getTargetCodeGenInfo().performAddrSpaceCast( 6565 *this, GV, AddrSpace, LangAS::Default, 6566 llvm::PointerType::get( 6567 getLLVMContext(), 6568 getContext().getTargetAddressSpace(LangAS::Default))); 6569 6570 // Update the map with the new temporary. If we created a placeholder above, 6571 // replace it with the new global now. 6572 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 6573 if (Entry) { 6574 Entry->replaceAllUsesWith(CV); 6575 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 6576 } 6577 Entry = CV; 6578 6579 return ConstantAddress(CV, Type, Align); 6580 } 6581 6582 /// EmitObjCPropertyImplementations - Emit information for synthesized 6583 /// properties for an implementation. 6584 void CodeGenModule::EmitObjCPropertyImplementations(const 6585 ObjCImplementationDecl *D) { 6586 for (const auto *PID : D->property_impls()) { 6587 // Dynamic is just for type-checking. 6588 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 6589 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 6590 6591 // Determine which methods need to be implemented, some may have 6592 // been overridden. Note that ::isPropertyAccessor is not the method 6593 // we want, that just indicates if the decl came from a 6594 // property. What we want to know is if the method is defined in 6595 // this implementation. 6596 auto *Getter = PID->getGetterMethodDecl(); 6597 if (!Getter || Getter->isSynthesizedAccessorStub()) 6598 CodeGenFunction(*this).GenerateObjCGetter( 6599 const_cast<ObjCImplementationDecl *>(D), PID); 6600 auto *Setter = PID->getSetterMethodDecl(); 6601 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 6602 CodeGenFunction(*this).GenerateObjCSetter( 6603 const_cast<ObjCImplementationDecl *>(D), PID); 6604 } 6605 } 6606 } 6607 6608 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 6609 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 6610 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 6611 ivar; ivar = ivar->getNextIvar()) 6612 if (ivar->getType().isDestructedType()) 6613 return true; 6614 6615 return false; 6616 } 6617 6618 static bool AllTrivialInitializers(CodeGenModule &CGM, 6619 ObjCImplementationDecl *D) { 6620 CodeGenFunction CGF(CGM); 6621 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 6622 E = D->init_end(); B != E; ++B) { 6623 CXXCtorInitializer *CtorInitExp = *B; 6624 Expr *Init = CtorInitExp->getInit(); 6625 if (!CGF.isTrivialInitializer(Init)) 6626 return false; 6627 } 6628 return true; 6629 } 6630 6631 /// EmitObjCIvarInitializations - Emit information for ivar initialization 6632 /// for an implementation. 6633 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 6634 // We might need a .cxx_destruct even if we don't have any ivar initializers. 6635 if (needsDestructMethod(D)) { 6636 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 6637 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6638 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 6639 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6640 getContext().VoidTy, nullptr, D, 6641 /*isInstance=*/true, /*isVariadic=*/false, 6642 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6643 /*isImplicitlyDeclared=*/true, 6644 /*isDefined=*/false, ObjCImplementationControl::Required); 6645 D->addInstanceMethod(DTORMethod); 6646 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 6647 D->setHasDestructors(true); 6648 } 6649 6650 // If the implementation doesn't have any ivar initializers, we don't need 6651 // a .cxx_construct. 6652 if (D->getNumIvarInitializers() == 0 || 6653 AllTrivialInitializers(*this, D)) 6654 return; 6655 6656 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 6657 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6658 // The constructor returns 'self'. 6659 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 6660 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6661 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 6662 /*isVariadic=*/false, 6663 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6664 /*isImplicitlyDeclared=*/true, 6665 /*isDefined=*/false, ObjCImplementationControl::Required); 6666 D->addInstanceMethod(CTORMethod); 6667 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 6668 D->setHasNonZeroConstructors(true); 6669 } 6670 6671 // EmitLinkageSpec - Emit all declarations in a linkage spec. 6672 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 6673 if (LSD->getLanguage() != LinkageSpecLanguageIDs::C && 6674 LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) { 6675 ErrorUnsupported(LSD, "linkage spec"); 6676 return; 6677 } 6678 6679 EmitDeclContext(LSD); 6680 } 6681 6682 void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) { 6683 // Device code should not be at top level. 6684 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6685 return; 6686 6687 std::unique_ptr<CodeGenFunction> &CurCGF = 6688 GlobalTopLevelStmtBlockInFlight.first; 6689 6690 // We emitted a top-level stmt but after it there is initialization. 6691 // Stop squashing the top-level stmts into a single function. 6692 if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) { 6693 CurCGF->FinishFunction(D->getEndLoc()); 6694 CurCGF = nullptr; 6695 } 6696 6697 if (!CurCGF) { 6698 // void __stmts__N(void) 6699 // FIXME: Ask the ABI name mangler to pick a name. 6700 std::string Name = "__stmts__" + llvm::utostr(CXXGlobalInits.size()); 6701 FunctionArgList Args; 6702 QualType RetTy = getContext().VoidTy; 6703 const CGFunctionInfo &FnInfo = 6704 getTypes().arrangeBuiltinFunctionDeclaration(RetTy, Args); 6705 llvm::FunctionType *FnTy = getTypes().GetFunctionType(FnInfo); 6706 llvm::Function *Fn = llvm::Function::Create( 6707 FnTy, llvm::GlobalValue::InternalLinkage, Name, &getModule()); 6708 6709 CurCGF.reset(new CodeGenFunction(*this)); 6710 GlobalTopLevelStmtBlockInFlight.second = D; 6711 CurCGF->StartFunction(GlobalDecl(), RetTy, Fn, FnInfo, Args, 6712 D->getBeginLoc(), D->getBeginLoc()); 6713 CXXGlobalInits.push_back(Fn); 6714 } 6715 6716 CurCGF->EmitStmt(D->getStmt()); 6717 } 6718 6719 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 6720 for (auto *I : DC->decls()) { 6721 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 6722 // are themselves considered "top-level", so EmitTopLevelDecl on an 6723 // ObjCImplDecl does not recursively visit them. We need to do that in 6724 // case they're nested inside another construct (LinkageSpecDecl / 6725 // ExportDecl) that does stop them from being considered "top-level". 6726 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 6727 for (auto *M : OID->methods()) 6728 EmitTopLevelDecl(M); 6729 } 6730 6731 EmitTopLevelDecl(I); 6732 } 6733 } 6734 6735 /// EmitTopLevelDecl - Emit code for a single top level declaration. 6736 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 6737 // Ignore dependent declarations. 6738 if (D->isTemplated()) 6739 return; 6740 6741 // Consteval function shouldn't be emitted. 6742 if (auto *FD = dyn_cast<FunctionDecl>(D); FD && FD->isImmediateFunction()) 6743 return; 6744 6745 switch (D->getKind()) { 6746 case Decl::CXXConversion: 6747 case Decl::CXXMethod: 6748 case Decl::Function: 6749 EmitGlobal(cast<FunctionDecl>(D)); 6750 // Always provide some coverage mapping 6751 // even for the functions that aren't emitted. 6752 AddDeferredUnusedCoverageMapping(D); 6753 break; 6754 6755 case Decl::CXXDeductionGuide: 6756 // Function-like, but does not result in code emission. 6757 break; 6758 6759 case Decl::Var: 6760 case Decl::Decomposition: 6761 case Decl::VarTemplateSpecialization: 6762 EmitGlobal(cast<VarDecl>(D)); 6763 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 6764 for (auto *B : DD->bindings()) 6765 if (auto *HD = B->getHoldingVar()) 6766 EmitGlobal(HD); 6767 break; 6768 6769 // Indirect fields from global anonymous structs and unions can be 6770 // ignored; only the actual variable requires IR gen support. 6771 case Decl::IndirectField: 6772 break; 6773 6774 // C++ Decls 6775 case Decl::Namespace: 6776 EmitDeclContext(cast<NamespaceDecl>(D)); 6777 break; 6778 case Decl::ClassTemplateSpecialization: { 6779 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 6780 if (CGDebugInfo *DI = getModuleDebugInfo()) 6781 if (Spec->getSpecializationKind() == 6782 TSK_ExplicitInstantiationDefinition && 6783 Spec->hasDefinition()) 6784 DI->completeTemplateDefinition(*Spec); 6785 } [[fallthrough]]; 6786 case Decl::CXXRecord: { 6787 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 6788 if (CGDebugInfo *DI = getModuleDebugInfo()) { 6789 if (CRD->hasDefinition()) 6790 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6791 if (auto *ES = D->getASTContext().getExternalSource()) 6792 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 6793 DI->completeUnusedClass(*CRD); 6794 } 6795 // Emit any static data members, they may be definitions. 6796 for (auto *I : CRD->decls()) 6797 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 6798 EmitTopLevelDecl(I); 6799 break; 6800 } 6801 // No code generation needed. 6802 case Decl::UsingShadow: 6803 case Decl::ClassTemplate: 6804 case Decl::VarTemplate: 6805 case Decl::Concept: 6806 case Decl::VarTemplatePartialSpecialization: 6807 case Decl::FunctionTemplate: 6808 case Decl::TypeAliasTemplate: 6809 case Decl::Block: 6810 case Decl::Empty: 6811 case Decl::Binding: 6812 break; 6813 case Decl::Using: // using X; [C++] 6814 if (CGDebugInfo *DI = getModuleDebugInfo()) 6815 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 6816 break; 6817 case Decl::UsingEnum: // using enum X; [C++] 6818 if (CGDebugInfo *DI = getModuleDebugInfo()) 6819 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 6820 break; 6821 case Decl::NamespaceAlias: 6822 if (CGDebugInfo *DI = getModuleDebugInfo()) 6823 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 6824 break; 6825 case Decl::UsingDirective: // using namespace X; [C++] 6826 if (CGDebugInfo *DI = getModuleDebugInfo()) 6827 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 6828 break; 6829 case Decl::CXXConstructor: 6830 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 6831 break; 6832 case Decl::CXXDestructor: 6833 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 6834 break; 6835 6836 case Decl::StaticAssert: 6837 // Nothing to do. 6838 break; 6839 6840 // Objective-C Decls 6841 6842 // Forward declarations, no (immediate) code generation. 6843 case Decl::ObjCInterface: 6844 case Decl::ObjCCategory: 6845 break; 6846 6847 case Decl::ObjCProtocol: { 6848 auto *Proto = cast<ObjCProtocolDecl>(D); 6849 if (Proto->isThisDeclarationADefinition()) 6850 ObjCRuntime->GenerateProtocol(Proto); 6851 break; 6852 } 6853 6854 case Decl::ObjCCategoryImpl: 6855 // Categories have properties but don't support synthesize so we 6856 // can ignore them here. 6857 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 6858 break; 6859 6860 case Decl::ObjCImplementation: { 6861 auto *OMD = cast<ObjCImplementationDecl>(D); 6862 EmitObjCPropertyImplementations(OMD); 6863 EmitObjCIvarInitializations(OMD); 6864 ObjCRuntime->GenerateClass(OMD); 6865 // Emit global variable debug information. 6866 if (CGDebugInfo *DI = getModuleDebugInfo()) 6867 if (getCodeGenOpts().hasReducedDebugInfo()) 6868 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 6869 OMD->getClassInterface()), OMD->getLocation()); 6870 break; 6871 } 6872 case Decl::ObjCMethod: { 6873 auto *OMD = cast<ObjCMethodDecl>(D); 6874 // If this is not a prototype, emit the body. 6875 if (OMD->getBody()) 6876 CodeGenFunction(*this).GenerateObjCMethod(OMD); 6877 break; 6878 } 6879 case Decl::ObjCCompatibleAlias: 6880 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 6881 break; 6882 6883 case Decl::PragmaComment: { 6884 const auto *PCD = cast<PragmaCommentDecl>(D); 6885 switch (PCD->getCommentKind()) { 6886 case PCK_Unknown: 6887 llvm_unreachable("unexpected pragma comment kind"); 6888 case PCK_Linker: 6889 AppendLinkerOptions(PCD->getArg()); 6890 break; 6891 case PCK_Lib: 6892 AddDependentLib(PCD->getArg()); 6893 break; 6894 case PCK_Compiler: 6895 case PCK_ExeStr: 6896 case PCK_User: 6897 break; // We ignore all of these. 6898 } 6899 break; 6900 } 6901 6902 case Decl::PragmaDetectMismatch: { 6903 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 6904 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 6905 break; 6906 } 6907 6908 case Decl::LinkageSpec: 6909 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 6910 break; 6911 6912 case Decl::FileScopeAsm: { 6913 // File-scope asm is ignored during device-side CUDA compilation. 6914 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6915 break; 6916 // File-scope asm is ignored during device-side OpenMP compilation. 6917 if (LangOpts.OpenMPIsTargetDevice) 6918 break; 6919 // File-scope asm is ignored during device-side SYCL compilation. 6920 if (LangOpts.SYCLIsDevice) 6921 break; 6922 auto *AD = cast<FileScopeAsmDecl>(D); 6923 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 6924 break; 6925 } 6926 6927 case Decl::TopLevelStmt: 6928 EmitTopLevelStmt(cast<TopLevelStmtDecl>(D)); 6929 break; 6930 6931 case Decl::Import: { 6932 auto *Import = cast<ImportDecl>(D); 6933 6934 // If we've already imported this module, we're done. 6935 if (!ImportedModules.insert(Import->getImportedModule())) 6936 break; 6937 6938 // Emit debug information for direct imports. 6939 if (!Import->getImportedOwningModule()) { 6940 if (CGDebugInfo *DI = getModuleDebugInfo()) 6941 DI->EmitImportDecl(*Import); 6942 } 6943 6944 // For C++ standard modules we are done - we will call the module 6945 // initializer for imported modules, and that will likewise call those for 6946 // any imports it has. 6947 if (CXX20ModuleInits && Import->getImportedOwningModule() && 6948 !Import->getImportedOwningModule()->isModuleMapModule()) 6949 break; 6950 6951 // For clang C++ module map modules the initializers for sub-modules are 6952 // emitted here. 6953 6954 // Find all of the submodules and emit the module initializers. 6955 llvm::SmallPtrSet<clang::Module *, 16> Visited; 6956 SmallVector<clang::Module *, 16> Stack; 6957 Visited.insert(Import->getImportedModule()); 6958 Stack.push_back(Import->getImportedModule()); 6959 6960 while (!Stack.empty()) { 6961 clang::Module *Mod = Stack.pop_back_val(); 6962 if (!EmittedModuleInitializers.insert(Mod).second) 6963 continue; 6964 6965 for (auto *D : Context.getModuleInitializers(Mod)) 6966 EmitTopLevelDecl(D); 6967 6968 // Visit the submodules of this module. 6969 for (auto *Submodule : Mod->submodules()) { 6970 // Skip explicit children; they need to be explicitly imported to emit 6971 // the initializers. 6972 if (Submodule->IsExplicit) 6973 continue; 6974 6975 if (Visited.insert(Submodule).second) 6976 Stack.push_back(Submodule); 6977 } 6978 } 6979 break; 6980 } 6981 6982 case Decl::Export: 6983 EmitDeclContext(cast<ExportDecl>(D)); 6984 break; 6985 6986 case Decl::OMPThreadPrivate: 6987 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 6988 break; 6989 6990 case Decl::OMPAllocate: 6991 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 6992 break; 6993 6994 case Decl::OMPDeclareReduction: 6995 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 6996 break; 6997 6998 case Decl::OMPDeclareMapper: 6999 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 7000 break; 7001 7002 case Decl::OMPRequires: 7003 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 7004 break; 7005 7006 case Decl::Typedef: 7007 case Decl::TypeAlias: // using foo = bar; [C++11] 7008 if (CGDebugInfo *DI = getModuleDebugInfo()) 7009 DI->EmitAndRetainType( 7010 getContext().getTypedefType(cast<TypedefNameDecl>(D))); 7011 break; 7012 7013 case Decl::Record: 7014 if (CGDebugInfo *DI = getModuleDebugInfo()) 7015 if (cast<RecordDecl>(D)->getDefinition()) 7016 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 7017 break; 7018 7019 case Decl::Enum: 7020 if (CGDebugInfo *DI = getModuleDebugInfo()) 7021 if (cast<EnumDecl>(D)->getDefinition()) 7022 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 7023 break; 7024 7025 case Decl::HLSLBuffer: 7026 getHLSLRuntime().addBuffer(cast<HLSLBufferDecl>(D)); 7027 break; 7028 7029 default: 7030 // Make sure we handled everything we should, every other kind is a 7031 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 7032 // function. Need to recode Decl::Kind to do that easily. 7033 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 7034 break; 7035 } 7036 } 7037 7038 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 7039 // Do we need to generate coverage mapping? 7040 if (!CodeGenOpts.CoverageMapping) 7041 return; 7042 switch (D->getKind()) { 7043 case Decl::CXXConversion: 7044 case Decl::CXXMethod: 7045 case Decl::Function: 7046 case Decl::ObjCMethod: 7047 case Decl::CXXConstructor: 7048 case Decl::CXXDestructor: { 7049 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 7050 break; 7051 SourceManager &SM = getContext().getSourceManager(); 7052 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 7053 break; 7054 DeferredEmptyCoverageMappingDecls.try_emplace(D, true); 7055 break; 7056 } 7057 default: 7058 break; 7059 }; 7060 } 7061 7062 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 7063 // Do we need to generate coverage mapping? 7064 if (!CodeGenOpts.CoverageMapping) 7065 return; 7066 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 7067 if (Fn->isTemplateInstantiation()) 7068 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 7069 } 7070 DeferredEmptyCoverageMappingDecls.insert_or_assign(D, false); 7071 } 7072 7073 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 7074 // We call takeVector() here to avoid use-after-free. 7075 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 7076 // we deserialize function bodies to emit coverage info for them, and that 7077 // deserializes more declarations. How should we handle that case? 7078 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 7079 if (!Entry.second) 7080 continue; 7081 const Decl *D = Entry.first; 7082 switch (D->getKind()) { 7083 case Decl::CXXConversion: 7084 case Decl::CXXMethod: 7085 case Decl::Function: 7086 case Decl::ObjCMethod: { 7087 CodeGenPGO PGO(*this); 7088 GlobalDecl GD(cast<FunctionDecl>(D)); 7089 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 7090 getFunctionLinkage(GD)); 7091 break; 7092 } 7093 case Decl::CXXConstructor: { 7094 CodeGenPGO PGO(*this); 7095 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 7096 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 7097 getFunctionLinkage(GD)); 7098 break; 7099 } 7100 case Decl::CXXDestructor: { 7101 CodeGenPGO PGO(*this); 7102 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 7103 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 7104 getFunctionLinkage(GD)); 7105 break; 7106 } 7107 default: 7108 break; 7109 }; 7110 } 7111 } 7112 7113 void CodeGenModule::EmitMainVoidAlias() { 7114 // In order to transition away from "__original_main" gracefully, emit an 7115 // alias for "main" in the no-argument case so that libc can detect when 7116 // new-style no-argument main is in used. 7117 if (llvm::Function *F = getModule().getFunction("main")) { 7118 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 7119 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) { 7120 auto *GA = llvm::GlobalAlias::create("__main_void", F); 7121 GA->setVisibility(llvm::GlobalValue::HiddenVisibility); 7122 } 7123 } 7124 } 7125 7126 /// Turns the given pointer into a constant. 7127 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 7128 const void *Ptr) { 7129 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 7130 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 7131 return llvm::ConstantInt::get(i64, PtrInt); 7132 } 7133 7134 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 7135 llvm::NamedMDNode *&GlobalMetadata, 7136 GlobalDecl D, 7137 llvm::GlobalValue *Addr) { 7138 if (!GlobalMetadata) 7139 GlobalMetadata = 7140 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 7141 7142 // TODO: should we report variant information for ctors/dtors? 7143 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 7144 llvm::ConstantAsMetadata::get(GetPointerConstant( 7145 CGM.getLLVMContext(), D.getDecl()))}; 7146 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 7147 } 7148 7149 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, 7150 llvm::GlobalValue *CppFunc) { 7151 // Store the list of ifuncs we need to replace uses in. 7152 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; 7153 // List of ConstantExprs that we should be able to delete when we're done 7154 // here. 7155 llvm::SmallVector<llvm::ConstantExpr *> CEs; 7156 7157 // It isn't valid to replace the extern-C ifuncs if all we find is itself! 7158 if (Elem == CppFunc) 7159 return false; 7160 7161 // First make sure that all users of this are ifuncs (or ifuncs via a 7162 // bitcast), and collect the list of ifuncs and CEs so we can work on them 7163 // later. 7164 for (llvm::User *User : Elem->users()) { 7165 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an 7166 // ifunc directly. In any other case, just give up, as we don't know what we 7167 // could break by changing those. 7168 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) { 7169 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) 7170 return false; 7171 7172 for (llvm::User *CEUser : ConstExpr->users()) { 7173 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) { 7174 IFuncs.push_back(IFunc); 7175 } else { 7176 return false; 7177 } 7178 } 7179 CEs.push_back(ConstExpr); 7180 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) { 7181 IFuncs.push_back(IFunc); 7182 } else { 7183 // This user is one we don't know how to handle, so fail redirection. This 7184 // will result in an ifunc retaining a resolver name that will ultimately 7185 // fail to be resolved to a defined function. 7186 return false; 7187 } 7188 } 7189 7190 // Now we know this is a valid case where we can do this alias replacement, we 7191 // need to remove all of the references to Elem (and the bitcasts!) so we can 7192 // delete it. 7193 for (llvm::GlobalIFunc *IFunc : IFuncs) 7194 IFunc->setResolver(nullptr); 7195 for (llvm::ConstantExpr *ConstExpr : CEs) 7196 ConstExpr->destroyConstant(); 7197 7198 // We should now be out of uses for the 'old' version of this function, so we 7199 // can erase it as well. 7200 Elem->eraseFromParent(); 7201 7202 for (llvm::GlobalIFunc *IFunc : IFuncs) { 7203 // The type of the resolver is always just a function-type that returns the 7204 // type of the IFunc, so create that here. If the type of the actual 7205 // resolver doesn't match, it just gets bitcast to the right thing. 7206 auto *ResolverTy = 7207 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false); 7208 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 7209 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false); 7210 IFunc->setResolver(Resolver); 7211 } 7212 return true; 7213 } 7214 7215 /// For each function which is declared within an extern "C" region and marked 7216 /// as 'used', but has internal linkage, create an alias from the unmangled 7217 /// name to the mangled name if possible. People expect to be able to refer 7218 /// to such functions with an unmangled name from inline assembly within the 7219 /// same translation unit. 7220 void CodeGenModule::EmitStaticExternCAliases() { 7221 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 7222 return; 7223 for (auto &I : StaticExternCValues) { 7224 IdentifierInfo *Name = I.first; 7225 llvm::GlobalValue *Val = I.second; 7226 7227 // If Val is null, that implies there were multiple declarations that each 7228 // had a claim to the unmangled name. In this case, generation of the alias 7229 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. 7230 if (!Val) 7231 break; 7232 7233 llvm::GlobalValue *ExistingElem = 7234 getModule().getNamedValue(Name->getName()); 7235 7236 // If there is either not something already by this name, or we were able to 7237 // replace all uses from IFuncs, create the alias. 7238 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val)) 7239 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 7240 } 7241 } 7242 7243 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 7244 GlobalDecl &Result) const { 7245 auto Res = Manglings.find(MangledName); 7246 if (Res == Manglings.end()) 7247 return false; 7248 Result = Res->getValue(); 7249 return true; 7250 } 7251 7252 /// Emits metadata nodes associating all the global values in the 7253 /// current module with the Decls they came from. This is useful for 7254 /// projects using IR gen as a subroutine. 7255 /// 7256 /// Since there's currently no way to associate an MDNode directly 7257 /// with an llvm::GlobalValue, we create a global named metadata 7258 /// with the name 'clang.global.decl.ptrs'. 7259 void CodeGenModule::EmitDeclMetadata() { 7260 llvm::NamedMDNode *GlobalMetadata = nullptr; 7261 7262 for (auto &I : MangledDeclNames) { 7263 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 7264 // Some mangled names don't necessarily have an associated GlobalValue 7265 // in this module, e.g. if we mangled it for DebugInfo. 7266 if (Addr) 7267 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 7268 } 7269 } 7270 7271 /// Emits metadata nodes for all the local variables in the current 7272 /// function. 7273 void CodeGenFunction::EmitDeclMetadata() { 7274 if (LocalDeclMap.empty()) return; 7275 7276 llvm::LLVMContext &Context = getLLVMContext(); 7277 7278 // Find the unique metadata ID for this name. 7279 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 7280 7281 llvm::NamedMDNode *GlobalMetadata = nullptr; 7282 7283 for (auto &I : LocalDeclMap) { 7284 const Decl *D = I.first; 7285 llvm::Value *Addr = I.second.getPointer(); 7286 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 7287 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 7288 Alloca->setMetadata( 7289 DeclPtrKind, llvm::MDNode::get( 7290 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 7291 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 7292 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 7293 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 7294 } 7295 } 7296 } 7297 7298 void CodeGenModule::EmitVersionIdentMetadata() { 7299 llvm::NamedMDNode *IdentMetadata = 7300 TheModule.getOrInsertNamedMetadata("llvm.ident"); 7301 std::string Version = getClangFullVersion(); 7302 llvm::LLVMContext &Ctx = TheModule.getContext(); 7303 7304 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 7305 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 7306 } 7307 7308 void CodeGenModule::EmitCommandLineMetadata() { 7309 llvm::NamedMDNode *CommandLineMetadata = 7310 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 7311 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 7312 llvm::LLVMContext &Ctx = TheModule.getContext(); 7313 7314 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 7315 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 7316 } 7317 7318 void CodeGenModule::EmitCoverageFile() { 7319 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 7320 if (!CUNode) 7321 return; 7322 7323 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 7324 llvm::LLVMContext &Ctx = TheModule.getContext(); 7325 auto *CoverageDataFile = 7326 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 7327 auto *CoverageNotesFile = 7328 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 7329 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 7330 llvm::MDNode *CU = CUNode->getOperand(i); 7331 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 7332 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 7333 } 7334 } 7335 7336 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 7337 bool ForEH) { 7338 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 7339 // FIXME: should we even be calling this method if RTTI is disabled 7340 // and it's not for EH? 7341 if (!shouldEmitRTTI(ForEH)) 7342 return llvm::Constant::getNullValue(GlobalsInt8PtrTy); 7343 7344 if (ForEH && Ty->isObjCObjectPointerType() && 7345 LangOpts.ObjCRuntime.isGNUFamily()) 7346 return ObjCRuntime->GetEHType(Ty); 7347 7348 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 7349 } 7350 7351 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 7352 // Do not emit threadprivates in simd-only mode. 7353 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 7354 return; 7355 for (auto RefExpr : D->varlists()) { 7356 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 7357 bool PerformInit = 7358 VD->getAnyInitializer() && 7359 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 7360 /*ForRef=*/false); 7361 7362 Address Addr(GetAddrOfGlobalVar(VD), 7363 getTypes().ConvertTypeForMem(VD->getType()), 7364 getContext().getDeclAlign(VD)); 7365 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 7366 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 7367 CXXGlobalInits.push_back(InitFunction); 7368 } 7369 } 7370 7371 llvm::Metadata * 7372 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 7373 StringRef Suffix) { 7374 if (auto *FnType = T->getAs<FunctionProtoType>()) 7375 T = getContext().getFunctionType( 7376 FnType->getReturnType(), FnType->getParamTypes(), 7377 FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 7378 7379 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 7380 if (InternalId) 7381 return InternalId; 7382 7383 if (isExternallyVisible(T->getLinkage())) { 7384 std::string OutName; 7385 llvm::raw_string_ostream Out(OutName); 7386 getCXXABI().getMangleContext().mangleCanonicalTypeName( 7387 T, Out, getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); 7388 7389 if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) 7390 Out << ".normalized"; 7391 7392 Out << Suffix; 7393 7394 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 7395 } else { 7396 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 7397 llvm::ArrayRef<llvm::Metadata *>()); 7398 } 7399 7400 return InternalId; 7401 } 7402 7403 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 7404 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 7405 } 7406 7407 llvm::Metadata * 7408 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 7409 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 7410 } 7411 7412 // Generalize pointer types to a void pointer with the qualifiers of the 7413 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 7414 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 7415 // 'void *'. 7416 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 7417 if (!Ty->isPointerType()) 7418 return Ty; 7419 7420 return Ctx.getPointerType( 7421 QualType(Ctx.VoidTy).withCVRQualifiers( 7422 Ty->getPointeeType().getCVRQualifiers())); 7423 } 7424 7425 // Apply type generalization to a FunctionType's return and argument types 7426 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 7427 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 7428 SmallVector<QualType, 8> GeneralizedParams; 7429 for (auto &Param : FnType->param_types()) 7430 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 7431 7432 return Ctx.getFunctionType( 7433 GeneralizeType(Ctx, FnType->getReturnType()), 7434 GeneralizedParams, FnType->getExtProtoInfo()); 7435 } 7436 7437 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 7438 return Ctx.getFunctionNoProtoType( 7439 GeneralizeType(Ctx, FnType->getReturnType())); 7440 7441 llvm_unreachable("Encountered unknown FunctionType"); 7442 } 7443 7444 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 7445 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 7446 GeneralizedMetadataIdMap, ".generalized"); 7447 } 7448 7449 /// Returns whether this module needs the "all-vtables" type identifier. 7450 bool CodeGenModule::NeedAllVtablesTypeId() const { 7451 // Returns true if at least one of vtable-based CFI checkers is enabled and 7452 // is not in the trapping mode. 7453 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 7454 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 7455 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 7456 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 7457 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 7458 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 7459 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 7460 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 7461 } 7462 7463 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 7464 CharUnits Offset, 7465 const CXXRecordDecl *RD) { 7466 llvm::Metadata *MD = 7467 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 7468 VTable->addTypeMetadata(Offset.getQuantity(), MD); 7469 7470 if (CodeGenOpts.SanitizeCfiCrossDso) 7471 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 7472 VTable->addTypeMetadata(Offset.getQuantity(), 7473 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 7474 7475 if (NeedAllVtablesTypeId()) { 7476 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 7477 VTable->addTypeMetadata(Offset.getQuantity(), MD); 7478 } 7479 } 7480 7481 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 7482 if (!SanStats) 7483 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 7484 7485 return *SanStats; 7486 } 7487 7488 llvm::Value * 7489 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 7490 CodeGenFunction &CGF) { 7491 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 7492 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 7493 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 7494 auto *Call = CGF.EmitRuntimeCall( 7495 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 7496 return Call; 7497 } 7498 7499 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 7500 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 7501 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 7502 /* forPointeeType= */ true); 7503 } 7504 7505 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 7506 LValueBaseInfo *BaseInfo, 7507 TBAAAccessInfo *TBAAInfo, 7508 bool forPointeeType) { 7509 if (TBAAInfo) 7510 *TBAAInfo = getTBAAAccessInfo(T); 7511 7512 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 7513 // that doesn't return the information we need to compute BaseInfo. 7514 7515 // Honor alignment typedef attributes even on incomplete types. 7516 // We also honor them straight for C++ class types, even as pointees; 7517 // there's an expressivity gap here. 7518 if (auto TT = T->getAs<TypedefType>()) { 7519 if (auto Align = TT->getDecl()->getMaxAlignment()) { 7520 if (BaseInfo) 7521 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 7522 return getContext().toCharUnitsFromBits(Align); 7523 } 7524 } 7525 7526 bool AlignForArray = T->isArrayType(); 7527 7528 // Analyze the base element type, so we don't get confused by incomplete 7529 // array types. 7530 T = getContext().getBaseElementType(T); 7531 7532 if (T->isIncompleteType()) { 7533 // We could try to replicate the logic from 7534 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 7535 // type is incomplete, so it's impossible to test. We could try to reuse 7536 // getTypeAlignIfKnown, but that doesn't return the information we need 7537 // to set BaseInfo. So just ignore the possibility that the alignment is 7538 // greater than one. 7539 if (BaseInfo) 7540 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 7541 return CharUnits::One(); 7542 } 7543 7544 if (BaseInfo) 7545 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 7546 7547 CharUnits Alignment; 7548 const CXXRecordDecl *RD; 7549 if (T.getQualifiers().hasUnaligned()) { 7550 Alignment = CharUnits::One(); 7551 } else if (forPointeeType && !AlignForArray && 7552 (RD = T->getAsCXXRecordDecl())) { 7553 // For C++ class pointees, we don't know whether we're pointing at a 7554 // base or a complete object, so we generally need to use the 7555 // non-virtual alignment. 7556 Alignment = getClassPointerAlignment(RD); 7557 } else { 7558 Alignment = getContext().getTypeAlignInChars(T); 7559 } 7560 7561 // Cap to the global maximum type alignment unless the alignment 7562 // was somehow explicit on the type. 7563 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 7564 if (Alignment.getQuantity() > MaxAlign && 7565 !getContext().isAlignmentRequired(T)) 7566 Alignment = CharUnits::fromQuantity(MaxAlign); 7567 } 7568 return Alignment; 7569 } 7570 7571 bool CodeGenModule::stopAutoInit() { 7572 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 7573 if (StopAfter) { 7574 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 7575 // used 7576 if (NumAutoVarInit >= StopAfter) { 7577 return true; 7578 } 7579 if (!NumAutoVarInit) { 7580 unsigned DiagID = getDiags().getCustomDiagID( 7581 DiagnosticsEngine::Warning, 7582 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 7583 "number of times ftrivial-auto-var-init=%1 gets applied."); 7584 getDiags().Report(DiagID) 7585 << StopAfter 7586 << (getContext().getLangOpts().getTrivialAutoVarInit() == 7587 LangOptions::TrivialAutoVarInitKind::Zero 7588 ? "zero" 7589 : "pattern"); 7590 } 7591 ++NumAutoVarInit; 7592 } 7593 return false; 7594 } 7595 7596 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, 7597 const Decl *D) const { 7598 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers 7599 // postfix beginning with '.' since the symbol name can be demangled. 7600 if (LangOpts.HIP) 7601 OS << (isa<VarDecl>(D) ? ".static." : ".intern."); 7602 else 7603 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__"); 7604 7605 // If the CUID is not specified we try to generate a unique postfix. 7606 if (getLangOpts().CUID.empty()) { 7607 SourceManager &SM = getContext().getSourceManager(); 7608 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation()); 7609 assert(PLoc.isValid() && "Source location is expected to be valid."); 7610 7611 // Get the hash of the user defined macros. 7612 llvm::MD5 Hash; 7613 llvm::MD5::MD5Result Result; 7614 for (const auto &Arg : PreprocessorOpts.Macros) 7615 Hash.update(Arg.first); 7616 Hash.final(Result); 7617 7618 // Get the UniqueID for the file containing the decl. 7619 llvm::sys::fs::UniqueID ID; 7620 if (llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { 7621 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false); 7622 assert(PLoc.isValid() && "Source location is expected to be valid."); 7623 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) 7624 SM.getDiagnostics().Report(diag::err_cannot_open_file) 7625 << PLoc.getFilename() << EC.message(); 7626 } 7627 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice()) 7628 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8); 7629 } else { 7630 OS << getContext().getCUIDHash(); 7631 } 7632 } 7633 7634 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) { 7635 assert(DeferredDeclsToEmit.empty() && 7636 "Should have emitted all decls deferred to emit."); 7637 assert(NewBuilder->DeferredDecls.empty() && 7638 "Newly created module should not have deferred decls"); 7639 NewBuilder->DeferredDecls = std::move(DeferredDecls); 7640 assert(EmittedDeferredDecls.empty() && 7641 "Still have (unmerged) EmittedDeferredDecls deferred decls"); 7642 7643 assert(NewBuilder->DeferredVTables.empty() && 7644 "Newly created module should not have deferred vtables"); 7645 NewBuilder->DeferredVTables = std::move(DeferredVTables); 7646 7647 assert(NewBuilder->MangledDeclNames.empty() && 7648 "Newly created module should not have mangled decl names"); 7649 assert(NewBuilder->Manglings.empty() && 7650 "Newly created module should not have manglings"); 7651 NewBuilder->Manglings = std::move(Manglings); 7652 7653 NewBuilder->WeakRefReferences = std::move(WeakRefReferences); 7654 7655 NewBuilder->TBAA = std::move(TBAA); 7656 7657 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx); 7658 } 7659