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