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