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