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