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