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