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