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