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