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