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