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