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