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