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