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