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