| 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 "QualTypeMapper.h" |
| 30 | #include "TargetInfo.h" |
| 31 | #include "clang/AST/ASTContext.h" |
| 32 | #include "clang/AST/ASTLambda.h" |
| 33 | #include "clang/AST/CharUnits.h" |
| 34 | #include "clang/AST/Decl.h" |
| 35 | #include "clang/AST/DeclCXX.h" |
| 36 | #include "clang/AST/DeclObjC.h" |
| 37 | #include "clang/AST/DeclTemplate.h" |
| 38 | #include "clang/AST/Mangle.h" |
| 39 | #include "clang/AST/RecursiveASTVisitor.h" |
| 40 | #include "clang/AST/StmtVisitor.h" |
| 41 | #include "clang/Basic/Builtins.h" |
| 42 | #include "clang/Basic/CodeGenOptions.h" |
| 43 | #include "clang/Basic/Diagnostic.h" |
| 44 | #include "clang/Basic/DiagnosticFrontend.h" |
| 45 | #include "clang/Basic/Module.h" |
| 46 | #include "clang/Basic/SourceManager.h" |
| 47 | #include "clang/Basic/TargetInfo.h" |
| 48 | #include "clang/Basic/Version.h" |
| 49 | #include "clang/CodeGen/BackendUtil.h" |
| 50 | #include "clang/CodeGen/ConstantInitBuilder.h" |
| 51 | #include "clang/Lex/Preprocessor.h" |
| 52 | #include "llvm/ABI/IRTypeMapper.h" |
| 53 | #include "llvm/ABI/TargetInfo.h" |
| 54 | #include "llvm/ADT/STLExtras.h" |
| 55 | #include "llvm/ADT/StringExtras.h" |
| 56 | #include "llvm/ADT/StringSwitch.h" |
| 57 | #include "llvm/Analysis/TargetLibraryInfo.h" |
| 58 | #include "llvm/BinaryFormat/ELF.h" |
| 59 | #include "llvm/IR/AttributeMask.h" |
| 60 | #include "llvm/IR/CallingConv.h" |
| 61 | #include "llvm/IR/DataLayout.h" |
| 62 | #include "llvm/IR/Intrinsics.h" |
| 63 | #include "llvm/IR/LLVMContext.h" |
| 64 | #include "llvm/IR/Module.h" |
| 65 | #include "llvm/IR/ProfileSummary.h" |
| 66 | #include "llvm/ProfileData/InstrProfReader.h" |
| 67 | #include "llvm/ProfileData/SampleProf.h" |
| 68 | #include "llvm/Support/ARMBuildAttributes.h" |
| 69 | #include "llvm/Support/CRC.h" |
| 70 | #include "llvm/Support/CodeGen.h" |
| 71 | #include "llvm/Support/CommandLine.h" |
| 72 | #include "llvm/Support/ConvertUTF.h" |
| 73 | #include "llvm/Support/ErrorHandling.h" |
| 74 | #include "llvm/Support/TimeProfiler.h" |
| 75 | #include "llvm/TargetParser/AArch64TargetParser.h" |
| 76 | #include "llvm/TargetParser/RISCVISAInfo.h" |
| 77 | #include "llvm/TargetParser/Triple.h" |
| 78 | #include "llvm/TargetParser/X86TargetParser.h" |
| 79 | #include "llvm/Transforms/Instrumentation/KCFI.h" |
| 80 | #include "llvm/Transforms/Utils/BuildLibCalls.h" |
| 81 | #include "llvm/Transforms/Utils/KCFIHash.h" |
| 82 | #include "llvm/Transforms/Utils/ModuleUtils.h" |
| 83 | #include <optional> |
| 84 | #include <set> |
| 85 | |
| 86 | using namespace clang; |
| 87 | using namespace CodeGen; |
| 88 | |
| 89 | static llvm::cl::opt<bool> LimitedCoverage( |
| 90 | "limited-coverage-experimental" , llvm::cl::Hidden, |
| 91 | llvm::cl::desc("Emit limited coverage mapping information (experimental)" )); |
| 92 | |
| 93 | static const char AnnotationSection[] = "llvm.metadata" ; |
| 94 | static constexpr auto ErrnoTBAAMDName = "llvm.errno.tbaa" ; |
| 95 | |
| 96 | static CGCXXABI *createCXXABI(CodeGenModule &CGM) { |
| 97 | switch (CGM.getContext().getCXXABIKind()) { |
| 98 | case TargetCXXABI::AppleARM64: |
| 99 | case TargetCXXABI::Fuchsia: |
| 100 | case TargetCXXABI::GenericAArch64: |
| 101 | case TargetCXXABI::GenericARM: |
| 102 | case TargetCXXABI::iOS: |
| 103 | case TargetCXXABI::WatchOS: |
| 104 | case TargetCXXABI::GenericMIPS: |
| 105 | case TargetCXXABI::GenericItanium: |
| 106 | case TargetCXXABI::WebAssembly: |
| 107 | case TargetCXXABI::XL: |
| 108 | return CreateItaniumCXXABI(CGM); |
| 109 | case TargetCXXABI::Microsoft: |
| 110 | return CreateMicrosoftCXXABI(CGM); |
| 111 | } |
| 112 | |
| 113 | llvm_unreachable("invalid C++ ABI kind" ); |
| 114 | } |
| 115 | |
| 116 | static std::unique_ptr<TargetCodeGenInfo> |
| 117 | createTargetCodeGenInfo(CodeGenModule &CGM) { |
| 118 | const TargetInfo &Target = CGM.getTarget(); |
| 119 | const llvm::Triple &Triple = Target.getTriple(); |
| 120 | const CodeGenOptions &CodeGenOpts = CGM.getCodeGenOpts(); |
| 121 | |
| 122 | switch (Triple.getArch()) { |
| 123 | default: |
| 124 | return createDefaultTargetCodeGenInfo(CGM); |
| 125 | |
| 126 | case llvm::Triple::m68k: |
| 127 | return createM68kTargetCodeGenInfo(CGM); |
| 128 | case llvm::Triple::mips: |
| 129 | case llvm::Triple::mipsel: |
| 130 | if (Triple.getOS() == llvm::Triple::Win32) |
| 131 | return createWindowsMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true); |
| 132 | return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/true); |
| 133 | |
| 134 | case llvm::Triple::mips64: |
| 135 | case llvm::Triple::mips64el: |
| 136 | return createMIPSTargetCodeGenInfo(CGM, /*IsOS32=*/false); |
| 137 | |
| 138 | case llvm::Triple::avr: { |
| 139 | // For passing parameters, R8~R25 are used on avr, and R18~R25 are used |
| 140 | // on avrtiny. For passing return value, R18~R25 are used on avr, and |
| 141 | // R22~R25 are used on avrtiny. |
| 142 | unsigned NPR = Target.getABI() == "avrtiny" ? 6 : 18; |
| 143 | unsigned NRR = Target.getABI() == "avrtiny" ? 4 : 8; |
| 144 | return createAVRTargetCodeGenInfo(CGM, NPR, NRR); |
| 145 | } |
| 146 | |
| 147 | case llvm::Triple::aarch64: |
| 148 | case llvm::Triple::aarch64_32: |
| 149 | case llvm::Triple::aarch64_be: { |
| 150 | AArch64ABIKind Kind = AArch64ABIKind::AAPCS; |
| 151 | if (Target.getABI() == "darwinpcs" ) |
| 152 | Kind = AArch64ABIKind::DarwinPCS; |
| 153 | else if (Triple.isOSWindows()) |
| 154 | return createWindowsAArch64TargetCodeGenInfo(CGM, K: AArch64ABIKind::Win64); |
| 155 | else if (Target.getABI() == "aapcs-soft" ) |
| 156 | Kind = AArch64ABIKind::AAPCSSoft; |
| 157 | |
| 158 | return createAArch64TargetCodeGenInfo(CGM, Kind); |
| 159 | } |
| 160 | |
| 161 | case llvm::Triple::wasm32: |
| 162 | case llvm::Triple::wasm64: { |
| 163 | WebAssemblyABIKind Kind = WebAssemblyABIKind::MVP; |
| 164 | if (Target.getABI() == "experimental-mv" ) |
| 165 | Kind = WebAssemblyABIKind::ExperimentalMV; |
| 166 | return createWebAssemblyTargetCodeGenInfo(CGM, K: Kind); |
| 167 | } |
| 168 | |
| 169 | case llvm::Triple::arm: |
| 170 | case llvm::Triple::armeb: |
| 171 | case llvm::Triple::thumb: |
| 172 | case llvm::Triple::thumbeb: { |
| 173 | if (Triple.getOS() == llvm::Triple::Win32) |
| 174 | return createWindowsARMTargetCodeGenInfo(CGM, K: ARMABIKind::AAPCS_VFP); |
| 175 | |
| 176 | ARMABIKind Kind = ARMABIKind::AAPCS; |
| 177 | StringRef ABIStr = Target.getABI(); |
| 178 | if (ABIStr == "apcs-gnu" ) |
| 179 | Kind = ARMABIKind::APCS; |
| 180 | else if (ABIStr == "aapcs16" ) |
| 181 | Kind = ARMABIKind::AAPCS16_VFP; |
| 182 | else if (CodeGenOpts.FloatABI == "hard" || |
| 183 | (CodeGenOpts.FloatABI != "soft" && Triple.isHardFloatABI())) |
| 184 | Kind = ARMABIKind::AAPCS_VFP; |
| 185 | |
| 186 | return createARMTargetCodeGenInfo(CGM, Kind); |
| 187 | } |
| 188 | |
| 189 | case llvm::Triple::ppc: { |
| 190 | if (Triple.isOSAIX()) |
| 191 | return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/false); |
| 192 | |
| 193 | bool IsSoftFloat = |
| 194 | CodeGenOpts.FloatABI == "soft" || Target.hasFeature(Feature: "spe" ); |
| 195 | return createPPC32TargetCodeGenInfo(CGM, SoftFloatABI: IsSoftFloat); |
| 196 | } |
| 197 | case llvm::Triple::ppcle: { |
| 198 | bool IsSoftFloat = |
| 199 | CodeGenOpts.FloatABI == "soft" || Target.hasFeature(Feature: "spe" ); |
| 200 | return createPPC32TargetCodeGenInfo(CGM, SoftFloatABI: IsSoftFloat); |
| 201 | } |
| 202 | case llvm::Triple::ppc64: |
| 203 | if (Triple.isOSAIX()) |
| 204 | return createAIXTargetCodeGenInfo(CGM, /*Is64Bit=*/true); |
| 205 | |
| 206 | if (Triple.isOSBinFormatELF()) { |
| 207 | PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv1; |
| 208 | if (Target.getABI() == "elfv2" ) |
| 209 | Kind = PPC64_SVR4_ABIKind::ELFv2; |
| 210 | bool IsSoftFloat = CodeGenOpts.FloatABI == "soft" ; |
| 211 | |
| 212 | return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, SoftFloatABI: IsSoftFloat); |
| 213 | } |
| 214 | return createPPC64TargetCodeGenInfo(CGM); |
| 215 | case llvm::Triple::ppc64le: { |
| 216 | assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!" ); |
| 217 | PPC64_SVR4_ABIKind Kind = PPC64_SVR4_ABIKind::ELFv2; |
| 218 | if (Target.getABI() == "elfv1" ) |
| 219 | Kind = PPC64_SVR4_ABIKind::ELFv1; |
| 220 | bool IsSoftFloat = CodeGenOpts.FloatABI == "soft" ; |
| 221 | |
| 222 | return createPPC64_SVR4_TargetCodeGenInfo(CGM, Kind, SoftFloatABI: IsSoftFloat); |
| 223 | } |
| 224 | |
| 225 | case llvm::Triple::nvptx: |
| 226 | case llvm::Triple::nvptx64: |
| 227 | return createNVPTXTargetCodeGenInfo(CGM); |
| 228 | |
| 229 | case llvm::Triple::msp430: |
| 230 | return createMSP430TargetCodeGenInfo(CGM); |
| 231 | |
| 232 | case llvm::Triple::riscv32: |
| 233 | case llvm::Triple::riscv64: |
| 234 | case llvm::Triple::riscv32be: |
| 235 | case llvm::Triple::riscv64be: { |
| 236 | StringRef ABIStr = Target.getABI(); |
| 237 | unsigned XLen = Target.getPointerWidth(AddrSpace: LangAS::Default); |
| 238 | unsigned ABIFLen = 0; |
| 239 | if (ABIStr.ends_with(Suffix: "f" )) |
| 240 | ABIFLen = 32; |
| 241 | else if (ABIStr.ends_with(Suffix: "d" )) |
| 242 | ABIFLen = 64; |
| 243 | bool EABI = ABIStr.ends_with(Suffix: "e" ); |
| 244 | return createRISCVTargetCodeGenInfo(CGM, XLen, FLen: ABIFLen, EABI); |
| 245 | } |
| 246 | |
| 247 | case llvm::Triple::systemz: { |
| 248 | bool SoftFloat = CodeGenOpts.FloatABI == "soft" ; |
| 249 | bool HasVector = !SoftFloat && Target.getABI() == "vector" ; |
| 250 | if (Triple.getOS() == llvm::Triple::ZOS) |
| 251 | return createSystemZ_ZOS_TargetCodeGenInfo(CGM, HasVector, SoftFloatABI: SoftFloat); |
| 252 | return createSystemZTargetCodeGenInfo(CGM, HasVector, SoftFloatABI: SoftFloat); |
| 253 | } |
| 254 | |
| 255 | case llvm::Triple::tce: |
| 256 | case llvm::Triple::tcele: |
| 257 | case llvm::Triple::tcele64: |
| 258 | return createTCETargetCodeGenInfo(CGM); |
| 259 | |
| 260 | case llvm::Triple::x86: { |
| 261 | bool IsDarwinVectorABI = Triple.isOSDarwin(); |
| 262 | bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing(); |
| 263 | |
| 264 | if (Triple.getOS() == llvm::Triple::Win32) { |
| 265 | return createWinX86_32TargetCodeGenInfo( |
| 266 | CGM, DarwinVectorABI: IsDarwinVectorABI, Win32StructABI: IsWin32FloatStructABI, |
| 267 | NumRegisterParameters: CodeGenOpts.NumRegisterParameters); |
| 268 | } |
| 269 | return createX86_32TargetCodeGenInfo( |
| 270 | CGM, DarwinVectorABI: IsDarwinVectorABI, Win32StructABI: IsWin32FloatStructABI, |
| 271 | NumRegisterParameters: CodeGenOpts.NumRegisterParameters, SoftFloatABI: CodeGenOpts.FloatABI == "soft" ); |
| 272 | } |
| 273 | |
| 274 | case llvm::Triple::x86_64: { |
| 275 | StringRef ABI = Target.getABI(); |
| 276 | X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 |
| 277 | : ABI == "avx" ? X86AVXABILevel::AVX |
| 278 | : X86AVXABILevel::None); |
| 279 | |
| 280 | switch (Triple.getOS()) { |
| 281 | case llvm::Triple::UEFI: |
| 282 | case llvm::Triple::Win32: |
| 283 | return createWinX86_64TargetCodeGenInfo(CGM, AVXLevel); |
| 284 | default: |
| 285 | return createX86_64TargetCodeGenInfo(CGM, AVXLevel); |
| 286 | } |
| 287 | } |
| 288 | case llvm::Triple::hexagon: |
| 289 | return createHexagonTargetCodeGenInfo(CGM); |
| 290 | case llvm::Triple::lanai: |
| 291 | return createLanaiTargetCodeGenInfo(CGM); |
| 292 | case llvm::Triple::r600: |
| 293 | return createAMDGPUTargetCodeGenInfo(CGM); |
| 294 | case llvm::Triple::amdgcn: |
| 295 | return createAMDGPUTargetCodeGenInfo(CGM); |
| 296 | case llvm::Triple::sparc: |
| 297 | return createSparcV8TargetCodeGenInfo(CGM); |
| 298 | case llvm::Triple::sparcv9: |
| 299 | return createSparcV9TargetCodeGenInfo(CGM); |
| 300 | case llvm::Triple::xcore: |
| 301 | return createXCoreTargetCodeGenInfo(CGM); |
| 302 | case llvm::Triple::arc: |
| 303 | return createARCTargetCodeGenInfo(CGM); |
| 304 | case llvm::Triple::spir: |
| 305 | case llvm::Triple::spir64: |
| 306 | return createCommonSPIRTargetCodeGenInfo(CGM); |
| 307 | case llvm::Triple::spirv32: |
| 308 | case llvm::Triple::spirv64: |
| 309 | case llvm::Triple::spirv: |
| 310 | return createSPIRVTargetCodeGenInfo(CGM); |
| 311 | case llvm::Triple::dxil: |
| 312 | return createDirectXTargetCodeGenInfo(CGM); |
| 313 | case llvm::Triple::ve: |
| 314 | return createVETargetCodeGenInfo(CGM); |
| 315 | case llvm::Triple::csky: { |
| 316 | bool IsSoftFloat = !Target.hasFeature(Feature: "hard-float-abi" ); |
| 317 | bool hasFP64 = |
| 318 | Target.hasFeature(Feature: "fpuv2_df" ) || Target.hasFeature(Feature: "fpuv3_df" ); |
| 319 | return createCSKYTargetCodeGenInfo(CGM, FLen: IsSoftFloat ? 0 |
| 320 | : hasFP64 ? 64 |
| 321 | : 32); |
| 322 | } |
| 323 | case llvm::Triple::bpfeb: |
| 324 | case llvm::Triple::bpfel: |
| 325 | return createBPFTargetCodeGenInfo(CGM); |
| 326 | case llvm::Triple::loongarch32: |
| 327 | case llvm::Triple::loongarch64: { |
| 328 | StringRef ABIStr = Target.getABI(); |
| 329 | unsigned ABIFRLen = 0; |
| 330 | if (ABIStr.ends_with(Suffix: "f" )) |
| 331 | ABIFRLen = 32; |
| 332 | else if (ABIStr.ends_with(Suffix: "d" )) |
| 333 | ABIFRLen = 64; |
| 334 | return createLoongArchTargetCodeGenInfo( |
| 335 | CGM, GRLen: Target.getPointerWidth(AddrSpace: LangAS::Default), FLen: ABIFRLen); |
| 336 | } |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() { |
| 341 | if (!TheTargetCodeGenInfo) |
| 342 | TheTargetCodeGenInfo = createTargetCodeGenInfo(CGM&: *this); |
| 343 | return *TheTargetCodeGenInfo; |
| 344 | } |
| 345 | |
| 346 | bool CodeGenModule::shouldUseLLVMABILowering() const { |
| 347 | if (!CodeGenOpts.ExperimentalABILowering) |
| 348 | return false; |
| 349 | // Only opt in for targets that have an LLVMABI implementation; others |
| 350 | // continue through the legacy ABIInfo path. |
| 351 | return getTriple().isBPF(); |
| 352 | } |
| 353 | |
| 354 | const llvm::abi::TargetInfo & |
| 355 | CodeGenModule::getLLVMABITargetInfo(llvm::abi::TypeBuilder &TB) { |
| 356 | if (TheLLVMABITargetInfo) |
| 357 | return *TheLLVMABITargetInfo; |
| 358 | |
| 359 | assert(getTriple().isBPF() && |
| 360 | "LLVMABI lowering requested for an unsupported target" ); |
| 361 | TheLLVMABITargetInfo = llvm::abi::createBPFTargetInfo(TB); |
| 362 | return *TheLLVMABITargetInfo; |
| 363 | } |
| 364 | |
| 365 | static void checkDataLayoutConsistency(const TargetInfo &Target, |
| 366 | llvm::LLVMContext &Context, |
| 367 | const LangOptions &Opts) { |
| 368 | #ifndef NDEBUG |
| 369 | // Don't verify non-standard ABI configurations. |
| 370 | if (Opts.AlignDouble || Opts.OpenCL) |
| 371 | return; |
| 372 | |
| 373 | llvm::Triple Triple = Target.getTriple(); |
| 374 | llvm::DataLayout DL(Target.getDataLayoutString()); |
| 375 | auto Check = [&](const char *Name, llvm::Type *Ty, unsigned Alignment) { |
| 376 | llvm::Align DLAlign = DL.getABITypeAlign(Ty); |
| 377 | llvm::Align ClangAlign(Alignment / 8); |
| 378 | if (DLAlign != ClangAlign) { |
| 379 | llvm::errs() << "For target " << Triple.str() << " type " << Name |
| 380 | << " mapping to " << *Ty << " has data layout alignment " |
| 381 | << DLAlign.value() << " while clang specifies " |
| 382 | << ClangAlign.value() << "\n" ; |
| 383 | abort(); |
| 384 | } |
| 385 | }; |
| 386 | |
| 387 | Check("bool" , llvm::Type::getIntNTy(Context, Target.BoolWidth), |
| 388 | Target.BoolAlign); |
| 389 | Check("short" , llvm::Type::getIntNTy(Context, Target.ShortWidth), |
| 390 | Target.ShortAlign); |
| 391 | Check("int" , llvm::Type::getIntNTy(Context, Target.IntWidth), |
| 392 | Target.IntAlign); |
| 393 | Check("long" , llvm::Type::getIntNTy(Context, Target.LongWidth), |
| 394 | Target.LongAlign); |
| 395 | // FIXME: M68k specifies incorrect long long alignment in both LLVM and Clang. |
| 396 | if (Triple.getArch() != llvm::Triple::m68k) |
| 397 | Check("long long" , llvm::Type::getIntNTy(Context, Target.LongLongWidth), |
| 398 | Target.LongLongAlign); |
| 399 | // FIXME: There are int128 alignment mismatches on multiple targets. |
| 400 | if (Target.hasInt128Type() && !Target.getTargetOpts().ForceEnableInt128 && |
| 401 | !Triple.isAMDGPU() && !Triple.isSPIRV() && |
| 402 | Triple.getArch() != llvm::Triple::ve) |
| 403 | Check("__int128" , llvm::Type::getIntNTy(Context, 128), Target.Int128Align); |
| 404 | |
| 405 | if (Target.hasFloat16Type()) |
| 406 | Check("half" , llvm::Type::getFloatingPointTy(Context, *Target.HalfFormat), |
| 407 | Target.HalfAlign); |
| 408 | if (Target.hasBFloat16Type()) |
| 409 | Check("bfloat" , llvm::Type::getBFloatTy(Context), Target.BFloat16Align); |
| 410 | Check("float" , llvm::Type::getFloatingPointTy(Context, *Target.FloatFormat), |
| 411 | Target.FloatAlign); |
| 412 | Check("double" , llvm::Type::getFloatingPointTy(Context, *Target.DoubleFormat), |
| 413 | Target.DoubleAlign); |
| 414 | Check("long double" , |
| 415 | llvm::Type::getFloatingPointTy(Context, *Target.LongDoubleFormat), |
| 416 | Target.LongDoubleAlign); |
| 417 | if (Target.hasFloat128Type()) |
| 418 | Check("__float128" , llvm::Type::getFP128Ty(Context), Target.Float128Align); |
| 419 | if (Target.hasIbm128Type()) |
| 420 | Check("__ibm128" , llvm::Type::getPPC_FP128Ty(Context), Target.Ibm128Align); |
| 421 | |
| 422 | Check("void*" , llvm::PointerType::getUnqual(Context), Target.PointerAlign); |
| 423 | |
| 424 | if (Target.vectorsAreElementAligned() != DL.vectorsAreElementAligned()) { |
| 425 | llvm::errs() << "Datalayout for target " << Triple.str() |
| 426 | << " sets element-aligned vectors to '" |
| 427 | << Target.vectorsAreElementAligned() |
| 428 | << "' but clang specifies '" << DL.vectorsAreElementAligned() |
| 429 | << "'\n" ; |
| 430 | abort(); |
| 431 | } |
| 432 | #endif |
| 433 | } |
| 434 | |
| 435 | CodeGenModule::(ASTContext &C, |
| 436 | IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS, |
| 437 | const HeaderSearchOptions &HSO, |
| 438 | const PreprocessorOptions &PPO, |
| 439 | const CodeGenOptions &CGO, llvm::Module &M, |
| 440 | DiagnosticsEngine &diags, |
| 441 | CoverageSourceInfo *CoverageInfo) |
| 442 | : Context(C), LangOpts(C.getLangOpts()), FS(FS), HeaderSearchOpts(HSO), |
| 443 | PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), |
| 444 | Target(C.getTargetInfo()), ABI(createCXXABI(CGM&: *this)), |
| 445 | VMContext(M.getContext()), VTables(*this), StackHandler(diags), |
| 446 | SanitizerMD(new SanitizerMetadata(*this)), |
| 447 | AtomicOpts(Target.getAtomicOpts()) { |
| 448 | |
| 449 | AbiMapper = std::make_unique<QualTypeMapper>(args&: C, args: M.getDataLayout(), args&: AbiAlloc); |
| 450 | AbiReverseMapper = std::make_unique<llvm::abi::IRTypeMapper>( |
| 451 | args&: M.getContext(), args: M.getDataLayout()); |
| 452 | |
| 453 | // Initialize the type cache. |
| 454 | Types.reset(p: new CodeGenTypes(*this)); |
| 455 | llvm::LLVMContext &LLVMContext = M.getContext(); |
| 456 | VoidTy = llvm::Type::getVoidTy(C&: LLVMContext); |
| 457 | Int8Ty = llvm::Type::getInt8Ty(C&: LLVMContext); |
| 458 | Int16Ty = llvm::Type::getInt16Ty(C&: LLVMContext); |
| 459 | Int32Ty = llvm::Type::getInt32Ty(C&: LLVMContext); |
| 460 | Int64Ty = llvm::Type::getInt64Ty(C&: LLVMContext); |
| 461 | HalfTy = llvm::Type::getHalfTy(C&: LLVMContext); |
| 462 | BFloatTy = llvm::Type::getBFloatTy(C&: LLVMContext); |
| 463 | FloatTy = llvm::Type::getFloatTy(C&: LLVMContext); |
| 464 | DoubleTy = llvm::Type::getDoubleTy(C&: LLVMContext); |
| 465 | PointerWidthInBits = C.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default); |
| 466 | PointerAlignInBytes = |
| 467 | C.toCharUnitsFromBits(BitSize: C.getTargetInfo().getPointerAlign(AddrSpace: LangAS::Default)) |
| 468 | .getQuantity(); |
| 469 | SizeSizeInBytes = |
| 470 | C.toCharUnitsFromBits(BitSize: C.getTargetInfo().getMaxPointerWidth()).getQuantity(); |
| 471 | IntAlignInBytes = |
| 472 | C.toCharUnitsFromBits(BitSize: C.getTargetInfo().getIntAlign()).getQuantity(); |
| 473 | CharTy = |
| 474 | llvm::IntegerType::get(C&: LLVMContext, NumBits: C.getTargetInfo().getCharWidth()); |
| 475 | IntTy = llvm::IntegerType::get(C&: LLVMContext, NumBits: C.getTargetInfo().getIntWidth()); |
| 476 | IntPtrTy = llvm::IntegerType::get(C&: LLVMContext, |
| 477 | NumBits: C.getTargetInfo().getMaxPointerWidth()); |
| 478 | Int8PtrTy = llvm::PointerType::get(C&: LLVMContext, |
| 479 | AddressSpace: C.getTargetAddressSpace(AS: LangAS::Default)); |
| 480 | const llvm::DataLayout &DL = M.getDataLayout(); |
| 481 | AllocaInt8PtrTy = |
| 482 | llvm::PointerType::get(C&: LLVMContext, AddressSpace: DL.getAllocaAddrSpace()); |
| 483 | GlobalsInt8PtrTy = |
| 484 | llvm::PointerType::get(C&: LLVMContext, AddressSpace: DL.getDefaultGlobalsAddressSpace()); |
| 485 | ProgramPtrTy = |
| 486 | llvm::PointerType::get(C&: LLVMContext, AddressSpace: DL.getProgramAddressSpace()); |
| 487 | ConstGlobalsPtrTy = llvm::PointerType::get( |
| 488 | C&: LLVMContext, AddressSpace: C.getTargetAddressSpace(AS: GetGlobalConstantAddressSpace())); |
| 489 | |
| 490 | // Build C++20 Module initializers. |
| 491 | // TODO: Add Microsoft here once we know the mangling required for the |
| 492 | // initializers. |
| 493 | CXX20ModuleInits = |
| 494 | LangOpts.CPlusPlusModules && getCXXABI().getMangleContext().getKind() == |
| 495 | ItaniumMangleContext::MK_Itanium; |
| 496 | |
| 497 | RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); |
| 498 | |
| 499 | if (LangOpts.ObjC) |
| 500 | createObjCRuntime(); |
| 501 | if (LangOpts.OpenCL) |
| 502 | createOpenCLRuntime(); |
| 503 | if (LangOpts.OpenMP) |
| 504 | createOpenMPRuntime(); |
| 505 | if (LangOpts.CUDA) |
| 506 | createCUDARuntime(); |
| 507 | if (LangOpts.HLSL) |
| 508 | createHLSLRuntime(); |
| 509 | |
| 510 | // Enable TBAA unless it's suppressed. TSan and TySan need TBAA even at O0. |
| 511 | if (LangOpts.Sanitize.hasOneOf(K: SanitizerKind::Thread | SanitizerKind::Type) || |
| 512 | (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) |
| 513 | TBAA.reset(p: new CodeGenTBAA(Context, getTypes(), TheModule, CodeGenOpts, |
| 514 | getLangOpts())); |
| 515 | |
| 516 | // If debug info or coverage generation is enabled, create the CGDebugInfo |
| 517 | // object. |
| 518 | if (CodeGenOpts.getDebugInfo() != llvm::codegenoptions::NoDebugInfo || |
| 519 | CodeGenOpts.CoverageNotesFile.size() || |
| 520 | CodeGenOpts.CoverageDataFile.size()) |
| 521 | DebugInfo.reset(p: new CGDebugInfo(*this)); |
| 522 | else if (getTriple().isOSWindows()) |
| 523 | // On Windows targets, we want to emit compiler info even if debug info is |
| 524 | // otherwise disabled. Use a temporary CGDebugInfo instance to emit only |
| 525 | // basic compiler metadata. |
| 526 | CGDebugInfo(*this); |
| 527 | |
| 528 | Block.GlobalUniqueCount = 0; |
| 529 | |
| 530 | if (C.getLangOpts().ObjC) |
| 531 | ObjCData.reset(p: new ObjCEntrypoints()); |
| 532 | |
| 533 | if (CodeGenOpts.hasProfileClangUse()) { |
| 534 | auto ReaderOrErr = llvm::IndexedInstrProfReader::create( |
| 535 | Path: CodeGenOpts.ProfileInstrumentUsePath, FS&: *FS, |
| 536 | RemappingPath: CodeGenOpts.ProfileRemappingFile); |
| 537 | if (auto E = ReaderOrErr.takeError()) { |
| 538 | llvm::handleAllErrors(E: std::move(E), Handlers: [&](const llvm::ErrorInfoBase &EI) { |
| 539 | Diags.Report(DiagID: diag::err_reading_profile) |
| 540 | << CodeGenOpts.ProfileInstrumentUsePath << EI.message(); |
| 541 | }); |
| 542 | return; |
| 543 | } |
| 544 | PGOReader = std::move(ReaderOrErr.get()); |
| 545 | } |
| 546 | |
| 547 | // If coverage mapping generation is enabled, create the |
| 548 | // CoverageMappingModuleGen object. |
| 549 | if (CodeGenOpts.CoverageMapping) |
| 550 | CoverageMapping.reset(p: new CoverageMappingModuleGen(*this, *CoverageInfo)); |
| 551 | |
| 552 | // Generate the module name hash here if needed. |
| 553 | if (CodeGenOpts.UniqueInternalLinkageNames && |
| 554 | !getModule().getSourceFileName().empty()) { |
| 555 | SmallString<256> Path(getModule().getSourceFileName()); |
| 556 | // Check if a path substitution is needed from the MacroPrefixMap. |
| 557 | clang::Preprocessor::processPathForFileMacro(Path, LangOpts, |
| 558 | TI: Context.getTargetInfo()); |
| 559 | ModuleNameHash = llvm::getUniqueInternalLinkagePostfix(FName: Path); |
| 560 | } |
| 561 | |
| 562 | // Record mregparm value now so it is visible through all of codegen. |
| 563 | if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) |
| 564 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "NumRegisterParameters" , |
| 565 | Val: CodeGenOpts.NumRegisterParameters); |
| 566 | |
| 567 | // If there are any functions that are marked for Windows secure hot-patching, |
| 568 | // then build the list of functions now. |
| 569 | if (!CGO.MSSecureHotPatchFunctionsFile.empty() || |
| 570 | !CGO.MSSecureHotPatchFunctionsList.empty()) { |
| 571 | if (!CGO.MSSecureHotPatchFunctionsFile.empty()) { |
| 572 | auto BufOrErr = FS->getBufferForFile(Name: CGO.MSSecureHotPatchFunctionsFile); |
| 573 | if (BufOrErr) { |
| 574 | const llvm::MemoryBuffer &FileBuffer = **BufOrErr; |
| 575 | for (llvm::line_iterator I(FileBuffer.getMemBufferRef(), true), E; |
| 576 | I != E; ++I) |
| 577 | this->MSHotPatchFunctions.push_back(x: std::string{*I}); |
| 578 | } else { |
| 579 | auto &DE = Context.getDiagnostics(); |
| 580 | DE.Report(DiagID: diag::err_open_hotpatch_file_failed) |
| 581 | << CGO.MSSecureHotPatchFunctionsFile |
| 582 | << BufOrErr.getError().message(); |
| 583 | } |
| 584 | } |
| 585 | |
| 586 | for (const auto &FuncName : CGO.MSSecureHotPatchFunctionsList) |
| 587 | this->MSHotPatchFunctions.push_back(x: FuncName); |
| 588 | |
| 589 | llvm::sort(C&: this->MSHotPatchFunctions); |
| 590 | } |
| 591 | |
| 592 | if (!Context.getAuxTargetInfo()) |
| 593 | checkDataLayoutConsistency(Target: Context.getTargetInfo(), Context&: LLVMContext, Opts: LangOpts); |
| 594 | } |
| 595 | |
| 596 | CodeGenModule::~CodeGenModule() {} |
| 597 | |
| 598 | void CodeGenModule::createObjCRuntime() { |
| 599 | // This is just isGNUFamily(), but we want to force implementors of |
| 600 | // new ABIs to decide how best to do this. |
| 601 | switch (LangOpts.ObjCRuntime.getKind()) { |
| 602 | case ObjCRuntime::GNUstep: |
| 603 | case ObjCRuntime::GCC: |
| 604 | case ObjCRuntime::ObjFW: |
| 605 | ObjCRuntime.reset(p: CreateGNUObjCRuntime(CGM&: *this)); |
| 606 | return; |
| 607 | |
| 608 | case ObjCRuntime::FragileMacOSX: |
| 609 | case ObjCRuntime::MacOSX: |
| 610 | case ObjCRuntime::iOS: |
| 611 | case ObjCRuntime::WatchOS: |
| 612 | ObjCRuntime.reset(p: CreateMacObjCRuntime(CGM&: *this)); |
| 613 | return; |
| 614 | } |
| 615 | llvm_unreachable("bad runtime kind" ); |
| 616 | } |
| 617 | |
| 618 | void CodeGenModule::createOpenCLRuntime() { |
| 619 | OpenCLRuntime.reset(p: new CGOpenCLRuntime(*this)); |
| 620 | } |
| 621 | |
| 622 | void CodeGenModule::createOpenMPRuntime() { |
| 623 | if (!LangOpts.OMPHostIRFile.empty() && !FS->exists(Path: LangOpts.OMPHostIRFile)) |
| 624 | Diags.Report(DiagID: diag::err_omp_host_ir_file_not_found) |
| 625 | << LangOpts.OMPHostIRFile; |
| 626 | |
| 627 | // Select a specialized code generation class based on the target, if any. |
| 628 | // If it does not exist use the default implementation. |
| 629 | switch (getTriple().getArch()) { |
| 630 | case llvm::Triple::nvptx: |
| 631 | case llvm::Triple::nvptx64: |
| 632 | case llvm::Triple::amdgcn: |
| 633 | case llvm::Triple::spirv64: |
| 634 | assert( |
| 635 | getLangOpts().OpenMPIsTargetDevice && |
| 636 | "OpenMP AMDGPU/NVPTX/SPIRV is only prepared to deal with device code." ); |
| 637 | OpenMPRuntime.reset(p: new CGOpenMPRuntimeGPU(*this)); |
| 638 | break; |
| 639 | default: |
| 640 | if (LangOpts.OpenMPSimd) |
| 641 | OpenMPRuntime.reset(p: new CGOpenMPSIMDRuntime(*this)); |
| 642 | else |
| 643 | OpenMPRuntime.reset(p: new CGOpenMPRuntime(*this)); |
| 644 | break; |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | void CodeGenModule::createCUDARuntime() { |
| 649 | CUDARuntime.reset(p: CreateNVCUDARuntime(CGM&: *this)); |
| 650 | } |
| 651 | |
| 652 | void CodeGenModule::createHLSLRuntime() { |
| 653 | HLSLRuntime.reset(p: new CGHLSLRuntime(*this)); |
| 654 | } |
| 655 | |
| 656 | void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { |
| 657 | Replacements[Name] = C; |
| 658 | } |
| 659 | |
| 660 | void CodeGenModule::applyReplacements() { |
| 661 | for (auto &I : Replacements) { |
| 662 | StringRef MangledName = I.first; |
| 663 | llvm::Constant *Replacement = I.second; |
| 664 | llvm::GlobalValue *Entry = GetGlobalValue(Ref: MangledName); |
| 665 | if (!Entry) |
| 666 | continue; |
| 667 | auto *OldF = cast<llvm::Function>(Val: Entry); |
| 668 | auto *NewF = dyn_cast<llvm::Function>(Val: Replacement); |
| 669 | if (!NewF) { |
| 670 | if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Val: Replacement)) { |
| 671 | NewF = dyn_cast<llvm::Function>(Val: Alias->getAliasee()); |
| 672 | } else { |
| 673 | auto *CE = cast<llvm::ConstantExpr>(Val: Replacement); |
| 674 | assert(CE->getOpcode() == llvm::Instruction::BitCast || |
| 675 | CE->getOpcode() == llvm::Instruction::GetElementPtr); |
| 676 | NewF = dyn_cast<llvm::Function>(Val: CE->getOperand(i_nocapture: 0)); |
| 677 | } |
| 678 | } |
| 679 | |
| 680 | // Replace old with new, but keep the old order. |
| 681 | OldF->replaceAllUsesWith(V: Replacement); |
| 682 | if (NewF) { |
| 683 | NewF->removeFromParent(); |
| 684 | OldF->getParent()->getFunctionList().insertAfter(where: OldF->getIterator(), |
| 685 | New: NewF); |
| 686 | } |
| 687 | OldF->eraseFromParent(); |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { |
| 692 | GlobalValReplacements.push_back(Elt: std::make_pair(x&: GV, y&: C)); |
| 693 | } |
| 694 | |
| 695 | void CodeGenModule::applyGlobalValReplacements() { |
| 696 | for (auto &I : GlobalValReplacements) { |
| 697 | llvm::GlobalValue *GV = I.first; |
| 698 | llvm::Constant *C = I.second; |
| 699 | |
| 700 | GV->replaceAllUsesWith(V: C); |
| 701 | GV->eraseFromParent(); |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | // This is only used in aliases that we created and we know they have a |
| 706 | // linear structure. |
| 707 | static const llvm::GlobalValue *getAliasedGlobal(const llvm::GlobalValue *GV) { |
| 708 | const llvm::Constant *C; |
| 709 | if (auto *GA = dyn_cast<llvm::GlobalAlias>(Val: GV)) |
| 710 | C = GA->getAliasee(); |
| 711 | else if (auto *GI = dyn_cast<llvm::GlobalIFunc>(Val: GV)) |
| 712 | C = GI->getResolver(); |
| 713 | else |
| 714 | return GV; |
| 715 | |
| 716 | const auto *AliaseeGV = dyn_cast<llvm::GlobalValue>(Val: C->stripPointerCasts()); |
| 717 | if (!AliaseeGV) |
| 718 | return nullptr; |
| 719 | |
| 720 | const llvm::GlobalValue *FinalGV = AliaseeGV->getAliaseeObject(); |
| 721 | if (FinalGV == GV) |
| 722 | return nullptr; |
| 723 | |
| 724 | return FinalGV; |
| 725 | } |
| 726 | |
| 727 | static bool checkAliasedGlobal( |
| 728 | const ASTContext &Context, DiagnosticsEngine &Diags, SourceLocation Location, |
| 729 | bool IsIFunc, const llvm::GlobalValue *Alias, const llvm::GlobalValue *&GV, |
| 730 | const llvm::MapVector<GlobalDecl, StringRef> &MangledDeclNames, |
| 731 | SourceRange AliasRange) { |
| 732 | GV = getAliasedGlobal(GV: Alias); |
| 733 | if (!GV) { |
| 734 | Diags.Report(Loc: Location, DiagID: diag::err_cyclic_alias) << IsIFunc; |
| 735 | return false; |
| 736 | } |
| 737 | |
| 738 | if (GV->hasCommonLinkage()) { |
| 739 | const llvm::Triple &Triple = Context.getTargetInfo().getTriple(); |
| 740 | if (Triple.getObjectFormat() == llvm::Triple::XCOFF) { |
| 741 | Diags.Report(Loc: Location, DiagID: diag::err_alias_to_common); |
| 742 | return false; |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | if (GV->isDeclaration()) { |
| 747 | Diags.Report(Loc: Location, DiagID: diag::err_alias_to_undefined) << IsIFunc << IsIFunc; |
| 748 | Diags.Report(Loc: Location, DiagID: diag::note_alias_requires_mangled_name) |
| 749 | << IsIFunc << IsIFunc; |
| 750 | // Provide a note if the given function is not found and exists as a |
| 751 | // mangled name. |
| 752 | for (const auto &[Decl, Name] : MangledDeclNames) { |
| 753 | if (const auto *ND = dyn_cast<NamedDecl>(Val: Decl.getDecl())) { |
| 754 | IdentifierInfo *II = ND->getIdentifier(); |
| 755 | if (II && II->getName() == GV->getName()) { |
| 756 | Diags.Report(Loc: Location, DiagID: diag::note_alias_mangled_name_alternative) |
| 757 | << Name |
| 758 | << FixItHint::CreateReplacement( |
| 759 | RemoveRange: AliasRange, |
| 760 | Code: (Twine(IsIFunc ? "ifunc" : "alias" ) + "(\"" + Name + "\")" ) |
| 761 | .str()); |
| 762 | } |
| 763 | } |
| 764 | } |
| 765 | return false; |
| 766 | } |
| 767 | |
| 768 | if (IsIFunc) { |
| 769 | // Check resolver function type. |
| 770 | const auto *F = dyn_cast<llvm::Function>(Val: GV); |
| 771 | if (!F) { |
| 772 | Diags.Report(Loc: Location, DiagID: diag::err_alias_to_undefined) |
| 773 | << IsIFunc << IsIFunc; |
| 774 | return false; |
| 775 | } |
| 776 | |
| 777 | llvm::FunctionType *FTy = F->getFunctionType(); |
| 778 | if (!FTy->getReturnType()->isPointerTy()) { |
| 779 | Diags.Report(Loc: Location, DiagID: diag::err_ifunc_resolver_return); |
| 780 | return false; |
| 781 | } |
| 782 | } |
| 783 | |
| 784 | return true; |
| 785 | } |
| 786 | |
| 787 | // Emit a warning if toc-data attribute is requested for global variables that |
| 788 | // have aliases and remove the toc-data attribute. |
| 789 | static void checkAliasForTocData(llvm::GlobalVariable *GVar, |
| 790 | const CodeGenOptions &CodeGenOpts, |
| 791 | DiagnosticsEngine &Diags, |
| 792 | SourceLocation Location) { |
| 793 | if (GVar->hasAttribute(Kind: "toc-data" )) { |
| 794 | auto GVId = GVar->getName(); |
| 795 | // Is this a global variable specified by the user as local? |
| 796 | if ((llvm::binary_search(Range: CodeGenOpts.TocDataVarsUserSpecified, Value&: GVId))) { |
| 797 | Diags.Report(Loc: Location, DiagID: diag::warn_toc_unsupported_type) |
| 798 | << GVId << "the variable has an alias" ; |
| 799 | } |
| 800 | llvm::AttributeSet CurrAttributes = GVar->getAttributes(); |
| 801 | llvm::AttributeSet NewAttributes = |
| 802 | CurrAttributes.removeAttribute(C&: GVar->getContext(), Kind: "toc-data" ); |
| 803 | GVar->setAttributes(NewAttributes); |
| 804 | } |
| 805 | } |
| 806 | |
| 807 | void CodeGenModule::checkAliases() { |
| 808 | // Check if the constructed aliases are well formed. It is really unfortunate |
| 809 | // that we have to do this in CodeGen, but we only construct mangled names |
| 810 | // and aliases during codegen. |
| 811 | bool Error = false; |
| 812 | DiagnosticsEngine &Diags = getDiags(); |
| 813 | for (const GlobalDecl &GD : Aliases) { |
| 814 | const auto *D = cast<ValueDecl>(Val: GD.getDecl()); |
| 815 | SourceLocation Location; |
| 816 | SourceRange Range; |
| 817 | bool IsIFunc = D->hasAttr<IFuncAttr>(); |
| 818 | if (const Attr *A = D->getDefiningAttr()) { |
| 819 | Location = A->getLocation(); |
| 820 | Range = A->getRange(); |
| 821 | } else |
| 822 | llvm_unreachable("Not an alias or ifunc?" ); |
| 823 | |
| 824 | StringRef MangledName = getMangledName(GD); |
| 825 | llvm::GlobalValue *Alias = GetGlobalValue(Ref: MangledName); |
| 826 | const llvm::GlobalValue *GV = nullptr; |
| 827 | if (!checkAliasedGlobal(Context: getContext(), Diags, Location, IsIFunc, Alias, GV, |
| 828 | MangledDeclNames, AliasRange: Range)) { |
| 829 | Error = true; |
| 830 | continue; |
| 831 | } |
| 832 | |
| 833 | if (!IsIFunc) { |
| 834 | GlobalDecl AliaseeGD; |
| 835 | if (!lookupRepresentativeDecl(MangledName: GV->getName(), Result&: AliaseeGD) || |
| 836 | !isa<VarDecl, FunctionDecl>(Val: AliaseeGD.getDecl())) { |
| 837 | Diags.Report(Loc: Location, DiagID: diag::err_alias_to_undefined) |
| 838 | << IsIFunc << IsIFunc; |
| 839 | Error = true; |
| 840 | continue; |
| 841 | } |
| 842 | |
| 843 | bool AliasIsFuncDecl = isa<FunctionDecl>(Val: D); |
| 844 | bool AliaseeIsFunc = isa<llvm::Function, llvm::GlobalIFunc>(Val: GV); |
| 845 | // Function declarations can only alias functions (including IFUNCs). |
| 846 | // Similarly, variable declarations can only alias variables. |
| 847 | if (AliasIsFuncDecl != AliaseeIsFunc) { |
| 848 | Diags.Report(Loc: Location, DiagID: diag::err_alias_between_function_and_variable) |
| 849 | << AliasIsFuncDecl; |
| 850 | Diags.Report(Loc: AliaseeGD.getDecl()->getLocation(), |
| 851 | DiagID: diag::note_aliasee_declaration); |
| 852 | Error = true; |
| 853 | continue; |
| 854 | } |
| 855 | |
| 856 | // Only report functions. |
| 857 | // Type mismatches for variables can be intentional. |
| 858 | if (AliasIsFuncDecl && AliaseeIsFunc) { |
| 859 | QualType AliasTy = D->getType(); |
| 860 | QualType AliaseeTy = cast<ValueDecl>(Val: AliaseeGD.getDecl())->getType(); |
| 861 | auto shouldReportTypeMismatch = [&]() { |
| 862 | const auto *AliasFTy = |
| 863 | AliasTy.getCanonicalType()->getAs<FunctionType>(); |
| 864 | const auto *AliaseeFTy = |
| 865 | AliaseeTy.getCanonicalType()->getAs<FunctionType>(); |
| 866 | assert(AliasFTy && AliaseeFTy); |
| 867 | if (!Context.typesAreCompatible(T1: AliasFTy->getReturnType(), |
| 868 | T2: AliaseeFTy->getReturnType())) |
| 869 | return true; |
| 870 | const auto *AliasFPTy = dyn_cast<FunctionProtoType>(Val: AliasFTy); |
| 871 | const auto *AliaseeFPTy = dyn_cast<FunctionProtoType>(Val: AliaseeFTy); |
| 872 | // Report variadic vs no-prototype. |
| 873 | if ((AliasFPTy && AliasFPTy->isVariadic() && !AliaseeFPTy) || |
| 874 | (AliaseeFPTy && AliaseeFPTy->isVariadic() && !AliasFPTy)) |
| 875 | return true; |
| 876 | // Do not report aliases with unspecified parameter lists. |
| 877 | if (!AliasFPTy || !AliaseeFPTy) |
| 878 | return false; |
| 879 | // Report if the parameter lists are different. Any other mismatches, |
| 880 | // such as in exception specifications, are ignored. |
| 881 | if (AliasFPTy->getNumParams() != AliaseeFPTy->getNumParams() || |
| 882 | AliasFPTy->isVariadic() != AliaseeFPTy->isVariadic()) |
| 883 | return true; |
| 884 | for (unsigned i = 0; i < AliasFPTy->getNumParams(); ++i) |
| 885 | if (!Context.typesAreCompatible(T1: AliasFPTy->getParamType(i), |
| 886 | T2: AliaseeFPTy->getParamType(i))) |
| 887 | return true; |
| 888 | return false; |
| 889 | }; |
| 890 | if (shouldReportTypeMismatch()) { |
| 891 | Diags.Report(Loc: Location, DiagID: diag::warn_alias_type_mismatch) |
| 892 | << AliasTy << AliaseeTy; |
| 893 | Diags.Report(Loc: AliaseeGD.getDecl()->getLocation(), |
| 894 | DiagID: diag::note_aliasee_declaration); |
| 895 | } |
| 896 | } |
| 897 | } |
| 898 | |
| 899 | if (getContext().getTargetInfo().getTriple().isOSAIX()) |
| 900 | if (const llvm::GlobalVariable *GVar = |
| 901 | dyn_cast<const llvm::GlobalVariable>(Val: GV)) |
| 902 | checkAliasForTocData(GVar: const_cast<llvm::GlobalVariable *>(GVar), |
| 903 | CodeGenOpts: getCodeGenOpts(), Diags, Location); |
| 904 | |
| 905 | llvm::Constant *Aliasee = |
| 906 | IsIFunc ? cast<llvm::GlobalIFunc>(Val: Alias)->getResolver() |
| 907 | : cast<llvm::GlobalAlias>(Val: Alias)->getAliasee(); |
| 908 | |
| 909 | llvm::GlobalValue *AliaseeGV; |
| 910 | if (auto CE = dyn_cast<llvm::ConstantExpr>(Val: Aliasee)) |
| 911 | AliaseeGV = cast<llvm::GlobalValue>(Val: CE->getOperand(i_nocapture: 0)); |
| 912 | else |
| 913 | AliaseeGV = cast<llvm::GlobalValue>(Val: Aliasee); |
| 914 | |
| 915 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { |
| 916 | StringRef AliasSection = SA->getName(); |
| 917 | if (AliasSection != AliaseeGV->getSection()) |
| 918 | Diags.Report(Loc: SA->getLocation(), DiagID: diag::warn_alias_with_section) |
| 919 | << AliasSection << IsIFunc << IsIFunc; |
| 920 | } |
| 921 | |
| 922 | // We have to handle alias to weak aliases in here. LLVM itself disallows |
| 923 | // this since the object semantics would not match the IL one. For |
| 924 | // compatibility with gcc we implement it by just pointing the alias |
| 925 | // to its aliasee's aliasee. We also warn, since the user is probably |
| 926 | // expecting the link to be weak. |
| 927 | if (auto *GA = dyn_cast<llvm::GlobalAlias>(Val: AliaseeGV)) { |
| 928 | if (GA->isInterposable()) { |
| 929 | Diags.Report(Loc: Location, DiagID: diag::warn_alias_to_weak_alias) |
| 930 | << GV->getName() << GA->getName() << IsIFunc; |
| 931 | Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( |
| 932 | C: GA->getAliasee(), Ty: Alias->getType()); |
| 933 | |
| 934 | if (IsIFunc) |
| 935 | cast<llvm::GlobalIFunc>(Val: Alias)->setResolver(Aliasee); |
| 936 | else |
| 937 | cast<llvm::GlobalAlias>(Val: Alias)->setAliasee(Aliasee); |
| 938 | } |
| 939 | } |
| 940 | // ifunc resolvers are usually implemented to run before sanitizer |
| 941 | // initialization. Disable instrumentation to prevent the ordering issue. |
| 942 | if (IsIFunc) |
| 943 | cast<llvm::Function>(Val: Aliasee)->addFnAttr( |
| 944 | Kind: llvm::Attribute::DisableSanitizerInstrumentation); |
| 945 | } |
| 946 | if (!Error) |
| 947 | return; |
| 948 | |
| 949 | for (const GlobalDecl &GD : Aliases) { |
| 950 | StringRef MangledName = getMangledName(GD); |
| 951 | llvm::GlobalValue *Alias = GetGlobalValue(Ref: MangledName); |
| 952 | Alias->replaceAllUsesWith(V: llvm::PoisonValue::get(T: Alias->getType())); |
| 953 | Alias->eraseFromParent(); |
| 954 | } |
| 955 | } |
| 956 | |
| 957 | void CodeGenModule::clear() { |
| 958 | DeferredDeclsToEmit.clear(); |
| 959 | EmittedDeferredDecls.clear(); |
| 960 | DeferredAnnotations.clear(); |
| 961 | if (OpenMPRuntime) |
| 962 | OpenMPRuntime->clear(); |
| 963 | } |
| 964 | |
| 965 | void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, |
| 966 | StringRef MainFile) { |
| 967 | if (!hasDiagnostics()) |
| 968 | return; |
| 969 | if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { |
| 970 | if (MainFile.empty()) |
| 971 | MainFile = "<stdin>" ; |
| 972 | Diags.Report(DiagID: diag::warn_profile_data_unprofiled) << MainFile; |
| 973 | } else { |
| 974 | if (Mismatched > 0) |
| 975 | Diags.Report(DiagID: diag::warn_profile_data_out_of_date) << Visited << Mismatched; |
| 976 | |
| 977 | if (Missing > 0) |
| 978 | Diags.Report(DiagID: diag::warn_profile_data_missing) << Visited << Missing; |
| 979 | } |
| 980 | } |
| 981 | |
| 982 | static std::optional<llvm::GlobalValue::VisibilityTypes> |
| 983 | getLLVMVisibility(clang::LangOptions::VisibilityFromDLLStorageClassKinds K) { |
| 984 | // Map to LLVM visibility. |
| 985 | switch (K) { |
| 986 | case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Keep: |
| 987 | return std::nullopt; |
| 988 | case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Default: |
| 989 | return llvm::GlobalValue::DefaultVisibility; |
| 990 | case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Hidden: |
| 991 | return llvm::GlobalValue::HiddenVisibility; |
| 992 | case clang::LangOptions::VisibilityFromDLLStorageClassKinds::Protected: |
| 993 | return llvm::GlobalValue::ProtectedVisibility; |
| 994 | } |
| 995 | llvm_unreachable("unknown option value!" ); |
| 996 | } |
| 997 | |
| 998 | static void |
| 999 | setLLVMVisibility(llvm::GlobalValue &GV, |
| 1000 | std::optional<llvm::GlobalValue::VisibilityTypes> V) { |
| 1001 | if (!V) |
| 1002 | return; |
| 1003 | |
| 1004 | // Reset DSO locality before setting the visibility. This removes |
| 1005 | // any effects that visibility options and annotations may have |
| 1006 | // had on the DSO locality. Setting the visibility will implicitly set |
| 1007 | // appropriate globals to DSO Local; however, this will be pessimistic |
| 1008 | // w.r.t. to the normal compiler IRGen. |
| 1009 | GV.setDSOLocal(false); |
| 1010 | GV.setVisibility(*V); |
| 1011 | } |
| 1012 | |
| 1013 | static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, |
| 1014 | llvm::Module &M) { |
| 1015 | if (!LO.VisibilityFromDLLStorageClass) |
| 1016 | return; |
| 1017 | |
| 1018 | std::optional<llvm::GlobalValue::VisibilityTypes> DLLExportVisibility = |
| 1019 | getLLVMVisibility(K: LO.getDLLExportVisibility()); |
| 1020 | |
| 1021 | std::optional<llvm::GlobalValue::VisibilityTypes> |
| 1022 | NoDLLStorageClassVisibility = |
| 1023 | getLLVMVisibility(K: LO.getNoDLLStorageClassVisibility()); |
| 1024 | |
| 1025 | std::optional<llvm::GlobalValue::VisibilityTypes> |
| 1026 | ExternDeclDLLImportVisibility = |
| 1027 | getLLVMVisibility(K: LO.getExternDeclDLLImportVisibility()); |
| 1028 | |
| 1029 | std::optional<llvm::GlobalValue::VisibilityTypes> |
| 1030 | ExternDeclNoDLLStorageClassVisibility = |
| 1031 | getLLVMVisibility(K: LO.getExternDeclNoDLLStorageClassVisibility()); |
| 1032 | |
| 1033 | for (llvm::GlobalValue &GV : M.global_values()) { |
| 1034 | if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) |
| 1035 | continue; |
| 1036 | |
| 1037 | if (GV.isDeclarationForLinker()) |
| 1038 | setLLVMVisibility(GV, V: GV.getDLLStorageClass() == |
| 1039 | llvm::GlobalValue::DLLImportStorageClass |
| 1040 | ? ExternDeclDLLImportVisibility |
| 1041 | : ExternDeclNoDLLStorageClassVisibility); |
| 1042 | else |
| 1043 | setLLVMVisibility(GV, V: GV.getDLLStorageClass() == |
| 1044 | llvm::GlobalValue::DLLExportStorageClass |
| 1045 | ? DLLExportVisibility |
| 1046 | : NoDLLStorageClassVisibility); |
| 1047 | |
| 1048 | GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); |
| 1049 | } |
| 1050 | } |
| 1051 | |
| 1052 | static bool isStackProtectorOn(const LangOptions &LangOpts, |
| 1053 | const llvm::Triple &Triple, |
| 1054 | clang::LangOptions::StackProtectorMode Mode) { |
| 1055 | if (Triple.isGPU()) |
| 1056 | return false; |
| 1057 | return LangOpts.getStackProtector() == Mode; |
| 1058 | } |
| 1059 | |
| 1060 | std::optional<llvm::Attribute::AttrKind> |
| 1061 | CodeGenModule::StackProtectorAttribute(const Decl *D) const { |
| 1062 | if (D && D->hasAttr<NoStackProtectorAttr>()) |
| 1063 | ; // Do nothing. |
| 1064 | else if (D && D->hasAttr<StrictGuardStackCheckAttr>() && |
| 1065 | isStackProtectorOn(LangOpts, Triple: getTriple(), Mode: LangOptions::SSPOn)) |
| 1066 | return llvm::Attribute::StackProtectStrong; |
| 1067 | else if (isStackProtectorOn(LangOpts, Triple: getTriple(), Mode: LangOptions::SSPOn)) |
| 1068 | return llvm::Attribute::StackProtect; |
| 1069 | else if (isStackProtectorOn(LangOpts, Triple: getTriple(), Mode: LangOptions::SSPStrong)) |
| 1070 | return llvm::Attribute::StackProtectStrong; |
| 1071 | else if (isStackProtectorOn(LangOpts, Triple: getTriple(), Mode: LangOptions::SSPReq)) |
| 1072 | return llvm::Attribute::StackProtectReq; |
| 1073 | return std::nullopt; |
| 1074 | } |
| 1075 | |
| 1076 | void CodeGenModule::Release() { |
| 1077 | Module *Primary = getContext().getCurrentNamedModule(); |
| 1078 | if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule()) |
| 1079 | EmitModuleInitializers(Primary); |
| 1080 | EmitDeferred(); |
| 1081 | DeferredDecls.insert_range(R&: EmittedDeferredDecls); |
| 1082 | EmittedDeferredDecls.clear(); |
| 1083 | EmitVTablesOpportunistically(); |
| 1084 | applyGlobalValReplacements(); |
| 1085 | applyReplacements(); |
| 1086 | emitMultiVersionFunctions(); |
| 1087 | emitPFPFieldsWithEvaluatedOffset(); |
| 1088 | |
| 1089 | if (Context.getLangOpts().IncrementalExtensions && |
| 1090 | GlobalTopLevelStmtBlockInFlight.first) { |
| 1091 | const TopLevelStmtDecl *TLSD = GlobalTopLevelStmtBlockInFlight.second; |
| 1092 | GlobalTopLevelStmtBlockInFlight.first->FinishFunction(EndLoc: TLSD->getEndLoc()); |
| 1093 | GlobalTopLevelStmtBlockInFlight = {nullptr, nullptr}; |
| 1094 | } |
| 1095 | |
| 1096 | // Module implementations are initialized the same way as a regular TU that |
| 1097 | // imports one or more modules. |
| 1098 | if (CXX20ModuleInits && Primary && Primary->isInterfaceOrPartition()) |
| 1099 | EmitCXXModuleInitFunc(Primary); |
| 1100 | else |
| 1101 | EmitCXXGlobalInitFunc(); |
| 1102 | EmitCXXGlobalCleanUpFunc(); |
| 1103 | registerGlobalDtorsWithAtExit(); |
| 1104 | EmitCXXThreadLocalInitFunc(); |
| 1105 | if (ObjCRuntime) |
| 1106 | if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) |
| 1107 | AddGlobalCtor(Ctor: ObjCInitFunction); |
| 1108 | if (Context.getLangOpts().CUDA && CUDARuntime) { |
| 1109 | if (llvm::Function *CudaCtorFunction = CUDARuntime->finalizeModule()) |
| 1110 | AddGlobalCtor(Ctor: CudaCtorFunction); |
| 1111 | } |
| 1112 | if (OpenMPRuntime) { |
| 1113 | OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); |
| 1114 | OpenMPRuntime->clear(); |
| 1115 | } |
| 1116 | if (PGOReader) { |
| 1117 | getModule().setProfileSummary( |
| 1118 | M: PGOReader->getSummary(/* UseCS */ false).getMD(Context&: VMContext), |
| 1119 | Kind: llvm::ProfileSummary::PSK_Instr); |
| 1120 | if (PGOStats.hasDiagnostics()) |
| 1121 | PGOStats.reportDiagnostics(Diags&: getDiags(), MainFile: getCodeGenOpts().MainFileName); |
| 1122 | } |
| 1123 | llvm::stable_sort(Range&: GlobalCtors, C: [](const Structor &L, const Structor &R) { |
| 1124 | return L.LexOrder < R.LexOrder; |
| 1125 | }); |
| 1126 | EmitCtorList(Fns&: GlobalCtors, GlobalName: "llvm.global_ctors" ); |
| 1127 | EmitCtorList(Fns&: GlobalDtors, GlobalName: "llvm.global_dtors" ); |
| 1128 | EmitGlobalAnnotations(); |
| 1129 | EmitStaticExternCAliases(); |
| 1130 | checkAliases(); |
| 1131 | EmitDeferredUnusedCoverageMappings(); |
| 1132 | CodeGenPGO(*this).setValueProfilingFlag(getModule()); |
| 1133 | CodeGenPGO(*this).setProfileVersion(getModule()); |
| 1134 | if (CoverageMapping) |
| 1135 | CoverageMapping->emit(); |
| 1136 | if (CodeGenOpts.SanitizeCfiCrossDso) { |
| 1137 | CodeGenFunction(*this).EmitCfiCheckFail(); |
| 1138 | CodeGenFunction(*this).EmitCfiCheckStub(); |
| 1139 | } |
| 1140 | if (LangOpts.Sanitize.has(K: SanitizerKind::KCFI)) |
| 1141 | finalizeKCFITypes(); |
| 1142 | emitAtAvailableLinkGuard(); |
| 1143 | if (Context.getTargetInfo().getTriple().isWasm()) |
| 1144 | EmitMainVoidAlias(); |
| 1145 | |
| 1146 | if (getTriple().isAMDGPU() || |
| 1147 | (getTriple().isSPIRV() && getTriple().getVendor() == llvm::Triple::AMD)) { |
| 1148 | // Emit amdhsa_code_object_version module flag, which is code object version |
| 1149 | // times 100. |
| 1150 | if (getTarget().getTargetOpts().CodeObjectVersion != |
| 1151 | llvm::CodeObjectVersionKind::COV_None) { |
| 1152 | getModule().addModuleFlag(Behavior: llvm::Module::Error, |
| 1153 | Key: "amdhsa_code_object_version" , |
| 1154 | Val: getTarget().getTargetOpts().CodeObjectVersion); |
| 1155 | } |
| 1156 | |
| 1157 | // Currently, "-mprintf-kind" option is only supported for HIP |
| 1158 | if (LangOpts.HIP) { |
| 1159 | auto *MDStr = llvm::MDString::get( |
| 1160 | Context&: getLLVMContext(), Str: (getTarget().getTargetOpts().AMDGPUPrintfKindVal == |
| 1161 | TargetOptions::AMDGPUPrintfKind::Hostcall) |
| 1162 | ? "hostcall" |
| 1163 | : "buffered" ); |
| 1164 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "amdgpu_printf_kind" , |
| 1165 | Val: MDStr); |
| 1166 | } |
| 1167 | } |
| 1168 | |
| 1169 | // Emit a global array containing all external kernels or device variables |
| 1170 | // used by host functions and mark it as used for CUDA/HIP. This is necessary |
| 1171 | // to get kernels or device variables in archives linked in even if these |
| 1172 | // kernels or device variables are only used in host functions. |
| 1173 | if (!Context.CUDAExternalDeviceDeclODRUsedByHost.empty()) { |
| 1174 | SmallVector<llvm::Constant *, 8> UsedArray; |
| 1175 | for (auto D : Context.CUDAExternalDeviceDeclODRUsedByHost) { |
| 1176 | GlobalDecl GD; |
| 1177 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
| 1178 | GD = GlobalDecl(FD, KernelReferenceKind::Kernel); |
| 1179 | else |
| 1180 | GD = GlobalDecl(D); |
| 1181 | UsedArray.push_back(Elt: llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( |
| 1182 | C: GetAddrOfGlobal(GD), Ty: Int8PtrTy)); |
| 1183 | } |
| 1184 | |
| 1185 | llvm::ArrayType *ATy = llvm::ArrayType::get(ElementType: Int8PtrTy, NumElements: UsedArray.size()); |
| 1186 | |
| 1187 | auto *GV = new llvm::GlobalVariable( |
| 1188 | getModule(), ATy, false, llvm::GlobalValue::InternalLinkage, |
| 1189 | llvm::ConstantArray::get(T: ATy, V: UsedArray), "__clang_gpu_used_external" ); |
| 1190 | addCompilerUsedGlobal(GV); |
| 1191 | } |
| 1192 | if (LangOpts.HIP) { |
| 1193 | // Emit a unique ID so that host and device binaries from the same |
| 1194 | // compilation unit can be associated. |
| 1195 | auto *GV = new llvm::GlobalVariable( |
| 1196 | getModule(), Int8Ty, false, llvm::GlobalValue::ExternalLinkage, |
| 1197 | llvm::Constant::getNullValue(Ty: Int8Ty), |
| 1198 | "__hip_cuid_" + getContext().getCUIDHash()); |
| 1199 | getSanitizerMetadata()->disableSanitizerForGlobal(GV); |
| 1200 | addCompilerUsedGlobal(GV); |
| 1201 | } |
| 1202 | emitLLVMUsed(); |
| 1203 | if (SanStats) |
| 1204 | SanStats->finish(); |
| 1205 | |
| 1206 | if (CodeGenOpts.Autolink && |
| 1207 | (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { |
| 1208 | EmitModuleLinkOptions(); |
| 1209 | } |
| 1210 | |
| 1211 | // On ELF we pass the dependent library specifiers directly to the linker |
| 1212 | // without manipulating them. This is in contrast to other platforms where |
| 1213 | // they are mapped to a specific linker option by the compiler. This |
| 1214 | // difference is a result of the greater variety of ELF linkers and the fact |
| 1215 | // that ELF linkers tend to handle libraries in a more complicated fashion |
| 1216 | // than on other platforms. This forces us to defer handling the dependent |
| 1217 | // libs to the linker. |
| 1218 | // |
| 1219 | // CUDA/HIP device and host libraries are different. Currently there is no |
| 1220 | // way to differentiate dependent libraries for host or device. Existing |
| 1221 | // usage of #pragma comment(lib, *) is intended for host libraries on |
| 1222 | // Windows. Therefore emit llvm.dependent-libraries only for host. |
| 1223 | if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { |
| 1224 | auto *NMD = getModule().getOrInsertNamedMetadata(Name: "llvm.dependent-libraries" ); |
| 1225 | for (auto *MD : ELFDependentLibraries) |
| 1226 | NMD->addOperand(M: MD); |
| 1227 | } |
| 1228 | |
| 1229 | if (CodeGenOpts.DwarfVersion) { |
| 1230 | getModule().addModuleFlag(Behavior: llvm::Module::Max, Key: "Dwarf Version" , |
| 1231 | Val: CodeGenOpts.DwarfVersion); |
| 1232 | } |
| 1233 | |
| 1234 | if (CodeGenOpts.Dwarf64) |
| 1235 | getModule().addModuleFlag(Behavior: llvm::Module::Max, Key: "DWARF64" , Val: 1); |
| 1236 | |
| 1237 | if (Context.getLangOpts().SemanticInterposition) |
| 1238 | // Require various optimization to respect semantic interposition. |
| 1239 | getModule().setSemanticInterposition(true); |
| 1240 | |
| 1241 | if (CodeGenOpts.EmitCodeView) { |
| 1242 | // Indicate that we want CodeView in the metadata. |
| 1243 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "CodeView" , Val: 1); |
| 1244 | } |
| 1245 | if (CodeGenOpts.CodeViewGHash) { |
| 1246 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "CodeViewGHash" , Val: 1); |
| 1247 | } |
| 1248 | if (CodeGenOpts.ControlFlowGuard) { |
| 1249 | // Function ID tables and checks for Control Flow Guard. |
| 1250 | getModule().addModuleFlag( |
| 1251 | Behavior: llvm::Module::Warning, Key: "cfguard" , |
| 1252 | Val: static_cast<unsigned>(llvm::ControlFlowGuardMode::Enabled)); |
| 1253 | } else if (CodeGenOpts.ControlFlowGuardNoChecks) { |
| 1254 | // Function ID tables for Control Flow Guard. |
| 1255 | getModule().addModuleFlag( |
| 1256 | Behavior: llvm::Module::Warning, Key: "cfguard" , |
| 1257 | Val: static_cast<unsigned>(llvm::ControlFlowGuardMode::TableOnly)); |
| 1258 | } |
| 1259 | if (CodeGenOpts.getWinControlFlowGuardMechanism() != |
| 1260 | llvm::ControlFlowGuardMechanism::Automatic) { |
| 1261 | // Specify the Control Flow Guard mechanism to use on Windows. |
| 1262 | getModule().addModuleFlag( |
| 1263 | Behavior: llvm::Module::Warning, Key: "cfguard-mechanism" , |
| 1264 | Val: static_cast<unsigned>(CodeGenOpts.getWinControlFlowGuardMechanism())); |
| 1265 | } |
| 1266 | if (CodeGenOpts.EHContGuard) { |
| 1267 | // Function ID tables for EH Continuation Guard. |
| 1268 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "ehcontguard" , Val: 1); |
| 1269 | } |
| 1270 | if (Context.getLangOpts().Kernel) { |
| 1271 | // Note if we are compiling with /kernel. |
| 1272 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "ms-kernel" , Val: 1); |
| 1273 | } |
| 1274 | if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { |
| 1275 | // We don't support LTO with 2 with different StrictVTablePointers |
| 1276 | // FIXME: we could support it by stripping all the information introduced |
| 1277 | // by StrictVTablePointers. |
| 1278 | |
| 1279 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "StrictVTablePointers" ,Val: 1); |
| 1280 | |
| 1281 | llvm::Metadata *Ops[2] = { |
| 1282 | llvm::MDString::get(Context&: VMContext, Str: "StrictVTablePointers" ), |
| 1283 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get( |
| 1284 | Ty: llvm::Type::getInt32Ty(C&: VMContext), V: 1))}; |
| 1285 | |
| 1286 | getModule().addModuleFlag(Behavior: llvm::Module::Require, |
| 1287 | Key: "StrictVTablePointersRequirement" , |
| 1288 | Val: llvm::MDNode::get(Context&: VMContext, MDs: Ops)); |
| 1289 | } |
| 1290 | if (getModuleDebugInfo() || getTriple().isOSWindows()) |
| 1291 | // We support a single version in the linked module. The LLVM |
| 1292 | // parser will drop debug info with a different version number |
| 1293 | // (and warn about it, too). |
| 1294 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "Debug Info Version" , |
| 1295 | Val: llvm::DEBUG_METADATA_VERSION); |
| 1296 | |
| 1297 | // We need to record the widths of enums and wchar_t, so that we can generate |
| 1298 | // the correct build attributes in the ARM backend. wchar_size is also used by |
| 1299 | // TargetLibraryInfo. |
| 1300 | uint64_t WCharWidth = |
| 1301 | Context.getTypeSizeInChars(T: Context.getWideCharType()).getQuantity(); |
| 1302 | if (WCharWidth != getTriple().getDefaultWCharSize()) |
| 1303 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "wchar_size" , Val: WCharWidth); |
| 1304 | |
| 1305 | if (getTriple().isOSzOS()) { |
| 1306 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, |
| 1307 | Key: "zos_product_major_version" , |
| 1308 | Val: uint32_t(CLANG_VERSION_MAJOR)); |
| 1309 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, |
| 1310 | Key: "zos_product_minor_version" , |
| 1311 | Val: uint32_t(CLANG_VERSION_MINOR)); |
| 1312 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "zos_product_patchlevel" , |
| 1313 | Val: uint32_t(CLANG_VERSION_PATCHLEVEL)); |
| 1314 | std::string ProductId = getClangVendor() + "clang" ; |
| 1315 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "zos_product_id" , |
| 1316 | Val: llvm::MDString::get(Context&: VMContext, Str: ProductId)); |
| 1317 | |
| 1318 | // Record the language because we need it for the PPA2. |
| 1319 | StringRef lang_str = languageToString( |
| 1320 | L: LangStandard::getLangStandardForKind(K: LangOpts.LangStd).Language); |
| 1321 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "zos_cu_language" , |
| 1322 | Val: llvm::MDString::get(Context&: VMContext, Str: lang_str)); |
| 1323 | |
| 1324 | time_t TT = PreprocessorOpts.SourceDateEpoch |
| 1325 | ? *PreprocessorOpts.SourceDateEpoch |
| 1326 | : std::time(timer: nullptr); |
| 1327 | getModule().addModuleFlag(Behavior: llvm::Module::Max, Key: "zos_translation_time" , |
| 1328 | Val: static_cast<uint64_t>(TT)); |
| 1329 | |
| 1330 | // Multiple modes will be supported here. |
| 1331 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "zos_le_char_mode" , |
| 1332 | Val: llvm::MDString::get(Context&: VMContext, Str: "ascii" )); |
| 1333 | } |
| 1334 | |
| 1335 | llvm::Triple T = Context.getTargetInfo().getTriple(); |
| 1336 | if (T.isARM() || T.isThumb()) { |
| 1337 | // The minimum width of an enum in bytes |
| 1338 | uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; |
| 1339 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "min_enum_size" , Val: EnumWidth); |
| 1340 | } |
| 1341 | |
| 1342 | if (T.isRISCV()) { |
| 1343 | StringRef ABIStr = Target.getABI(); |
| 1344 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
| 1345 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "target-abi" , |
| 1346 | Val: llvm::MDString::get(Context&: Ctx, Str: ABIStr)); |
| 1347 | |
| 1348 | // Add the canonical ISA string as metadata so the backend can set the ELF |
| 1349 | // attributes correctly. We use AppendUnique so LTO will keep all of the |
| 1350 | // unique ISA strings that were linked together. |
| 1351 | const std::vector<std::string> &Features = |
| 1352 | getTarget().getTargetOpts().Features; |
| 1353 | auto ParseResult = |
| 1354 | llvm::RISCVISAInfo::parseFeatures(XLen: T.isRISCV64() ? 64 : 32, Features); |
| 1355 | if (!errorToBool(Err: ParseResult.takeError())) |
| 1356 | getModule().addModuleFlag( |
| 1357 | Behavior: llvm::Module::AppendUnique, Key: "riscv-isa" , |
| 1358 | Val: llvm::MDNode::get( |
| 1359 | Context&: Ctx, MDs: llvm::MDString::get(Context&: Ctx, Str: (*ParseResult)->toString()))); |
| 1360 | } |
| 1361 | |
| 1362 | if (CodeGenOpts.SanitizeCfiCrossDso) { |
| 1363 | // Indicate that we want cross-DSO control flow integrity checks. |
| 1364 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "Cross-DSO CFI" , Val: 1); |
| 1365 | } |
| 1366 | |
| 1367 | if (CodeGenOpts.WholeProgramVTables) { |
| 1368 | // Indicate whether VFE was enabled for this module, so that the |
| 1369 | // vcall_visibility metadata added under whole program vtables is handled |
| 1370 | // appropriately in the optimizer. |
| 1371 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "Virtual Function Elim" , |
| 1372 | Val: CodeGenOpts.VirtualFunctionElimination); |
| 1373 | } |
| 1374 | |
| 1375 | if (LangOpts.Sanitize.has(K: SanitizerKind::CFIICall)) { |
| 1376 | getModule().addModuleFlag(Behavior: llvm::Module::Override, |
| 1377 | Key: "CFI Canonical Jump Tables" , |
| 1378 | Val: CodeGenOpts.SanitizeCfiCanonicalJumpTables); |
| 1379 | } |
| 1380 | |
| 1381 | if (CodeGenOpts.SanitizeCfiICallNormalizeIntegers) { |
| 1382 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "cfi-normalize-integers" , |
| 1383 | Val: 1); |
| 1384 | } |
| 1385 | |
| 1386 | if (!CodeGenOpts.UniqueSourceFileIdentifier.empty()) { |
| 1387 | getModule().addModuleFlag( |
| 1388 | Behavior: llvm::Module::Append, Key: "Unique Source File Identifier" , |
| 1389 | Val: llvm::MDTuple::get( |
| 1390 | Context&: TheModule.getContext(), |
| 1391 | MDs: llvm::MDString::get(Context&: TheModule.getContext(), |
| 1392 | Str: CodeGenOpts.UniqueSourceFileIdentifier))); |
| 1393 | } |
| 1394 | |
| 1395 | if (LangOpts.Sanitize.has(K: SanitizerKind::KCFI)) { |
| 1396 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "kcfi" , Val: 1); |
| 1397 | // KCFI assumes patchable-function-prefix is the same for all indirectly |
| 1398 | // called functions. Store the expected offset for code generation. |
| 1399 | if (CodeGenOpts.PatchableFunctionEntryOffset) |
| 1400 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "kcfi-offset" , |
| 1401 | Val: CodeGenOpts.PatchableFunctionEntryOffset); |
| 1402 | if (CodeGenOpts.SanitizeKcfiArity) |
| 1403 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "kcfi-arity" , Val: 1); |
| 1404 | // Store the hash algorithm choice for use in LLVM passes |
| 1405 | getModule().addModuleFlag( |
| 1406 | Behavior: llvm::Module::Override, Key: "kcfi-hash" , |
| 1407 | Val: llvm::MDString::get( |
| 1408 | Context&: getLLVMContext(), |
| 1409 | Str: llvm::stringifyKCFIHashAlgorithm(Algorithm: CodeGenOpts.SanitizeKcfiHash))); |
| 1410 | } |
| 1411 | |
| 1412 | if (CodeGenOpts.CFProtectionReturn && |
| 1413 | Target.checkCFProtectionReturnSupported(Diags&: getDiags())) { |
| 1414 | // Indicate that we want to instrument return control flow protection. |
| 1415 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "cf-protection-return" , |
| 1416 | Val: 1); |
| 1417 | } |
| 1418 | |
| 1419 | if (CodeGenOpts.CFProtectionBranch && |
| 1420 | Target.checkCFProtectionBranchSupported(Diags&: getDiags())) { |
| 1421 | // Indicate that we want to instrument branch control flow protection. |
| 1422 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "cf-protection-branch" , |
| 1423 | Val: 1); |
| 1424 | |
| 1425 | auto Scheme = CodeGenOpts.getCFBranchLabelScheme(); |
| 1426 | if (Target.checkCFBranchLabelSchemeSupported(Scheme, Diags&: getDiags())) { |
| 1427 | if (Scheme == CFBranchLabelSchemeKind::Default) |
| 1428 | Scheme = Target.getDefaultCFBranchLabelScheme(); |
| 1429 | getModule().addModuleFlag( |
| 1430 | Behavior: llvm::Module::Error, Key: "cf-branch-label-scheme" , |
| 1431 | Val: llvm::MDString::get(Context&: getLLVMContext(), |
| 1432 | Str: getCFBranchLabelSchemeFlagVal(Scheme))); |
| 1433 | } |
| 1434 | } |
| 1435 | |
| 1436 | if (CodeGenOpts.FunctionReturnThunks) |
| 1437 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "function_return_thunk_extern" , Val: 1); |
| 1438 | |
| 1439 | if (CodeGenOpts.IndirectBranchCSPrefix) |
| 1440 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "indirect_branch_cs_prefix" , Val: 1); |
| 1441 | |
| 1442 | // Add module metadata for return address signing (ignoring |
| 1443 | // non-leaf/all) and stack tagging. These are actually turned on by function |
| 1444 | // attributes, but we use module metadata to emit build attributes. This is |
| 1445 | // needed for LTO, where the function attributes are inside bitcode |
| 1446 | // serialised into a global variable by the time build attributes are |
| 1447 | // emitted, so we can't access them. LTO objects could be compiled with |
| 1448 | // different flags therefore module flags are set to "Min" behavior to achieve |
| 1449 | // the same end result of the normal build where e.g BTI is off if any object |
| 1450 | // doesn't support it. |
| 1451 | if (Context.getTargetInfo().hasFeature(Feature: "ptrauth" ) && |
| 1452 | LangOpts.getSignReturnAddressScope() != |
| 1453 | LangOptions::SignReturnAddressScopeKind::None) |
| 1454 | getModule().addModuleFlag(Behavior: llvm::Module::Override, |
| 1455 | Key: "sign-return-address-buildattr" , Val: 1); |
| 1456 | if (LangOpts.Sanitize.has(K: SanitizerKind::MemtagStack)) |
| 1457 | getModule().addModuleFlag(Behavior: llvm::Module::Override, |
| 1458 | Key: "tag-stack-memory-buildattr" , Val: 1); |
| 1459 | |
| 1460 | if (T.isARM() || T.isThumb() || T.isAArch64()) { |
| 1461 | // Previously 1 is used and meant for the backed to derive the function |
| 1462 | // attribute form it. 2 now means function attributes already set for all |
| 1463 | // functions in this module, so no need to propagate those from the module |
| 1464 | // flag. Value is only used in case of LTO module merge because the backend |
| 1465 | // will see all required function attribute set already. Value is used |
| 1466 | // before modules got merged. Any posive value means the feature is active |
| 1467 | // and required binary markings need to be emit accordingly. |
| 1468 | if (LangOpts.BranchTargetEnforcement) |
| 1469 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "branch-target-enforcement" , |
| 1470 | Val: 2); |
| 1471 | if (LangOpts.BranchProtectionPAuthLR) |
| 1472 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "branch-protection-pauth-lr" , |
| 1473 | Val: 2); |
| 1474 | if (LangOpts.GuardedControlStack) |
| 1475 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "guarded-control-stack" , Val: 2); |
| 1476 | if (LangOpts.hasSignReturnAddress()) |
| 1477 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "sign-return-address" , Val: 2); |
| 1478 | if (LangOpts.isSignReturnAddressScopeAll()) |
| 1479 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "sign-return-address-all" , |
| 1480 | Val: 2); |
| 1481 | if (!LangOpts.isSignReturnAddressWithAKey()) |
| 1482 | getModule().addModuleFlag(Behavior: llvm::Module::Min, |
| 1483 | Key: "sign-return-address-with-bkey" , Val: 2); |
| 1484 | |
| 1485 | if (LangOpts.PointerAuthELFGOT) |
| 1486 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "ptrauth-elf-got" , Val: 1); |
| 1487 | |
| 1488 | if (getTriple().isOSLinux()) { |
| 1489 | if (LangOpts.PointerAuthCalls) |
| 1490 | getModule().addModuleFlag(Behavior: llvm::Module::Error, |
| 1491 | Key: "ptrauth-sign-personality" , Val: 1); |
| 1492 | assert(getTriple().isOSBinFormatELF()); |
| 1493 | using namespace llvm::ELF; |
| 1494 | uint64_t PAuthABIVersion = |
| 1495 | (LangOpts.PointerAuthIntrinsics |
| 1496 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INTRINSICS) | |
| 1497 | (LangOpts.PointerAuthCalls |
| 1498 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_CALLS) | |
| 1499 | (LangOpts.PointerAuthReturns |
| 1500 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_RETURNS) | |
| 1501 | (LangOpts.PointerAuthAuthTraps |
| 1502 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_AUTHTRAPS) | |
| 1503 | (LangOpts.PointerAuthVTPtrAddressDiscrimination |
| 1504 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRADDRDISCR) | |
| 1505 | (LangOpts.PointerAuthVTPtrTypeDiscrimination |
| 1506 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_VPTRTYPEDISCR) | |
| 1507 | (LangOpts.PointerAuthInitFini |
| 1508 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINI) | |
| 1509 | (LangOpts.PointerAuthInitFiniAddressDiscrimination |
| 1510 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_INITFINIADDRDISC) | |
| 1511 | (LangOpts.PointerAuthELFGOT |
| 1512 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOT) | |
| 1513 | (LangOpts.PointerAuthIndirectGotos |
| 1514 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_GOTOS) | |
| 1515 | (LangOpts.PointerAuthTypeInfoVTPtrDiscrimination |
| 1516 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_TYPEINFOVPTRDISCR) | |
| 1517 | (LangOpts.PointerAuthFunctionTypeDiscrimination |
| 1518 | << AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR); |
| 1519 | static_assert(AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_FPTRTYPEDISCR == |
| 1520 | AARCH64_PAUTH_PLATFORM_LLVM_LINUX_VERSION_LAST, |
| 1521 | "Update when new enum items are defined" ); |
| 1522 | if (PAuthABIVersion != 0) { |
| 1523 | getModule().addModuleFlag(Behavior: llvm::Module::Error, |
| 1524 | Key: "aarch64-elf-pauthabi-platform" , |
| 1525 | Val: AARCH64_PAUTH_PLATFORM_LLVM_LINUX); |
| 1526 | getModule().addModuleFlag(Behavior: llvm::Module::Error, |
| 1527 | Key: "aarch64-elf-pauthabi-version" , |
| 1528 | Val: PAuthABIVersion); |
| 1529 | } |
| 1530 | } |
| 1531 | } |
| 1532 | if ((T.isARM() || T.isThumb()) && getTriple().isTargetAEABI() && |
| 1533 | getTriple().isOSBinFormatELF()) { |
| 1534 | uint32_t TagVal = 0; |
| 1535 | llvm::Module::ModFlagBehavior DenormalTagBehavior = llvm::Module::Max; |
| 1536 | if (getCodeGenOpts().FPDenormalMode == |
| 1537 | llvm::DenormalMode::getPositiveZero()) { |
| 1538 | TagVal = llvm::ARMBuildAttrs::PositiveZero; |
| 1539 | } else if (getCodeGenOpts().FPDenormalMode == |
| 1540 | llvm::DenormalMode::getIEEE()) { |
| 1541 | TagVal = llvm::ARMBuildAttrs::IEEEDenormals; |
| 1542 | DenormalTagBehavior = llvm::Module::Override; |
| 1543 | } else if (getCodeGenOpts().FPDenormalMode == |
| 1544 | llvm::DenormalMode::getPreserveSign()) { |
| 1545 | TagVal = llvm::ARMBuildAttrs::PreserveFPSign; |
| 1546 | } |
| 1547 | getModule().addModuleFlag(Behavior: DenormalTagBehavior, Key: "arm-eabi-fp-denormal" , |
| 1548 | Val: TagVal); |
| 1549 | |
| 1550 | if (getLangOpts().getDefaultExceptionMode() != |
| 1551 | LangOptions::FPExceptionModeKind::FPE_Ignore) |
| 1552 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "arm-eabi-fp-exceptions" , |
| 1553 | Val: llvm::ARMBuildAttrs::Allowed); |
| 1554 | |
| 1555 | if (getLangOpts().NoHonorNaNs && getLangOpts().NoHonorInfs) |
| 1556 | TagVal = llvm::ARMBuildAttrs::AllowIEEENormal; |
| 1557 | else |
| 1558 | TagVal = llvm::ARMBuildAttrs::AllowIEEE754; |
| 1559 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "arm-eabi-fp-number-model" , |
| 1560 | Val: TagVal); |
| 1561 | } |
| 1562 | |
| 1563 | if (CodeGenOpts.StackClashProtector) |
| 1564 | getModule().addModuleFlag( |
| 1565 | Behavior: llvm::Module::Override, Key: "probe-stack" , |
| 1566 | Val: llvm::MDString::get(Context&: TheModule.getContext(), Str: "inline-asm" )); |
| 1567 | |
| 1568 | if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) |
| 1569 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "stack-probe-size" , |
| 1570 | Val: CodeGenOpts.StackProbeSize); |
| 1571 | |
| 1572 | if (!CodeGenOpts.MemoryProfileOutput.empty()) { |
| 1573 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
| 1574 | getModule().addModuleFlag( |
| 1575 | Behavior: llvm::Module::Error, Key: "MemProfProfileFilename" , |
| 1576 | Val: llvm::MDString::get(Context&: Ctx, Str: CodeGenOpts.MemoryProfileOutput)); |
| 1577 | } |
| 1578 | |
| 1579 | if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { |
| 1580 | // Indicate whether __nvvm_reflect should be configured to flush denormal |
| 1581 | // floating point values to 0. (This corresponds to its "__CUDA_FTZ" |
| 1582 | // property.) |
| 1583 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "nvvm-reflect-ftz" , |
| 1584 | Val: CodeGenOpts.FP32DenormalMode.Output != |
| 1585 | llvm::DenormalMode::IEEE); |
| 1586 | } |
| 1587 | |
| 1588 | if (LangOpts.EHAsynch) |
| 1589 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "eh-asynch" , Val: 1); |
| 1590 | |
| 1591 | // Emit Import Call section. |
| 1592 | if (CodeGenOpts.ImportCallOptimization) |
| 1593 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "import-call-optimization" , |
| 1594 | Val: 1); |
| 1595 | |
| 1596 | // Enable unwind v2/v3. |
| 1597 | // Set the module flag here based on the user's requested mode (or auto- |
| 1598 | // promote to V3 when EGPR is enabled module-wide, since V1/V2 cannot encode |
| 1599 | // R16-R31). The per-function EGPR compatibility check is performed in |
| 1600 | // EmitGlobalFunctionDefinition so that `__attribute__((target("egpr")))` |
| 1601 | // and `nounwind` are respected. |
| 1602 | |
| 1603 | auto UnwindMode = CodeGenOpts.getWinX64EHUnwind(); |
| 1604 | if (UnwindMode == llvm::WinX64EHUnwindMode::Default) { |
| 1605 | if (T.isOSWindows() && T.isX86_64() && |
| 1606 | Context.getTargetInfo().hasFeature(Feature: "egpr" )) |
| 1607 | UnwindMode = llvm::WinX64EHUnwindMode::V3; |
| 1608 | else |
| 1609 | UnwindMode = llvm::WinX64EHUnwindMode::V1; |
| 1610 | } |
| 1611 | if (UnwindMode != llvm::WinX64EHUnwindMode::V1) |
| 1612 | getModule().addModuleFlag(Behavior: llvm::Module::Warning, Key: "winx64-eh-unwind" , |
| 1613 | Val: static_cast<unsigned>(UnwindMode)); |
| 1614 | |
| 1615 | // Indicate whether this Module was compiled with -fopenmp |
| 1616 | if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) |
| 1617 | getModule().addModuleFlag(Behavior: llvm::Module::Max, Key: "openmp" , Val: LangOpts.OpenMP); |
| 1618 | if (getLangOpts().OpenMPIsTargetDevice) |
| 1619 | getModule().addModuleFlag(Behavior: llvm::Module::Max, Key: "openmp-device" , |
| 1620 | Val: LangOpts.OpenMP); |
| 1621 | |
| 1622 | // Emit OpenCL specific module metadata: OpenCL/SPIR version. |
| 1623 | if (LangOpts.OpenCL || (LangOpts.CUDAIsDevice && getTriple().isSPIRV())) { |
| 1624 | EmitOpenCLMetadata(); |
| 1625 | // Emit SPIR version. |
| 1626 | if (getTriple().isSPIR()) { |
| 1627 | // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the |
| 1628 | // opencl.spir.version named metadata. |
| 1629 | // C++ for OpenCL has a distinct mapping for version compatibility with |
| 1630 | // OpenCL. |
| 1631 | auto Version = LangOpts.getOpenCLCompatibleVersion(); |
| 1632 | llvm::Metadata *SPIRVerElts[] = { |
| 1633 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get( |
| 1634 | Ty: Int32Ty, V: Version / 100)), |
| 1635 | llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get( |
| 1636 | Ty: Int32Ty, V: (Version / 100 > 1) ? 0 : 2))}; |
| 1637 | llvm::NamedMDNode *SPIRVerMD = |
| 1638 | TheModule.getOrInsertNamedMetadata(Name: "opencl.spir.version" ); |
| 1639 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
| 1640 | SPIRVerMD->addOperand(M: llvm::MDNode::get(Context&: Ctx, MDs: SPIRVerElts)); |
| 1641 | } |
| 1642 | } |
| 1643 | |
| 1644 | // HLSL related end of code gen work items. |
| 1645 | if (LangOpts.HLSL) |
| 1646 | getHLSLRuntime().finishCodeGen(); |
| 1647 | |
| 1648 | if (uint32_t PLevel = Context.getLangOpts().PICLevel) { |
| 1649 | assert(PLevel < 3 && "Invalid PIC Level" ); |
| 1650 | getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); |
| 1651 | if (Context.getLangOpts().PIE) |
| 1652 | getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); |
| 1653 | } |
| 1654 | |
| 1655 | if (getCodeGenOpts().CodeModel.size() > 0) { |
| 1656 | unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) |
| 1657 | .Case(S: "tiny" , Value: llvm::CodeModel::Tiny) |
| 1658 | .Case(S: "small" , Value: llvm::CodeModel::Small) |
| 1659 | .Case(S: "kernel" , Value: llvm::CodeModel::Kernel) |
| 1660 | .Case(S: "medium" , Value: llvm::CodeModel::Medium) |
| 1661 | .Case(S: "large" , Value: llvm::CodeModel::Large) |
| 1662 | .Default(Value: ~0u); |
| 1663 | if (CM != ~0u) { |
| 1664 | llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); |
| 1665 | getModule().setCodeModel(codeModel); |
| 1666 | |
| 1667 | if ((CM == llvm::CodeModel::Medium || CM == llvm::CodeModel::Large) && |
| 1668 | Context.getTargetInfo().getTriple().getArch() == |
| 1669 | llvm::Triple::x86_64) { |
| 1670 | getModule().setLargeDataThreshold(getCodeGenOpts().LargeDataThreshold); |
| 1671 | } |
| 1672 | } |
| 1673 | } |
| 1674 | |
| 1675 | if (CodeGenOpts.NoPLT) |
| 1676 | getModule().setRtLibUseGOT(); |
| 1677 | if (getTriple().isOSBinFormatELF() && |
| 1678 | CodeGenOpts.DirectAccessExternalData != |
| 1679 | getModule().getDirectAccessExternalData()) { |
| 1680 | getModule().setDirectAccessExternalData( |
| 1681 | CodeGenOpts.DirectAccessExternalData); |
| 1682 | } |
| 1683 | if (CodeGenOpts.UnwindTables) |
| 1684 | getModule().setUwtable(llvm::UWTableKind(CodeGenOpts.UnwindTables)); |
| 1685 | |
| 1686 | switch (CodeGenOpts.getFramePointer()) { |
| 1687 | case CodeGenOptions::FramePointerKind::None: |
| 1688 | // 0 ("none") is the default. |
| 1689 | break; |
| 1690 | case CodeGenOptions::FramePointerKind::Reserved: |
| 1691 | getModule().setFramePointer(llvm::FramePointerKind::Reserved); |
| 1692 | break; |
| 1693 | case CodeGenOptions::FramePointerKind::NonLeafNoReserve: |
| 1694 | getModule().setFramePointer(llvm::FramePointerKind::NonLeafNoReserve); |
| 1695 | break; |
| 1696 | case CodeGenOptions::FramePointerKind::NonLeaf: |
| 1697 | getModule().setFramePointer(llvm::FramePointerKind::NonLeaf); |
| 1698 | break; |
| 1699 | case CodeGenOptions::FramePointerKind::All: |
| 1700 | getModule().setFramePointer(llvm::FramePointerKind::All); |
| 1701 | break; |
| 1702 | } |
| 1703 | |
| 1704 | SimplifyPersonality(); |
| 1705 | |
| 1706 | if (getCodeGenOpts().EmitDeclMetadata) |
| 1707 | EmitDeclMetadata(); |
| 1708 | |
| 1709 | if (getCodeGenOpts().CoverageNotesFile.size() || |
| 1710 | getCodeGenOpts().CoverageDataFile.size()) |
| 1711 | EmitCoverageFile(); |
| 1712 | |
| 1713 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 1714 | DI->finalize(); |
| 1715 | |
| 1716 | if (getCodeGenOpts().EmitVersionIdentMetadata) |
| 1717 | EmitVersionIdentMetadata(); |
| 1718 | |
| 1719 | if (!getCodeGenOpts().RecordCommandLine.empty()) |
| 1720 | EmitCommandLineMetadata(); |
| 1721 | |
| 1722 | if (!getCodeGenOpts().StackProtectorGuard.empty()) |
| 1723 | getModule().setStackProtectorGuard(getCodeGenOpts().StackProtectorGuard); |
| 1724 | if (!getCodeGenOpts().StackProtectorGuardReg.empty()) |
| 1725 | getModule().setStackProtectorGuardReg( |
| 1726 | getCodeGenOpts().StackProtectorGuardReg); |
| 1727 | if (!getCodeGenOpts().StackProtectorGuardSymbol.empty()) |
| 1728 | getModule().setStackProtectorGuardSymbol( |
| 1729 | getCodeGenOpts().StackProtectorGuardSymbol); |
| 1730 | if (getCodeGenOpts().StackProtectorGuardOffset != INT_MAX) |
| 1731 | getModule().setStackProtectorGuardOffset( |
| 1732 | getCodeGenOpts().StackProtectorGuardOffset); |
| 1733 | if (getCodeGenOpts().StackProtectorGuardValueWidth != UINT_MAX) |
| 1734 | getModule().setStackProtectorGuardValueWidth( |
| 1735 | getCodeGenOpts().StackProtectorGuardValueWidth); |
| 1736 | if (getCodeGenOpts().StackProtectorGuardRecord) { |
| 1737 | if (getModule().getStackProtectorGuard() != "global" ) { |
| 1738 | Diags.Report(DiagID: diag::err_opt_not_valid_without_opt) |
| 1739 | << "-mstack-protector-guard-record" |
| 1740 | << "-mstack-protector-guard=global" ; |
| 1741 | } |
| 1742 | getModule().setStackProtectorGuardRecord(true); |
| 1743 | } |
| 1744 | if (getCodeGenOpts().StackAlignment) |
| 1745 | getModule().setOverrideStackAlignment(getCodeGenOpts().StackAlignment); |
| 1746 | if (getCodeGenOpts().SkipRaxSetup) |
| 1747 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "SkipRaxSetup" , Val: 1); |
| 1748 | if (getLangOpts().RegCall4) |
| 1749 | getModule().addModuleFlag(Behavior: llvm::Module::Override, Key: "RegCallv4" , Val: 1); |
| 1750 | |
| 1751 | if (getContext().getTargetInfo().getMaxTLSAlign()) |
| 1752 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "MaxTLSAlign" , |
| 1753 | Val: getContext().getTargetInfo().getMaxTLSAlign()); |
| 1754 | |
| 1755 | getTargetCodeGenInfo().emitTargetGlobals(CGM&: *this); |
| 1756 | |
| 1757 | getTargetCodeGenInfo().emitTargetMetadata(CGM&: *this, MangledDeclNames); |
| 1758 | |
| 1759 | EmitBackendOptionsMetadata(CodeGenOpts: getCodeGenOpts()); |
| 1760 | |
| 1761 | // If there is device offloading code embed it in the host now. |
| 1762 | EmbedObject(M: &getModule(), CGOpts: CodeGenOpts, VFS&: *getFileSystem(), Diags&: getDiags()); |
| 1763 | |
| 1764 | // Set visibility from DLL storage class |
| 1765 | // We do this at the end of LLVM IR generation; after any operation |
| 1766 | // that might affect the DLL storage class or the visibility, and |
| 1767 | // before anything that might act on these. |
| 1768 | setVisibilityFromDLLStorageClass(LO: LangOpts, M&: getModule()); |
| 1769 | |
| 1770 | // Check the tail call symbols are truly undefined. |
| 1771 | if (!MustTailCallUndefinedGlobals.empty()) { |
| 1772 | if (getTriple().isPPC()) { |
| 1773 | for (auto &I : MustTailCallUndefinedGlobals) { |
| 1774 | if (!I.first->isDefined()) |
| 1775 | getDiags().Report(Loc: I.second, DiagID: diag::err_ppc_impossible_musttail) << 2; |
| 1776 | else { |
| 1777 | StringRef MangledName = getMangledName(GD: GlobalDecl(I.first)); |
| 1778 | llvm::GlobalValue *Entry = GetGlobalValue(Ref: MangledName); |
| 1779 | if (!Entry || Entry->isWeakForLinker() || |
| 1780 | Entry->isDeclarationForLinker()) |
| 1781 | getDiags().Report(Loc: I.second, DiagID: diag::err_ppc_impossible_musttail) << 2; |
| 1782 | } |
| 1783 | } |
| 1784 | } else if (getTriple().isMIPS()) { |
| 1785 | for (auto &I : MustTailCallUndefinedGlobals) { |
| 1786 | const FunctionDecl *FD = I.first; |
| 1787 | StringRef MangledName = getMangledName(GD: GlobalDecl(FD)); |
| 1788 | llvm::GlobalValue *Entry = GetGlobalValue(Ref: MangledName); |
| 1789 | |
| 1790 | if (!Entry) |
| 1791 | continue; |
| 1792 | |
| 1793 | bool CalleeIsLocal; |
| 1794 | if (Entry->isDeclarationForLinker()) { |
| 1795 | // For declarations, only visibility can indicate locality. |
| 1796 | CalleeIsLocal = |
| 1797 | Entry->hasHiddenVisibility() || Entry->hasProtectedVisibility(); |
| 1798 | } else { |
| 1799 | CalleeIsLocal = Entry->isDSOLocal(); |
| 1800 | } |
| 1801 | |
| 1802 | if (!CalleeIsLocal) |
| 1803 | getDiags().Report(Loc: I.second, DiagID: diag::err_mips_impossible_musttail) << 1; |
| 1804 | } |
| 1805 | } |
| 1806 | } |
| 1807 | |
| 1808 | // Emit `!llvm.errno.tbaa`, a module-level metadata that specifies the TBAA |
| 1809 | // for an int access. This allows LLVM to reason about what memory can be |
| 1810 | // accessed by certain library calls that only touch errno. |
| 1811 | if (TBAA) { |
| 1812 | TBAAAccessInfo TBAAInfo = getTBAAAccessInfo(AccessType: Context.IntTy); |
| 1813 | if (llvm::MDNode *IntegerNode = getTBAAAccessTagInfo(Info: TBAAInfo)) { |
| 1814 | auto *ErrnoTBAAMD = TheModule.getOrInsertNamedMetadata(Name: ErrnoTBAAMDName); |
| 1815 | ErrnoTBAAMD->addOperand(M: IntegerNode); |
| 1816 | } |
| 1817 | } |
| 1818 | } |
| 1819 | |
| 1820 | void CodeGenModule::EmitOpenCLMetadata() { |
| 1821 | // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the |
| 1822 | // opencl.ocl.version named metadata node. |
| 1823 | // C++ for OpenCL has a distinct mapping for versions compatible with OpenCL. |
| 1824 | auto CLVersion = LangOpts.getOpenCLCompatibleVersion(); |
| 1825 | |
| 1826 | auto EmitVersion = [this](StringRef MDName, int Version) { |
| 1827 | llvm::Metadata *OCLVerElts[] = { |
| 1828 | llvm::ConstantAsMetadata::get( |
| 1829 | C: llvm::ConstantInt::get(Ty: Int32Ty, V: Version / 100)), |
| 1830 | llvm::ConstantAsMetadata::get( |
| 1831 | C: llvm::ConstantInt::get(Ty: Int32Ty, V: (Version % 100) / 10))}; |
| 1832 | llvm::NamedMDNode *OCLVerMD = TheModule.getOrInsertNamedMetadata(Name: MDName); |
| 1833 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
| 1834 | OCLVerMD->addOperand(M: llvm::MDNode::get(Context&: Ctx, MDs: OCLVerElts)); |
| 1835 | }; |
| 1836 | |
| 1837 | EmitVersion("opencl.ocl.version" , CLVersion); |
| 1838 | if (LangOpts.OpenCLCPlusPlus) { |
| 1839 | // In addition to the OpenCL compatible version, emit the C++ version. |
| 1840 | EmitVersion("opencl.cxx.version" , LangOpts.OpenCLCPlusPlusVersion); |
| 1841 | } |
| 1842 | } |
| 1843 | |
| 1844 | void CodeGenModule::EmitBackendOptionsMetadata( |
| 1845 | const CodeGenOptions &CodeGenOpts) { |
| 1846 | if (getTriple().isRISCV()) { |
| 1847 | getModule().addModuleFlag(Behavior: llvm::Module::Min, Key: "SmallDataLimit" , |
| 1848 | Val: CodeGenOpts.SmallDataLimit); |
| 1849 | } |
| 1850 | |
| 1851 | // Set AllocToken configuration for backend pipeline. |
| 1852 | if (LangOpts.AllocTokenMode) { |
| 1853 | StringRef S = llvm::getAllocTokenModeAsString(Mode: *LangOpts.AllocTokenMode); |
| 1854 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "alloc-token-mode" , |
| 1855 | Val: llvm::MDString::get(Context&: VMContext, Str: S)); |
| 1856 | } |
| 1857 | if (LangOpts.AllocTokenMax) |
| 1858 | getModule().addModuleFlag( |
| 1859 | Behavior: llvm::Module::Error, Key: "alloc-token-max" , |
| 1860 | Val: llvm::ConstantInt::get(Ty: llvm::Type::getInt64Ty(C&: VMContext), |
| 1861 | V: *LangOpts.AllocTokenMax)); |
| 1862 | if (CodeGenOpts.SanitizeAllocTokenFastABI) |
| 1863 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "alloc-token-fast-abi" , Val: 1); |
| 1864 | if (CodeGenOpts.SanitizeAllocTokenExtended) |
| 1865 | getModule().addModuleFlag(Behavior: llvm::Module::Error, Key: "alloc-token-extended" , Val: 1); |
| 1866 | } |
| 1867 | |
| 1868 | void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { |
| 1869 | // Make sure that this type is translated. |
| 1870 | getTypes().UpdateCompletedType(TD); |
| 1871 | } |
| 1872 | |
| 1873 | void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { |
| 1874 | // Make sure that this type is translated. |
| 1875 | getTypes().RefreshTypeCacheForClass(RD); |
| 1876 | } |
| 1877 | |
| 1878 | llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { |
| 1879 | if (!TBAA) |
| 1880 | return nullptr; |
| 1881 | return TBAA->getTypeInfo(QTy); |
| 1882 | } |
| 1883 | |
| 1884 | TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { |
| 1885 | if (!TBAA) |
| 1886 | return TBAAAccessInfo(); |
| 1887 | if (getLangOpts().CUDAIsDevice) { |
| 1888 | // As CUDA builtin surface/texture types are replaced, skip generating TBAA |
| 1889 | // access info. |
| 1890 | if (AccessType->isCUDADeviceBuiltinSurfaceType()) { |
| 1891 | if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != |
| 1892 | nullptr) |
| 1893 | return TBAAAccessInfo(); |
| 1894 | } else if (AccessType->isCUDADeviceBuiltinTextureType()) { |
| 1895 | if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != |
| 1896 | nullptr) |
| 1897 | return TBAAAccessInfo(); |
| 1898 | } |
| 1899 | } |
| 1900 | return TBAA->getAccessInfo(AccessType); |
| 1901 | } |
| 1902 | |
| 1903 | TBAAAccessInfo |
| 1904 | CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { |
| 1905 | if (!TBAA) |
| 1906 | return TBAAAccessInfo(); |
| 1907 | return TBAA->getVTablePtrAccessInfo(VTablePtrType); |
| 1908 | } |
| 1909 | |
| 1910 | llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { |
| 1911 | if (!TBAA) |
| 1912 | return nullptr; |
| 1913 | return TBAA->getTBAAStructInfo(QTy); |
| 1914 | } |
| 1915 | |
| 1916 | llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { |
| 1917 | if (!TBAA) |
| 1918 | return nullptr; |
| 1919 | return TBAA->getBaseTypeInfo(QTy); |
| 1920 | } |
| 1921 | |
| 1922 | llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { |
| 1923 | if (!TBAA) |
| 1924 | return nullptr; |
| 1925 | return TBAA->getAccessTagInfo(Info); |
| 1926 | } |
| 1927 | |
| 1928 | TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, |
| 1929 | TBAAAccessInfo TargetInfo) { |
| 1930 | if (!TBAA) |
| 1931 | return TBAAAccessInfo(); |
| 1932 | return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); |
| 1933 | } |
| 1934 | |
| 1935 | TBAAAccessInfo |
| 1936 | CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, |
| 1937 | TBAAAccessInfo InfoB) { |
| 1938 | if (!TBAA) |
| 1939 | return TBAAAccessInfo(); |
| 1940 | return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); |
| 1941 | } |
| 1942 | |
| 1943 | TBAAAccessInfo |
| 1944 | CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, |
| 1945 | TBAAAccessInfo SrcInfo) { |
| 1946 | if (!TBAA) |
| 1947 | return TBAAAccessInfo(); |
| 1948 | return TBAA->mergeTBAAInfoForConditionalOperator(InfoA: DestInfo, InfoB: SrcInfo); |
| 1949 | } |
| 1950 | |
| 1951 | void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, |
| 1952 | TBAAAccessInfo TBAAInfo) { |
| 1953 | if (llvm::MDNode *Tag = getTBAAAccessTagInfo(Info: TBAAInfo)) |
| 1954 | Inst->setMetadata(KindID: llvm::LLVMContext::MD_tbaa, Node: Tag); |
| 1955 | } |
| 1956 | |
| 1957 | void CodeGenModule::DecorateInstructionWithInvariantGroup( |
| 1958 | llvm::Instruction *I, const CXXRecordDecl *RD) { |
| 1959 | I->setMetadata(KindID: llvm::LLVMContext::MD_invariant_group, |
| 1960 | Node: llvm::MDNode::get(Context&: getLLVMContext(), MDs: {})); |
| 1961 | } |
| 1962 | |
| 1963 | void CodeGenModule::Error(SourceLocation loc, StringRef message) { |
| 1964 | unsigned diagID = getDiags().getCustomDiagID(L: DiagnosticsEngine::Error, FormatString: "%0" ); |
| 1965 | getDiags().Report(Loc: Context.getFullLoc(Loc: loc), DiagID: diagID) << message; |
| 1966 | } |
| 1967 | |
| 1968 | /// ErrorUnsupported - Print out an error that codegen doesn't support the |
| 1969 | /// specified stmt yet. |
| 1970 | void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { |
| 1971 | std::string Msg = Type; |
| 1972 | getDiags().Report(Loc: Context.getFullLoc(Loc: S->getBeginLoc()), |
| 1973 | DiagID: diag::err_codegen_unsupported) |
| 1974 | << Msg << S->getSourceRange(); |
| 1975 | } |
| 1976 | |
| 1977 | void CodeGenModule::ErrorUnsupported(const Stmt *S, llvm::StringRef Type) { |
| 1978 | getDiags().Report(Loc: Context.getFullLoc(Loc: S->getBeginLoc()), |
| 1979 | DiagID: diag::err_codegen_unsupported) |
| 1980 | << Type << S->getSourceRange(); |
| 1981 | } |
| 1982 | |
| 1983 | /// ErrorUnsupported - Print out an error that codegen doesn't support the |
| 1984 | /// specified decl yet. |
| 1985 | void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { |
| 1986 | std::string Msg = Type; |
| 1987 | getDiags().Report(Loc: Context.getFullLoc(Loc: D->getLocation()), |
| 1988 | DiagID: diag::err_codegen_unsupported) |
| 1989 | << Msg; |
| 1990 | } |
| 1991 | |
| 1992 | void CodeGenModule::runWithSufficientStackSpace(SourceLocation Loc, |
| 1993 | llvm::function_ref<void()> Fn) { |
| 1994 | StackHandler.runWithSufficientStackSpace(Loc, Fn); |
| 1995 | } |
| 1996 | |
| 1997 | llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { |
| 1998 | return llvm::ConstantInt::get(Ty: SizeTy, V: size.getQuantity()); |
| 1999 | } |
| 2000 | |
| 2001 | void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, |
| 2002 | const NamedDecl *D) const { |
| 2003 | // Internal definitions always have default visibility. |
| 2004 | if (GV->hasLocalLinkage()) { |
| 2005 | GV->setVisibility(llvm::GlobalValue::DefaultVisibility); |
| 2006 | return; |
| 2007 | } |
| 2008 | if (!D) |
| 2009 | return; |
| 2010 | |
| 2011 | // Set visibility for definitions, and for declarations if requested globally |
| 2012 | // or set explicitly. |
| 2013 | LinkageInfo LV = D->getLinkageAndVisibility(); |
| 2014 | |
| 2015 | // OpenMP declare target variables must be visible to the host so they can |
| 2016 | // be registered. We require protected visibility unless the variable has |
| 2017 | // the DT_nohost modifier and does not need to be registered. |
| 2018 | if (Context.getLangOpts().OpenMP && |
| 2019 | Context.getLangOpts().OpenMPIsTargetDevice && isa<VarDecl>(Val: D) && |
| 2020 | D->hasAttr<OMPDeclareTargetDeclAttr>() && |
| 2021 | D->getAttr<OMPDeclareTargetDeclAttr>()->getDevType() != |
| 2022 | OMPDeclareTargetDeclAttr::DT_NoHost && |
| 2023 | LV.getVisibility() == HiddenVisibility) { |
| 2024 | GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); |
| 2025 | return; |
| 2026 | } |
| 2027 | |
| 2028 | // CUDA/HIP device kernels and global variables must be visible to the host |
| 2029 | // so they can be registered / initialized. We require protected visibility |
| 2030 | // unless the user explicitly requested hidden via an attribute. |
| 2031 | if (Context.getLangOpts().CUDAIsDevice && |
| 2032 | LV.getVisibility() == HiddenVisibility && !LV.isVisibilityExplicit() && |
| 2033 | !D->hasAttr<OMPDeclareTargetDeclAttr>()) { |
| 2034 | bool NeedsProtected = false; |
| 2035 | if (isa<FunctionDecl>(Val: D)) |
| 2036 | NeedsProtected = |
| 2037 | D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<DeviceKernelAttr>(); |
| 2038 | else if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
| 2039 | NeedsProtected = VD->hasAttr<CUDADeviceAttr>() || |
| 2040 | VD->hasAttr<CUDAConstantAttr>() || |
| 2041 | VD->getType()->isCUDADeviceBuiltinSurfaceType() || |
| 2042 | VD->getType()->isCUDADeviceBuiltinTextureType(); |
| 2043 | if (NeedsProtected) { |
| 2044 | GV->setVisibility(llvm::GlobalValue::ProtectedVisibility); |
| 2045 | return; |
| 2046 | } |
| 2047 | } |
| 2048 | |
| 2049 | if (Context.getLangOpts().HLSL && !D->isInExportDeclContext()) { |
| 2050 | GV->setVisibility(llvm::GlobalValue::HiddenVisibility); |
| 2051 | return; |
| 2052 | } |
| 2053 | |
| 2054 | if (GV->hasDLLExportStorageClass() || GV->hasDLLImportStorageClass()) { |
| 2055 | // Reject incompatible dlllstorage and visibility annotations. |
| 2056 | if (!LV.isVisibilityExplicit()) |
| 2057 | return; |
| 2058 | if (GV->hasDLLExportStorageClass()) { |
| 2059 | if (LV.getVisibility() == HiddenVisibility) |
| 2060 | getDiags().Report(Loc: D->getLocation(), |
| 2061 | DiagID: diag::err_hidden_visibility_dllexport); |
| 2062 | } else if (LV.getVisibility() != DefaultVisibility) { |
| 2063 | getDiags().Report(Loc: D->getLocation(), |
| 2064 | DiagID: diag::err_non_default_visibility_dllimport); |
| 2065 | } |
| 2066 | return; |
| 2067 | } |
| 2068 | |
| 2069 | if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || |
| 2070 | !GV->isDeclarationForLinker()) |
| 2071 | GV->setVisibility(GetLLVMVisibility(V: LV.getVisibility())); |
| 2072 | } |
| 2073 | |
| 2074 | static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, |
| 2075 | llvm::GlobalValue *GV) { |
| 2076 | if (GV->hasLocalLinkage()) |
| 2077 | return true; |
| 2078 | |
| 2079 | if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) |
| 2080 | return true; |
| 2081 | |
| 2082 | // DLLImport explicitly marks the GV as external. |
| 2083 | if (GV->hasDLLImportStorageClass()) |
| 2084 | return false; |
| 2085 | |
| 2086 | const llvm::Triple &TT = CGM.getTriple(); |
| 2087 | const auto &CGOpts = CGM.getCodeGenOpts(); |
| 2088 | if (TT.isOSCygMing()) { |
| 2089 | // In MinGW, variables without DLLImport can still be automatically |
| 2090 | // imported from a DLL by the linker; don't mark variables that |
| 2091 | // potentially could come from another DLL as DSO local. |
| 2092 | |
| 2093 | // With EmulatedTLS, TLS variables can be autoimported from other DLLs |
| 2094 | // (and this actually happens in the public interface of libstdc++), so |
| 2095 | // such variables can't be marked as DSO local. (Native TLS variables |
| 2096 | // can't be dllimported at all, though.) |
| 2097 | if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(Val: GV) && |
| 2098 | (!GV->isThreadLocal() || CGM.getCodeGenOpts().EmulatedTLS) && |
| 2099 | CGOpts.AutoImport) |
| 2100 | return false; |
| 2101 | } |
| 2102 | |
| 2103 | // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols |
| 2104 | // remain unresolved in the link, they can be resolved to zero, which is |
| 2105 | // outside the current DSO. |
| 2106 | if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) |
| 2107 | return false; |
| 2108 | |
| 2109 | // Every other GV is local on COFF. |
| 2110 | // Make an exception for windows OS in the triple: Some firmware builds use |
| 2111 | // *-win32-macho triples. This (accidentally?) produced windows relocations |
| 2112 | // without GOT tables in older clang versions; Keep this behaviour. |
| 2113 | // FIXME: even thread local variables? |
| 2114 | if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) |
| 2115 | return true; |
| 2116 | |
| 2117 | // Only handle COFF and ELF for now. |
| 2118 | if (!TT.isOSBinFormatELF()) |
| 2119 | return false; |
| 2120 | |
| 2121 | // If this is not an executable, don't assume anything is local. |
| 2122 | llvm::Reloc::Model RM = CGOpts.RelocationModel; |
| 2123 | const auto &LOpts = CGM.getLangOpts(); |
| 2124 | if (RM != llvm::Reloc::Static && !LOpts.PIE) { |
| 2125 | // On ELF, if -fno-semantic-interposition is specified and the target |
| 2126 | // supports local aliases, there will be neither CC1 |
| 2127 | // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set |
| 2128 | // dso_local on the function if using a local alias is preferable (can avoid |
| 2129 | // PLT indirection). |
| 2130 | if (!(isa<llvm::Function>(Val: GV) && GV->canBenefitFromLocalAlias())) |
| 2131 | return false; |
| 2132 | return !(CGM.getLangOpts().SemanticInterposition || |
| 2133 | CGM.getLangOpts().HalfNoSemanticInterposition); |
| 2134 | } |
| 2135 | |
| 2136 | // A definition cannot be preempted from an executable. |
| 2137 | if (!GV->isDeclarationForLinker()) |
| 2138 | return true; |
| 2139 | |
| 2140 | // Most PIC code sequences that assume that a symbol is local cannot produce a |
| 2141 | // 0 if it turns out the symbol is undefined. While this is ABI and relocation |
| 2142 | // depended, it seems worth it to handle it here. |
| 2143 | if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) |
| 2144 | return false; |
| 2145 | |
| 2146 | // PowerPC64 prefers TOC indirection to avoid copy relocations. |
| 2147 | if (TT.isPPC64()) |
| 2148 | return false; |
| 2149 | |
| 2150 | if (CGOpts.DirectAccessExternalData) { |
| 2151 | // If -fdirect-access-external-data (default for -fno-pic), set dso_local |
| 2152 | // for non-thread-local variables. If the symbol is not defined in the |
| 2153 | // executable, a copy relocation will be needed at link time. dso_local is |
| 2154 | // excluded for thread-local variables because they generally don't support |
| 2155 | // copy relocations. |
| 2156 | if (auto *Var = dyn_cast<llvm::GlobalVariable>(Val: GV)) |
| 2157 | if (!Var->isThreadLocal()) |
| 2158 | return true; |
| 2159 | |
| 2160 | // -fno-pic sets dso_local on a function declaration to allow direct |
| 2161 | // accesses when taking its address (similar to a data symbol). If the |
| 2162 | // function is not defined in the executable, a canonical PLT entry will be |
| 2163 | // needed at link time. -fno-direct-access-external-data can avoid the |
| 2164 | // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as |
| 2165 | // it could just cause trouble without providing perceptible benefits. |
| 2166 | if (isa<llvm::Function>(Val: GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) |
| 2167 | return true; |
| 2168 | } |
| 2169 | |
| 2170 | // If we can use copy relocations we can assume it is local. |
| 2171 | |
| 2172 | // Otherwise don't assume it is local. |
| 2173 | return false; |
| 2174 | } |
| 2175 | |
| 2176 | void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { |
| 2177 | GV->setDSOLocal(shouldAssumeDSOLocal(CGM: *this, GV)); |
| 2178 | } |
| 2179 | |
| 2180 | void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, |
| 2181 | GlobalDecl GD) const { |
| 2182 | const auto *D = dyn_cast<NamedDecl>(Val: GD.getDecl()); |
| 2183 | // C++ destructors have a few C++ ABI specific special cases. |
| 2184 | if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(Val: D)) { |
| 2185 | getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, DT: GD.getDtorType()); |
| 2186 | return; |
| 2187 | } |
| 2188 | setDLLImportDLLExport(GV, D); |
| 2189 | } |
| 2190 | |
| 2191 | void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, |
| 2192 | const NamedDecl *D) const { |
| 2193 | if (D && D->isExternallyVisible()) { |
| 2194 | if (D->hasAttr<DLLImportAttr>()) |
| 2195 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); |
| 2196 | else if ((D->hasAttr<DLLExportAttr>() || |
| 2197 | shouldMapVisibilityToDLLExport(D)) && |
| 2198 | !GV->isDeclarationForLinker()) |
| 2199 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); |
| 2200 | } |
| 2201 | } |
| 2202 | |
| 2203 | void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, |
| 2204 | GlobalDecl GD) const { |
| 2205 | setDLLImportDLLExport(GV, GD); |
| 2206 | setGVPropertiesAux(GV, D: dyn_cast<NamedDecl>(Val: GD.getDecl())); |
| 2207 | } |
| 2208 | |
| 2209 | void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, |
| 2210 | const NamedDecl *D) const { |
| 2211 | setDLLImportDLLExport(GV, D); |
| 2212 | setGVPropertiesAux(GV, D); |
| 2213 | } |
| 2214 | |
| 2215 | void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, |
| 2216 | const NamedDecl *D) const { |
| 2217 | setGlobalVisibility(GV, D); |
| 2218 | setDSOLocal(GV); |
| 2219 | GV->setPartition(CodeGenOpts.SymbolPartition); |
| 2220 | } |
| 2221 | |
| 2222 | static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { |
| 2223 | return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) |
| 2224 | .Case(S: "global-dynamic" , Value: llvm::GlobalVariable::GeneralDynamicTLSModel) |
| 2225 | .Case(S: "local-dynamic" , Value: llvm::GlobalVariable::LocalDynamicTLSModel) |
| 2226 | .Case(S: "initial-exec" , Value: llvm::GlobalVariable::InitialExecTLSModel) |
| 2227 | .Case(S: "local-exec" , Value: llvm::GlobalVariable::LocalExecTLSModel); |
| 2228 | } |
| 2229 | |
| 2230 | llvm::GlobalVariable::ThreadLocalMode |
| 2231 | CodeGenModule::GetDefaultLLVMTLSModel() const { |
| 2232 | switch (CodeGenOpts.getDefaultTLSModel()) { |
| 2233 | case CodeGenOptions::GeneralDynamicTLSModel: |
| 2234 | return llvm::GlobalVariable::GeneralDynamicTLSModel; |
| 2235 | case CodeGenOptions::LocalDynamicTLSModel: |
| 2236 | return llvm::GlobalVariable::LocalDynamicTLSModel; |
| 2237 | case CodeGenOptions::InitialExecTLSModel: |
| 2238 | return llvm::GlobalVariable::InitialExecTLSModel; |
| 2239 | case CodeGenOptions::LocalExecTLSModel: |
| 2240 | return llvm::GlobalVariable::LocalExecTLSModel; |
| 2241 | } |
| 2242 | llvm_unreachable("Invalid TLS model!" ); |
| 2243 | } |
| 2244 | |
| 2245 | void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { |
| 2246 | assert(D.getTLSKind() && "setting TLS mode on non-TLS var!" ); |
| 2247 | |
| 2248 | llvm::GlobalValue::ThreadLocalMode TLM; |
| 2249 | TLM = GetDefaultLLVMTLSModel(); |
| 2250 | |
| 2251 | // Override the TLS model if it is explicitly specified. |
| 2252 | if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { |
| 2253 | TLM = GetLLVMTLSModel(S: Attr->getModel()); |
| 2254 | } |
| 2255 | |
| 2256 | GV->setThreadLocalMode(TLM); |
| 2257 | } |
| 2258 | |
| 2259 | static std::string getCPUSpecificMangling(const CodeGenModule &CGM, |
| 2260 | StringRef Name) { |
| 2261 | const TargetInfo &Target = CGM.getTarget(); |
| 2262 | return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); |
| 2263 | } |
| 2264 | |
| 2265 | static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, |
| 2266 | const CPUSpecificAttr *Attr, |
| 2267 | unsigned CPUIndex, |
| 2268 | raw_ostream &Out) { |
| 2269 | // cpu_specific gets the current name, dispatch gets the resolver if IFunc is |
| 2270 | // supported. |
| 2271 | if (Attr) |
| 2272 | Out << getCPUSpecificMangling(CGM, Name: Attr->getCPUName(Index: CPUIndex)->getName()); |
| 2273 | else if (CGM.getTarget().supportsIFunc()) |
| 2274 | Out << ".resolver" ; |
| 2275 | } |
| 2276 | |
| 2277 | // Returns true if GD is a function decl with internal linkage and |
| 2278 | // needs a unique suffix after the mangled name. |
| 2279 | static bool isUniqueInternalLinkageDecl(GlobalDecl GD, |
| 2280 | CodeGenModule &CGM) { |
| 2281 | const Decl *D = GD.getDecl(); |
| 2282 | return !CGM.getModuleNameHash().empty() && isa<FunctionDecl>(Val: D) && |
| 2283 | !D->hasAttr<AsmLabelAttr>() && |
| 2284 | (CGM.getFunctionLinkage(GD) == llvm::GlobalValue::InternalLinkage); |
| 2285 | } |
| 2286 | |
| 2287 | static std::string getMangledNameImpl(CodeGenModule &CGM, GlobalDecl GD, |
| 2288 | const NamedDecl *ND, |
| 2289 | bool OmitMultiVersionMangling = false) { |
| 2290 | SmallString<256> Buffer; |
| 2291 | llvm::raw_svector_ostream Out(Buffer); |
| 2292 | MangleContext &MC = CGM.getCXXABI().getMangleContext(); |
| 2293 | if (!CGM.getModuleNameHash().empty()) |
| 2294 | MC.needsUniqueInternalLinkageNames(); |
| 2295 | bool ShouldMangle = MC.shouldMangleDeclName(D: ND); |
| 2296 | if (ShouldMangle) |
| 2297 | MC.mangleName(GD: GD.getWithDecl(D: ND), Out); |
| 2298 | else { |
| 2299 | IdentifierInfo *II = ND->getIdentifier(); |
| 2300 | assert(II && "Attempt to mangle unnamed decl." ); |
| 2301 | const auto *FD = dyn_cast<FunctionDecl>(Val: ND); |
| 2302 | |
| 2303 | if (FD && |
| 2304 | FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { |
| 2305 | if (CGM.getLangOpts().RegCall4) |
| 2306 | Out << "__regcall4__" << II->getName(); |
| 2307 | else |
| 2308 | Out << "__regcall3__" << II->getName(); |
| 2309 | } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && |
| 2310 | GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { |
| 2311 | Out << "__device_stub__" << II->getName(); |
| 2312 | } else if (FD && |
| 2313 | DeviceKernelAttr::isOpenCLSpelling( |
| 2314 | A: FD->getAttr<DeviceKernelAttr>()) && |
| 2315 | GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { |
| 2316 | Out << "__clang_ocl_kern_imp_" << II->getName(); |
| 2317 | } else { |
| 2318 | Out << II->getName(); |
| 2319 | } |
| 2320 | } |
| 2321 | |
| 2322 | // Check if the module name hash should be appended for internal linkage |
| 2323 | // symbols. This should come before multi-version target suffixes are |
| 2324 | // appended. This is to keep the name and module hash suffix of the |
| 2325 | // internal linkage function together. The unique suffix should only be |
| 2326 | // added when name mangling is done to make sure that the final name can |
| 2327 | // be properly demangled. For example, for C functions without prototypes, |
| 2328 | // name mangling is not done and the unique suffix should not be appeneded |
| 2329 | // then. |
| 2330 | if (ShouldMangle && isUniqueInternalLinkageDecl(GD, CGM)) { |
| 2331 | assert(CGM.getCodeGenOpts().UniqueInternalLinkageNames && |
| 2332 | "Hash computed when not explicitly requested" ); |
| 2333 | Out << CGM.getModuleNameHash(); |
| 2334 | } |
| 2335 | |
| 2336 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: ND)) |
| 2337 | if (FD->isMultiVersion() && !OmitMultiVersionMangling) { |
| 2338 | switch (FD->getMultiVersionKind()) { |
| 2339 | case MultiVersionKind::CPUDispatch: |
| 2340 | case MultiVersionKind::CPUSpecific: |
| 2341 | AppendCPUSpecificCPUDispatchMangling(CGM, |
| 2342 | Attr: FD->getAttr<CPUSpecificAttr>(), |
| 2343 | CPUIndex: GD.getMultiVersionIndex(), Out); |
| 2344 | break; |
| 2345 | case MultiVersionKind::Target: { |
| 2346 | auto *Attr = FD->getAttr<TargetAttr>(); |
| 2347 | assert(Attr && "Expected TargetAttr to be present " |
| 2348 | "for attribute mangling" ); |
| 2349 | const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo(); |
| 2350 | Info.appendAttributeMangling(Attr, Out); |
| 2351 | break; |
| 2352 | } |
| 2353 | case MultiVersionKind::TargetVersion: { |
| 2354 | auto *Attr = FD->getAttr<TargetVersionAttr>(); |
| 2355 | assert(Attr && "Expected TargetVersionAttr to be present " |
| 2356 | "for attribute mangling" ); |
| 2357 | const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo(); |
| 2358 | Info.appendAttributeMangling(Attr, Out); |
| 2359 | break; |
| 2360 | } |
| 2361 | case MultiVersionKind::TargetClones: { |
| 2362 | auto *Attr = FD->getAttr<TargetClonesAttr>(); |
| 2363 | assert(Attr && "Expected TargetClonesAttr to be present " |
| 2364 | "for attribute mangling" ); |
| 2365 | unsigned Index = GD.getMultiVersionIndex(); |
| 2366 | const ABIInfo &Info = CGM.getTargetCodeGenInfo().getABIInfo(); |
| 2367 | Info.appendAttributeMangling(Attr, Index, Out); |
| 2368 | break; |
| 2369 | } |
| 2370 | case MultiVersionKind::None: |
| 2371 | llvm_unreachable("None multiversion type isn't valid here" ); |
| 2372 | } |
| 2373 | } |
| 2374 | |
| 2375 | // Make unique name for device side static file-scope variable for HIP. |
| 2376 | if (CGM.getContext().shouldExternalize(D: ND) && |
| 2377 | CGM.getLangOpts().GPURelocatableDeviceCode && |
| 2378 | CGM.getLangOpts().CUDAIsDevice) |
| 2379 | CGM.printPostfixForExternalizedDecl(OS&: Out, D: ND); |
| 2380 | |
| 2381 | return std::string(Out.str()); |
| 2382 | } |
| 2383 | |
| 2384 | void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, |
| 2385 | const FunctionDecl *FD, |
| 2386 | StringRef &CurName) { |
| 2387 | if (!FD->isMultiVersion()) |
| 2388 | return; |
| 2389 | |
| 2390 | // Get the name of what this would be without the 'target' attribute. This |
| 2391 | // allows us to lookup the version that was emitted when this wasn't a |
| 2392 | // multiversion function. |
| 2393 | std::string NonTargetName = |
| 2394 | getMangledNameImpl(CGM&: *this, GD, ND: FD, /*OmitMultiVersionMangling=*/true); |
| 2395 | GlobalDecl OtherGD; |
| 2396 | if (lookupRepresentativeDecl(MangledName: NonTargetName, Result&: OtherGD)) { |
| 2397 | assert(OtherGD.getCanonicalDecl() |
| 2398 | .getDecl() |
| 2399 | ->getAsFunction() |
| 2400 | ->isMultiVersion() && |
| 2401 | "Other GD should now be a multiversioned function" ); |
| 2402 | // OtherFD is the version of this function that was mangled BEFORE |
| 2403 | // becoming a MultiVersion function. It potentially needs to be updated. |
| 2404 | const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() |
| 2405 | .getDecl() |
| 2406 | ->getAsFunction() |
| 2407 | ->getMostRecentDecl(); |
| 2408 | std::string OtherName = getMangledNameImpl(CGM&: *this, GD: OtherGD, ND: OtherFD); |
| 2409 | // This is so that if the initial version was already the 'default' |
| 2410 | // version, we don't try to update it. |
| 2411 | if (OtherName != NonTargetName) { |
| 2412 | // Remove instead of erase, since others may have stored the StringRef |
| 2413 | // to this. |
| 2414 | const auto ExistingRecord = Manglings.find(Key: NonTargetName); |
| 2415 | if (ExistingRecord != std::end(cont&: Manglings)) |
| 2416 | Manglings.remove(KeyValue: &(*ExistingRecord)); |
| 2417 | auto Result = Manglings.insert(KV: std::make_pair(x&: OtherName, y&: OtherGD)); |
| 2418 | StringRef OtherNameRef = MangledDeclNames[OtherGD.getCanonicalDecl()] = |
| 2419 | Result.first->first(); |
| 2420 | // If this is the current decl is being created, make sure we update the name. |
| 2421 | if (GD.getCanonicalDecl() == OtherGD.getCanonicalDecl()) |
| 2422 | CurName = OtherNameRef; |
| 2423 | if (llvm::GlobalValue *Entry = GetGlobalValue(Ref: NonTargetName)) |
| 2424 | Entry->setName(OtherName); |
| 2425 | } |
| 2426 | } |
| 2427 | } |
| 2428 | |
| 2429 | StringRef CodeGenModule::getMangledName(GlobalDecl GD) { |
| 2430 | GlobalDecl CanonicalGD = GD.getCanonicalDecl(); |
| 2431 | |
| 2432 | // Some ABIs don't have constructor variants. Make sure that base and |
| 2433 | // complete constructors get mangled the same. |
| 2434 | if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: CanonicalGD.getDecl())) { |
| 2435 | if (!getTarget().getCXXABI().hasConstructorVariants()) { |
| 2436 | CXXCtorType OrigCtorType = GD.getCtorType(); |
| 2437 | assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); |
| 2438 | if (OrigCtorType == Ctor_Base) |
| 2439 | CanonicalGD = GlobalDecl(CD, Ctor_Complete); |
| 2440 | } |
| 2441 | } |
| 2442 | |
| 2443 | // In CUDA/HIP device compilation with -fgpu-rdc, the mangled name of a |
| 2444 | // static device variable depends on whether the variable is referenced by |
| 2445 | // a host or device host function. Therefore the mangled name cannot be |
| 2446 | // cached. |
| 2447 | if (!LangOpts.CUDAIsDevice || !getContext().mayExternalize(D: GD.getDecl())) { |
| 2448 | auto FoundName = MangledDeclNames.find(Key: CanonicalGD); |
| 2449 | if (FoundName != MangledDeclNames.end()) |
| 2450 | return FoundName->second; |
| 2451 | } |
| 2452 | |
| 2453 | // Keep the first result in the case of a mangling collision. |
| 2454 | const auto *ND = cast<NamedDecl>(Val: GD.getDecl()); |
| 2455 | std::string MangledName = getMangledNameImpl(CGM&: *this, GD, ND); |
| 2456 | |
| 2457 | // Ensure either we have different ABIs between host and device compilations, |
| 2458 | // says host compilation following MSVC ABI but device compilation follows |
| 2459 | // Itanium C++ ABI or, if they follow the same ABI, kernel names after |
| 2460 | // mangling should be the same after name stubbing. The later checking is |
| 2461 | // very important as the device kernel name being mangled in host-compilation |
| 2462 | // is used to resolve the device binaries to be executed. Inconsistent naming |
| 2463 | // result in undefined behavior. Even though we cannot check that naming |
| 2464 | // directly between host- and device-compilations, the host- and |
| 2465 | // device-mangling in host compilation could help catching certain ones. |
| 2466 | assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || |
| 2467 | getContext().shouldExternalize(ND) || getLangOpts().CUDAIsDevice || |
| 2468 | (getContext().getAuxTargetInfo() && |
| 2469 | (getContext().getAuxTargetInfo()->getCXXABI() != |
| 2470 | getContext().getTargetInfo().getCXXABI())) || |
| 2471 | getCUDARuntime().getDeviceSideName(ND) == |
| 2472 | getMangledNameImpl( |
| 2473 | *this, |
| 2474 | GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), |
| 2475 | ND)); |
| 2476 | |
| 2477 | // This invariant should hold true in the future. |
| 2478 | // Prior work: |
| 2479 | // https://discourse.llvm.org/t/rfc-clang-diagnostic-for-demangling-failures/82835/8 |
| 2480 | // https://github.com/llvm/llvm-project/issues/111345 |
| 2481 | // assert(!((StringRef(MangledName).starts_with("_Z") || |
| 2482 | // StringRef(MangledName).starts_with("?")) && |
| 2483 | // !GD.getDecl()->hasAttr<AsmLabelAttr>() && |
| 2484 | // llvm::demangle(MangledName) == MangledName) && |
| 2485 | // "LLVM demangler must demangle clang-generated names"); |
| 2486 | |
| 2487 | auto Result = Manglings.insert(KV: std::make_pair(x&: MangledName, y&: GD)); |
| 2488 | return MangledDeclNames[CanonicalGD] = Result.first->first(); |
| 2489 | } |
| 2490 | |
| 2491 | StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, |
| 2492 | const BlockDecl *BD) { |
| 2493 | MangleContext &MangleCtx = getCXXABI().getMangleContext(); |
| 2494 | const Decl *D = GD.getDecl(); |
| 2495 | |
| 2496 | SmallString<256> Buffer; |
| 2497 | llvm::raw_svector_ostream Out(Buffer); |
| 2498 | if (!D) |
| 2499 | MangleCtx.mangleGlobalBlock(BD, |
| 2500 | ID: dyn_cast_or_null<VarDecl>(Val: initializedGlobalDecl.getDecl()), Out); |
| 2501 | else if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: D)) |
| 2502 | MangleCtx.mangleCtorBlock(CD, CT: GD.getCtorType(), BD, Out); |
| 2503 | else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Val: D)) |
| 2504 | MangleCtx.mangleDtorBlock(CD: DD, DT: GD.getDtorType(), BD, Out); |
| 2505 | else |
| 2506 | MangleCtx.mangleBlock(DC: cast<DeclContext>(Val: D), BD, Out); |
| 2507 | |
| 2508 | auto Result = Manglings.insert(KV: std::make_pair(x: Out.str(), y&: BD)); |
| 2509 | return Result.first->first(); |
| 2510 | } |
| 2511 | |
| 2512 | const GlobalDecl CodeGenModule::getMangledNameDecl(StringRef Name) { |
| 2513 | auto it = MangledDeclNames.begin(); |
| 2514 | while (it != MangledDeclNames.end()) { |
| 2515 | if (it->second == Name) |
| 2516 | return it->first; |
| 2517 | it++; |
| 2518 | } |
| 2519 | return GlobalDecl(); |
| 2520 | } |
| 2521 | |
| 2522 | llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { |
| 2523 | return getModule().getNamedValue(Name); |
| 2524 | } |
| 2525 | |
| 2526 | /// AddGlobalCtor - Add a function to the list that will be called before |
| 2527 | /// main() runs. |
| 2528 | void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, |
| 2529 | unsigned LexOrder, |
| 2530 | llvm::Constant *AssociatedData) { |
| 2531 | // FIXME: Type coercion of void()* types. |
| 2532 | GlobalCtors.push_back(x: Structor(Priority, LexOrder, Ctor, AssociatedData)); |
| 2533 | } |
| 2534 | |
| 2535 | /// AddGlobalDtor - Add a function to the list that will be called |
| 2536 | /// when the module is unloaded. |
| 2537 | void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, |
| 2538 | bool IsDtorAttrFunc) { |
| 2539 | if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && |
| 2540 | (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { |
| 2541 | DtorsUsingAtExit[Priority].push_back(NewVal: Dtor); |
| 2542 | return; |
| 2543 | } |
| 2544 | |
| 2545 | // FIXME: Type coercion of void()* types. |
| 2546 | GlobalDtors.push_back(x: Structor(Priority, ~0U, Dtor, nullptr)); |
| 2547 | } |
| 2548 | |
| 2549 | void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { |
| 2550 | if (Fns.empty()) return; |
| 2551 | |
| 2552 | const PointerAuthSchema &InitFiniAuthSchema = |
| 2553 | getCodeGenOpts().PointerAuth.InitFiniPointers; |
| 2554 | |
| 2555 | // Ctor function type is ptr. |
| 2556 | llvm::PointerType *PtrTy = llvm::PointerType::get( |
| 2557 | C&: getLLVMContext(), AddressSpace: TheModule.getDataLayout().getProgramAddressSpace()); |
| 2558 | |
| 2559 | // Get the type of a ctor entry, { i32, ptr, ptr }. |
| 2560 | llvm::StructType *CtorStructTy = llvm::StructType::get(elt1: Int32Ty, elts: PtrTy, elts: PtrTy); |
| 2561 | |
| 2562 | // Construct the constructor and destructor arrays. |
| 2563 | ConstantInitBuilder Builder(*this); |
| 2564 | auto Ctors = Builder.beginArray(eltTy: CtorStructTy); |
| 2565 | for (const auto &I : Fns) { |
| 2566 | auto Ctor = Ctors.beginStruct(ty: CtorStructTy); |
| 2567 | Ctor.addInt(intTy: Int32Ty, value: I.Priority); |
| 2568 | if (InitFiniAuthSchema) { |
| 2569 | llvm::Constant *StorageAddress = |
| 2570 | (InitFiniAuthSchema.isAddressDiscriminated() |
| 2571 | ? llvm::ConstantExpr::getIntToPtr( |
| 2572 | C: llvm::ConstantInt::get( |
| 2573 | Ty: IntPtrTy, |
| 2574 | V: llvm::ConstantPtrAuth::AddrDiscriminator_CtorsDtors), |
| 2575 | Ty: PtrTy) |
| 2576 | : nullptr); |
| 2577 | llvm::Constant *SignedCtorPtr = getConstantSignedPointer( |
| 2578 | Pointer: I.Initializer, Key: InitFiniAuthSchema.getKey(), StorageAddress, |
| 2579 | OtherDiscriminator: llvm::ConstantInt::get( |
| 2580 | Ty: SizeTy, V: InitFiniAuthSchema.getConstantDiscrimination())); |
| 2581 | Ctor.add(value: SignedCtorPtr); |
| 2582 | } else { |
| 2583 | Ctor.add(value: I.Initializer); |
| 2584 | } |
| 2585 | if (I.AssociatedData) |
| 2586 | Ctor.add(value: I.AssociatedData); |
| 2587 | else |
| 2588 | Ctor.addNullPointer(ptrTy: PtrTy); |
| 2589 | Ctor.finishAndAddTo(parent&: Ctors); |
| 2590 | } |
| 2591 | |
| 2592 | auto List = Ctors.finishAndCreateGlobal(args&: GlobalName, args: getPointerAlign(), |
| 2593 | /*constant*/ args: false, |
| 2594 | args: llvm::GlobalValue::AppendingLinkage); |
| 2595 | |
| 2596 | // The LTO linker doesn't seem to like it when we set an alignment |
| 2597 | // on appending variables. Take it off as a workaround. |
| 2598 | List->setAlignment(std::nullopt); |
| 2599 | |
| 2600 | Fns.clear(); |
| 2601 | } |
| 2602 | |
| 2603 | llvm::GlobalValue::LinkageTypes |
| 2604 | CodeGenModule::getFunctionLinkage(GlobalDecl GD) { |
| 2605 | const auto *D = cast<FunctionDecl>(Val: GD.getDecl()); |
| 2606 | |
| 2607 | GVALinkage Linkage = getContext().GetGVALinkageForFunction(FD: D); |
| 2608 | |
| 2609 | if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: D)) |
| 2610 | return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, DT: GD.getDtorType()); |
| 2611 | |
| 2612 | return getLLVMLinkageForDeclarator(D, Linkage); |
| 2613 | } |
| 2614 | |
| 2615 | llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { |
| 2616 | llvm::MDString *MDS = dyn_cast<llvm::MDString>(Val: MD); |
| 2617 | if (!MDS) return nullptr; |
| 2618 | |
| 2619 | return llvm::ConstantInt::get(Ty: Int64Ty, V: llvm::MD5Hash(Str: MDS->getString())); |
| 2620 | } |
| 2621 | |
| 2622 | static QualType GeneralizeTransparentUnion(QualType Ty) { |
| 2623 | const RecordType *UT = Ty->getAsUnionType(); |
| 2624 | if (!UT) |
| 2625 | return Ty; |
| 2626 | const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf(); |
| 2627 | if (!UD->hasAttr<TransparentUnionAttr>()) |
| 2628 | return Ty; |
| 2629 | if (!UD->fields().empty()) |
| 2630 | return UD->fields().begin()->getType(); |
| 2631 | return Ty; |
| 2632 | } |
| 2633 | |
| 2634 | // If `GeneralizePointers` is true, generalizes types to a void pointer with the |
| 2635 | // qualifiers of the originally pointed-to type, e.g. 'const char *' and 'char * |
| 2636 | // const *' generalize to 'const void *' while 'char *' and 'const char **' |
| 2637 | // generalize to 'void *'. |
| 2638 | static QualType GeneralizeType(ASTContext &Ctx, QualType Ty, |
| 2639 | bool GeneralizePointers) { |
| 2640 | Ty = GeneralizeTransparentUnion(Ty); |
| 2641 | |
| 2642 | if (!GeneralizePointers || !Ty->isPointerType()) |
| 2643 | return Ty; |
| 2644 | |
| 2645 | return Ctx.getPointerType( |
| 2646 | T: QualType(Ctx.VoidTy) |
| 2647 | .withCVRQualifiers(CVR: Ty->getPointeeType().getCVRQualifiers())); |
| 2648 | } |
| 2649 | |
| 2650 | // Apply type generalization to a FunctionType's return and argument types |
| 2651 | static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty, |
| 2652 | bool GeneralizePointers) { |
| 2653 | if (auto *FnType = Ty->getAs<FunctionProtoType>()) { |
| 2654 | SmallVector<QualType, 8> GeneralizedParams; |
| 2655 | for (auto &Param : FnType->param_types()) |
| 2656 | GeneralizedParams.push_back( |
| 2657 | Elt: GeneralizeType(Ctx, Ty: Param, GeneralizePointers)); |
| 2658 | |
| 2659 | return Ctx.getFunctionType( |
| 2660 | ResultTy: GeneralizeType(Ctx, Ty: FnType->getReturnType(), GeneralizePointers), |
| 2661 | Args: GeneralizedParams, EPI: FnType->getExtProtoInfo()); |
| 2662 | } |
| 2663 | |
| 2664 | if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) |
| 2665 | return Ctx.getFunctionNoProtoType( |
| 2666 | ResultTy: GeneralizeType(Ctx, Ty: FnType->getReturnType(), GeneralizePointers)); |
| 2667 | |
| 2668 | llvm_unreachable("Encountered unknown FunctionType" ); |
| 2669 | } |
| 2670 | |
| 2671 | llvm::ConstantInt *CodeGenModule::CreateKCFITypeId(QualType T, StringRef Salt) { |
| 2672 | T = GeneralizeFunctionType( |
| 2673 | Ctx&: getContext(), Ty: T, GeneralizePointers: getCodeGenOpts().SanitizeCfiICallGeneralizePointers); |
| 2674 | if (auto *FnType = T->getAs<FunctionProtoType>()) |
| 2675 | T = getContext().getFunctionType( |
| 2676 | ResultTy: FnType->getReturnType(), Args: FnType->getParamTypes(), |
| 2677 | EPI: FnType->getExtProtoInfo().withExceptionSpec(ESI: EST_None)); |
| 2678 | |
| 2679 | std::string OutName; |
| 2680 | llvm::raw_string_ostream Out(OutName); |
| 2681 | getCXXABI().getMangleContext().mangleCanonicalTypeName( |
| 2682 | T, Out, NormalizeIntegers: getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); |
| 2683 | |
| 2684 | if (!Salt.empty()) |
| 2685 | Out << "." << Salt; |
| 2686 | |
| 2687 | if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) |
| 2688 | Out << ".normalized" ; |
| 2689 | if (getCodeGenOpts().SanitizeCfiICallGeneralizePointers) |
| 2690 | Out << ".generalized" ; |
| 2691 | |
| 2692 | return llvm::ConstantInt::get( |
| 2693 | Ty: Int32Ty, V: llvm::getKCFITypeID(MangledTypeName: OutName, Algorithm: getCodeGenOpts().SanitizeKcfiHash)); |
| 2694 | } |
| 2695 | |
| 2696 | void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, |
| 2697 | const CGFunctionInfo &Info, |
| 2698 | llvm::Function *F, bool IsThunk) { |
| 2699 | unsigned CallingConv; |
| 2700 | llvm::AttributeList PAL; |
| 2701 | ConstructAttributeList(Name: F->getName(), Info, CalleeInfo: GD, Attrs&: PAL, CallingConv, |
| 2702 | /*AttrOnCallSite=*/false, IsThunk); |
| 2703 | if (CallingConv == llvm::CallingConv::X86_VectorCall && |
| 2704 | getTarget().getTriple().isWindowsArm64EC()) { |
| 2705 | SourceLocation Loc; |
| 2706 | if (const Decl *D = GD.getDecl()) |
| 2707 | Loc = D->getLocation(); |
| 2708 | |
| 2709 | Error(loc: Loc, message: "__vectorcall calling convention is not currently supported" ); |
| 2710 | } |
| 2711 | F->setAttributes(PAL); |
| 2712 | F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); |
| 2713 | } |
| 2714 | |
| 2715 | static void removeImageAccessQualifier(std::string& TyName) { |
| 2716 | std::string ReadOnlyQual("__read_only" ); |
| 2717 | std::string::size_type ReadOnlyPos = TyName.find(str: ReadOnlyQual); |
| 2718 | if (ReadOnlyPos != std::string::npos) |
| 2719 | // "+ 1" for the space after access qualifier. |
| 2720 | TyName.erase(pos: ReadOnlyPos, n: ReadOnlyQual.size() + 1); |
| 2721 | else { |
| 2722 | std::string WriteOnlyQual("__write_only" ); |
| 2723 | std::string::size_type WriteOnlyPos = TyName.find(str: WriteOnlyQual); |
| 2724 | if (WriteOnlyPos != std::string::npos) |
| 2725 | TyName.erase(pos: WriteOnlyPos, n: WriteOnlyQual.size() + 1); |
| 2726 | else { |
| 2727 | std::string ReadWriteQual("__read_write" ); |
| 2728 | std::string::size_type ReadWritePos = TyName.find(str: ReadWriteQual); |
| 2729 | if (ReadWritePos != std::string::npos) |
| 2730 | TyName.erase(pos: ReadWritePos, n: ReadWriteQual.size() + 1); |
| 2731 | } |
| 2732 | } |
| 2733 | } |
| 2734 | |
| 2735 | // Returns the address space id that should be produced to the |
| 2736 | // kernel_arg_addr_space metadata. This is always fixed to the ids |
| 2737 | // as specified in the SPIR 2.0 specification in order to differentiate |
| 2738 | // for example in clGetKernelArgInfo() implementation between the address |
| 2739 | // spaces with targets without unique mapping to the OpenCL address spaces |
| 2740 | // (basically all single AS CPUs). |
| 2741 | static unsigned ArgInfoAddressSpace(LangAS AS) { |
| 2742 | switch (AS) { |
| 2743 | case LangAS::opencl_global: |
| 2744 | return 1; |
| 2745 | case LangAS::opencl_constant: |
| 2746 | return 2; |
| 2747 | case LangAS::opencl_local: |
| 2748 | return 3; |
| 2749 | case LangAS::opencl_generic: |
| 2750 | return 4; // Not in SPIR 2.0 specs. |
| 2751 | case LangAS::opencl_global_device: |
| 2752 | return 5; |
| 2753 | case LangAS::opencl_global_host: |
| 2754 | return 6; |
| 2755 | default: |
| 2756 | return 0; // Assume private. |
| 2757 | } |
| 2758 | } |
| 2759 | |
| 2760 | void CodeGenModule::GenKernelArgMetadata(llvm::Function *Fn, |
| 2761 | const FunctionDecl *FD, |
| 2762 | CodeGenFunction *CGF) { |
| 2763 | assert(((FD && CGF) || (!FD && !CGF)) && |
| 2764 | "Incorrect use - FD and CGF should either be both null or not!" ); |
| 2765 | // Create MDNodes that represent the kernel arg metadata. |
| 2766 | // Each MDNode is a list in the form of "key", N number of values which is |
| 2767 | // the same number of values as their are kernel arguments. |
| 2768 | |
| 2769 | const PrintingPolicy &Policy = Context.getPrintingPolicy(); |
| 2770 | |
| 2771 | // MDNode for the kernel argument address space qualifiers. |
| 2772 | SmallVector<llvm::Metadata *, 8> addressQuals; |
| 2773 | |
| 2774 | // MDNode for the kernel argument access qualifiers (images only). |
| 2775 | SmallVector<llvm::Metadata *, 8> accessQuals; |
| 2776 | |
| 2777 | // MDNode for the kernel argument type names. |
| 2778 | SmallVector<llvm::Metadata *, 8> argTypeNames; |
| 2779 | |
| 2780 | // MDNode for the kernel argument base type names. |
| 2781 | SmallVector<llvm::Metadata *, 8> argBaseTypeNames; |
| 2782 | |
| 2783 | // MDNode for the kernel argument type qualifiers. |
| 2784 | SmallVector<llvm::Metadata *, 8> argTypeQuals; |
| 2785 | |
| 2786 | // MDNode for the kernel argument names. |
| 2787 | SmallVector<llvm::Metadata *, 8> argNames; |
| 2788 | |
| 2789 | if (FD && CGF) |
| 2790 | for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { |
| 2791 | const ParmVarDecl *parm = FD->getParamDecl(i); |
| 2792 | // Get argument name. |
| 2793 | argNames.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: parm->getName())); |
| 2794 | |
| 2795 | if (!getLangOpts().OpenCL) |
| 2796 | continue; |
| 2797 | QualType ty = parm->getType(); |
| 2798 | std::string typeQuals; |
| 2799 | |
| 2800 | // Get image and pipe access qualifier: |
| 2801 | if (ty->isImageType() || ty->isPipeType()) { |
| 2802 | const Decl *PDecl = parm; |
| 2803 | if (const auto *TD = ty->getAs<TypedefType>()) |
| 2804 | PDecl = TD->getDecl(); |
| 2805 | const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); |
| 2806 | if (A && A->isWriteOnly()) |
| 2807 | accessQuals.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: "write_only" )); |
| 2808 | else if (A && A->isReadWrite()) |
| 2809 | accessQuals.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: "read_write" )); |
| 2810 | else |
| 2811 | accessQuals.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: "read_only" )); |
| 2812 | } else |
| 2813 | accessQuals.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: "none" )); |
| 2814 | |
| 2815 | auto getTypeSpelling = [&](QualType Ty) { |
| 2816 | auto typeName = Ty.getUnqualifiedType().getAsString(Policy); |
| 2817 | |
| 2818 | if (Ty.isCanonical()) { |
| 2819 | StringRef typeNameRef = typeName; |
| 2820 | // Turn "unsigned type" to "utype" |
| 2821 | if (typeNameRef.consume_front(Prefix: "unsigned " )) |
| 2822 | return std::string("u" ) + typeNameRef.str(); |
| 2823 | if (typeNameRef.consume_front(Prefix: "signed " )) |
| 2824 | return typeNameRef.str(); |
| 2825 | } |
| 2826 | |
| 2827 | return typeName; |
| 2828 | }; |
| 2829 | |
| 2830 | if (ty->isPointerType()) { |
| 2831 | QualType pointeeTy = ty->getPointeeType(); |
| 2832 | |
| 2833 | // Get address qualifier. |
| 2834 | addressQuals.push_back( |
| 2835 | Elt: llvm::ConstantAsMetadata::get(C: CGF->Builder.getInt32( |
| 2836 | C: ArgInfoAddressSpace(AS: pointeeTy.getAddressSpace())))); |
| 2837 | |
| 2838 | // Get argument type name. |
| 2839 | std::string typeName = getTypeSpelling(pointeeTy) + "*" ; |
| 2840 | std::string baseTypeName = |
| 2841 | getTypeSpelling(pointeeTy.getCanonicalType()) + "*" ; |
| 2842 | argTypeNames.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: typeName)); |
| 2843 | argBaseTypeNames.push_back( |
| 2844 | Elt: llvm::MDString::get(Context&: VMContext, Str: baseTypeName)); |
| 2845 | |
| 2846 | // Get argument type qualifiers: |
| 2847 | if (ty.isRestrictQualified()) |
| 2848 | typeQuals = "restrict" ; |
| 2849 | if (pointeeTy.isConstQualified() || |
| 2850 | (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) |
| 2851 | typeQuals += typeQuals.empty() ? "const" : " const" ; |
| 2852 | if (pointeeTy.isVolatileQualified()) |
| 2853 | typeQuals += typeQuals.empty() ? "volatile" : " volatile" ; |
| 2854 | } else { |
| 2855 | uint32_t AddrSpc = 0; |
| 2856 | bool isPipe = ty->isPipeType(); |
| 2857 | if (ty->isImageType() || isPipe) |
| 2858 | AddrSpc = ArgInfoAddressSpace(AS: LangAS::opencl_global); |
| 2859 | |
| 2860 | addressQuals.push_back( |
| 2861 | Elt: llvm::ConstantAsMetadata::get(C: CGF->Builder.getInt32(C: AddrSpc))); |
| 2862 | |
| 2863 | // Get argument type name. |
| 2864 | ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; |
| 2865 | std::string typeName = getTypeSpelling(ty); |
| 2866 | std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); |
| 2867 | |
| 2868 | // Remove access qualifiers on images |
| 2869 | // (as they are inseparable from type in clang implementation, |
| 2870 | // but OpenCL spec provides a special query to get access qualifier |
| 2871 | // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): |
| 2872 | if (ty->isImageType()) { |
| 2873 | removeImageAccessQualifier(TyName&: typeName); |
| 2874 | removeImageAccessQualifier(TyName&: baseTypeName); |
| 2875 | } |
| 2876 | |
| 2877 | argTypeNames.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: typeName)); |
| 2878 | argBaseTypeNames.push_back( |
| 2879 | Elt: llvm::MDString::get(Context&: VMContext, Str: baseTypeName)); |
| 2880 | |
| 2881 | if (isPipe) |
| 2882 | typeQuals = "pipe" ; |
| 2883 | } |
| 2884 | argTypeQuals.push_back(Elt: llvm::MDString::get(Context&: VMContext, Str: typeQuals)); |
| 2885 | } |
| 2886 | |
| 2887 | if (getLangOpts().OpenCL) { |
| 2888 | Fn->setMetadata(Kind: "kernel_arg_addr_space" , |
| 2889 | Node: llvm::MDNode::get(Context&: VMContext, MDs: addressQuals)); |
| 2890 | Fn->setMetadata(Kind: "kernel_arg_access_qual" , |
| 2891 | Node: llvm::MDNode::get(Context&: VMContext, MDs: accessQuals)); |
| 2892 | Fn->setMetadata(Kind: "kernel_arg_type" , |
| 2893 | Node: llvm::MDNode::get(Context&: VMContext, MDs: argTypeNames)); |
| 2894 | Fn->setMetadata(Kind: "kernel_arg_base_type" , |
| 2895 | Node: llvm::MDNode::get(Context&: VMContext, MDs: argBaseTypeNames)); |
| 2896 | Fn->setMetadata(Kind: "kernel_arg_type_qual" , |
| 2897 | Node: llvm::MDNode::get(Context&: VMContext, MDs: argTypeQuals)); |
| 2898 | } |
| 2899 | if (getCodeGenOpts().EmitOpenCLArgMetadata || |
| 2900 | getCodeGenOpts().HIPSaveKernelArgName) |
| 2901 | Fn->setMetadata(Kind: "kernel_arg_name" , |
| 2902 | Node: llvm::MDNode::get(Context&: VMContext, MDs: argNames)); |
| 2903 | } |
| 2904 | |
| 2905 | /// Determines whether the language options require us to model |
| 2906 | /// unwind exceptions. We treat -fexceptions as mandating this |
| 2907 | /// except under the fragile ObjC ABI with only ObjC exceptions |
| 2908 | /// enabled. This means, for example, that C with -fexceptions |
| 2909 | /// enables this. |
| 2910 | static bool hasUnwindExceptions(const LangOptions &LangOpts) { |
| 2911 | // If exceptions are completely disabled, obviously this is false. |
| 2912 | if (!LangOpts.Exceptions) return false; |
| 2913 | |
| 2914 | // If C++ exceptions are enabled, this is true. |
| 2915 | if (LangOpts.CXXExceptions) return true; |
| 2916 | |
| 2917 | // If ObjC exceptions are enabled, this depends on the ABI. |
| 2918 | if (LangOpts.ObjCExceptions) { |
| 2919 | return LangOpts.ObjCRuntime.hasUnwindExceptions(); |
| 2920 | } |
| 2921 | |
| 2922 | return true; |
| 2923 | } |
| 2924 | |
| 2925 | static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, |
| 2926 | const CXXMethodDecl *MD) { |
| 2927 | // Check that the type metadata can ever actually be used by a call. |
| 2928 | if (!CGM.getCodeGenOpts().LTOUnit || |
| 2929 | !CGM.HasHiddenLTOVisibility(RD: MD->getParent())) |
| 2930 | return false; |
| 2931 | |
| 2932 | // Only functions whose address can be taken with a member function pointer |
| 2933 | // need this sort of type metadata. |
| 2934 | return MD->isImplicitObjectMemberFunction() && !MD->isVirtual() && |
| 2935 | !isa<CXXConstructorDecl, CXXDestructorDecl>(Val: MD); |
| 2936 | } |
| 2937 | |
| 2938 | SmallVector<const CXXRecordDecl *, 0> |
| 2939 | CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { |
| 2940 | llvm::SetVector<const CXXRecordDecl *> MostBases; |
| 2941 | |
| 2942 | std::function<void (const CXXRecordDecl *)> CollectMostBases; |
| 2943 | CollectMostBases = [&](const CXXRecordDecl *RD) { |
| 2944 | if (RD->getNumBases() == 0) |
| 2945 | MostBases.insert(X: RD); |
| 2946 | for (const CXXBaseSpecifier &B : RD->bases()) |
| 2947 | CollectMostBases(B.getType()->getAsCXXRecordDecl()); |
| 2948 | }; |
| 2949 | CollectMostBases(RD); |
| 2950 | return MostBases.takeVector(); |
| 2951 | } |
| 2952 | |
| 2953 | void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, |
| 2954 | llvm::Function *F) { |
| 2955 | llvm::AttrBuilder B(F->getContext()); |
| 2956 | |
| 2957 | if ((!D || !D->hasAttr<NoUwtableAttr>()) && CodeGenOpts.UnwindTables) |
| 2958 | B.addUWTableAttr(Kind: llvm::UWTableKind(CodeGenOpts.UnwindTables)); |
| 2959 | |
| 2960 | if (CodeGenOpts.StackClashProtector) |
| 2961 | B.addAttribute(A: "probe-stack" , V: "inline-asm" ); |
| 2962 | |
| 2963 | if (CodeGenOpts.StackProbeSize && CodeGenOpts.StackProbeSize != 4096) |
| 2964 | B.addAttribute(A: "stack-probe-size" , |
| 2965 | V: std::to_string(val: CodeGenOpts.StackProbeSize)); |
| 2966 | |
| 2967 | if (!hasUnwindExceptions(LangOpts)) |
| 2968 | B.addAttribute(Val: llvm::Attribute::NoUnwind); |
| 2969 | |
| 2970 | if (std::optional<llvm::Attribute::AttrKind> Attr = |
| 2971 | StackProtectorAttribute(D)) { |
| 2972 | B.addAttribute(Val: *Attr); |
| 2973 | } |
| 2974 | |
| 2975 | if (!D) { |
| 2976 | // Non-entry HLSL functions must always be inlined. |
| 2977 | if (getLangOpts().HLSL && !F->hasFnAttribute(Kind: llvm::Attribute::NoInline)) |
| 2978 | B.addAttribute(Val: llvm::Attribute::AlwaysInline); |
| 2979 | // If we don't have a declaration to control inlining, the function isn't |
| 2980 | // explicitly marked as alwaysinline for semantic reasons, and inlining is |
| 2981 | // disabled, mark the function as noinline. |
| 2982 | else if (!F->hasFnAttribute(Kind: llvm::Attribute::AlwaysInline) && |
| 2983 | CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) |
| 2984 | B.addAttribute(Val: llvm::Attribute::NoInline); |
| 2985 | |
| 2986 | F->addFnAttrs(Attrs: B); |
| 2987 | return; |
| 2988 | } |
| 2989 | |
| 2990 | // Handle SME attributes that apply to function definitions, |
| 2991 | // rather than to function prototypes. |
| 2992 | if (D->hasAttr<ArmLocallyStreamingAttr>()) |
| 2993 | B.addAttribute(A: "aarch64_pstate_sm_body" ); |
| 2994 | |
| 2995 | if (auto *Attr = D->getAttr<ArmNewAttr>()) { |
| 2996 | if (Attr->isNewZA()) |
| 2997 | B.addAttribute(A: "aarch64_new_za" ); |
| 2998 | if (Attr->isNewZT0()) |
| 2999 | B.addAttribute(A: "aarch64_new_zt0" ); |
| 3000 | } |
| 3001 | |
| 3002 | // Track whether we need to add the optnone LLVM attribute, |
| 3003 | // starting with the default for this optimization level. |
| 3004 | bool ShouldAddOptNone = |
| 3005 | !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; |
| 3006 | // We can't add optnone in the following cases, it won't pass the verifier. |
| 3007 | ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); |
| 3008 | ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); |
| 3009 | |
| 3010 | // Non-entry HLSL functions must always be inlined. |
| 3011 | if (getLangOpts().HLSL && !F->hasFnAttribute(Kind: llvm::Attribute::NoInline) && |
| 3012 | !D->hasAttr<NoInlineAttr>()) { |
| 3013 | B.addAttribute(Val: llvm::Attribute::AlwaysInline); |
| 3014 | } else if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && |
| 3015 | !F->hasFnAttribute(Kind: llvm::Attribute::AlwaysInline)) { |
| 3016 | // Add optnone, but do so only if the function isn't always_inline. |
| 3017 | B.addAttribute(Val: llvm::Attribute::OptimizeNone); |
| 3018 | |
| 3019 | // OptimizeNone implies noinline; we should not be inlining such functions. |
| 3020 | B.addAttribute(Val: llvm::Attribute::NoInline); |
| 3021 | |
| 3022 | // We still need to handle naked functions even though optnone subsumes |
| 3023 | // much of their semantics. |
| 3024 | if (D->hasAttr<NakedAttr>()) |
| 3025 | B.addAttribute(Val: llvm::Attribute::Naked); |
| 3026 | |
| 3027 | // OptimizeNone wins over OptimizeForSize and MinSize. |
| 3028 | F->removeFnAttr(Kind: llvm::Attribute::OptimizeForSize); |
| 3029 | F->removeFnAttr(Kind: llvm::Attribute::MinSize); |
| 3030 | } else if (D->hasAttr<NakedAttr>()) { |
| 3031 | // Naked implies noinline: we should not be inlining such functions. |
| 3032 | B.addAttribute(Val: llvm::Attribute::Naked); |
| 3033 | B.addAttribute(Val: llvm::Attribute::NoInline); |
| 3034 | } else if (D->hasAttr<NoDuplicateAttr>()) { |
| 3035 | B.addAttribute(Val: llvm::Attribute::NoDuplicate); |
| 3036 | } else if (D->hasAttr<NoInlineAttr>() && |
| 3037 | !F->hasFnAttribute(Kind: llvm::Attribute::AlwaysInline)) { |
| 3038 | // Add noinline if the function isn't always_inline. |
| 3039 | B.addAttribute(Val: llvm::Attribute::NoInline); |
| 3040 | } else if (D->hasAttr<AlwaysInlineAttr>() && |
| 3041 | !F->hasFnAttribute(Kind: llvm::Attribute::NoInline)) { |
| 3042 | // (noinline wins over always_inline, and we can't specify both in IR) |
| 3043 | B.addAttribute(Val: llvm::Attribute::AlwaysInline); |
| 3044 | } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { |
| 3045 | // If we're not inlining, then force everything that isn't always_inline to |
| 3046 | // carry an explicit noinline attribute. |
| 3047 | if (!F->hasFnAttribute(Kind: llvm::Attribute::AlwaysInline)) |
| 3048 | B.addAttribute(Val: llvm::Attribute::NoInline); |
| 3049 | } else { |
| 3050 | // Otherwise, propagate the inline hint attribute and potentially use its |
| 3051 | // absence to mark things as noinline. |
| 3052 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 3053 | // Search function and template pattern redeclarations for inline. |
| 3054 | auto CheckForInline = [](const FunctionDecl *FD) { |
| 3055 | auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { |
| 3056 | return Redecl->isInlineSpecified(); |
| 3057 | }; |
| 3058 | if (any_of(Range: FD->redecls(), P: CheckRedeclForInline)) |
| 3059 | return true; |
| 3060 | const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); |
| 3061 | if (!Pattern) |
| 3062 | return false; |
| 3063 | return any_of(Range: Pattern->redecls(), P: CheckRedeclForInline); |
| 3064 | }; |
| 3065 | if (CheckForInline(FD)) { |
| 3066 | B.addAttribute(Val: llvm::Attribute::InlineHint); |
| 3067 | } else if (CodeGenOpts.getInlining() == |
| 3068 | CodeGenOptions::OnlyHintInlining && |
| 3069 | !FD->isInlined() && |
| 3070 | !F->hasFnAttribute(Kind: llvm::Attribute::AlwaysInline)) { |
| 3071 | B.addAttribute(Val: llvm::Attribute::NoInline); |
| 3072 | } |
| 3073 | } |
| 3074 | } |
| 3075 | |
| 3076 | // Add other optimization related attributes if we are optimizing this |
| 3077 | // function. |
| 3078 | if (!D->hasAttr<OptimizeNoneAttr>()) { |
| 3079 | if (D->hasAttr<ColdAttr>()) { |
| 3080 | if (!ShouldAddOptNone) |
| 3081 | B.addAttribute(Val: llvm::Attribute::OptimizeForSize); |
| 3082 | B.addAttribute(Val: llvm::Attribute::Cold); |
| 3083 | } |
| 3084 | if (D->hasAttr<HotAttr>()) |
| 3085 | B.addAttribute(Val: llvm::Attribute::Hot); |
| 3086 | if (D->hasAttr<MinSizeAttr>()) |
| 3087 | B.addAttribute(Val: llvm::Attribute::MinSize); |
| 3088 | } |
| 3089 | |
| 3090 | // Add `nooutline` if Outlining is disabled with a command-line flag or a |
| 3091 | // function attribute. |
| 3092 | if (CodeGenOpts.DisableOutlining || D->hasAttr<NoOutlineAttr>()) |
| 3093 | B.addAttribute(Val: llvm::Attribute::NoOutline); |
| 3094 | |
| 3095 | F->addFnAttrs(Attrs: B); |
| 3096 | |
| 3097 | llvm::MaybeAlign ExplicitAlignment; |
| 3098 | if (unsigned alignment = D->getMaxAlignment() / Context.getCharWidth()) |
| 3099 | ExplicitAlignment = llvm::Align(alignment); |
| 3100 | else if (LangOpts.FunctionAlignment) |
| 3101 | ExplicitAlignment = llvm::Align(1ull << LangOpts.FunctionAlignment); |
| 3102 | |
| 3103 | if (ExplicitAlignment) { |
| 3104 | F->setAlignment(ExplicitAlignment); |
| 3105 | F->setPreferredAlignment(ExplicitAlignment); |
| 3106 | } else if (LangOpts.PreferredFunctionAlignment) { |
| 3107 | F->setPreferredAlignment(llvm::Align(LangOpts.PreferredFunctionAlignment)); |
| 3108 | } |
| 3109 | |
| 3110 | // Some C++ ABIs require 2-byte alignment for member functions, in order to |
| 3111 | // reserve a bit for differentiating between virtual and non-virtual member |
| 3112 | // functions. If the current target's C++ ABI requires this and this is a |
| 3113 | // member function, set its alignment accordingly. |
| 3114 | if (getTarget().getCXXABI().areMemberFunctionsAligned()) { |
| 3115 | if (isa<CXXMethodDecl>(Val: D) && F->getPointerAlignment(DL: getDataLayout()) < 2) |
| 3116 | F->setAlignment(std::max(a: llvm::Align(2), b: F->getAlign().valueOrOne())); |
| 3117 | } |
| 3118 | |
| 3119 | // In the cross-dso CFI mode with canonical jump tables, we want !type |
| 3120 | // attributes on definitions only. |
| 3121 | if (CodeGenOpts.SanitizeCfiCrossDso && |
| 3122 | CodeGenOpts.SanitizeCfiCanonicalJumpTables) { |
| 3123 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 3124 | // Skip available_externally functions. They won't be codegen'ed in the |
| 3125 | // current module anyway. |
| 3126 | if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) |
| 3127 | createFunctionTypeMetadataForIcall(FD, F); |
| 3128 | } |
| 3129 | } |
| 3130 | |
| 3131 | if (CodeGenOpts.CallGraphSection) { |
| 3132 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
| 3133 | createIndirectFunctionTypeMD(FD, F); |
| 3134 | } |
| 3135 | |
| 3136 | // Emit type metadata on member functions for member function pointer checks. |
| 3137 | // These are only ever necessary on definitions; we're guaranteed that the |
| 3138 | // definition will be present in the LTO unit as a result of LTO visibility. |
| 3139 | auto *MD = dyn_cast<CXXMethodDecl>(Val: D); |
| 3140 | if (MD && requiresMemberFunctionPointerTypeMetadata(CGM&: *this, MD)) { |
| 3141 | for (const CXXRecordDecl *Base : getMostBaseClasses(RD: MD->getParent())) { |
| 3142 | llvm::Metadata *Id = |
| 3143 | CreateMetadataIdentifierForType(T: Context.getMemberPointerType( |
| 3144 | T: MD->getType(), /*Qualifier=*/std::nullopt, Cls: Base)); |
| 3145 | F->addTypeMetadata(Offset: 0, TypeID: Id); |
| 3146 | } |
| 3147 | } |
| 3148 | |
| 3149 | // Attach "sycl-module-id" to sycl_external function definitions to mark |
| 3150 | // them as entry points for per-translation-unit device-code splitting. |
| 3151 | if (getLangOpts().SYCLIsDevice) { |
| 3152 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) |
| 3153 | if (FD->hasAttr<SYCLExternalAttr>()) |
| 3154 | addSYCLModuleIdAttr(Fn: F); |
| 3155 | } |
| 3156 | } |
| 3157 | |
| 3158 | void CodeGenModule::addSYCLModuleIdAttr(llvm::Function *Fn) { |
| 3159 | assert(getLangOpts().SYCLIsDevice); |
| 3160 | Fn->addFnAttr(Kind: "sycl-module-id" , Val: getModule().getModuleIdentifier()); |
| 3161 | } |
| 3162 | |
| 3163 | void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { |
| 3164 | const Decl *D = GD.getDecl(); |
| 3165 | if (isa_and_nonnull<NamedDecl>(Val: D)) |
| 3166 | setGVProperties(GV, GD); |
| 3167 | else |
| 3168 | GV->setVisibility(llvm::GlobalValue::DefaultVisibility); |
| 3169 | |
| 3170 | if (D && D->hasAttr<UsedAttr>()) |
| 3171 | addUsedOrCompilerUsedGlobal(GV); |
| 3172 | |
| 3173 | if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: D); |
| 3174 | VD && |
| 3175 | ((CodeGenOpts.KeepPersistentStorageVariables && |
| 3176 | (VD->getStorageDuration() == SD_Static || |
| 3177 | VD->getStorageDuration() == SD_Thread)) || |
| 3178 | (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && |
| 3179 | VD->getType().isConstQualified()))) |
| 3180 | addUsedOrCompilerUsedGlobal(GV); |
| 3181 | } |
| 3182 | |
| 3183 | /// Get the feature delta from the default feature map for the given target CPU. |
| 3184 | static std::vector<std::string> |
| 3185 | getFeatureDeltaFromDefault(const CodeGenModule &CGM, StringRef TargetCPU, |
| 3186 | llvm::StringMap<bool> &FeatureMap) { |
| 3187 | llvm::StringMap<bool> DefaultFeatureMap; |
| 3188 | CGM.getTarget().initFeatureMap( |
| 3189 | Features&: DefaultFeatureMap, Diags&: CGM.getContext().getDiagnostics(), CPU: TargetCPU, FeatureVec: {}); |
| 3190 | |
| 3191 | std::vector<std::string> Delta; |
| 3192 | for (const auto &[K, V] : FeatureMap) { |
| 3193 | auto DefaultIt = DefaultFeatureMap.find(Key: K); |
| 3194 | if (DefaultIt == DefaultFeatureMap.end() || DefaultIt->getValue() != V) |
| 3195 | Delta.push_back(x: (V ? "+" : "-" ) + K.str()); |
| 3196 | } |
| 3197 | |
| 3198 | return Delta; |
| 3199 | } |
| 3200 | |
| 3201 | bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, |
| 3202 | llvm::AttrBuilder &Attrs, |
| 3203 | bool SetTargetFeatures) { |
| 3204 | // Add target-cpu and target-features attributes to functions. If |
| 3205 | // we have a decl for the function and it has a target attribute then |
| 3206 | // parse that and add it to the feature set. |
| 3207 | StringRef TargetCPU = getTarget().getTargetOpts().CPU; |
| 3208 | StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; |
| 3209 | std::vector<std::string> Features; |
| 3210 | const auto *FD = dyn_cast_or_null<FunctionDecl>(Val: GD.getDecl()); |
| 3211 | FD = FD ? FD->getMostRecentDecl() : FD; |
| 3212 | const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; |
| 3213 | const auto *TV = FD ? FD->getAttr<TargetVersionAttr>() : nullptr; |
| 3214 | assert((!TD || !TV) && "both target_version and target specified" ); |
| 3215 | const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; |
| 3216 | const auto *TC = FD ? FD->getAttr<TargetClonesAttr>() : nullptr; |
| 3217 | bool AddedAttr = false; |
| 3218 | if (TD || TV || SD || TC) { |
| 3219 | llvm::StringMap<bool> FeatureMap; |
| 3220 | getContext().getFunctionFeatureMap(FeatureMap, GD); |
| 3221 | |
| 3222 | // Now add the target-cpu and target-features to the function. |
| 3223 | // While we populated the feature map above, we still need to |
| 3224 | // get and parse the target/target_clones attribute so we can |
| 3225 | // get the cpu for the function. |
| 3226 | StringRef FeatureStr = TD ? TD->getFeaturesStr() : StringRef(); |
| 3227 | if (TC && (getTriple().isOSAIX() || getTriple().isX86())) |
| 3228 | FeatureStr = TC->getFeatureStr(Index: GD.getMultiVersionIndex()); |
| 3229 | if (!FeatureStr.empty()) { |
| 3230 | ParsedTargetAttr ParsedAttr = Target.parseTargetAttr(Str: FeatureStr); |
| 3231 | if (!ParsedAttr.CPU.empty() && |
| 3232 | getTarget().isValidCPUName(Name: ParsedAttr.CPU)) { |
| 3233 | TargetCPU = ParsedAttr.CPU; |
| 3234 | TuneCPU = "" ; // Clear the tune CPU. |
| 3235 | } |
| 3236 | if (!ParsedAttr.Tune.empty() && |
| 3237 | getTarget().isValidCPUName(Name: ParsedAttr.Tune)) |
| 3238 | TuneCPU = ParsedAttr.Tune; |
| 3239 | } |
| 3240 | |
| 3241 | if (SD) { |
| 3242 | // Apply the given CPU name as the 'tune-cpu' so that the optimizer can |
| 3243 | // favor this processor. |
| 3244 | TuneCPU = SD->getCPUName(Index: GD.getMultiVersionIndex())->getName(); |
| 3245 | } |
| 3246 | |
| 3247 | // For AMDGPU, only emit delta features (features that differ from the |
| 3248 | // target CPU's defaults). Other targets might want to follow a similar |
| 3249 | // pattern. |
| 3250 | if (getTarget().getTriple().isAMDGPU()) { |
| 3251 | Features = getFeatureDeltaFromDefault(CGM: *this, TargetCPU, FeatureMap); |
| 3252 | } else { |
| 3253 | // Produce the canonical string for this set of features. |
| 3254 | for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) |
| 3255 | Features.push_back(x: (Entry.getValue() ? "+" : "-" ) + |
| 3256 | Entry.getKey().str()); |
| 3257 | } |
| 3258 | } else { |
| 3259 | // Otherwise just add the existing target cpu and target features to the |
| 3260 | // function. |
| 3261 | if (SetTargetFeatures && getTarget().getTriple().isAMDGPU()) { |
| 3262 | llvm::StringMap<bool> FeatureMap; |
| 3263 | if (FD) { |
| 3264 | getContext().getFunctionFeatureMap(FeatureMap, GD); |
| 3265 | } else { |
| 3266 | getTarget().initFeatureMap(Features&: FeatureMap, Diags&: getContext().getDiagnostics(), |
| 3267 | CPU: TargetCPU, |
| 3268 | FeatureVec: getTarget().getTargetOpts().Features); |
| 3269 | } |
| 3270 | Features = getFeatureDeltaFromDefault(CGM: *this, TargetCPU, FeatureMap); |
| 3271 | } else { |
| 3272 | Features = getTarget().getTargetOpts().Features; |
| 3273 | } |
| 3274 | } |
| 3275 | |
| 3276 | if (!TargetCPU.empty()) { |
| 3277 | Attrs.addAttribute(A: "target-cpu" , V: TargetCPU); |
| 3278 | AddedAttr = true; |
| 3279 | } |
| 3280 | if (!TuneCPU.empty()) { |
| 3281 | Attrs.addAttribute(A: "tune-cpu" , V: TuneCPU); |
| 3282 | AddedAttr = true; |
| 3283 | } |
| 3284 | if (!Features.empty() && SetTargetFeatures) { |
| 3285 | llvm::erase_if(C&: Features, P: [&](const std::string& F) { |
| 3286 | return getTarget().isReadOnlyFeature(Feature: F.substr(pos: 1)); |
| 3287 | }); |
| 3288 | llvm::sort(C&: Features); |
| 3289 | Attrs.addAttribute(A: "target-features" , V: llvm::join(R&: Features, Separator: "," )); |
| 3290 | AddedAttr = true; |
| 3291 | } |
| 3292 | // Add metadata for AArch64 Function Multi Versioning. |
| 3293 | if (getTarget().getTriple().isAArch64()) { |
| 3294 | llvm::SmallVector<StringRef, 8> Feats; |
| 3295 | bool IsDefault = false; |
| 3296 | if (TV) { |
| 3297 | IsDefault = TV->isDefaultVersion(); |
| 3298 | TV->getFeatures(Out&: Feats); |
| 3299 | } else if (TC) { |
| 3300 | IsDefault = TC->isDefaultVersion(Index: GD.getMultiVersionIndex()); |
| 3301 | TC->getFeatures(Out&: Feats, Index: GD.getMultiVersionIndex()); |
| 3302 | } |
| 3303 | if (IsDefault) { |
| 3304 | Attrs.addAttribute(A: "fmv-features" ); |
| 3305 | AddedAttr = true; |
| 3306 | } else if (!Feats.empty()) { |
| 3307 | // Sort features and remove duplicates. |
| 3308 | std::set<StringRef> OrderedFeats(Feats.begin(), Feats.end()); |
| 3309 | std::string FMVFeatures; |
| 3310 | for (StringRef F : OrderedFeats) |
| 3311 | FMVFeatures.append(str: "," + F.str()); |
| 3312 | Attrs.addAttribute(A: "fmv-features" , V: FMVFeatures.substr(pos: 1)); |
| 3313 | AddedAttr = true; |
| 3314 | } |
| 3315 | } |
| 3316 | return AddedAttr; |
| 3317 | } |
| 3318 | |
| 3319 | void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, |
| 3320 | llvm::GlobalObject *GO) { |
| 3321 | const Decl *D = GD.getDecl(); |
| 3322 | SetCommonAttributes(GD, GV: GO); |
| 3323 | |
| 3324 | if (D) { |
| 3325 | if (auto *GV = dyn_cast<llvm::GlobalVariable>(Val: GO)) { |
| 3326 | if (D->hasAttr<RetainAttr>()) |
| 3327 | addUsedGlobal(GV); |
| 3328 | if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) |
| 3329 | GV->addAttribute(Kind: "bss-section" , Val: SA->getName()); |
| 3330 | if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) |
| 3331 | GV->addAttribute(Kind: "data-section" , Val: SA->getName()); |
| 3332 | if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) |
| 3333 | GV->addAttribute(Kind: "rodata-section" , Val: SA->getName()); |
| 3334 | if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) |
| 3335 | GV->addAttribute(Kind: "relro-section" , Val: SA->getName()); |
| 3336 | } |
| 3337 | |
| 3338 | if (auto *F = dyn_cast<llvm::Function>(Val: GO)) { |
| 3339 | if (D->hasAttr<RetainAttr>()) |
| 3340 | addUsedGlobal(GV: F); |
| 3341 | if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) |
| 3342 | if (!D->getAttr<SectionAttr>()) |
| 3343 | F->setSection(SA->getName()); |
| 3344 | |
| 3345 | llvm::AttrBuilder Attrs(F->getContext()); |
| 3346 | if (GetCPUAndFeaturesAttributes(GD, Attrs)) { |
| 3347 | // We know that GetCPUAndFeaturesAttributes will always have the |
| 3348 | // newest set, since it has the newest possible FunctionDecl, so the |
| 3349 | // new ones should replace the old. |
| 3350 | llvm::AttributeMask RemoveAttrs; |
| 3351 | RemoveAttrs.addAttribute(A: "target-cpu" ); |
| 3352 | RemoveAttrs.addAttribute(A: "target-features" ); |
| 3353 | RemoveAttrs.addAttribute(A: "fmv-features" ); |
| 3354 | RemoveAttrs.addAttribute(A: "tune-cpu" ); |
| 3355 | F->removeFnAttrs(Attrs: RemoveAttrs); |
| 3356 | F->addFnAttrs(Attrs); |
| 3357 | } |
| 3358 | } |
| 3359 | |
| 3360 | if (const auto *CSA = D->getAttr<CodeSegAttr>()) |
| 3361 | GO->setSection(CSA->getName()); |
| 3362 | else if (const auto *SA = D->getAttr<SectionAttr>()) |
| 3363 | GO->setSection(SA->getName()); |
| 3364 | } |
| 3365 | |
| 3366 | getTargetCodeGenInfo().setTargetAttributes(D, GV: GO, M&: *this); |
| 3367 | } |
| 3368 | |
| 3369 | void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, |
| 3370 | llvm::Function *F, |
| 3371 | const CGFunctionInfo &FI) { |
| 3372 | const Decl *D = GD.getDecl(); |
| 3373 | SetLLVMFunctionAttributes(GD, Info: FI, F, /*IsThunk=*/false); |
| 3374 | SetLLVMFunctionAttributesForDefinition(D, F); |
| 3375 | |
| 3376 | F->setLinkage(llvm::Function::InternalLinkage); |
| 3377 | |
| 3378 | setNonAliasAttributes(GD, GO: F); |
| 3379 | } |
| 3380 | |
| 3381 | static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { |
| 3382 | // Set linkage and visibility in case we never see a definition. |
| 3383 | LinkageInfo LV = ND->getLinkageAndVisibility(); |
| 3384 | // Don't set internal linkage on declarations. |
| 3385 | // "extern_weak" is overloaded in LLVM; we probably should have |
| 3386 | // separate linkage types for this. |
| 3387 | if (isExternallyVisible(L: LV.getLinkage()) && |
| 3388 | (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) |
| 3389 | GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); |
| 3390 | } |
| 3391 | |
| 3392 | static bool hasExistingGeneralizedTypeMD(llvm::Function *F) { |
| 3393 | llvm::MDNode *MD = F->getMetadata(KindID: llvm::LLVMContext::MD_type); |
| 3394 | return MD && MD->hasGeneralizedMDString(); |
| 3395 | } |
| 3396 | |
| 3397 | void CodeGenModule::createIndirectFunctionTypeMD(const FunctionDecl *FD, |
| 3398 | llvm::Function *F) { |
| 3399 | // Return if generalized type metadata is already attached. |
| 3400 | if (hasExistingGeneralizedTypeMD(F)) |
| 3401 | return; |
| 3402 | |
| 3403 | // All functions which are not internal linkage could be indirect targets. |
| 3404 | // Address taken functions with internal linkage could be indirect targets. |
| 3405 | if (!F->hasLocalLinkage() || |
| 3406 | F->getFunction().hasAddressTaken(nullptr, /*IgnoreCallbackUses=*/true, |
| 3407 | /*IgnoreAssumeLikeCalls=*/true, |
| 3408 | /*IgnoreLLVMUsed=*/IngoreLLVMUsed: false)) |
| 3409 | F->addTypeMetadata(Offset: 0, TypeID: CreateMetadataIdentifierGeneralized(T: FD->getType())); |
| 3410 | } |
| 3411 | |
| 3412 | void CodeGenModule::createFunctionTypeMetadataForIcall(const FunctionDecl *FD, |
| 3413 | llvm::Function *F) { |
| 3414 | // Only if we are checking indirect calls. |
| 3415 | if (!LangOpts.Sanitize.has(K: SanitizerKind::CFIICall)) |
| 3416 | return; |
| 3417 | |
| 3418 | // Non-static class methods are handled via vtable or member function pointer |
| 3419 | // checks elsewhere. |
| 3420 | if (isa<CXXMethodDecl>(Val: FD) && !cast<CXXMethodDecl>(Val: FD)->isStatic()) |
| 3421 | return; |
| 3422 | |
| 3423 | QualType FnType = GeneralizeFunctionType(Ctx&: getContext(), Ty: FD->getType(), |
| 3424 | /*GeneralizePointers=*/false); |
| 3425 | llvm::Metadata *MD = CreateMetadataIdentifierForType(T: FnType); |
| 3426 | F->addTypeMetadata(Offset: 0, TypeID: MD); |
| 3427 | // Add the generalized identifier if not added already. |
| 3428 | if (!hasExistingGeneralizedTypeMD(F)) { |
| 3429 | QualType GenPtrFnType = GeneralizeFunctionType(Ctx&: getContext(), Ty: FD->getType(), |
| 3430 | /*GeneralizePointers=*/true); |
| 3431 | F->addTypeMetadata(Offset: 0, TypeID: CreateMetadataIdentifierGeneralized(T: GenPtrFnType)); |
| 3432 | } |
| 3433 | |
| 3434 | // Emit a hash-based bit set entry for cross-DSO calls. |
| 3435 | if (CodeGenOpts.SanitizeCfiCrossDso) |
| 3436 | if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) |
| 3437 | F->addTypeMetadata(Offset: 0, TypeID: llvm::ConstantAsMetadata::get(C: CrossDsoTypeId)); |
| 3438 | } |
| 3439 | |
| 3440 | void CodeGenModule::createCalleeTypeMetadataForIcall(const QualType &QT, |
| 3441 | llvm::CallBase *CB) { |
| 3442 | // Only if needed for call graph section and only for indirect calls that are |
| 3443 | // visible externally. |
| 3444 | // TODO: Handle local linkage symbols so they are not left out of call graph |
| 3445 | // reducing precision. |
| 3446 | if (!CodeGenOpts.CallGraphSection || !CB->isIndirectCall() || |
| 3447 | !isExternallyVisible(L: QT->getLinkage())) |
| 3448 | return; |
| 3449 | |
| 3450 | llvm::Metadata *TypeIdMD = CreateMetadataIdentifierGeneralized(T: QT); |
| 3451 | llvm::MDTuple *TypeTuple = llvm::MDTuple::get( |
| 3452 | Context&: getLLVMContext(), MDs: {llvm::ConstantAsMetadata::get(C: llvm::ConstantInt::get( |
| 3453 | Ty: llvm::Type::getInt64Ty(C&: getLLVMContext()), V: 0)), |
| 3454 | TypeIdMD}); |
| 3455 | llvm::MDTuple *MDN = llvm::MDNode::get(Context&: getLLVMContext(), MDs: {TypeTuple}); |
| 3456 | CB->setMetadata(KindID: llvm::LLVMContext::MD_callee_type, Node: MDN); |
| 3457 | } |
| 3458 | |
| 3459 | void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) { |
| 3460 | llvm::LLVMContext &Ctx = F->getContext(); |
| 3461 | llvm::MDBuilder MDB(Ctx); |
| 3462 | llvm::StringRef Salt; |
| 3463 | |
| 3464 | if (const auto *FP = FD->getType()->getAs<FunctionProtoType>()) |
| 3465 | if (const auto &Info = FP->getExtraAttributeInfo()) |
| 3466 | Salt = Info.CFISalt; |
| 3467 | |
| 3468 | F->setMetadata(KindID: llvm::LLVMContext::MD_kcfi_type, |
| 3469 | Node: llvm::MDNode::get(Context&: Ctx, MDs: MDB.createConstant(C: CreateKCFITypeId( |
| 3470 | T: FD->getType(), Salt)))); |
| 3471 | } |
| 3472 | |
| 3473 | static bool allowKCFIIdentifier(StringRef Name) { |
| 3474 | // KCFI type identifier constants are only necessary for external assembly |
| 3475 | // functions, which means it's safe to skip unusual names. Subset of |
| 3476 | // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar(). |
| 3477 | return llvm::all_of(Range&: Name, P: [](const char &C) { |
| 3478 | return llvm::isAlnum(C) || C == '_' || C == '.'; |
| 3479 | }); |
| 3480 | } |
| 3481 | |
| 3482 | void CodeGenModule::finalizeKCFITypes() { |
| 3483 | llvm::Module &M = getModule(); |
| 3484 | for (auto &F : M.functions()) { |
| 3485 | // Remove KCFI type metadata from non-address-taken local functions. |
| 3486 | bool AddressTaken = F.hasAddressTaken(); |
| 3487 | if (!AddressTaken && F.hasLocalLinkage()) |
| 3488 | F.eraseMetadata(KindID: llvm::LLVMContext::MD_kcfi_type); |
| 3489 | |
| 3490 | // Generate a constant with the expected KCFI type identifier for all |
| 3491 | // address-taken function declarations to support annotating indirectly |
| 3492 | // called assembly functions. |
| 3493 | if (!AddressTaken || !F.isDeclaration()) |
| 3494 | continue; |
| 3495 | |
| 3496 | const llvm::ConstantInt *Type; |
| 3497 | if (const llvm::MDNode *MD = F.getMetadata(KindID: llvm::LLVMContext::MD_kcfi_type)) |
| 3498 | Type = llvm::mdconst::extract<llvm::ConstantInt>(MD: MD->getOperand(I: 0)); |
| 3499 | else |
| 3500 | continue; |
| 3501 | |
| 3502 | StringRef Name = F.getName(); |
| 3503 | if (!allowKCFIIdentifier(Name)) |
| 3504 | continue; |
| 3505 | |
| 3506 | std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" + |
| 3507 | Name + ", " + Twine(Type->getZExtValue()) + " /* " + |
| 3508 | Twine(Type->getSExtValue()) + " */\n" ) |
| 3509 | .str(); |
| 3510 | M.appendModuleInlineAsm(Asm); |
| 3511 | } |
| 3512 | } |
| 3513 | |
| 3514 | void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, |
| 3515 | bool IsIncompleteFunction, |
| 3516 | bool IsThunk) { |
| 3517 | |
| 3518 | if (F->getIntrinsicID() != llvm::Intrinsic::not_intrinsic) { |
| 3519 | // If this is an intrinsic function, the attributes will have been set |
| 3520 | // when the function was created. |
| 3521 | return; |
| 3522 | } |
| 3523 | |
| 3524 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
| 3525 | |
| 3526 | if (!IsIncompleteFunction) |
| 3527 | SetLLVMFunctionAttributes(GD, Info: getTypes().arrangeGlobalDeclaration(GD), F, |
| 3528 | IsThunk); |
| 3529 | |
| 3530 | // Add the Returned attribute for "this", except for iOS 5 and earlier |
| 3531 | // where substantial code, including the libstdc++ dylib, was compiled with |
| 3532 | // GCC and does not actually return "this". |
| 3533 | if (!IsThunk && getCXXABI().HasThisReturn(GD) && |
| 3534 | !(getTriple().isiOS() && getTriple().isOSVersionLT(Major: 6))) { |
| 3535 | assert(!F->arg_empty() && |
| 3536 | F->arg_begin()->getType() |
| 3537 | ->canLosslesslyBitCastTo(F->getReturnType()) && |
| 3538 | "unexpected this return" ); |
| 3539 | F->addParamAttr(ArgNo: 0, Kind: llvm::Attribute::Returned); |
| 3540 | } |
| 3541 | |
| 3542 | // Only a few attributes are set on declarations; these may later be |
| 3543 | // overridden by a definition. |
| 3544 | |
| 3545 | setLinkageForGV(GV: F, ND: FD); |
| 3546 | setGVProperties(GV: F, D: FD); |
| 3547 | |
| 3548 | // Setup target-specific attributes. |
| 3549 | if (!IsIncompleteFunction && F->isDeclaration()) |
| 3550 | getTargetCodeGenInfo().setTargetAttributes(D: FD, GV: F, M&: *this); |
| 3551 | |
| 3552 | if (const auto *CSA = FD->getAttr<CodeSegAttr>()) |
| 3553 | F->setSection(CSA->getName()); |
| 3554 | else if (const auto *SA = FD->getAttr<SectionAttr>()) |
| 3555 | F->setSection(SA->getName()); |
| 3556 | |
| 3557 | if (const auto *EA = FD->getAttr<ErrorAttr>()) { |
| 3558 | if (EA->isError()) |
| 3559 | F->addFnAttr(Kind: "dontcall-error" , Val: EA->getUserDiagnostic()); |
| 3560 | else if (EA->isWarning()) |
| 3561 | F->addFnAttr(Kind: "dontcall-warn" , Val: EA->getUserDiagnostic()); |
| 3562 | } |
| 3563 | |
| 3564 | // If we plan on emitting this inline builtin, we can't treat it as a builtin. |
| 3565 | if (FD->isInlineBuiltinDeclaration()) { |
| 3566 | const FunctionDecl *FDBody; |
| 3567 | bool HasBody = FD->hasBody(Definition&: FDBody); |
| 3568 | (void)HasBody; |
| 3569 | assert(HasBody && "Inline builtin declarations should always have an " |
| 3570 | "available body!" ); |
| 3571 | if (shouldEmitFunction(GD: FDBody)) |
| 3572 | F->addFnAttr(Kind: llvm::Attribute::NoBuiltin); |
| 3573 | } |
| 3574 | |
| 3575 | if (FD->isReplaceableGlobalAllocationFunction()) { |
| 3576 | // A replaceable global allocation function does not act like a builtin by |
| 3577 | // default, only if it is invoked by a new-expression or delete-expression. |
| 3578 | F->addFnAttr(Kind: llvm::Attribute::NoBuiltin); |
| 3579 | } |
| 3580 | |
| 3581 | if (isa<CXXConstructorDecl>(Val: FD) || isa<CXXDestructorDecl>(Val: FD)) |
| 3582 | F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
| 3583 | else if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) |
| 3584 | if (MD->isVirtual()) |
| 3585 | F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
| 3586 | |
| 3587 | // Don't emit entries for function declarations in the cross-DSO mode. This |
| 3588 | // is handled with better precision by the receiving DSO. But if jump tables |
| 3589 | // are non-canonical then we need type metadata in order to produce the local |
| 3590 | // jump table. |
| 3591 | if (!CodeGenOpts.SanitizeCfiCrossDso || |
| 3592 | !CodeGenOpts.SanitizeCfiCanonicalJumpTables) |
| 3593 | createFunctionTypeMetadataForIcall(FD, F); |
| 3594 | |
| 3595 | if (CodeGenOpts.CallGraphSection) |
| 3596 | createIndirectFunctionTypeMD(FD, F); |
| 3597 | |
| 3598 | if (LangOpts.Sanitize.has(K: SanitizerKind::KCFI)) |
| 3599 | setKCFIType(FD, F); |
| 3600 | |
| 3601 | if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) |
| 3602 | getOpenMPRuntime().emitDeclareSimdFunction(FD, Fn: F); |
| 3603 | |
| 3604 | if (CodeGenOpts.InlineMaxStackSize != UINT_MAX) |
| 3605 | F->addFnAttr(Kind: "inline-max-stacksize" , Val: llvm::utostr(X: CodeGenOpts.InlineMaxStackSize)); |
| 3606 | |
| 3607 | if (const auto *CB = FD->getAttr<CallbackAttr>()) { |
| 3608 | // Annotate the callback behavior as metadata: |
| 3609 | // - The callback callee (as argument number). |
| 3610 | // - The callback payloads (as argument numbers). |
| 3611 | llvm::LLVMContext &Ctx = F->getContext(); |
| 3612 | llvm::MDBuilder MDB(Ctx); |
| 3613 | |
| 3614 | // The payload indices are all but the first one in the encoding. The first |
| 3615 | // identifies the callback callee. |
| 3616 | int CalleeIdx = *CB->encoding_begin(); |
| 3617 | ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); |
| 3618 | F->addMetadata(KindID: llvm::LLVMContext::MD_callback, |
| 3619 | MD&: *llvm::MDNode::get(Context&: Ctx, MDs: {MDB.createCallbackEncoding( |
| 3620 | CalleeArgNo: CalleeIdx, Arguments: PayloadIndices, |
| 3621 | /* VarArgsArePassed */ false)})); |
| 3622 | } |
| 3623 | } |
| 3624 | |
| 3625 | void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { |
| 3626 | assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && |
| 3627 | "Only globals with definition can force usage." ); |
| 3628 | LLVMUsed.emplace_back(args&: GV); |
| 3629 | } |
| 3630 | |
| 3631 | void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { |
| 3632 | assert(!GV->isDeclaration() && |
| 3633 | "Only globals with definition can force usage." ); |
| 3634 | LLVMCompilerUsed.emplace_back(args&: GV); |
| 3635 | } |
| 3636 | |
| 3637 | void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { |
| 3638 | assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && |
| 3639 | "Only globals with definition can force usage." ); |
| 3640 | if (getTriple().isOSBinFormatELF()) |
| 3641 | LLVMCompilerUsed.emplace_back(args&: GV); |
| 3642 | else |
| 3643 | LLVMUsed.emplace_back(args&: GV); |
| 3644 | } |
| 3645 | |
| 3646 | static void emitUsed(CodeGenModule &CGM, StringRef Name, |
| 3647 | std::vector<llvm::WeakTrackingVH> &List) { |
| 3648 | // Don't create llvm.used if there is no need. |
| 3649 | if (List.empty()) |
| 3650 | return; |
| 3651 | |
| 3652 | // Convert List to what ConstantArray needs. |
| 3653 | SmallVector<llvm::Constant*, 8> UsedArray; |
| 3654 | UsedArray.resize(N: List.size()); |
| 3655 | for (unsigned i = 0, e = List.size(); i != e; ++i) { |
| 3656 | UsedArray[i] = |
| 3657 | llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( |
| 3658 | C: cast<llvm::Constant>(Val: &*List[i]), Ty: CGM.Int8PtrTy); |
| 3659 | } |
| 3660 | |
| 3661 | if (UsedArray.empty()) |
| 3662 | return; |
| 3663 | llvm::ArrayType *ATy = llvm::ArrayType::get(ElementType: CGM.Int8PtrTy, NumElements: UsedArray.size()); |
| 3664 | |
| 3665 | auto *GV = new llvm::GlobalVariable( |
| 3666 | CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, |
| 3667 | llvm::ConstantArray::get(T: ATy, V: UsedArray), Name); |
| 3668 | |
| 3669 | GV->setSection("llvm.metadata" ); |
| 3670 | } |
| 3671 | |
| 3672 | void CodeGenModule::emitLLVMUsed() { |
| 3673 | emitUsed(CGM&: *this, Name: "llvm.used" , List&: LLVMUsed); |
| 3674 | emitUsed(CGM&: *this, Name: "llvm.compiler.used" , List&: LLVMCompilerUsed); |
| 3675 | } |
| 3676 | |
| 3677 | void CodeGenModule::AppendLinkerOptions(StringRef Opts) { |
| 3678 | auto *MDOpts = llvm::MDString::get(Context&: getLLVMContext(), Str: Opts); |
| 3679 | LinkerOptionsMetadata.push_back(Elt: llvm::MDNode::get(Context&: getLLVMContext(), MDs: MDOpts)); |
| 3680 | } |
| 3681 | |
| 3682 | void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { |
| 3683 | llvm::SmallString<32> Opt; |
| 3684 | getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); |
| 3685 | if (Opt.empty()) |
| 3686 | return; |
| 3687 | auto *MDOpts = llvm::MDString::get(Context&: getLLVMContext(), Str: Opt); |
| 3688 | LinkerOptionsMetadata.push_back(Elt: llvm::MDNode::get(Context&: getLLVMContext(), MDs: MDOpts)); |
| 3689 | } |
| 3690 | |
| 3691 | void CodeGenModule::AddDependentLib(StringRef Lib) { |
| 3692 | auto &C = getLLVMContext(); |
| 3693 | if (getTarget().getTriple().isOSBinFormatELF()) { |
| 3694 | ELFDependentLibraries.push_back( |
| 3695 | Elt: llvm::MDNode::get(Context&: C, MDs: llvm::MDString::get(Context&: C, Str: Lib))); |
| 3696 | return; |
| 3697 | } |
| 3698 | |
| 3699 | llvm::SmallString<24> Opt; |
| 3700 | getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); |
| 3701 | auto *MDOpts = llvm::MDString::get(Context&: getLLVMContext(), Str: Opt); |
| 3702 | LinkerOptionsMetadata.push_back(Elt: llvm::MDNode::get(Context&: C, MDs: MDOpts)); |
| 3703 | } |
| 3704 | |
| 3705 | /// Process copyright pragma and create a weak_odr hidden string global variable |
| 3706 | /// in the __loadtime_comment section, marked with !loadtime_comment metadata. |
| 3707 | /// Only one copyright pragma is allowed per translation unit. Subsequent |
| 3708 | /// pragmas in the same TU are ignored with a warning at the parse level. |
| 3709 | void CodeGenModule::(StringRef , |
| 3710 | bool isFromASTFile) { |
| 3711 | assert(getTriple().isOSAIX() && |
| 3712 | "pragma comment copyright is supported only when targeting AIX" ); |
| 3713 | |
| 3714 | // Interaction with C++20 Modules and PCH: |
| 3715 | // When a module interface unit containing a copyright pragma is imported, |
| 3716 | // Clang deserializes the PragmaCommentDecl from the precompiled module file |
| 3717 | // (.pcm) into the importing TU's AST. isFromASTFile() returns true for such |
| 3718 | // deserialized declarations. We skip those to ensure only the module |
| 3719 | // interface TU that originally parsed the pragma emits the copyright metadata |
| 3720 | // -- not every TU that imports it. This prevents duplicate copyright strings |
| 3721 | // in the final binary. |
| 3722 | if (isFromASTFile) |
| 3723 | return; |
| 3724 | |
| 3725 | assert(!LoadTimeCommentGlobal && |
| 3726 | "Only one copyright pragma allowed per translation unit." ); |
| 3727 | |
| 3728 | // Create a weak_odr hidden global variable containing the copyright string. |
| 3729 | // Hash the content to generate a stable, unique name across TUs. |
| 3730 | auto &C = getLLVMContext(); |
| 3731 | uint64_t Hash = xxh3_64bits(data: Comment); |
| 3732 | std::string GlobalName = |
| 3733 | ("__loadtime_comment_str_" + Twine::utohexstr(Val: Hash)).str(); |
| 3734 | |
| 3735 | // Create null-terminated string constant |
| 3736 | llvm::Constant *StrInit = |
| 3737 | llvm::ConstantDataArray::getString(Context&: C, Initializer: Comment, /*AddNull=*/true); |
| 3738 | |
| 3739 | // Create weak_odr linkage so multiple TUs with identical strings merge |
| 3740 | auto *GV = new llvm::GlobalVariable(getModule(), StrInit->getType(), |
| 3741 | /*isConstant=*/true, |
| 3742 | llvm::GlobalValue::WeakODRLinkage, |
| 3743 | StrInit, GlobalName); |
| 3744 | |
| 3745 | GV->setVisibility(llvm::GlobalValue::HiddenVisibility); |
| 3746 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
| 3747 | GV->setAlignment(llvm::Align(1)); |
| 3748 | // Place the copyright string in a dedicated section for better memory layout. |
| 3749 | // Tradeoff: In full LTO builds, multiple copyright strings may be grouped |
| 3750 | // into a single csect, preventing individual GC by the linker. However, this |
| 3751 | // groups copyright strings "out of the way" from other data, which is likely |
| 3752 | // beneficial for memory layout. ThinLTO is not affected by this grouping. |
| 3753 | GV->setSection("__loadtime_comment" ); |
| 3754 | |
| 3755 | // Mark with loadtime_comment metadata for LowerCommentStringPass |
| 3756 | GV->setMetadata(Kind: "loadtime_comment" , Node: llvm::MDNode::get(Context&: C, MDs: {})); |
| 3757 | |
| 3758 | // Prevent optimizer from removing the Global Var. |
| 3759 | llvm::appendToCompilerUsed(M&: getModule(), Values: {GV}); |
| 3760 | |
| 3761 | LoadTimeCommentGlobal = GV; |
| 3762 | } |
| 3763 | |
| 3764 | /// Add link options implied by the given module, including modules |
| 3765 | /// it depends on, using a postorder walk. |
| 3766 | static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, |
| 3767 | SmallVectorImpl<llvm::MDNode *> &Metadata, |
| 3768 | llvm::SmallPtrSet<Module *, 16> &Visited) { |
| 3769 | // Import this module's parent. |
| 3770 | if (Mod->Parent && Visited.insert(Ptr: Mod->Parent).second) { |
| 3771 | addLinkOptionsPostorder(CGM, Mod: Mod->Parent, Metadata, Visited); |
| 3772 | } |
| 3773 | |
| 3774 | // Import this module's dependencies. |
| 3775 | for (Module *Import : llvm::reverse(C&: Mod->Imports)) { |
| 3776 | if (Visited.insert(Ptr: Import).second) |
| 3777 | addLinkOptionsPostorder(CGM, Mod: Import, Metadata, Visited); |
| 3778 | } |
| 3779 | |
| 3780 | // Add linker options to link against the libraries/frameworks |
| 3781 | // described by this module. |
| 3782 | llvm::LLVMContext &Context = CGM.getLLVMContext(); |
| 3783 | bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); |
| 3784 | |
| 3785 | // For modules that use export_as for linking, use that module |
| 3786 | // name instead. |
| 3787 | if (Mod->UseExportAsModuleLinkName) |
| 3788 | return; |
| 3789 | |
| 3790 | for (const Module::LinkLibrary &LL : llvm::reverse(C&: Mod->LinkLibraries)) { |
| 3791 | // Link against a framework. Frameworks are currently Darwin only, so we |
| 3792 | // don't to ask TargetCodeGenInfo for the spelling of the linker option. |
| 3793 | if (LL.IsFramework) { |
| 3794 | llvm::Metadata *Args[2] = {llvm::MDString::get(Context, Str: "-framework" ), |
| 3795 | llvm::MDString::get(Context, Str: LL.Library)}; |
| 3796 | |
| 3797 | Metadata.push_back(Elt: llvm::MDNode::get(Context, MDs: Args)); |
| 3798 | continue; |
| 3799 | } |
| 3800 | |
| 3801 | // Link against a library. |
| 3802 | if (IsELF) { |
| 3803 | llvm::Metadata *Args[2] = { |
| 3804 | llvm::MDString::get(Context, Str: "lib" ), |
| 3805 | llvm::MDString::get(Context, Str: LL.Library), |
| 3806 | }; |
| 3807 | Metadata.push_back(Elt: llvm::MDNode::get(Context, MDs: Args)); |
| 3808 | } else { |
| 3809 | llvm::SmallString<24> Opt; |
| 3810 | CGM.getTargetCodeGenInfo().getDependentLibraryOption(Lib: LL.Library, Opt); |
| 3811 | auto *OptString = llvm::MDString::get(Context, Str: Opt); |
| 3812 | Metadata.push_back(Elt: llvm::MDNode::get(Context, MDs: OptString)); |
| 3813 | } |
| 3814 | } |
| 3815 | } |
| 3816 | |
| 3817 | void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) { |
| 3818 | assert(Primary->isNamedModuleUnit() && |
| 3819 | "We should only emit module initializers for named modules." ); |
| 3820 | |
| 3821 | // Emit the initializers in the order that sub-modules appear in the |
| 3822 | // source, first Global Module Fragments, if present. |
| 3823 | if (auto GMF = Primary->getGlobalModuleFragment()) { |
| 3824 | for (Decl *D : getContext().getModuleInitializers(M: GMF)) { |
| 3825 | if (isa<ImportDecl>(Val: D)) |
| 3826 | continue; |
| 3827 | assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?" ); |
| 3828 | EmitTopLevelDecl(D); |
| 3829 | } |
| 3830 | } |
| 3831 | // Second any associated with the module, itself. |
| 3832 | for (Decl *D : getContext().getModuleInitializers(M: Primary)) { |
| 3833 | // Skip import decls, the inits for those are called explicitly. |
| 3834 | if (isa<ImportDecl>(Val: D)) |
| 3835 | continue; |
| 3836 | EmitTopLevelDecl(D); |
| 3837 | } |
| 3838 | // Third any associated with the Privat eMOdule Fragment, if present. |
| 3839 | if (auto PMF = Primary->getPrivateModuleFragment()) { |
| 3840 | for (Decl *D : getContext().getModuleInitializers(M: PMF)) { |
| 3841 | // Skip import decls, the inits for those are called explicitly. |
| 3842 | if (isa<ImportDecl>(Val: D)) |
| 3843 | continue; |
| 3844 | assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?" ); |
| 3845 | EmitTopLevelDecl(D); |
| 3846 | } |
| 3847 | } |
| 3848 | } |
| 3849 | |
| 3850 | void CodeGenModule::EmitModuleLinkOptions() { |
| 3851 | // Collect the set of all of the modules we want to visit to emit link |
| 3852 | // options, which is essentially the imported modules and all of their |
| 3853 | // non-explicit child modules. |
| 3854 | llvm::SetVector<clang::Module *> LinkModules; |
| 3855 | llvm::SmallPtrSet<clang::Module *, 16> Visited; |
| 3856 | SmallVector<clang::Module *, 16> Stack; |
| 3857 | |
| 3858 | // Seed the stack with imported modules. |
| 3859 | for (Module *M : ImportedModules) { |
| 3860 | // Do not add any link flags when an implementation TU of a module imports |
| 3861 | // a header of that same module. |
| 3862 | if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && |
| 3863 | !getLangOpts().isCompilingModule()) |
| 3864 | continue; |
| 3865 | if (Visited.insert(Ptr: M).second) |
| 3866 | Stack.push_back(Elt: M); |
| 3867 | } |
| 3868 | |
| 3869 | // Find all of the modules to import, making a little effort to prune |
| 3870 | // non-leaf modules. |
| 3871 | while (!Stack.empty()) { |
| 3872 | clang::Module *Mod = Stack.pop_back_val(); |
| 3873 | |
| 3874 | bool AnyChildren = false; |
| 3875 | |
| 3876 | // Visit the submodules of this module. |
| 3877 | for (const auto &SM : Mod->submodules()) { |
| 3878 | // Skip explicit children; they need to be explicitly imported to be |
| 3879 | // linked against. |
| 3880 | if (SM->IsExplicit) |
| 3881 | continue; |
| 3882 | |
| 3883 | if (Visited.insert(Ptr: SM).second) { |
| 3884 | Stack.push_back(Elt: SM); |
| 3885 | AnyChildren = true; |
| 3886 | } |
| 3887 | } |
| 3888 | |
| 3889 | // We didn't find any children, so add this module to the list of |
| 3890 | // modules to link against. |
| 3891 | if (!AnyChildren) { |
| 3892 | LinkModules.insert(X: Mod); |
| 3893 | } |
| 3894 | } |
| 3895 | |
| 3896 | // Add link options for all of the imported modules in reverse topological |
| 3897 | // order. We don't do anything to try to order import link flags with respect |
| 3898 | // to linker options inserted by things like #pragma comment(). |
| 3899 | SmallVector<llvm::MDNode *, 16> MetadataArgs; |
| 3900 | Visited.clear(); |
| 3901 | for (Module *M : LinkModules) |
| 3902 | if (Visited.insert(Ptr: M).second) |
| 3903 | addLinkOptionsPostorder(CGM&: *this, Mod: M, Metadata&: MetadataArgs, Visited); |
| 3904 | std::reverse(first: MetadataArgs.begin(), last: MetadataArgs.end()); |
| 3905 | LinkerOptionsMetadata.append(in_start: MetadataArgs.begin(), in_end: MetadataArgs.end()); |
| 3906 | |
| 3907 | // Add the linker options metadata flag. |
| 3908 | if (!LinkerOptionsMetadata.empty()) { |
| 3909 | auto *NMD = getModule().getOrInsertNamedMetadata(Name: "llvm.linker.options" ); |
| 3910 | for (auto *MD : LinkerOptionsMetadata) |
| 3911 | NMD->addOperand(M: MD); |
| 3912 | } |
| 3913 | } |
| 3914 | |
| 3915 | void CodeGenModule::EmitDeferred() { |
| 3916 | // Emit deferred declare target declarations. |
| 3917 | if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) |
| 3918 | getOpenMPRuntime().emitDeferredTargetDecls(); |
| 3919 | |
| 3920 | // Emit code for any potentially referenced deferred decls. Since a |
| 3921 | // previously unused static decl may become used during the generation of code |
| 3922 | // for a static function, iterate until no changes are made. |
| 3923 | |
| 3924 | if (!DeferredVTables.empty()) { |
| 3925 | EmitDeferredVTables(); |
| 3926 | |
| 3927 | // Emitting a vtable doesn't directly cause more vtables to |
| 3928 | // become deferred, although it can cause functions to be |
| 3929 | // emitted that then need those vtables. |
| 3930 | assert(DeferredVTables.empty()); |
| 3931 | } |
| 3932 | |
| 3933 | // Emit CUDA/HIP static device variables referenced by host code only. |
| 3934 | // Note we should not clear CUDADeviceVarODRUsedByHost since it is still |
| 3935 | // needed for further handling. |
| 3936 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) |
| 3937 | llvm::append_range(C&: DeferredDeclsToEmit, |
| 3938 | R&: getContext().CUDADeviceVarODRUsedByHost); |
| 3939 | |
| 3940 | // Stop if we're out of both deferred vtables and deferred declarations. |
| 3941 | if (DeferredDeclsToEmit.empty()) |
| 3942 | return; |
| 3943 | |
| 3944 | // Grab the list of decls to emit. If EmitGlobalDefinition schedules more |
| 3945 | // work, it will not interfere with this. |
| 3946 | std::vector<GlobalDecl> CurDeclsToEmit; |
| 3947 | CurDeclsToEmit.swap(x&: DeferredDeclsToEmit); |
| 3948 | |
| 3949 | for (GlobalDecl &D : CurDeclsToEmit) { |
| 3950 | // Functions declared with the sycl_kernel_entry_point attribute are |
| 3951 | // emitted normally during host compilation. During device compilation, |
| 3952 | // a SYCL kernel caller offload entry point function is generated and |
| 3953 | // emitted in place of each of these functions. |
| 3954 | if (const auto *FD = D.getDecl()->getAsFunction()) { |
| 3955 | if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelEntryPointAttr>() && |
| 3956 | FD->isDefined()) { |
| 3957 | // Functions with an invalid sycl_kernel_entry_point attribute are |
| 3958 | // ignored during device compilation. |
| 3959 | if (!FD->getAttr<SYCLKernelEntryPointAttr>()->isInvalidAttr()) { |
| 3960 | // Generate and emit the SYCL kernel caller function. |
| 3961 | EmitSYCLKernelCaller(KernelEntryPointFn: FD, Ctx&: getContext()); |
| 3962 | // Recurse to emit any symbols directly or indirectly referenced |
| 3963 | // by the SYCL kernel caller function. |
| 3964 | EmitDeferred(); |
| 3965 | } |
| 3966 | // Do not emit the sycl_kernel_entry_point attributed function. |
| 3967 | continue; |
| 3968 | } |
| 3969 | } |
| 3970 | |
| 3971 | // We should call GetAddrOfGlobal with IsForDefinition set to true in order |
| 3972 | // to get GlobalValue with exactly the type we need, not something that |
| 3973 | // might had been created for another decl with the same mangled name but |
| 3974 | // different type. |
| 3975 | llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( |
| 3976 | Val: GetAddrOfGlobal(GD: D, IsForDefinition: ForDefinition)); |
| 3977 | |
| 3978 | // In case of different address spaces, we may still get a cast, even with |
| 3979 | // IsForDefinition equal to true. Query mangled names table to get |
| 3980 | // GlobalValue. |
| 3981 | if (!GV) |
| 3982 | GV = GetGlobalValue(Name: getMangledName(GD: D)); |
| 3983 | |
| 3984 | // Make sure GetGlobalValue returned non-null. |
| 3985 | assert(GV); |
| 3986 | |
| 3987 | // Check to see if we've already emitted this. This is necessary |
| 3988 | // for a couple of reasons: first, decls can end up in the |
| 3989 | // deferred-decls queue multiple times, and second, decls can end |
| 3990 | // up with definitions in unusual ways (e.g. by an extern inline |
| 3991 | // function acquiring a strong function redefinition). Just |
| 3992 | // ignore these cases. |
| 3993 | if (!GV->isDeclaration()) |
| 3994 | continue; |
| 3995 | |
| 3996 | // If this is OpenMP, check if it is legal to emit this global normally. |
| 3997 | if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD: D)) |
| 3998 | continue; |
| 3999 | |
| 4000 | // Otherwise, emit the definition and move on to the next one. |
| 4001 | EmitGlobalDefinition(D, GV); |
| 4002 | |
| 4003 | // If we found out that we need to emit more decls, do that recursively. |
| 4004 | // This has the advantage that the decls are emitted in a DFS and related |
| 4005 | // ones are close together, which is convenient for testing. |
| 4006 | if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { |
| 4007 | EmitDeferred(); |
| 4008 | assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); |
| 4009 | } |
| 4010 | } |
| 4011 | } |
| 4012 | |
| 4013 | void CodeGenModule::EmitVTablesOpportunistically() { |
| 4014 | // Try to emit external vtables as available_externally if they have emitted |
| 4015 | // all inlined virtual functions. It runs after EmitDeferred() and therefore |
| 4016 | // is not allowed to create new references to things that need to be emitted |
| 4017 | // lazily. Note that it also uses fact that we eagerly emitting RTTI. |
| 4018 | |
| 4019 | assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) |
| 4020 | && "Only emit opportunistic vtables with optimizations" ); |
| 4021 | |
| 4022 | for (const CXXRecordDecl *RD : OpportunisticVTables) { |
| 4023 | assert(getVTables().isVTableExternal(RD) && |
| 4024 | "This queue should only contain external vtables" ); |
| 4025 | if (getCXXABI().canSpeculativelyEmitVTable(RD)) |
| 4026 | VTables.GenerateClassData(RD); |
| 4027 | } |
| 4028 | OpportunisticVTables.clear(); |
| 4029 | } |
| 4030 | |
| 4031 | void CodeGenModule::EmitGlobalAnnotations() { |
| 4032 | for (const auto& [MangledName, VD] : DeferredAnnotations) { |
| 4033 | llvm::GlobalValue *GV = GetGlobalValue(Name: MangledName); |
| 4034 | if (GV) |
| 4035 | AddGlobalAnnotations(D: VD, GV); |
| 4036 | } |
| 4037 | DeferredAnnotations.clear(); |
| 4038 | |
| 4039 | if (Annotations.empty()) |
| 4040 | return; |
| 4041 | |
| 4042 | // Create a new global variable for the ConstantStruct in the Module. |
| 4043 | llvm::Constant *Array = llvm::ConstantArray::get(T: llvm::ArrayType::get( |
| 4044 | ElementType: Annotations[0]->getType(), NumElements: Annotations.size()), V: Annotations); |
| 4045 | auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, |
| 4046 | llvm::GlobalValue::AppendingLinkage, |
| 4047 | Array, "llvm.global.annotations" ); |
| 4048 | gv->setSection(AnnotationSection); |
| 4049 | } |
| 4050 | |
| 4051 | llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { |
| 4052 | llvm::Constant *&AStr = AnnotationStrings[Str]; |
| 4053 | if (AStr) |
| 4054 | return AStr; |
| 4055 | |
| 4056 | // Not found yet, create a new global. |
| 4057 | llvm::Constant *s = llvm::ConstantDataArray::getString(Context&: getLLVMContext(), Initializer: Str); |
| 4058 | auto *gv = new llvm::GlobalVariable( |
| 4059 | getModule(), s->getType(), true, llvm::GlobalValue::PrivateLinkage, s, |
| 4060 | ".str" , nullptr, llvm::GlobalValue::NotThreadLocal, |
| 4061 | ConstGlobalsPtrTy->getAddressSpace()); |
| 4062 | gv->setSection(AnnotationSection); |
| 4063 | gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
| 4064 | AStr = gv; |
| 4065 | return gv; |
| 4066 | } |
| 4067 | |
| 4068 | llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { |
| 4069 | SourceManager &SM = getContext().getSourceManager(); |
| 4070 | PresumedLoc PLoc = SM.getPresumedLoc(Loc); |
| 4071 | if (PLoc.isValid()) |
| 4072 | return EmitAnnotationString(Str: PLoc.getFilename()); |
| 4073 | return EmitAnnotationString(Str: SM.getBufferName(Loc)); |
| 4074 | } |
| 4075 | |
| 4076 | llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { |
| 4077 | SourceManager &SM = getContext().getSourceManager(); |
| 4078 | PresumedLoc PLoc = SM.getPresumedLoc(Loc: L); |
| 4079 | unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : |
| 4080 | SM.getExpansionLineNumber(Loc: L); |
| 4081 | return llvm::ConstantInt::get(Ty: Int32Ty, V: LineNo); |
| 4082 | } |
| 4083 | |
| 4084 | llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { |
| 4085 | ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; |
| 4086 | if (Exprs.empty()) |
| 4087 | return llvm::ConstantPointerNull::get(T: ConstGlobalsPtrTy); |
| 4088 | |
| 4089 | llvm::FoldingSetNodeID ID; |
| 4090 | for (Expr *E : Exprs) { |
| 4091 | ID.Add(x: cast<clang::ConstantExpr>(Val: E)->getAPValueResult()); |
| 4092 | } |
| 4093 | llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; |
| 4094 | if (Lookup) |
| 4095 | return Lookup; |
| 4096 | |
| 4097 | llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; |
| 4098 | LLVMArgs.reserve(N: Exprs.size()); |
| 4099 | ConstantEmitter ConstEmiter(*this); |
| 4100 | llvm::transform(Range&: Exprs, d_first: std::back_inserter(x&: LLVMArgs), F: [&](const Expr *E) { |
| 4101 | const auto *CE = cast<clang::ConstantExpr>(Val: E); |
| 4102 | return ConstEmiter.emitAbstract(loc: CE->getBeginLoc(), value: CE->getAPValueResult(), |
| 4103 | T: CE->getType()); |
| 4104 | }); |
| 4105 | auto *Struct = llvm::ConstantStruct::getAnon(V: LLVMArgs); |
| 4106 | auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, |
| 4107 | llvm::GlobalValue::PrivateLinkage, Struct, |
| 4108 | ".args" ); |
| 4109 | GV->setSection(AnnotationSection); |
| 4110 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
| 4111 | |
| 4112 | Lookup = GV; |
| 4113 | return GV; |
| 4114 | } |
| 4115 | |
| 4116 | llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, |
| 4117 | const AnnotateAttr *AA, |
| 4118 | SourceLocation L) { |
| 4119 | // Get the globals for file name, annotation, and the line number. |
| 4120 | llvm::Constant *AnnoGV = EmitAnnotationString(Str: AA->getAnnotation()), |
| 4121 | *UnitGV = EmitAnnotationUnit(Loc: L), |
| 4122 | *LineNoCst = EmitAnnotationLineNo(L), |
| 4123 | *Args = EmitAnnotationArgs(Attr: AA); |
| 4124 | |
| 4125 | llvm::Constant *GVInGlobalsAS = GV; |
| 4126 | if (GV->getAddressSpace() != |
| 4127 | getDataLayout().getDefaultGlobalsAddressSpace()) { |
| 4128 | GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( |
| 4129 | C: GV, |
| 4130 | Ty: llvm::PointerType::get( |
| 4131 | C&: GV->getContext(), AddressSpace: getDataLayout().getDefaultGlobalsAddressSpace())); |
| 4132 | } |
| 4133 | |
| 4134 | // Create the ConstantStruct for the global annotation. |
| 4135 | llvm::Constant *Fields[] = { |
| 4136 | GVInGlobalsAS, AnnoGV, UnitGV, LineNoCst, Args, |
| 4137 | }; |
| 4138 | return llvm::ConstantStruct::getAnon(V: Fields); |
| 4139 | } |
| 4140 | |
| 4141 | void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, |
| 4142 | llvm::GlobalValue *GV) { |
| 4143 | assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute" ); |
| 4144 | // Get the struct elements for these annotations. |
| 4145 | for (const auto *I : D->specific_attrs<AnnotateAttr>()) |
| 4146 | Annotations.push_back(x: EmitAnnotateAttr(GV, AA: I, L: D->getLocation())); |
| 4147 | } |
| 4148 | |
| 4149 | bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, |
| 4150 | SourceLocation Loc) const { |
| 4151 | const auto &NoSanitizeL = getContext().getNoSanitizeList(); |
| 4152 | // NoSanitize by function name. |
| 4153 | if (NoSanitizeL.containsFunction(Mask: Kind, FunctionName: Fn->getName())) |
| 4154 | return true; |
| 4155 | // NoSanitize by location. Check "mainfile" prefix. |
| 4156 | auto &SM = Context.getSourceManager(); |
| 4157 | FileEntryRef MainFile = *SM.getFileEntryRefForID(FID: SM.getMainFileID()); |
| 4158 | if (NoSanitizeL.containsMainFile(Mask: Kind, FileName: MainFile.getName())) |
| 4159 | return true; |
| 4160 | |
| 4161 | // Check "src" prefix. |
| 4162 | if (Loc.isValid()) |
| 4163 | return NoSanitizeL.containsLocation(Mask: Kind, Loc); |
| 4164 | // If location is unknown, this may be a compiler-generated function. Assume |
| 4165 | // it's located in the main file. |
| 4166 | return NoSanitizeL.containsFile(Mask: Kind, FileName: MainFile.getName()); |
| 4167 | } |
| 4168 | |
| 4169 | bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, |
| 4170 | llvm::GlobalVariable *GV, |
| 4171 | SourceLocation Loc, QualType Ty, |
| 4172 | StringRef Category) const { |
| 4173 | const auto &NoSanitizeL = getContext().getNoSanitizeList(); |
| 4174 | if (NoSanitizeL.containsGlobal(Mask: Kind, GlobalName: GV->getName(), Category)) |
| 4175 | return true; |
| 4176 | auto &SM = Context.getSourceManager(); |
| 4177 | if (NoSanitizeL.containsMainFile( |
| 4178 | Mask: Kind, FileName: SM.getFileEntryRefForID(FID: SM.getMainFileID())->getName(), |
| 4179 | Category)) |
| 4180 | return true; |
| 4181 | if (NoSanitizeL.containsLocation(Mask: Kind, Loc, Category)) |
| 4182 | return true; |
| 4183 | |
| 4184 | // Check global type. |
| 4185 | if (!Ty.isNull()) { |
| 4186 | // Drill down the array types: if global variable of a fixed type is |
| 4187 | // not sanitized, we also don't instrument arrays of them. |
| 4188 | while (auto AT = dyn_cast<ArrayType>(Val: Ty.getTypePtr())) |
| 4189 | Ty = AT->getElementType(); |
| 4190 | Ty = Ty.getCanonicalType().getUnqualifiedType(); |
| 4191 | // Only record types (classes, structs etc.) are ignored. |
| 4192 | if (Ty->isRecordType()) { |
| 4193 | std::string TypeStr = Ty.getAsString(Policy: getContext().getPrintingPolicy()); |
| 4194 | if (NoSanitizeL.containsType(Mask: Kind, MangledTypeName: TypeStr, Category)) |
| 4195 | return true; |
| 4196 | } |
| 4197 | } |
| 4198 | return false; |
| 4199 | } |
| 4200 | |
| 4201 | bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, |
| 4202 | StringRef Category) const { |
| 4203 | const auto &XRayFilter = getContext().getXRayFilter(); |
| 4204 | using ImbueAttr = XRayFunctionFilter::ImbueAttribute; |
| 4205 | auto Attr = ImbueAttr::NONE; |
| 4206 | if (Loc.isValid()) |
| 4207 | Attr = XRayFilter.shouldImbueLocation(Loc, Category); |
| 4208 | if (Attr == ImbueAttr::NONE) |
| 4209 | Attr = XRayFilter.shouldImbueFunction(FunctionName: Fn->getName()); |
| 4210 | switch (Attr) { |
| 4211 | case ImbueAttr::NONE: |
| 4212 | return false; |
| 4213 | case ImbueAttr::ALWAYS: |
| 4214 | Fn->addFnAttr(Kind: "function-instrument" , Val: "xray-always" ); |
| 4215 | break; |
| 4216 | case ImbueAttr::ALWAYS_ARG1: |
| 4217 | Fn->addFnAttr(Kind: "function-instrument" , Val: "xray-always" ); |
| 4218 | Fn->addFnAttr(Kind: "xray-log-args" , Val: "1" ); |
| 4219 | break; |
| 4220 | case ImbueAttr::NEVER: |
| 4221 | Fn->addFnAttr(Kind: "function-instrument" , Val: "xray-never" ); |
| 4222 | break; |
| 4223 | } |
| 4224 | return true; |
| 4225 | } |
| 4226 | |
| 4227 | ProfileList::ExclusionType |
| 4228 | CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn, |
| 4229 | SourceLocation Loc) const { |
| 4230 | const auto &ProfileList = getContext().getProfileList(); |
| 4231 | // If the profile list is empty, then instrument everything. |
| 4232 | if (ProfileList.isEmpty()) |
| 4233 | return ProfileList::Allow; |
| 4234 | llvm::driver::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); |
| 4235 | // First, check the function name. |
| 4236 | if (auto V = ProfileList.isFunctionExcluded(FunctionName: Fn->getName(), Kind)) |
| 4237 | return *V; |
| 4238 | // Next, check the source location. |
| 4239 | if (Loc.isValid()) |
| 4240 | if (auto V = ProfileList.isLocationExcluded(Loc, Kind)) |
| 4241 | return *V; |
| 4242 | // If location is unknown, this may be a compiler-generated function. Assume |
| 4243 | // it's located in the main file. |
| 4244 | auto &SM = Context.getSourceManager(); |
| 4245 | if (auto MainFile = SM.getFileEntryRefForID(FID: SM.getMainFileID())) |
| 4246 | if (auto V = ProfileList.isFileExcluded(FileName: MainFile->getName(), Kind)) |
| 4247 | return *V; |
| 4248 | return ProfileList.getDefault(Kind); |
| 4249 | } |
| 4250 | |
| 4251 | ProfileList::ExclusionType |
| 4252 | CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn, |
| 4253 | SourceLocation Loc) const { |
| 4254 | auto V = isFunctionBlockedByProfileList(Fn, Loc); |
| 4255 | if (V != ProfileList::Allow) |
| 4256 | return V; |
| 4257 | |
| 4258 | auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups; |
| 4259 | if (NumGroups > 1) { |
| 4260 | auto Group = llvm::crc32(Data: arrayRefFromStringRef(Input: Fn->getName())) % NumGroups; |
| 4261 | if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup) |
| 4262 | return ProfileList::Skip; |
| 4263 | } |
| 4264 | return ProfileList::Allow; |
| 4265 | } |
| 4266 | |
| 4267 | bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { |
| 4268 | // Never defer when EmitAllDecls is specified. |
| 4269 | if (LangOpts.EmitAllDecls) |
| 4270 | return true; |
| 4271 | |
| 4272 | const auto *VD = dyn_cast<VarDecl>(Val: Global); |
| 4273 | if (VD && |
| 4274 | ((CodeGenOpts.KeepPersistentStorageVariables && |
| 4275 | (VD->getStorageDuration() == SD_Static || |
| 4276 | VD->getStorageDuration() == SD_Thread)) || |
| 4277 | (CodeGenOpts.KeepStaticConsts && VD->getStorageDuration() == SD_Static && |
| 4278 | VD->getType().isConstQualified()))) |
| 4279 | return true; |
| 4280 | |
| 4281 | return getContext().DeclMustBeEmitted(D: Global); |
| 4282 | } |
| 4283 | |
| 4284 | bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { |
| 4285 | // In OpenMP 5.0 variables and function may be marked as |
| 4286 | // device_type(host/nohost) and we should not emit them eagerly unless we sure |
| 4287 | // that they must be emitted on the host/device. To be sure we need to have |
| 4288 | // seen a declare target with an explicit mentioning of the function, we know |
| 4289 | // we have if the level of the declare target attribute is -1. Note that we |
| 4290 | // check somewhere else if we should emit this at all. |
| 4291 | if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { |
| 4292 | std::optional<OMPDeclareTargetDeclAttr *> ActiveAttr = |
| 4293 | OMPDeclareTargetDeclAttr::getActiveAttr(VD: Global); |
| 4294 | if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) |
| 4295 | return false; |
| 4296 | } |
| 4297 | |
| 4298 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: Global)) { |
| 4299 | if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) |
| 4300 | // Implicit template instantiations may change linkage if they are later |
| 4301 | // explicitly instantiated, so they should not be emitted eagerly. |
| 4302 | return false; |
| 4303 | // Defer until all versions have been semantically checked. |
| 4304 | if (FD->hasAttr<TargetVersionAttr>() && !FD->isMultiVersion()) |
| 4305 | return false; |
| 4306 | // Defer emission of SYCL kernel entry point functions during device |
| 4307 | // compilation. |
| 4308 | if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelEntryPointAttr>()) |
| 4309 | return false; |
| 4310 | // Wait for Sema's end-of-TU classification to decide between real body |
| 4311 | // and trap body (see Sema::emitDeferredDiags). |
| 4312 | if (LangOpts.CUDAIsDevice && FD->isImplicitHDExplicitInstantiation()) |
| 4313 | return false; |
| 4314 | } |
| 4315 | if (const auto *VD = dyn_cast<VarDecl>(Val: Global)) { |
| 4316 | if (Context.getInlineVariableDefinitionKind(VD) == |
| 4317 | ASTContext::InlineVariableDefinitionKind::WeakUnknown) |
| 4318 | // A definition of an inline constexpr static data member may change |
| 4319 | // linkage later if it's redeclared outside the class. |
| 4320 | return false; |
| 4321 | if (CXX20ModuleInits && VD->getOwningModule() && |
| 4322 | !VD->getOwningModule()->isModuleMapModule()) { |
| 4323 | // For CXX20, module-owned initializers need to be deferred, since it is |
| 4324 | // not known at this point if they will be run for the current module or |
| 4325 | // as part of the initializer for an imported one. |
| 4326 | return false; |
| 4327 | } |
| 4328 | } |
| 4329 | // If OpenMP is enabled and threadprivates must be generated like TLS, delay |
| 4330 | // codegen for global variables, because they may be marked as threadprivate. |
| 4331 | if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && |
| 4332 | getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Val: Global) && |
| 4333 | !Global->getType().isConstantStorage(Ctx: getContext(), ExcludeCtor: false, ExcludeDtor: false) && |
| 4334 | !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: Global)) |
| 4335 | return false; |
| 4336 | |
| 4337 | return true; |
| 4338 | } |
| 4339 | |
| 4340 | ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { |
| 4341 | StringRef Name = getMangledName(GD); |
| 4342 | |
| 4343 | // The UUID descriptor should be pointer aligned. |
| 4344 | CharUnits Alignment = CharUnits::fromQuantity(Quantity: PointerAlignInBytes); |
| 4345 | |
| 4346 | // Look for an existing global. |
| 4347 | if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) |
| 4348 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
| 4349 | |
| 4350 | ConstantEmitter Emitter(*this); |
| 4351 | llvm::Constant *Init; |
| 4352 | |
| 4353 | APValue &V = GD->getAsAPValue(); |
| 4354 | if (!V.isAbsent()) { |
| 4355 | // If possible, emit the APValue version of the initializer. In particular, |
| 4356 | // this gets the type of the constant right. |
| 4357 | Init = Emitter.emitForInitializer( |
| 4358 | value: GD->getAsAPValue(), destAddrSpace: GD->getType().getAddressSpace(), destType: GD->getType()); |
| 4359 | } else { |
| 4360 | // As a fallback, directly construct the constant. |
| 4361 | // FIXME: This may get padding wrong under esoteric struct layout rules. |
| 4362 | // MSVC appears to create a complete type 'struct __s_GUID' that it |
| 4363 | // presumably uses to represent these constants. |
| 4364 | MSGuidDecl::Parts Parts = GD->getParts(); |
| 4365 | llvm::Constant *Fields[4] = { |
| 4366 | llvm::ConstantInt::get(Ty: Int32Ty, V: Parts.Part1), |
| 4367 | llvm::ConstantInt::get(Ty: Int16Ty, V: Parts.Part2), |
| 4368 | llvm::ConstantInt::get(Ty: Int16Ty, V: Parts.Part3), |
| 4369 | llvm::ConstantDataArray::getRaw( |
| 4370 | Data: StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), NumElements: 8, |
| 4371 | ElementTy: Int8Ty)}; |
| 4372 | Init = llvm::ConstantStruct::getAnon(V: Fields); |
| 4373 | } |
| 4374 | |
| 4375 | auto *GV = new llvm::GlobalVariable( |
| 4376 | getModule(), Init->getType(), |
| 4377 | /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); |
| 4378 | if (supportsCOMDAT()) |
| 4379 | GV->setComdat(TheModule.getOrInsertComdat(Name: GV->getName())); |
| 4380 | setDSOLocal(GV); |
| 4381 | |
| 4382 | if (!V.isAbsent()) { |
| 4383 | Emitter.finalize(global: GV); |
| 4384 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
| 4385 | } |
| 4386 | |
| 4387 | llvm::Type *Ty = getTypes().ConvertTypeForMem(T: GD->getType()); |
| 4388 | return ConstantAddress(GV, Ty, Alignment); |
| 4389 | } |
| 4390 | |
| 4391 | ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl( |
| 4392 | const UnnamedGlobalConstantDecl *GCD) { |
| 4393 | CharUnits Alignment = getContext().getTypeAlignInChars(T: GCD->getType()); |
| 4394 | |
| 4395 | llvm::GlobalVariable **Entry = nullptr; |
| 4396 | Entry = &UnnamedGlobalConstantDeclMap[GCD]; |
| 4397 | if (*Entry) |
| 4398 | return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment); |
| 4399 | |
| 4400 | ConstantEmitter Emitter(*this); |
| 4401 | llvm::Constant *Init; |
| 4402 | |
| 4403 | const APValue &V = GCD->getValue(); |
| 4404 | |
| 4405 | assert(!V.isAbsent()); |
| 4406 | Init = Emitter.emitForInitializer(value: V, destAddrSpace: GCD->getType().getAddressSpace(), |
| 4407 | destType: GCD->getType()); |
| 4408 | |
| 4409 | auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), |
| 4410 | /*isConstant=*/true, |
| 4411 | llvm::GlobalValue::PrivateLinkage, Init, |
| 4412 | ".constant" ); |
| 4413 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
| 4414 | GV->setAlignment(Alignment.getAsAlign()); |
| 4415 | |
| 4416 | Emitter.finalize(global: GV); |
| 4417 | |
| 4418 | *Entry = GV; |
| 4419 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
| 4420 | } |
| 4421 | |
| 4422 | ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( |
| 4423 | const TemplateParamObjectDecl *TPO) { |
| 4424 | StringRef Name = getMangledName(GD: TPO); |
| 4425 | CharUnits Alignment = getNaturalTypeAlignment(T: TPO->getType()); |
| 4426 | llvm::Type *Type = getTypes().ConvertTypeForMem(T: TPO->getType()); |
| 4427 | |
| 4428 | if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) |
| 4429 | return ConstantAddress(GV, Type, Alignment); |
| 4430 | |
| 4431 | ConstantEmitter Emitter(*this); |
| 4432 | llvm::Constant *Init = Emitter.emitForInitializer( |
| 4433 | value: TPO->getValue(), destAddrSpace: TPO->getType().getAddressSpace(), destType: TPO->getType()); |
| 4434 | |
| 4435 | if (!Init) { |
| 4436 | ErrorUnsupported(D: TPO, Type: "template parameter object" ); |
| 4437 | return ConstantAddress::invalid(); |
| 4438 | } |
| 4439 | |
| 4440 | llvm::GlobalValue::LinkageTypes Linkage = |
| 4441 | isExternallyVisible(L: TPO->getLinkageAndVisibility().getLinkage()) |
| 4442 | ? llvm::GlobalValue::LinkOnceODRLinkage |
| 4443 | : llvm::GlobalValue::InternalLinkage; |
| 4444 | auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), |
| 4445 | /*isConstant=*/true, Linkage, Init, Name); |
| 4446 | setGVProperties(GV, D: TPO); |
| 4447 | if (supportsCOMDAT() && Linkage == llvm::GlobalValue::LinkOnceODRLinkage) |
| 4448 | GV->setComdat(TheModule.getOrInsertComdat(Name: GV->getName())); |
| 4449 | Emitter.finalize(global: GV); |
| 4450 | |
| 4451 | return ConstantAddress(GV, Type, Alignment); |
| 4452 | } |
| 4453 | |
| 4454 | ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { |
| 4455 | const AliasAttr *AA = VD->getAttr<AliasAttr>(); |
| 4456 | assert(AA && "No alias?" ); |
| 4457 | |
| 4458 | CharUnits Alignment = getContext().getDeclAlign(D: VD); |
| 4459 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(T: VD->getType()); |
| 4460 | |
| 4461 | // See if there is already something with the target's name in the module. |
| 4462 | llvm::GlobalValue *Entry = GetGlobalValue(Name: AA->getAliasee()); |
| 4463 | if (Entry) |
| 4464 | return ConstantAddress(Entry, DeclTy, Alignment); |
| 4465 | |
| 4466 | llvm::Constant *Aliasee; |
| 4467 | if (isa<llvm::FunctionType>(Val: DeclTy)) |
| 4468 | Aliasee = GetOrCreateLLVMFunction(MangledName: AA->getAliasee(), Ty: DeclTy, |
| 4469 | D: GlobalDecl(cast<FunctionDecl>(Val: VD)), |
| 4470 | /*ForVTable=*/false); |
| 4471 | else |
| 4472 | Aliasee = GetOrCreateLLVMGlobal(MangledName: AA->getAliasee(), Ty: DeclTy, AddrSpace: LangAS::Default, |
| 4473 | D: nullptr); |
| 4474 | |
| 4475 | auto *F = cast<llvm::GlobalValue>(Val: Aliasee); |
| 4476 | F->setLinkage(llvm::Function::ExternalWeakLinkage); |
| 4477 | WeakRefReferences.insert(Ptr: F); |
| 4478 | |
| 4479 | return ConstantAddress(Aliasee, DeclTy, Alignment); |
| 4480 | } |
| 4481 | |
| 4482 | template <typename AttrT> static bool hasImplicitAttr(const ValueDecl *D) { |
| 4483 | if (!D) |
| 4484 | return false; |
| 4485 | if (auto *A = D->getAttr<AttrT>()) |
| 4486 | return A->isImplicit(); |
| 4487 | return D->isImplicit(); |
| 4488 | } |
| 4489 | |
| 4490 | static bool shouldSkipAliasEmission(const CodeGenModule &CGM, |
| 4491 | const ValueDecl *Global) { |
| 4492 | const LangOptions &LangOpts = CGM.getLangOpts(); |
| 4493 | if (!LangOpts.OpenMPIsTargetDevice && !LangOpts.CUDA) |
| 4494 | return false; |
| 4495 | |
| 4496 | const auto *AA = Global->getAttr<AliasAttr>(); |
| 4497 | GlobalDecl AliaseeGD; |
| 4498 | |
| 4499 | // Check if the aliasee exists, if the aliasee is not found, skip the alias |
| 4500 | // emission. This is executed for both the host and device. |
| 4501 | if (!CGM.lookupRepresentativeDecl(MangledName: AA->getAliasee(), Result&: AliaseeGD)) |
| 4502 | return true; |
| 4503 | |
| 4504 | const auto *AliaseeDecl = dyn_cast<ValueDecl>(Val: AliaseeGD.getDecl()); |
| 4505 | if (LangOpts.OpenMPIsTargetDevice) |
| 4506 | return !AliaseeDecl || |
| 4507 | !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD: AliaseeDecl); |
| 4508 | |
| 4509 | // CUDA / HIP |
| 4510 | const bool HasDeviceAttr = Global->hasAttr<CUDADeviceAttr>(); |
| 4511 | const bool AliaseeHasDeviceAttr = |
| 4512 | AliaseeDecl && AliaseeDecl->hasAttr<CUDADeviceAttr>(); |
| 4513 | |
| 4514 | if (LangOpts.CUDAIsDevice) |
| 4515 | return !HasDeviceAttr || !AliaseeHasDeviceAttr; |
| 4516 | |
| 4517 | // CUDA / HIP Host |
| 4518 | // we know that the aliasee exists from above, so we know to emit |
| 4519 | return false; |
| 4520 | } |
| 4521 | |
| 4522 | bool CodeGenModule::shouldEmitCUDAGlobalVar(const VarDecl *Global) const { |
| 4523 | assert(LangOpts.CUDA && "Should not be called by non-CUDA languages" ); |
| 4524 | // We need to emit host-side 'shadows' for all global |
| 4525 | // device-side variables because the CUDA runtime needs their |
| 4526 | // size and host-side address in order to provide access to |
| 4527 | // their device-side incarnations. |
| 4528 | return !LangOpts.CUDAIsDevice || Global->hasAttr<CUDADeviceAttr>() || |
| 4529 | Global->hasAttr<CUDAConstantAttr>() || |
| 4530 | Global->hasAttr<CUDASharedAttr>() || |
| 4531 | Global->getType()->isCUDADeviceBuiltinSurfaceType() || |
| 4532 | Global->getType()->isCUDADeviceBuiltinTextureType(); |
| 4533 | } |
| 4534 | |
| 4535 | void CodeGenModule::EmitGlobal(GlobalDecl GD) { |
| 4536 | const auto *Global = cast<ValueDecl>(Val: GD.getDecl()); |
| 4537 | |
| 4538 | // Weak references don't produce any output by themselves. |
| 4539 | if (Global->hasAttr<WeakRefAttr>()) |
| 4540 | return; |
| 4541 | |
| 4542 | // If this is an alias definition (which otherwise looks like a declaration) |
| 4543 | // emit it now. |
| 4544 | if (Global->hasAttr<AliasAttr>()) { |
| 4545 | if (shouldSkipAliasEmission(CGM: *this, Global)) |
| 4546 | return; |
| 4547 | return EmitAliasDefinition(GD); |
| 4548 | } |
| 4549 | |
| 4550 | // IFunc like an alias whose value is resolved at runtime by calling resolver. |
| 4551 | if (Global->hasAttr<IFuncAttr>()) |
| 4552 | return emitIFuncDefinition(GD); |
| 4553 | |
| 4554 | // If this is a cpu_dispatch multiversion function, emit the resolver. |
| 4555 | if (Global->hasAttr<CPUDispatchAttr>()) |
| 4556 | return emitCPUDispatchDefinition(GD); |
| 4557 | |
| 4558 | // If this is CUDA, be selective about which declarations we emit. |
| 4559 | // Non-constexpr non-lambda implicit host device functions are not emitted |
| 4560 | // unless they are used on device side. |
| 4561 | if (LangOpts.CUDA) { |
| 4562 | assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && |
| 4563 | "Expected Variable or Function" ); |
| 4564 | if (const auto *VD = dyn_cast<VarDecl>(Val: Global)) { |
| 4565 | if (!shouldEmitCUDAGlobalVar(Global: VD)) |
| 4566 | return; |
| 4567 | } else if (LangOpts.CUDAIsDevice) { |
| 4568 | const auto *FD = dyn_cast<FunctionDecl>(Val: Global); |
| 4569 | if ((!Global->hasAttr<CUDADeviceAttr>() || |
| 4570 | (LangOpts.OffloadImplicitHostDeviceTemplates && |
| 4571 | hasImplicitAttr<CUDAHostAttr>(D: FD) && |
| 4572 | hasImplicitAttr<CUDADeviceAttr>(D: FD) && !FD->isConstexpr() && |
| 4573 | !isLambdaCallOperator(DC: FD) && |
| 4574 | !getContext().CUDAImplicitHostDeviceFunUsedByDevice.count(V: FD))) && |
| 4575 | !Global->hasAttr<CUDAGlobalAttr>() && |
| 4576 | !(LangOpts.HIPStdPar && isa<FunctionDecl>(Val: Global) && |
| 4577 | !Global->hasAttr<CUDAHostAttr>())) |
| 4578 | return; |
| 4579 | // Device-only functions are the only things we skip. |
| 4580 | } else if (!Global->hasAttr<CUDAHostAttr>() && |
| 4581 | Global->hasAttr<CUDADeviceAttr>()) |
| 4582 | return; |
| 4583 | } |
| 4584 | |
| 4585 | if (LangOpts.OpenMP) { |
| 4586 | // If this is OpenMP, check if it is legal to emit this global normally. |
| 4587 | if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) |
| 4588 | return; |
| 4589 | if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Val: Global)) { |
| 4590 | if (MustBeEmitted(Global)) |
| 4591 | EmitOMPDeclareReduction(D: DRD); |
| 4592 | return; |
| 4593 | } |
| 4594 | if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Val: Global)) { |
| 4595 | if (MustBeEmitted(Global)) |
| 4596 | EmitOMPDeclareMapper(D: DMD); |
| 4597 | return; |
| 4598 | } |
| 4599 | } |
| 4600 | |
| 4601 | // Ignore declarations, they will be emitted on their first use. |
| 4602 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: Global)) { |
| 4603 | if (DeviceKernelAttr::isOpenCLSpelling(A: FD->getAttr<DeviceKernelAttr>()) && |
| 4604 | FD->doesThisDeclarationHaveABody()) |
| 4605 | addDeferredDeclToEmit(GD: GlobalDecl(FD, KernelReferenceKind::Stub)); |
| 4606 | |
| 4607 | // Update deferred annotations with the latest declaration if the function |
| 4608 | // function was already used or defined. |
| 4609 | if (FD->hasAttr<AnnotateAttr>()) { |
| 4610 | StringRef MangledName = getMangledName(GD); |
| 4611 | if (GetGlobalValue(Name: MangledName)) |
| 4612 | DeferredAnnotations[MangledName] = FD; |
| 4613 | } |
| 4614 | |
| 4615 | // Forward declarations are emitted lazily on first use. |
| 4616 | if (!FD->doesThisDeclarationHaveABody()) { |
| 4617 | if (!FD->doesDeclarationForceExternallyVisibleDefinition() && |
| 4618 | (!FD->isMultiVersion() || !getTarget().getTriple().isAArch64())) |
| 4619 | return; |
| 4620 | |
| 4621 | StringRef MangledName = getMangledName(GD); |
| 4622 | |
| 4623 | // Compute the function info and LLVM type. |
| 4624 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
| 4625 | llvm::Type *Ty = getTypes().GetFunctionType(Info: FI); |
| 4626 | |
| 4627 | GetOrCreateLLVMFunction(MangledName, Ty, D: GD, /*ForVTable=*/false, |
| 4628 | /*DontDefer=*/false); |
| 4629 | return; |
| 4630 | } |
| 4631 | } else { |
| 4632 | const auto *VD = cast<VarDecl>(Val: Global); |
| 4633 | assert(VD->isFileVarDecl() && "Cannot emit local var decl as global." ); |
| 4634 | if (VD->isThisDeclarationADefinition() != VarDecl::Definition && |
| 4635 | !Context.isMSStaticDataMemberInlineDefinition(VD)) { |
| 4636 | if (LangOpts.OpenMP) { |
| 4637 | // Emit declaration of the must-be-emitted declare target variable. |
| 4638 | if (std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = |
| 4639 | OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { |
| 4640 | |
| 4641 | // If this variable has external storage and doesn't require special |
| 4642 | // link handling we defer to its canonical definition. |
| 4643 | if (VD->hasExternalStorage() && |
| 4644 | Res != OMPDeclareTargetDeclAttr::MT_Link) |
| 4645 | return; |
| 4646 | |
| 4647 | bool UnifiedMemoryEnabled = |
| 4648 | getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); |
| 4649 | if (*Res == OMPDeclareTargetDeclAttr::MT_Local || |
| 4650 | ((*Res == OMPDeclareTargetDeclAttr::MT_To || |
| 4651 | *Res == OMPDeclareTargetDeclAttr::MT_Enter) && |
| 4652 | !UnifiedMemoryEnabled)) { |
| 4653 | (void)GetAddrOfGlobalVar(D: VD); |
| 4654 | } else { |
| 4655 | assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || |
| 4656 | ((*Res == OMPDeclareTargetDeclAttr::MT_To || |
| 4657 | *Res == OMPDeclareTargetDeclAttr::MT_Enter) && |
| 4658 | UnifiedMemoryEnabled)) && |
| 4659 | "Link clause or to clause with unified memory expected." ); |
| 4660 | (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); |
| 4661 | } |
| 4662 | |
| 4663 | return; |
| 4664 | } |
| 4665 | } |
| 4666 | |
| 4667 | // HLSL extern globals can be read/written to by the pipeline. Those |
| 4668 | // are declared, but never defined. |
| 4669 | if (LangOpts.HLSL) { |
| 4670 | if (VD->getStorageClass() == SC_Extern) { |
| 4671 | auto GV = cast<llvm::GlobalVariable>(Val: GetAddrOfGlobalVar(D: VD)); |
| 4672 | getHLSLRuntime().handleGlobalVarDefinition(VD, Var: GV); |
| 4673 | return; |
| 4674 | } |
| 4675 | } |
| 4676 | |
| 4677 | // If this declaration may have caused an inline variable definition to |
| 4678 | // change linkage, make sure that it's emitted. |
| 4679 | if (Context.getInlineVariableDefinitionKind(VD) == |
| 4680 | ASTContext::InlineVariableDefinitionKind::Strong) |
| 4681 | GetAddrOfGlobalVar(D: VD); |
| 4682 | return; |
| 4683 | } |
| 4684 | } |
| 4685 | |
| 4686 | // Defer code generation to first use when possible, e.g. if this is an inline |
| 4687 | // function. If the global must always be emitted, do it eagerly if possible |
| 4688 | // to benefit from cache locality. |
| 4689 | if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { |
| 4690 | // Emit the definition if it can't be deferred. |
| 4691 | EmitGlobalDefinition(D: GD); |
| 4692 | addEmittedDeferredDecl(GD); |
| 4693 | return; |
| 4694 | } |
| 4695 | |
| 4696 | // If we're deferring emission of a C++ variable with an |
| 4697 | // initializer, remember the order in which it appeared in the file. |
| 4698 | if (getLangOpts().CPlusPlus && isa<VarDecl>(Val: Global) && |
| 4699 | cast<VarDecl>(Val: Global)->hasInit()) { |
| 4700 | DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); |
| 4701 | CXXGlobalInits.push_back(x: nullptr); |
| 4702 | } |
| 4703 | |
| 4704 | StringRef MangledName = getMangledName(GD); |
| 4705 | if (GetGlobalValue(Name: MangledName) != nullptr) { |
| 4706 | // The value has already been used and should therefore be emitted. |
| 4707 | addDeferredDeclToEmit(GD); |
| 4708 | } else if (MustBeEmitted(Global)) { |
| 4709 | // The value must be emitted, but cannot be emitted eagerly. |
| 4710 | assert(!MayBeEmittedEagerly(Global)); |
| 4711 | addDeferredDeclToEmit(GD); |
| 4712 | } else { |
| 4713 | // Otherwise, remember that we saw a deferred decl with this name. The |
| 4714 | // first use of the mangled name will cause it to move into |
| 4715 | // DeferredDeclsToEmit. |
| 4716 | DeferredDecls[MangledName] = GD; |
| 4717 | } |
| 4718 | } |
| 4719 | |
| 4720 | // Check if T is a class type with a destructor that's not dllimport. |
| 4721 | static bool HasNonDllImportDtor(QualType T) { |
| 4722 | if (const auto *RT = |
| 4723 | T->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>()) |
| 4724 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: RT->getDecl())) { |
| 4725 | RD = RD->getDefinitionOrSelf(); |
| 4726 | if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) |
| 4727 | return true; |
| 4728 | } |
| 4729 | |
| 4730 | return false; |
| 4731 | } |
| 4732 | |
| 4733 | namespace { |
| 4734 | // Make sure we're not referencing non-imported vars or functions. |
| 4735 | struct DLLImportFunctionVisitor |
| 4736 | : public RecursiveASTVisitor<DLLImportFunctionVisitor> { |
| 4737 | bool SafeToInline = true; |
| 4738 | |
| 4739 | bool shouldVisitImplicitCode() const { return true; } |
| 4740 | |
| 4741 | bool VisitVarDecl(VarDecl *VD) { |
| 4742 | if (VD->getTLSKind()) { |
| 4743 | // A thread-local variable cannot be imported. |
| 4744 | SafeToInline = false; |
| 4745 | return SafeToInline; |
| 4746 | } |
| 4747 | |
| 4748 | // A variable definition might imply a destructor call. |
| 4749 | if (VD->isThisDeclarationADefinition()) |
| 4750 | SafeToInline = !HasNonDllImportDtor(T: VD->getType()); |
| 4751 | |
| 4752 | return SafeToInline; |
| 4753 | } |
| 4754 | |
| 4755 | bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { |
| 4756 | if (const auto *D = E->getTemporary()->getDestructor()) |
| 4757 | SafeToInline = D->hasAttr<DLLImportAttr>(); |
| 4758 | return SafeToInline; |
| 4759 | } |
| 4760 | |
| 4761 | bool VisitDeclRefExpr(DeclRefExpr *E) { |
| 4762 | ValueDecl *VD = E->getDecl(); |
| 4763 | if (isa<FunctionDecl>(Val: VD)) |
| 4764 | SafeToInline = VD->hasAttr<DLLImportAttr>(); |
| 4765 | else if (VarDecl *V = dyn_cast<VarDecl>(Val: VD)) |
| 4766 | SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); |
| 4767 | return SafeToInline; |
| 4768 | } |
| 4769 | |
| 4770 | bool VisitCXXConstructExpr(CXXConstructExpr *E) { |
| 4771 | SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); |
| 4772 | return SafeToInline; |
| 4773 | } |
| 4774 | |
| 4775 | bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { |
| 4776 | CXXMethodDecl *M = E->getMethodDecl(); |
| 4777 | if (!M) { |
| 4778 | // Call through a pointer to member function. This is safe to inline. |
| 4779 | SafeToInline = true; |
| 4780 | } else { |
| 4781 | SafeToInline = M->hasAttr<DLLImportAttr>(); |
| 4782 | } |
| 4783 | return SafeToInline; |
| 4784 | } |
| 4785 | |
| 4786 | bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { |
| 4787 | SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); |
| 4788 | return SafeToInline; |
| 4789 | } |
| 4790 | |
| 4791 | bool VisitCXXNewExpr(CXXNewExpr *E) { |
| 4792 | SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); |
| 4793 | return SafeToInline; |
| 4794 | } |
| 4795 | }; |
| 4796 | } // namespace |
| 4797 | |
| 4798 | bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { |
| 4799 | if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) |
| 4800 | return true; |
| 4801 | |
| 4802 | const auto *F = cast<FunctionDecl>(Val: GD.getDecl()); |
| 4803 | // Inline builtins declaration must be emitted. They often are fortified |
| 4804 | // functions. |
| 4805 | if (F->isInlineBuiltinDeclaration()) |
| 4806 | return true; |
| 4807 | |
| 4808 | if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) |
| 4809 | return false; |
| 4810 | |
| 4811 | // We don't import function bodies from other named module units since that |
| 4812 | // behavior may break ABI compatibility of the current unit. |
| 4813 | if (const Module *M = F->getOwningModule(); |
| 4814 | M && M->getTopLevelModule()->isNamedModule() && |
| 4815 | getContext().getCurrentNamedModule() != M->getTopLevelModule()) { |
| 4816 | // There are practices to mark template member function as always-inline |
| 4817 | // and mark the template as extern explicit instantiation but not give |
| 4818 | // the definition for member function. So we have to emit the function |
| 4819 | // from explicitly instantiation with always-inline. |
| 4820 | // |
| 4821 | // See https://github.com/llvm/llvm-project/issues/86893 for details. |
| 4822 | // |
| 4823 | // TODO: Maybe it is better to give it a warning if we call a non-inline |
| 4824 | // function from other module units which is marked as always-inline. |
| 4825 | if (!F->isTemplateInstantiation() || !F->hasAttr<AlwaysInlineAttr>()) { |
| 4826 | return false; |
| 4827 | } |
| 4828 | } |
| 4829 | |
| 4830 | if (F->hasAttr<NoInlineAttr>()) |
| 4831 | return false; |
| 4832 | |
| 4833 | if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { |
| 4834 | // Check whether it would be safe to inline this dllimport function. |
| 4835 | DLLImportFunctionVisitor Visitor; |
| 4836 | Visitor.TraverseFunctionDecl(D: const_cast<FunctionDecl*>(F)); |
| 4837 | if (!Visitor.SafeToInline) |
| 4838 | return false; |
| 4839 | |
| 4840 | if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(Val: F)) { |
| 4841 | // Implicit destructor invocations aren't captured in the AST, so the |
| 4842 | // check above can't see them. Check for them manually here. |
| 4843 | for (const Decl *Member : Dtor->getParent()->decls()) |
| 4844 | if (isa<FieldDecl>(Val: Member)) |
| 4845 | if (HasNonDllImportDtor(T: cast<FieldDecl>(Val: Member)->getType())) |
| 4846 | return false; |
| 4847 | for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) |
| 4848 | if (HasNonDllImportDtor(T: B.getType())) |
| 4849 | return false; |
| 4850 | } |
| 4851 | } |
| 4852 | |
| 4853 | // PR9614. Avoid cases where the source code is lying to us. An available |
| 4854 | // externally function should have an equivalent function somewhere else, |
| 4855 | // but a function that calls itself through asm label/`__builtin_` trickery is |
| 4856 | // clearly not equivalent to the real implementation. |
| 4857 | // This happens in glibc's btowc and in some configure checks. |
| 4858 | return !getCXXABI().getMangleContext().isTriviallyRecursive(FD: F); |
| 4859 | } |
| 4860 | |
| 4861 | bool CodeGenModule::shouldOpportunisticallyEmitVTables() { |
| 4862 | return CodeGenOpts.OptimizationLevel > 0; |
| 4863 | } |
| 4864 | |
| 4865 | void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, |
| 4866 | llvm::GlobalValue *GV) { |
| 4867 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
| 4868 | |
| 4869 | if (FD->isCPUSpecificMultiVersion()) { |
| 4870 | auto *Spec = FD->getAttr<CPUSpecificAttr>(); |
| 4871 | for (unsigned I = 0; I < Spec->cpus_size(); ++I) |
| 4872 | EmitGlobalFunctionDefinition(GD: GD.getWithMultiVersionIndex(Index: I), GV: nullptr); |
| 4873 | } else if (auto *TC = FD->getAttr<TargetClonesAttr>()) { |
| 4874 | for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) |
| 4875 | if (TC->isFirstOfVersion(Index: I)) |
| 4876 | EmitGlobalFunctionDefinition(GD: GD.getWithMultiVersionIndex(Index: I), GV: nullptr); |
| 4877 | } else |
| 4878 | EmitGlobalFunctionDefinition(GD, GV); |
| 4879 | |
| 4880 | // Ensure that the resolver function is also emitted. |
| 4881 | if (FD->isTargetVersionMultiVersion() || FD->isTargetClonesMultiVersion()) { |
| 4882 | // On AArch64 defer the resolver emission until the entire TU is processed. |
| 4883 | if (getTarget().getTriple().isAArch64()) |
| 4884 | AddDeferredMultiVersionResolverToEmit(GD); |
| 4885 | else |
| 4886 | GetOrCreateMultiVersionResolver(GD); |
| 4887 | } |
| 4888 | } |
| 4889 | |
| 4890 | void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { |
| 4891 | const auto *D = cast<ValueDecl>(Val: GD.getDecl()); |
| 4892 | |
| 4893 | PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), |
| 4894 | Context.getSourceManager(), |
| 4895 | "Generating code for declaration" ); |
| 4896 | |
| 4897 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 4898 | // At -O0, don't generate IR for functions with available_externally |
| 4899 | // linkage. |
| 4900 | if (!shouldEmitFunction(GD)) |
| 4901 | return; |
| 4902 | |
| 4903 | llvm::TimeTraceScope TimeScope("CodeGen Function" , [&]() { |
| 4904 | std::string Name; |
| 4905 | llvm::raw_string_ostream OS(Name); |
| 4906 | FD->getNameForDiagnostic(OS, Policy: getContext().getPrintingPolicy(), |
| 4907 | /*Qualified=*/true); |
| 4908 | return Name; |
| 4909 | }); |
| 4910 | |
| 4911 | if (const auto *Method = dyn_cast<CXXMethodDecl>(Val: D)) { |
| 4912 | // Make sure to emit the definition(s) before we emit the thunks. |
| 4913 | // This is necessary for the generation of certain thunks. |
| 4914 | if (isa<CXXConstructorDecl>(Val: Method) || isa<CXXDestructorDecl>(Val: Method)) |
| 4915 | ABI->emitCXXStructor(GD); |
| 4916 | else if (FD->isMultiVersion()) |
| 4917 | EmitMultiVersionFunctionDefinition(GD, GV); |
| 4918 | else |
| 4919 | EmitGlobalFunctionDefinition(GD, GV); |
| 4920 | |
| 4921 | if (Method->isVirtual()) |
| 4922 | getVTables().EmitThunks(GD); |
| 4923 | |
| 4924 | return; |
| 4925 | } |
| 4926 | |
| 4927 | if (FD->isMultiVersion()) |
| 4928 | return EmitMultiVersionFunctionDefinition(GD, GV); |
| 4929 | return EmitGlobalFunctionDefinition(GD, GV); |
| 4930 | } |
| 4931 | |
| 4932 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
| 4933 | return EmitGlobalVarDefinition(D: VD, IsTentative: !VD->hasDefinition()); |
| 4934 | |
| 4935 | llvm_unreachable("Invalid argument to EmitGlobalDefinition()" ); |
| 4936 | } |
| 4937 | |
| 4938 | static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, |
| 4939 | llvm::Function *NewFn); |
| 4940 | |
| 4941 | static llvm::APInt |
| 4942 | getFMVPriority(const TargetInfo &TI, |
| 4943 | const CodeGenFunction::FMVResolverOption &RO) { |
| 4944 | llvm::SmallVector<StringRef, 8> Features{RO.Features}; |
| 4945 | if (RO.Architecture) |
| 4946 | Features.push_back(Elt: *RO.Architecture); |
| 4947 | return TI.getFMVPriority(Features); |
| 4948 | } |
| 4949 | |
| 4950 | // Multiversion functions should be at most 'WeakODRLinkage' so that a different |
| 4951 | // TU can forward declare the function without causing problems. Particularly |
| 4952 | // in the cases of CPUDispatch, this causes issues. This also makes sure we |
| 4953 | // work with internal linkage functions, so that the same function name can be |
| 4954 | // used with internal linkage in multiple TUs. |
| 4955 | static llvm::GlobalValue::LinkageTypes |
| 4956 | getMultiversionLinkage(CodeGenModule &CGM, GlobalDecl GD) { |
| 4957 | const FunctionDecl *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
| 4958 | if (FD->getFormalLinkage() == Linkage::Internal || CGM.getTriple().isOSAIX()) |
| 4959 | return llvm::GlobalValue::InternalLinkage; |
| 4960 | return llvm::GlobalValue::WeakODRLinkage; |
| 4961 | } |
| 4962 | |
| 4963 | void CodeGenModule::emitMultiVersionFunctions() { |
| 4964 | std::vector<GlobalDecl> MVFuncsToEmit; |
| 4965 | MultiVersionFuncs.swap(x&: MVFuncsToEmit); |
| 4966 | for (GlobalDecl GD : MVFuncsToEmit) { |
| 4967 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
| 4968 | assert(FD && "Expected a FunctionDecl" ); |
| 4969 | |
| 4970 | auto createFunction = [&](const FunctionDecl *Decl, unsigned MVIdx = 0) { |
| 4971 | GlobalDecl CurGD{Decl->isDefined() ? Decl->getDefinition() : Decl, MVIdx}; |
| 4972 | StringRef MangledName = getMangledName(GD: CurGD); |
| 4973 | llvm::Constant *Func = GetGlobalValue(Name: MangledName); |
| 4974 | if (!Func) { |
| 4975 | if (Decl->isDefined()) { |
| 4976 | EmitGlobalFunctionDefinition(GD: CurGD, GV: nullptr); |
| 4977 | Func = GetGlobalValue(Name: MangledName); |
| 4978 | } else { |
| 4979 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD: CurGD); |
| 4980 | llvm::FunctionType *Ty = getTypes().GetFunctionType(Info: FI); |
| 4981 | Func = GetAddrOfFunction(GD: CurGD, Ty, /*ForVTable=*/false, |
| 4982 | /*DontDefer=*/false, IsForDefinition: ForDefinition); |
| 4983 | } |
| 4984 | assert(Func && "This should have just been created" ); |
| 4985 | } |
| 4986 | return cast<llvm::Function>(Val: Func); |
| 4987 | }; |
| 4988 | |
| 4989 | // For AArch64, a resolver is only emitted if a function marked with |
| 4990 | // target_version("default")) or target_clones("default") is defined |
| 4991 | // in this TU. For other architectures it is always emitted. |
| 4992 | bool ShouldEmitResolver = !getTriple().isAArch64(); |
| 4993 | SmallVector<CodeGenFunction::FMVResolverOption, 10> Options; |
| 4994 | llvm::DenseMap<llvm::Function *, const FunctionDecl *> DeclMap; |
| 4995 | |
| 4996 | getContext().forEachMultiversionedFunctionVersion( |
| 4997 | FD, Pred: [&](const FunctionDecl *CurFD) { |
| 4998 | llvm::SmallVector<StringRef, 8> Feats; |
| 4999 | bool IsDefined = CurFD->getDefinition() != nullptr; |
| 5000 | |
| 5001 | if (const auto *TA = CurFD->getAttr<TargetAttr>()) { |
| 5002 | assert(getTarget().getTriple().isX86() && "Unsupported target" ); |
| 5003 | TA->getX86AddedFeatures(Out&: Feats); |
| 5004 | llvm::Function *Func = createFunction(CurFD); |
| 5005 | DeclMap.insert(KV: {Func, CurFD}); |
| 5006 | Options.emplace_back(Args&: Func, Args&: Feats, Args: TA->getX86Architecture()); |
| 5007 | } else if (const auto *TVA = CurFD->getAttr<TargetVersionAttr>()) { |
| 5008 | if (TVA->isDefaultVersion() && IsDefined) |
| 5009 | ShouldEmitResolver = true; |
| 5010 | llvm::Function *Func = createFunction(CurFD); |
| 5011 | DeclMap.insert(KV: {Func, CurFD}); |
| 5012 | char Delim = getTarget().getTriple().isAArch64() ? '+' : ','; |
| 5013 | TVA->getFeatures(Out&: Feats, Delim); |
| 5014 | Options.emplace_back(Args&: Func, Args&: Feats); |
| 5015 | } else if (const auto *TC = CurFD->getAttr<TargetClonesAttr>()) { |
| 5016 | for (unsigned I = 0; I < TC->featuresStrs_size(); ++I) { |
| 5017 | if (!TC->isFirstOfVersion(Index: I)) |
| 5018 | continue; |
| 5019 | if (TC->isDefaultVersion(Index: I) && IsDefined) |
| 5020 | ShouldEmitResolver = true; |
| 5021 | llvm::Function *Func = createFunction(CurFD, I); |
| 5022 | DeclMap.insert(KV: {Func, CurFD}); |
| 5023 | Feats.clear(); |
| 5024 | if (getTarget().getTriple().isX86()) { |
| 5025 | TC->getX86Feature(Out&: Feats, Index: I); |
| 5026 | Options.emplace_back(Args&: Func, Args&: Feats, Args: TC->getX86Architecture(Index: I)); |
| 5027 | } else { |
| 5028 | char Delim = getTarget().getTriple().isAArch64() ? '+' : ','; |
| 5029 | TC->getFeatures(Out&: Feats, Index: I, Delim); |
| 5030 | Options.emplace_back(Args&: Func, Args&: Feats); |
| 5031 | } |
| 5032 | } |
| 5033 | } else |
| 5034 | llvm_unreachable("unexpected MultiVersionKind" ); |
| 5035 | }); |
| 5036 | |
| 5037 | if (!ShouldEmitResolver) |
| 5038 | continue; |
| 5039 | |
| 5040 | llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD); |
| 5041 | if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(Val: ResolverConstant)) { |
| 5042 | ResolverConstant = IFunc->getResolver(); |
| 5043 | if (FD->isTargetClonesMultiVersion() && |
| 5044 | !getTarget().getTriple().isAArch64() && |
| 5045 | !getTarget().getTriple().isOSAIX()) { |
| 5046 | std::string MangledName = getMangledNameImpl( |
| 5047 | CGM&: *this, GD, ND: FD, /*OmitMultiVersionMangling=*/true); |
| 5048 | if (!GetGlobalValue(Name: MangledName + ".ifunc" )) { |
| 5049 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
| 5050 | llvm::FunctionType *DeclTy = getTypes().GetFunctionType(Info: FI); |
| 5051 | // In prior versions of Clang, the mangling for ifuncs incorrectly |
| 5052 | // included an .ifunc suffix. This alias is generated for backward |
| 5053 | // compatibility. It is deprecated, and may be removed in the future. |
| 5054 | auto *Alias = llvm::GlobalAlias::create( |
| 5055 | Ty: DeclTy, AddressSpace: 0, Linkage: getMultiversionLinkage(CGM&: *this, GD), |
| 5056 | Name: MangledName + ".ifunc" , Aliasee: IFunc, Parent: &getModule()); |
| 5057 | SetCommonAttributes(GD: FD, GV: Alias); |
| 5058 | } |
| 5059 | } |
| 5060 | } |
| 5061 | llvm::Function *ResolverFunc = cast<llvm::Function>(Val: ResolverConstant); |
| 5062 | |
| 5063 | const TargetInfo &TI = getTarget(); |
| 5064 | llvm::stable_sort( |
| 5065 | Range&: Options, C: [&TI](const CodeGenFunction::FMVResolverOption &LHS, |
| 5066 | const CodeGenFunction::FMVResolverOption &RHS) { |
| 5067 | return getFMVPriority(TI, RO: LHS).ugt(RHS: getFMVPriority(TI, RO: RHS)); |
| 5068 | }); |
| 5069 | |
| 5070 | // Diagnose unreachable function versions. |
| 5071 | if (getTarget().getTriple().isAArch64()) { |
| 5072 | for (auto I = Options.begin() + 1, E = Options.end(); I != E; ++I) { |
| 5073 | llvm::APInt RHS = llvm::AArch64::getCpuSupportsMask(Features: I->Features); |
| 5074 | if (std::any_of(first: Options.begin(), last: I, pred: [RHS](auto RO) { |
| 5075 | llvm::APInt LHS = llvm::AArch64::getCpuSupportsMask(Features: RO.Features); |
| 5076 | return LHS.isSubsetOf(RHS); |
| 5077 | })) { |
| 5078 | Diags.Report(Loc: DeclMap[I->Function]->getLocation(), |
| 5079 | DiagID: diag::warn_unreachable_version) |
| 5080 | << I->Function->getName(); |
| 5081 | assert(I->Function->user_empty() && "unexpected users" ); |
| 5082 | I->Function->eraseFromParent(); |
| 5083 | I->Function = nullptr; |
| 5084 | } |
| 5085 | } |
| 5086 | } |
| 5087 | CodeGenFunction CGF(*this); |
| 5088 | CGF.EmitMultiVersionResolver(Resolver: ResolverFunc, Options); |
| 5089 | |
| 5090 | setMultiVersionResolverAttributes(Resolver: ResolverFunc, GD); |
| 5091 | if (!ResolverFunc->hasLocalLinkage() && supportsCOMDAT()) |
| 5092 | ResolverFunc->setComdat( |
| 5093 | getModule().getOrInsertComdat(Name: ResolverFunc->getName())); |
| 5094 | } |
| 5095 | |
| 5096 | // Ensure that any additions to the deferred decls list caused by emitting a |
| 5097 | // variant are emitted. This can happen when the variant itself is inline and |
| 5098 | // calls a function without linkage. |
| 5099 | if (!MVFuncsToEmit.empty()) |
| 5100 | EmitDeferred(); |
| 5101 | |
| 5102 | // Ensure that any additions to the multiversion funcs list from either the |
| 5103 | // deferred decls or the multiversion functions themselves are emitted. |
| 5104 | if (!MultiVersionFuncs.empty()) |
| 5105 | emitMultiVersionFunctions(); |
| 5106 | } |
| 5107 | |
| 5108 | // Symbols with this prefix are used as deactivation symbols for PFP fields. |
| 5109 | // See clang/docs/StructureProtection.rst for more information. |
| 5110 | static const char PFPDeactivationSymbolPrefix[] = "__pfp_ds_" ; |
| 5111 | |
| 5112 | llvm::GlobalValue * |
| 5113 | CodeGenModule::getPFPDeactivationSymbol(const FieldDecl *FD) { |
| 5114 | std::string DSName = PFPDeactivationSymbolPrefix + getPFPFieldName(FD); |
| 5115 | llvm::GlobalValue *DS = TheModule.getNamedValue(Name: DSName); |
| 5116 | if (!DS) { |
| 5117 | DS = new llvm::GlobalVariable(TheModule, Int8Ty, false, |
| 5118 | llvm::GlobalVariable::ExternalWeakLinkage, |
| 5119 | nullptr, DSName); |
| 5120 | DS->setVisibility(llvm::GlobalValue::HiddenVisibility); |
| 5121 | } |
| 5122 | return DS; |
| 5123 | } |
| 5124 | |
| 5125 | void CodeGenModule::emitPFPFieldsWithEvaluatedOffset() { |
| 5126 | llvm::Constant *Nop = llvm::ConstantExpr::getIntToPtr( |
| 5127 | C: llvm::ConstantInt::get(Ty: Int64Ty, V: 0xd503201f), Ty: VoidPtrTy); |
| 5128 | for (auto *FD : getContext().PFPFieldsWithEvaluatedOffset) { |
| 5129 | std::string DSName = PFPDeactivationSymbolPrefix + getPFPFieldName(FD); |
| 5130 | llvm::GlobalValue *OldDS = TheModule.getNamedValue(Name: DSName); |
| 5131 | llvm::GlobalValue *DS = llvm::GlobalAlias::create( |
| 5132 | Ty: Int8Ty, AddressSpace: 0, Linkage: llvm::GlobalValue::ExternalLinkage, Name: DSName, Aliasee: Nop, Parent: &TheModule); |
| 5133 | DS->setVisibility(llvm::GlobalValue::HiddenVisibility); |
| 5134 | if (OldDS) { |
| 5135 | DS->takeName(V: OldDS); |
| 5136 | OldDS->replaceAllUsesWith(V: DS); |
| 5137 | OldDS->eraseFromParent(); |
| 5138 | } |
| 5139 | } |
| 5140 | } |
| 5141 | |
| 5142 | static void replaceDeclarationWith(llvm::GlobalValue *Old, |
| 5143 | llvm::Constant *New) { |
| 5144 | assert(cast<llvm::Function>(Old)->isDeclaration() && "Not a declaration" ); |
| 5145 | New->takeName(V: Old); |
| 5146 | Old->replaceAllUsesWith(V: New); |
| 5147 | Old->eraseFromParent(); |
| 5148 | } |
| 5149 | |
| 5150 | void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { |
| 5151 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
| 5152 | assert(FD && "Not a FunctionDecl?" ); |
| 5153 | assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?" ); |
| 5154 | const auto *DD = FD->getAttr<CPUDispatchAttr>(); |
| 5155 | assert(DD && "Not a cpu_dispatch Function?" ); |
| 5156 | |
| 5157 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
| 5158 | llvm::FunctionType *DeclTy = getTypes().GetFunctionType(Info: FI); |
| 5159 | |
| 5160 | StringRef ResolverName = getMangledName(GD); |
| 5161 | UpdateMultiVersionNames(GD, FD, CurName&: ResolverName); |
| 5162 | |
| 5163 | llvm::Type *ResolverType; |
| 5164 | GlobalDecl ResolverGD; |
| 5165 | if (getTarget().supportsIFunc()) { |
| 5166 | ResolverType = llvm::FunctionType::get( |
| 5167 | Result: llvm::PointerType::get(C&: getLLVMContext(), |
| 5168 | AddressSpace: getTypes().getTargetAddressSpace(T: FD->getType())), |
| 5169 | isVarArg: false); |
| 5170 | } |
| 5171 | else { |
| 5172 | ResolverType = DeclTy; |
| 5173 | ResolverGD = GD; |
| 5174 | } |
| 5175 | |
| 5176 | auto *ResolverFunc = cast<llvm::Function>(Val: GetOrCreateLLVMFunction( |
| 5177 | MangledName: ResolverName, Ty: ResolverType, D: ResolverGD, /*ForVTable=*/false)); |
| 5178 | |
| 5179 | if (supportsCOMDAT()) |
| 5180 | ResolverFunc->setComdat( |
| 5181 | getModule().getOrInsertComdat(Name: ResolverFunc->getName())); |
| 5182 | |
| 5183 | SmallVector<CodeGenFunction::FMVResolverOption, 10> Options; |
| 5184 | const TargetInfo &Target = getTarget(); |
| 5185 | unsigned Index = 0; |
| 5186 | for (const IdentifierInfo *II : DD->cpus()) { |
| 5187 | // Get the name of the target function so we can look it up/create it. |
| 5188 | std::string MangledName = getMangledNameImpl(CGM&: *this, GD, ND: FD, OmitMultiVersionMangling: true) + |
| 5189 | getCPUSpecificMangling(CGM: *this, Name: II->getName()); |
| 5190 | |
| 5191 | llvm::Constant *Func = GetGlobalValue(Name: MangledName); |
| 5192 | |
| 5193 | if (!Func) { |
| 5194 | GlobalDecl ExistingDecl = Manglings.lookup(Key: MangledName); |
| 5195 | if (ExistingDecl.getDecl() && |
| 5196 | ExistingDecl.getDecl()->getAsFunction()->isDefined()) { |
| 5197 | EmitGlobalFunctionDefinition(GD: ExistingDecl, GV: nullptr); |
| 5198 | Func = GetGlobalValue(Name: MangledName); |
| 5199 | } else { |
| 5200 | if (!ExistingDecl.getDecl()) |
| 5201 | ExistingDecl = GD.getWithMultiVersionIndex(Index); |
| 5202 | |
| 5203 | Func = GetOrCreateLLVMFunction( |
| 5204 | MangledName, Ty: DeclTy, D: ExistingDecl, |
| 5205 | /*ForVTable=*/false, /*DontDefer=*/true, |
| 5206 | /*IsThunk=*/false, ExtraAttrs: llvm::AttributeList(), IsForDefinition: ForDefinition); |
| 5207 | } |
| 5208 | } |
| 5209 | |
| 5210 | llvm::SmallVector<StringRef, 32> Features; |
| 5211 | Target.getCPUSpecificCPUDispatchFeatures(Name: II->getName(), Features); |
| 5212 | llvm::transform(Range&: Features, d_first: Features.begin(), |
| 5213 | F: [](StringRef Str) { return Str.substr(Start: 1); }); |
| 5214 | llvm::erase_if(C&: Features, P: [&Target](StringRef Feat) { |
| 5215 | return !Target.validateCpuSupports(Name: Feat); |
| 5216 | }); |
| 5217 | Options.emplace_back(Args: cast<llvm::Function>(Val: Func), Args&: Features); |
| 5218 | ++Index; |
| 5219 | } |
| 5220 | |
| 5221 | llvm::stable_sort(Range&: Options, C: [](const CodeGenFunction::FMVResolverOption &LHS, |
| 5222 | const CodeGenFunction::FMVResolverOption &RHS) { |
| 5223 | return llvm::X86::getCpuSupportsMask(FeatureStrs: LHS.Features) > |
| 5224 | llvm::X86::getCpuSupportsMask(FeatureStrs: RHS.Features); |
| 5225 | }); |
| 5226 | |
| 5227 | // If the list contains multiple 'default' versions, such as when it contains |
| 5228 | // 'pentium' and 'generic', don't emit the call to the generic one (since we |
| 5229 | // always run on at least a 'pentium'). We do this by deleting the 'least |
| 5230 | // advanced' (read, lowest mangling letter). |
| 5231 | while (Options.size() > 1 && llvm::all_of(Range: llvm::X86::getCpuSupportsMask( |
| 5232 | FeatureStrs: (Options.end() - 2)->Features), |
| 5233 | P: [](auto X) { return X == 0; })) { |
| 5234 | StringRef LHSName = (Options.end() - 2)->Function->getName(); |
| 5235 | StringRef RHSName = (Options.end() - 1)->Function->getName(); |
| 5236 | if (LHSName.compare(RHS: RHSName) < 0) |
| 5237 | Options.erase(CI: Options.end() - 2); |
| 5238 | else |
| 5239 | Options.erase(CI: Options.end() - 1); |
| 5240 | } |
| 5241 | |
| 5242 | CodeGenFunction CGF(*this); |
| 5243 | CGF.EmitMultiVersionResolver(Resolver: ResolverFunc, Options); |
| 5244 | setMultiVersionResolverAttributes(Resolver: ResolverFunc, GD); |
| 5245 | |
| 5246 | if (getTarget().supportsIFunc()) { |
| 5247 | llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(CGM&: *this, GD); |
| 5248 | auto *IFunc = cast<llvm::GlobalValue>(Val: GetOrCreateMultiVersionResolver(GD)); |
| 5249 | unsigned AS = IFunc->getType()->getPointerAddressSpace(); |
| 5250 | |
| 5251 | // Fix up function declarations that were created for cpu_specific before |
| 5252 | // cpu_dispatch was known |
| 5253 | if (!isa<llvm::GlobalIFunc>(Val: IFunc)) { |
| 5254 | auto *GI = llvm::GlobalIFunc::create(Ty: DeclTy, AddressSpace: AS, Linkage, Name: "" , |
| 5255 | Resolver: ResolverFunc, Parent: &getModule()); |
| 5256 | replaceDeclarationWith(Old: IFunc, New: GI); |
| 5257 | IFunc = GI; |
| 5258 | } |
| 5259 | |
| 5260 | std::string AliasName = getMangledNameImpl( |
| 5261 | CGM&: *this, GD, ND: FD, /*OmitMultiVersionMangling=*/true); |
| 5262 | llvm::Constant *AliasFunc = GetGlobalValue(Name: AliasName); |
| 5263 | if (!AliasFunc) { |
| 5264 | auto *GA = llvm::GlobalAlias::create(Ty: DeclTy, AddressSpace: AS, Linkage, Name: AliasName, |
| 5265 | Aliasee: IFunc, Parent: &getModule()); |
| 5266 | SetCommonAttributes(GD, GV: GA); |
| 5267 | } |
| 5268 | } |
| 5269 | } |
| 5270 | |
| 5271 | /// Adds a declaration to the list of multi version functions if not present. |
| 5272 | void CodeGenModule::AddDeferredMultiVersionResolverToEmit(GlobalDecl GD) { |
| 5273 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
| 5274 | assert(FD && "Not a FunctionDecl?" ); |
| 5275 | |
| 5276 | if (FD->isTargetVersionMultiVersion() || FD->isTargetClonesMultiVersion()) { |
| 5277 | std::string MangledName = |
| 5278 | getMangledNameImpl(CGM&: *this, GD, ND: FD, /*OmitMultiVersionMangling=*/true); |
| 5279 | if (!DeferredResolversToEmit.insert(key: MangledName).second) |
| 5280 | return; |
| 5281 | } |
| 5282 | MultiVersionFuncs.push_back(x: GD); |
| 5283 | } |
| 5284 | |
| 5285 | /// If a dispatcher for the specified mangled name is not in the module, create |
| 5286 | /// and return it. The dispatcher is either an llvm Function with the specified |
| 5287 | /// type, or a global ifunc. |
| 5288 | llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) { |
| 5289 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
| 5290 | assert(FD && "Not a FunctionDecl?" ); |
| 5291 | |
| 5292 | std::string MangledName = |
| 5293 | getMangledNameImpl(CGM&: *this, GD, ND: FD, /*OmitMultiVersionMangling=*/true); |
| 5294 | |
| 5295 | // Holds the name of the resolver, in ifunc mode this is the ifunc (which has |
| 5296 | // a separate resolver). |
| 5297 | std::string ResolverName = MangledName; |
| 5298 | if (getTarget().supportsIFunc()) { |
| 5299 | switch (FD->getMultiVersionKind()) { |
| 5300 | case MultiVersionKind::None: |
| 5301 | llvm_unreachable("unexpected MultiVersionKind::None for resolver" ); |
| 5302 | case MultiVersionKind::Target: |
| 5303 | case MultiVersionKind::CPUSpecific: |
| 5304 | case MultiVersionKind::CPUDispatch: |
| 5305 | ResolverName += ".ifunc" ; |
| 5306 | break; |
| 5307 | case MultiVersionKind::TargetClones: |
| 5308 | case MultiVersionKind::TargetVersion: |
| 5309 | break; |
| 5310 | } |
| 5311 | } else if (FD->isTargetMultiVersion()) { |
| 5312 | ResolverName += ".resolver" ; |
| 5313 | } |
| 5314 | |
| 5315 | bool ShouldReturnIFunc = |
| 5316 | getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion(); |
| 5317 | |
| 5318 | // If the resolver has already been created, just return it. This lookup may |
| 5319 | // yield a function declaration instead of a resolver on AArch64. That is |
| 5320 | // because we didn't know whether a resolver will be generated when we first |
| 5321 | // encountered a use of the symbol named after this resolver. Therefore, |
| 5322 | // targets which support ifuncs should not return here unless we actually |
| 5323 | // found an ifunc. |
| 5324 | llvm::GlobalValue *ResolverGV = GetGlobalValue(Name: ResolverName); |
| 5325 | if (ResolverGV && (isa<llvm::GlobalIFunc>(Val: ResolverGV) || !ShouldReturnIFunc)) |
| 5326 | return ResolverGV; |
| 5327 | |
| 5328 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
| 5329 | llvm::FunctionType *DeclTy = getTypes().GetFunctionType(Info: FI); |
| 5330 | |
| 5331 | // The resolver needs to be created. For target and target_clones, defer |
| 5332 | // creation until the end of the TU. |
| 5333 | if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion()) |
| 5334 | AddDeferredMultiVersionResolverToEmit(GD); |
| 5335 | |
| 5336 | // For cpu_specific, don't create an ifunc yet because we don't know if the |
| 5337 | // cpu_dispatch will be emitted in this translation unit. |
| 5338 | if (ShouldReturnIFunc) { |
| 5339 | unsigned AS = getTypes().getTargetAddressSpace(T: FD->getType()); |
| 5340 | llvm::Type *ResolverType = llvm::FunctionType::get( |
| 5341 | Result: llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: AS), isVarArg: false); |
| 5342 | llvm::Constant *Resolver = GetOrCreateLLVMFunction( |
| 5343 | MangledName: MangledName + ".resolver" , Ty: ResolverType, D: GlobalDecl{}, |
| 5344 | /*ForVTable=*/false); |
| 5345 | |
| 5346 | // on AIX, the FMV is ignored on a declaration, and so we don't need the |
| 5347 | // ifunc, which is only generated on FMV definitions, to be weak. |
| 5348 | auto Linkage = getTriple().isOSAIX() ? getFunctionLinkage(GD) |
| 5349 | : getMultiversionLinkage(CGM&: *this, GD); |
| 5350 | |
| 5351 | llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(Ty: DeclTy, AddressSpace: AS, Linkage, Name: "" , |
| 5352 | Resolver, Parent: &getModule()); |
| 5353 | GIF->setName(ResolverName); |
| 5354 | SetCommonAttributes(GD: FD, GV: GIF); |
| 5355 | if (ResolverGV) |
| 5356 | replaceDeclarationWith(Old: ResolverGV, New: GIF); |
| 5357 | return GIF; |
| 5358 | } |
| 5359 | |
| 5360 | llvm::Constant *Resolver = GetOrCreateLLVMFunction( |
| 5361 | MangledName: ResolverName, Ty: DeclTy, D: GlobalDecl{}, /*ForVTable=*/false); |
| 5362 | assert(isa<llvm::GlobalValue>(Resolver) && !ResolverGV && |
| 5363 | "Resolver should be created for the first time" ); |
| 5364 | SetCommonAttributes(GD: FD, GV: cast<llvm::GlobalValue>(Val: Resolver)); |
| 5365 | return Resolver; |
| 5366 | } |
| 5367 | |
| 5368 | void CodeGenModule::setMultiVersionResolverAttributes(llvm::Function *Resolver, |
| 5369 | GlobalDecl GD) { |
| 5370 | const NamedDecl *D = dyn_cast_or_null<NamedDecl>(Val: GD.getDecl()); |
| 5371 | |
| 5372 | Resolver->setLinkage(getMultiversionLinkage(CGM&: *this, GD)); |
| 5373 | |
| 5374 | // Function body has to be emitted before calling setGlobalVisibility |
| 5375 | // for Resolver to be considered as definition. |
| 5376 | setGlobalVisibility(GV: Resolver, D); |
| 5377 | |
| 5378 | setDSOLocal(Resolver); |
| 5379 | |
| 5380 | // The resolver must be exempt from sanitizer instrumentation, as it can run |
| 5381 | // before the sanitizer is initialized. |
| 5382 | // (https://github.com/llvm/llvm-project/issues/163369) |
| 5383 | Resolver->addFnAttr(Kind: llvm::Attribute::DisableSanitizerInstrumentation); |
| 5384 | |
| 5385 | // Set the default target-specific attributes, such as PAC and BTI ones on |
| 5386 | // AArch64. Not passing Decl to prevent setting unrelated attributes, |
| 5387 | // as Resolver can be shared by multiple declarations. |
| 5388 | // FIXME Some targets may require a non-null D to set some attributes |
| 5389 | // (such as "stackrealign" on X86, even when it is requested via |
| 5390 | // "-mstackrealign" command line option). |
| 5391 | getTargetCodeGenInfo().setTargetAttributes(/*D=*/nullptr, GV: Resolver, M&: *this); |
| 5392 | } |
| 5393 | |
| 5394 | bool CodeGenModule::shouldDropDLLAttribute(const Decl *D, |
| 5395 | const llvm::GlobalValue *GV) const { |
| 5396 | auto SC = GV->getDLLStorageClass(); |
| 5397 | if (SC == llvm::GlobalValue::DefaultStorageClass) |
| 5398 | return false; |
| 5399 | const Decl *MRD = D->getMostRecentDecl(); |
| 5400 | return (((SC == llvm::GlobalValue::DLLImportStorageClass && |
| 5401 | !MRD->hasAttr<DLLImportAttr>()) || |
| 5402 | (SC == llvm::GlobalValue::DLLExportStorageClass && |
| 5403 | !MRD->hasAttr<DLLExportAttr>())) && |
| 5404 | !shouldMapVisibilityToDLLExport(D: cast<NamedDecl>(Val: MRD))); |
| 5405 | } |
| 5406 | |
| 5407 | /// GetOrCreateLLVMFunction - If the specified mangled name is not in the |
| 5408 | /// module, create and return an llvm Function with the specified type. If there |
| 5409 | /// is something in the module with the specified name, return it potentially |
| 5410 | /// bitcasted to the right type. |
| 5411 | /// |
| 5412 | /// If D is non-null, it specifies a decl that correspond to this. This is used |
| 5413 | /// to set the attributes on the function when it is first created. |
| 5414 | llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( |
| 5415 | StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, |
| 5416 | bool DontDefer, bool IsThunk, llvm::AttributeList , |
| 5417 | ForDefinition_t IsForDefinition) { |
| 5418 | const Decl *D = GD.getDecl(); |
| 5419 | |
| 5420 | std::string NameWithoutMultiVersionMangling; |
| 5421 | if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(Val: D)) { |
| 5422 | // For the device mark the function as one that should be emitted. |
| 5423 | if (getLangOpts().OpenMPIsTargetDevice && OpenMPRuntime && |
| 5424 | !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && |
| 5425 | !DontDefer && !IsForDefinition) { |
| 5426 | if (const FunctionDecl *FDDef = FD->getDefinition()) { |
| 5427 | GlobalDecl GDDef; |
| 5428 | if (const auto *CD = dyn_cast<CXXConstructorDecl>(Val: FDDef)) |
| 5429 | GDDef = GlobalDecl(CD, GD.getCtorType()); |
| 5430 | else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Val: FDDef)) |
| 5431 | GDDef = GlobalDecl(DD, GD.getDtorType()); |
| 5432 | else |
| 5433 | GDDef = GlobalDecl(FDDef); |
| 5434 | EmitGlobal(GD: GDDef); |
| 5435 | } |
| 5436 | } |
| 5437 | |
| 5438 | // Any attempts to use a MultiVersion function should result in retrieving |
| 5439 | // the iFunc instead. Name Mangling will handle the rest of the changes. |
| 5440 | if (FD->isMultiVersion()) { |
| 5441 | UpdateMultiVersionNames(GD, FD, CurName&: MangledName); |
| 5442 | if (!IsForDefinition) { |
| 5443 | // On AArch64 we do not immediatelly emit an ifunc resolver when a |
| 5444 | // function is used. Instead we defer the emission until we see a |
| 5445 | // default definition. In the meantime we just reference the symbol |
| 5446 | // without FMV mangling (it may or may not be replaced later). |
| 5447 | if (getTarget().getTriple().isAArch64()) { |
| 5448 | AddDeferredMultiVersionResolverToEmit(GD); |
| 5449 | NameWithoutMultiVersionMangling = getMangledNameImpl( |
| 5450 | CGM&: *this, GD, ND: FD, /*OmitMultiVersionMangling=*/true); |
| 5451 | } |
| 5452 | // On AIX, a declared (but not defined) FMV shall be treated like a |
| 5453 | // regular non-FMV function. If a definition is later seen, then |
| 5454 | // GetOrCreateMultiVersionResolver will get called (when processing said |
| 5455 | // definition) which will replace the IR declaration we're creating here |
| 5456 | // with the FMV ifunc (see replaceDeclarationWith). |
| 5457 | else if (getTriple().isOSAIX() && !FD->isDefined()) { |
| 5458 | NameWithoutMultiVersionMangling = getMangledNameImpl( |
| 5459 | CGM&: *this, GD, ND: FD, /*OmitMultiVersionMangling=*/true); |
| 5460 | } else |
| 5461 | return GetOrCreateMultiVersionResolver(GD); |
| 5462 | } |
| 5463 | } |
| 5464 | } |
| 5465 | |
| 5466 | if (!NameWithoutMultiVersionMangling.empty()) |
| 5467 | MangledName = NameWithoutMultiVersionMangling; |
| 5468 | |
| 5469 | // Lookup the entry, lazily creating it if necessary. |
| 5470 | llvm::GlobalValue *Entry = GetGlobalValue(Name: MangledName); |
| 5471 | if (Entry) { |
| 5472 | if (WeakRefReferences.erase(Ptr: Entry)) { |
| 5473 | const FunctionDecl *FD = cast_or_null<FunctionDecl>(Val: D); |
| 5474 | if (FD && !FD->hasAttr<WeakAttr>()) |
| 5475 | Entry->setLinkage(llvm::Function::ExternalLinkage); |
| 5476 | } |
| 5477 | |
| 5478 | // Handle dropped DLL attributes. |
| 5479 | if (D && shouldDropDLLAttribute(D, GV: Entry)) { |
| 5480 | Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); |
| 5481 | setDSOLocal(Entry); |
| 5482 | } |
| 5483 | |
| 5484 | // If there are two attempts to define the same mangled name, issue an |
| 5485 | // error. |
| 5486 | if (IsForDefinition && !Entry->isDeclaration()) { |
| 5487 | GlobalDecl OtherGD; |
| 5488 | // Check that GD is not yet in DiagnosedConflictingDefinitions is required |
| 5489 | // to make sure that we issue an error only once. |
| 5490 | if (lookupRepresentativeDecl(MangledName, Result&: OtherGD) && |
| 5491 | (GD.getCanonicalDecl().getDecl() != |
| 5492 | OtherGD.getCanonicalDecl().getDecl()) && |
| 5493 | DiagnosedConflictingDefinitions.insert(V: GD).second) { |
| 5494 | getDiags().Report(Loc: D->getLocation(), DiagID: diag::err_duplicate_mangled_name) |
| 5495 | << MangledName; |
| 5496 | getDiags().Report(Loc: OtherGD.getDecl()->getLocation(), |
| 5497 | DiagID: diag::note_previous_definition); |
| 5498 | } |
| 5499 | } |
| 5500 | |
| 5501 | if ((isa<llvm::Function>(Val: Entry) || isa<llvm::GlobalAlias>(Val: Entry)) && |
| 5502 | (Entry->getValueType() == Ty)) { |
| 5503 | return Entry; |
| 5504 | } |
| 5505 | |
| 5506 | // Make sure the result is of the correct type. |
| 5507 | // (If function is requested for a definition, we always need to create a new |
| 5508 | // function, not just return a bitcast.) |
| 5509 | if (!IsForDefinition) |
| 5510 | return Entry; |
| 5511 | } |
| 5512 | |
| 5513 | // This function doesn't have a complete type (for example, the return |
| 5514 | // type is an incomplete struct). Use a fake type instead, and make |
| 5515 | // sure not to try to set attributes. |
| 5516 | bool IsIncompleteFunction = false; |
| 5517 | |
| 5518 | llvm::FunctionType *FTy; |
| 5519 | if (isa<llvm::FunctionType>(Val: Ty)) { |
| 5520 | FTy = cast<llvm::FunctionType>(Val: Ty); |
| 5521 | } else { |
| 5522 | FTy = llvm::FunctionType::get(Result: VoidTy, isVarArg: false); |
| 5523 | IsIncompleteFunction = true; |
| 5524 | } |
| 5525 | |
| 5526 | llvm::Function *F = |
| 5527 | llvm::Function::Create(Ty: FTy, Linkage: llvm::Function::ExternalLinkage, |
| 5528 | N: Entry ? StringRef() : MangledName, M: &getModule()); |
| 5529 | |
| 5530 | // Store the declaration associated with this function so it is potentially |
| 5531 | // updated by further declarations or definitions and emitted at the end. |
| 5532 | if (D && D->hasAttr<AnnotateAttr>()) |
| 5533 | DeferredAnnotations[MangledName] = cast<ValueDecl>(Val: D); |
| 5534 | |
| 5535 | // If we already created a function with the same mangled name (but different |
| 5536 | // type) before, take its name and add it to the list of functions to be |
| 5537 | // replaced with F at the end of CodeGen. |
| 5538 | // |
| 5539 | // This happens if there is a prototype for a function (e.g. "int f()") and |
| 5540 | // then a definition of a different type (e.g. "int f(int x)"). |
| 5541 | if (Entry) { |
| 5542 | F->takeName(V: Entry); |
| 5543 | |
| 5544 | // This might be an implementation of a function without a prototype, in |
| 5545 | // which case, try to do special replacement of calls which match the new |
| 5546 | // prototype. The really key thing here is that we also potentially drop |
| 5547 | // arguments from the call site so as to make a direct call, which makes the |
| 5548 | // inliner happier and suppresses a number of optimizer warnings (!) about |
| 5549 | // dropping arguments. |
| 5550 | if (!Entry->use_empty()) { |
| 5551 | ReplaceUsesOfNonProtoTypeWithRealFunction(Old: Entry, NewFn: F); |
| 5552 | Entry->removeDeadConstantUsers(); |
| 5553 | } |
| 5554 | |
| 5555 | addGlobalValReplacement(GV: Entry, C: F); |
| 5556 | } |
| 5557 | |
| 5558 | assert(F->getName() == MangledName && "name was uniqued!" ); |
| 5559 | if (D) |
| 5560 | SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); |
| 5561 | if (ExtraAttrs.hasFnAttrs()) { |
| 5562 | llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); |
| 5563 | F->addFnAttrs(Attrs: B); |
| 5564 | } |
| 5565 | |
| 5566 | if (!DontDefer) { |
| 5567 | // All MSVC dtors other than the base dtor are linkonce_odr and delegate to |
| 5568 | // each other bottoming out with the base dtor. Therefore we emit non-base |
| 5569 | // dtors on usage, even if there is no dtor definition in the TU. |
| 5570 | if (isa_and_nonnull<CXXDestructorDecl>(Val: D) && |
| 5571 | getCXXABI().useThunkForDtorVariant(Dtor: cast<CXXDestructorDecl>(Val: D), |
| 5572 | DT: GD.getDtorType())) |
| 5573 | addDeferredDeclToEmit(GD); |
| 5574 | |
| 5575 | // This is the first use or definition of a mangled name. If there is a |
| 5576 | // deferred decl with this name, remember that we need to emit it at the end |
| 5577 | // of the file. |
| 5578 | auto DDI = DeferredDecls.find(Val: MangledName); |
| 5579 | if (DDI != DeferredDecls.end()) { |
| 5580 | // Move the potentially referenced deferred decl to the |
| 5581 | // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we |
| 5582 | // don't need it anymore). |
| 5583 | addDeferredDeclToEmit(GD: DDI->second); |
| 5584 | DeferredDecls.erase(I: DDI); |
| 5585 | |
| 5586 | // Otherwise, there are cases we have to worry about where we're |
| 5587 | // using a declaration for which we must emit a definition but where |
| 5588 | // we might not find a top-level definition: |
| 5589 | // - member functions defined inline in their classes |
| 5590 | // - friend functions defined inline in some class |
| 5591 | // - special member functions with implicit definitions |
| 5592 | // If we ever change our AST traversal to walk into class methods, |
| 5593 | // this will be unnecessary. |
| 5594 | // |
| 5595 | // We also don't emit a definition for a function if it's going to be an |
| 5596 | // entry in a vtable, unless it's already marked as used. |
| 5597 | } else if (getLangOpts().CPlusPlus && D) { |
| 5598 | // Look for a declaration that's lexically in a record. |
| 5599 | for (const auto *FD = cast<FunctionDecl>(Val: D)->getMostRecentDecl(); FD; |
| 5600 | FD = FD->getPreviousDecl()) { |
| 5601 | if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) { |
| 5602 | if (FD->doesThisDeclarationHaveABody()) { |
| 5603 | addDeferredDeclToEmit(GD: GD.getWithDecl(D: FD)); |
| 5604 | break; |
| 5605 | } |
| 5606 | } |
| 5607 | } |
| 5608 | } |
| 5609 | } |
| 5610 | |
| 5611 | // Make sure the result is of the requested type. |
| 5612 | if (!IsIncompleteFunction) { |
| 5613 | assert(F->getFunctionType() == Ty); |
| 5614 | return F; |
| 5615 | } |
| 5616 | |
| 5617 | return F; |
| 5618 | } |
| 5619 | |
| 5620 | /// GetAddrOfFunction - Return the address of the given function. If Ty is |
| 5621 | /// non-null, then this function will use the specified type if it has to |
| 5622 | /// create it (this occurs when we see a definition of the function). |
| 5623 | llvm::Constant * |
| 5624 | CodeGenModule::GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty, bool ForVTable, |
| 5625 | bool DontDefer, |
| 5626 | ForDefinition_t IsForDefinition) { |
| 5627 | // If there was no specific requested type, just convert it now. |
| 5628 | if (!Ty) { |
| 5629 | const auto *FD = cast<FunctionDecl>(Val: GD.getDecl()); |
| 5630 | Ty = getTypes().ConvertType(T: FD->getType()); |
| 5631 | if (DeviceKernelAttr::isOpenCLSpelling(A: FD->getAttr<DeviceKernelAttr>()) && |
| 5632 | GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { |
| 5633 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
| 5634 | Ty = getTypes().GetFunctionType(Info: FI); |
| 5635 | } |
| 5636 | } |
| 5637 | |
| 5638 | // Devirtualized destructor calls may come through here instead of via |
| 5639 | // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead |
| 5640 | // of the complete destructor when necessary. |
| 5641 | if (const auto *DD = dyn_cast<CXXDestructorDecl>(Val: GD.getDecl())) { |
| 5642 | if (getTarget().getCXXABI().isMicrosoft() && |
| 5643 | GD.getDtorType() == Dtor_Complete && |
| 5644 | DD->getParent()->getNumVBases() == 0) |
| 5645 | GD = GlobalDecl(DD, Dtor_Base); |
| 5646 | } |
| 5647 | |
| 5648 | StringRef MangledName = getMangledName(GD); |
| 5649 | auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, |
| 5650 | /*IsThunk=*/false, ExtraAttrs: llvm::AttributeList(), |
| 5651 | IsForDefinition); |
| 5652 | // Returns kernel handle for HIP kernel stub function. |
| 5653 | if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && |
| 5654 | cast<FunctionDecl>(Val: GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { |
| 5655 | auto *Handle = getCUDARuntime().getKernelHandle( |
| 5656 | Stub: cast<llvm::Function>(Val: F->stripPointerCasts()), GD); |
| 5657 | if (IsForDefinition) |
| 5658 | return F; |
| 5659 | return Handle; |
| 5660 | } |
| 5661 | return F; |
| 5662 | } |
| 5663 | |
| 5664 | llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { |
| 5665 | llvm::GlobalValue *F = |
| 5666 | cast<llvm::GlobalValue>(Val: GetAddrOfFunction(GD: Decl)->stripPointerCasts()); |
| 5667 | |
| 5668 | return llvm::NoCFIValue::get(GV: F); |
| 5669 | } |
| 5670 | |
| 5671 | static const FunctionDecl * |
| 5672 | GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { |
| 5673 | TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); |
| 5674 | DeclContext *DC = TranslationUnitDecl::castToDeclContext(D: TUDecl); |
| 5675 | |
| 5676 | IdentifierInfo &CII = C.Idents.get(Name); |
| 5677 | for (const auto *Result : DC->lookup(Name: &CII)) |
| 5678 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: Result)) |
| 5679 | return FD; |
| 5680 | |
| 5681 | if (!C.getLangOpts().CPlusPlus) |
| 5682 | return nullptr; |
| 5683 | |
| 5684 | // Demangle the premangled name from getTerminateFn() |
| 5685 | IdentifierInfo &CXXII = |
| 5686 | (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ" ) |
| 5687 | ? C.Idents.get(Name: "terminate" ) |
| 5688 | : C.Idents.get(Name); |
| 5689 | |
| 5690 | for (const auto &N : {"__cxxabiv1" , "std" }) { |
| 5691 | IdentifierInfo &NS = C.Idents.get(Name: N); |
| 5692 | for (const auto *Result : DC->lookup(Name: &NS)) { |
| 5693 | const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: Result); |
| 5694 | if (auto *LSD = dyn_cast<LinkageSpecDecl>(Val: Result)) |
| 5695 | for (const auto *Result : LSD->lookup(Name: &NS)) |
| 5696 | if ((ND = dyn_cast<NamespaceDecl>(Val: Result))) |
| 5697 | break; |
| 5698 | |
| 5699 | if (ND) |
| 5700 | for (const auto *Result : ND->lookup(Name: &CXXII)) |
| 5701 | if (const auto *FD = dyn_cast<FunctionDecl>(Val: Result)) |
| 5702 | return FD; |
| 5703 | } |
| 5704 | } |
| 5705 | |
| 5706 | return nullptr; |
| 5707 | } |
| 5708 | |
| 5709 | static void setWindowsItaniumDLLImport(CodeGenModule &CGM, bool Local, |
| 5710 | llvm::Function *F, StringRef Name) { |
| 5711 | // In Windows Itanium environments, try to mark runtime functions |
| 5712 | // dllimport. For Mingw and MSVC, don't. We don't really know if the user |
| 5713 | // will link their standard library statically or dynamically. Marking |
| 5714 | // functions imported when they are not imported can cause linker errors |
| 5715 | // and warnings. |
| 5716 | if (!Local && CGM.getTriple().isWindowsItaniumEnvironment() && |
| 5717 | !CGM.getCodeGenOpts().LTOVisibilityPublicStd) { |
| 5718 | const FunctionDecl *FD = GetRuntimeFunctionDecl(C&: CGM.getContext(), Name); |
| 5719 | if (!FD || FD->hasAttr<DLLImportAttr>()) { |
| 5720 | F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); |
| 5721 | F->setLinkage(llvm::GlobalValue::ExternalLinkage); |
| 5722 | } |
| 5723 | } |
| 5724 | } |
| 5725 | |
| 5726 | llvm::FunctionCallee CodeGenModule::CreateRuntimeFunction( |
| 5727 | QualType ReturnTy, ArrayRef<QualType> ArgTys, StringRef Name, |
| 5728 | llvm::AttributeList , bool Local, bool AssumeConvergent) { |
| 5729 | if (AssumeConvergent) { |
| 5730 | ExtraAttrs = |
| 5731 | ExtraAttrs.addFnAttribute(C&: VMContext, Kind: llvm::Attribute::Convergent); |
| 5732 | } |
| 5733 | |
| 5734 | QualType FTy = Context.getFunctionType(ResultTy: ReturnTy, Args: ArgTys, |
| 5735 | EPI: FunctionProtoType::ExtProtoInfo()); |
| 5736 | const CGFunctionInfo &Info = getTypes().arrangeFreeFunctionType( |
| 5737 | Ty: Context.getCanonicalType(T: FTy).castAs<FunctionProtoType>()); |
| 5738 | auto *ConvTy = getTypes().GetFunctionType(Info); |
| 5739 | llvm::Constant *C = GetOrCreateLLVMFunction( |
| 5740 | MangledName: Name, Ty: ConvTy, GD: GlobalDecl(), /*ForVTable=*/false, |
| 5741 | /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs); |
| 5742 | |
| 5743 | if (auto *F = dyn_cast<llvm::Function>(Val: C)) { |
| 5744 | if (F->empty()) { |
| 5745 | SetLLVMFunctionAttributes(GD: GlobalDecl(), Info, F, /*IsThunk*/ false); |
| 5746 | // FIXME: Set calling-conv properly in ExtProtoInfo |
| 5747 | F->setCallingConv(getRuntimeCC()); |
| 5748 | setWindowsItaniumDLLImport(CGM&: *this, Local, F, Name); |
| 5749 | setDSOLocal(F); |
| 5750 | } |
| 5751 | } |
| 5752 | return {ConvTy, C}; |
| 5753 | } |
| 5754 | |
| 5755 | /// CreateRuntimeFunction - Create a new runtime function with the specified |
| 5756 | /// type and name. |
| 5757 | llvm::FunctionCallee |
| 5758 | CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, |
| 5759 | llvm::AttributeList , bool Local, |
| 5760 | bool AssumeConvergent) { |
| 5761 | if (AssumeConvergent) { |
| 5762 | ExtraAttrs = |
| 5763 | ExtraAttrs.addFnAttribute(C&: VMContext, Kind: llvm::Attribute::Convergent); |
| 5764 | } |
| 5765 | |
| 5766 | llvm::Constant *C = |
| 5767 | GetOrCreateLLVMFunction(MangledName: Name, Ty: FTy, GD: GlobalDecl(), /*ForVTable=*/false, |
| 5768 | /*DontDefer=*/false, /*IsThunk=*/false, |
| 5769 | ExtraAttrs); |
| 5770 | |
| 5771 | if (auto *F = dyn_cast<llvm::Function>(Val: C)) { |
| 5772 | if (F->empty()) { |
| 5773 | F->setCallingConv(getRuntimeCC()); |
| 5774 | setWindowsItaniumDLLImport(CGM&: *this, Local, F, Name); |
| 5775 | setDSOLocal(F); |
| 5776 | // FIXME: We should use CodeGenModule::SetLLVMFunctionAttributes() instead |
| 5777 | // of trying to approximate the attributes using the LLVM function |
| 5778 | // signature. The other overload of CreateRuntimeFunction does this; it |
| 5779 | // should be used for new code. |
| 5780 | markRegisterParameterAttributes(F); |
| 5781 | } |
| 5782 | } |
| 5783 | |
| 5784 | return {FTy, C}; |
| 5785 | } |
| 5786 | |
| 5787 | /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, |
| 5788 | /// create and return an llvm GlobalVariable with the specified type and address |
| 5789 | /// space. If there is something in the module with the specified name, return |
| 5790 | /// it potentially bitcasted to the right type. |
| 5791 | /// |
| 5792 | /// If D is non-null, it specifies a decl that correspond to this. This is used |
| 5793 | /// to set the attributes on the global when it is first created. |
| 5794 | /// |
| 5795 | /// If IsForDefinition is true, it is guaranteed that an actual global with |
| 5796 | /// type Ty will be returned, not conversion of a variable with the same |
| 5797 | /// mangled name but some other type. |
| 5798 | llvm::Constant * |
| 5799 | CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, |
| 5800 | LangAS AddrSpace, const VarDecl *D, |
| 5801 | ForDefinition_t IsForDefinition) { |
| 5802 | // Lookup the entry, lazily creating it if necessary. |
| 5803 | llvm::GlobalValue *Entry = GetGlobalValue(Name: MangledName); |
| 5804 | unsigned TargetAS = getContext().getTargetAddressSpace(AS: AddrSpace); |
| 5805 | if (Entry) { |
| 5806 | if (WeakRefReferences.erase(Ptr: Entry)) { |
| 5807 | if (D && !D->hasAttr<WeakAttr>()) |
| 5808 | Entry->setLinkage(llvm::Function::ExternalLinkage); |
| 5809 | } |
| 5810 | |
| 5811 | // Handle dropped DLL attributes. |
| 5812 | if (D && shouldDropDLLAttribute(D, GV: Entry)) |
| 5813 | Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); |
| 5814 | |
| 5815 | if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) |
| 5816 | getOpenMPRuntime().registerTargetGlobalVariable(VD: D, Addr: Entry); |
| 5817 | |
| 5818 | if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) |
| 5819 | return Entry; |
| 5820 | |
| 5821 | // If there are two attempts to define the same mangled name, issue an |
| 5822 | // error. |
| 5823 | if (IsForDefinition && !Entry->isDeclaration()) { |
| 5824 | GlobalDecl OtherGD; |
| 5825 | const VarDecl *OtherD; |
| 5826 | |
| 5827 | // Check that D is not yet in DiagnosedConflictingDefinitions is required |
| 5828 | // to make sure that we issue an error only once. |
| 5829 | if (D && lookupRepresentativeDecl(MangledName, Result&: OtherGD) && |
| 5830 | (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && |
| 5831 | (OtherD = dyn_cast<VarDecl>(Val: OtherGD.getDecl())) && |
| 5832 | OtherD->hasInit() && |
| 5833 | DiagnosedConflictingDefinitions.insert(V: D).second) { |
| 5834 | getDiags().Report(Loc: D->getLocation(), DiagID: diag::err_duplicate_mangled_name) |
| 5835 | << MangledName; |
| 5836 | getDiags().Report(Loc: OtherGD.getDecl()->getLocation(), |
| 5837 | DiagID: diag::note_previous_definition); |
| 5838 | } |
| 5839 | } |
| 5840 | |
| 5841 | // Make sure the result is of the correct type. |
| 5842 | if (Entry->getType()->getAddressSpace() != TargetAS) |
| 5843 | return llvm::ConstantExpr::getAddrSpaceCast( |
| 5844 | C: Entry, Ty: llvm::PointerType::get(C&: Ty->getContext(), AddressSpace: TargetAS)); |
| 5845 | |
| 5846 | // (If global is requested for a definition, we always need to create a new |
| 5847 | // global, not just return a bitcast.) |
| 5848 | if (!IsForDefinition) |
| 5849 | return Entry; |
| 5850 | } |
| 5851 | |
| 5852 | auto DAddrSpace = GetGlobalVarAddressSpace(D); |
| 5853 | |
| 5854 | auto *GV = new llvm::GlobalVariable( |
| 5855 | getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, |
| 5856 | MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, |
| 5857 | getContext().getTargetAddressSpace(AS: DAddrSpace)); |
| 5858 | |
| 5859 | // If we already created a global with the same mangled name (but different |
| 5860 | // type) before, take its name and remove it from its parent. |
| 5861 | if (Entry) { |
| 5862 | GV->takeName(V: Entry); |
| 5863 | |
| 5864 | if (!Entry->use_empty()) { |
| 5865 | Entry->replaceAllUsesWith(V: GV); |
| 5866 | } |
| 5867 | |
| 5868 | Entry->eraseFromParent(); |
| 5869 | } |
| 5870 | |
| 5871 | // This is the first use or definition of a mangled name. If there is a |
| 5872 | // deferred decl with this name, remember that we need to emit it at the end |
| 5873 | // of the file. |
| 5874 | auto DDI = DeferredDecls.find(Val: MangledName); |
| 5875 | if (DDI != DeferredDecls.end()) { |
| 5876 | // Move the potentially referenced deferred decl to the DeferredDeclsToEmit |
| 5877 | // list, and remove it from DeferredDecls (since we don't need it anymore). |
| 5878 | addDeferredDeclToEmit(GD: DDI->second); |
| 5879 | DeferredDecls.erase(I: DDI); |
| 5880 | } |
| 5881 | |
| 5882 | // Handle things which are present even on external declarations. |
| 5883 | if (D) { |
| 5884 | if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) |
| 5885 | getOpenMPRuntime().registerTargetGlobalVariable(VD: D, Addr: GV); |
| 5886 | |
| 5887 | // FIXME: This code is overly simple and should be merged with other global |
| 5888 | // handling. |
| 5889 | GV->setConstant(D->getType().isConstantStorage(Ctx: getContext(), ExcludeCtor: false, ExcludeDtor: false)); |
| 5890 | |
| 5891 | GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); |
| 5892 | |
| 5893 | setLinkageForGV(GV, ND: D); |
| 5894 | |
| 5895 | if (D->getTLSKind()) { |
| 5896 | if (D->getTLSKind() == VarDecl::TLS_Dynamic) |
| 5897 | CXXThreadLocals.push_back(x: D); |
| 5898 | setTLSMode(GV, D: *D); |
| 5899 | } |
| 5900 | |
| 5901 | setGVProperties(GV, D); |
| 5902 | |
| 5903 | // If required by the ABI, treat declarations of static data members with |
| 5904 | // inline initializers as definitions. |
| 5905 | if (getContext().isMSStaticDataMemberInlineDefinition(VD: D)) { |
| 5906 | EmitGlobalVarDefinition(D); |
| 5907 | } |
| 5908 | |
| 5909 | // Emit section information for extern variables. |
| 5910 | if (D->hasExternalStorage()) { |
| 5911 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) |
| 5912 | GV->setSection(SA->getName()); |
| 5913 | } |
| 5914 | |
| 5915 | // Handle XCore specific ABI requirements. |
| 5916 | if (getTriple().getArch() == llvm::Triple::xcore && |
| 5917 | D->getLanguageLinkage() == CLanguageLinkage && |
| 5918 | D->getType().isConstant(Ctx: Context) && |
| 5919 | isExternallyVisible(L: D->getLinkageAndVisibility().getLinkage())) |
| 5920 | GV->setSection(".cp.rodata" ); |
| 5921 | |
| 5922 | // Handle code model attribute |
| 5923 | if (const auto *CMA = D->getAttr<CodeModelAttr>()) |
| 5924 | GV->setCodeModel(CMA->getModel()); |
| 5925 | |
| 5926 | // Check if we a have a const declaration with an initializer, we may be |
| 5927 | // able to emit it as available_externally to expose it's value to the |
| 5928 | // optimizer. |
| 5929 | if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && |
| 5930 | D->getType().isConstQualified() && !GV->hasInitializer() && |
| 5931 | !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { |
| 5932 | const auto *Record = |
| 5933 | Context.getBaseElementType(QT: D->getType())->getAsCXXRecordDecl(); |
| 5934 | bool HasMutableFields = Record && Record->hasMutableFields(); |
| 5935 | if (!HasMutableFields) { |
| 5936 | const VarDecl *InitDecl; |
| 5937 | const Expr *InitExpr = D->getAnyInitializer(D&: InitDecl); |
| 5938 | if (InitExpr) { |
| 5939 | ConstantEmitter emitter(*this); |
| 5940 | llvm::Constant *Init = emitter.tryEmitForInitializer(D: *InitDecl); |
| 5941 | if (Init) { |
| 5942 | auto *InitType = Init->getType(); |
| 5943 | if (GV->getValueType() != InitType) { |
| 5944 | // The type of the initializer does not match the definition. |
| 5945 | // This happens when an initializer has a different type from |
| 5946 | // the type of the global (because of padding at the end of a |
| 5947 | // structure for instance). |
| 5948 | GV->setName(StringRef()); |
| 5949 | // Make a new global with the correct type, this is now guaranteed |
| 5950 | // to work. |
| 5951 | auto *NewGV = cast<llvm::GlobalVariable>( |
| 5952 | Val: GetAddrOfGlobalVar(D, Ty: InitType, IsForDefinition) |
| 5953 | ->stripPointerCasts()); |
| 5954 | |
| 5955 | // Erase the old global, since it is no longer used. |
| 5956 | GV->eraseFromParent(); |
| 5957 | GV = NewGV; |
| 5958 | } else { |
| 5959 | GV->setInitializer(Init); |
| 5960 | GV->setConstant(true); |
| 5961 | GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); |
| 5962 | } |
| 5963 | emitter.finalize(global: GV); |
| 5964 | } |
| 5965 | } |
| 5966 | } |
| 5967 | } |
| 5968 | } |
| 5969 | |
| 5970 | if (D && |
| 5971 | D->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly) { |
| 5972 | getTargetCodeGenInfo().setTargetAttributes(D, GV, M&: *this); |
| 5973 | // External HIP managed variables needed to be recorded for transformation |
| 5974 | // in both device and host compilations. |
| 5975 | if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && |
| 5976 | D->hasExternalStorage()) |
| 5977 | getCUDARuntime().handleVarRegistration(VD: D, Var&: *GV); |
| 5978 | } |
| 5979 | |
| 5980 | if (D) |
| 5981 | SanitizerMD->reportGlobal(GV, D: *D); |
| 5982 | |
| 5983 | LangAS ExpectedAS = |
| 5984 | D ? D->getType().getAddressSpace() |
| 5985 | : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); |
| 5986 | assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); |
| 5987 | if (DAddrSpace != ExpectedAS) |
| 5988 | return performAddrSpaceCast( |
| 5989 | Src: GV, DestTy: llvm::PointerType::get(C&: getLLVMContext(), AddressSpace: TargetAS)); |
| 5990 | |
| 5991 | return GV; |
| 5992 | } |
| 5993 | |
| 5994 | llvm::Constant * |
| 5995 | CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { |
| 5996 | const Decl *D = GD.getDecl(); |
| 5997 | |
| 5998 | if (isa<CXXConstructorDecl>(Val: D) || isa<CXXDestructorDecl>(Val: D)) |
| 5999 | return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, |
| 6000 | /*DontDefer=*/false, IsForDefinition); |
| 6001 | |
| 6002 | if (isa<CXXMethodDecl>(Val: D)) { |
| 6003 | auto FInfo = |
| 6004 | &getTypes().arrangeCXXMethodDeclaration(MD: cast<CXXMethodDecl>(Val: D)); |
| 6005 | auto Ty = getTypes().GetFunctionType(Info: *FInfo); |
| 6006 | return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, |
| 6007 | IsForDefinition); |
| 6008 | } |
| 6009 | |
| 6010 | if (isa<FunctionDecl>(Val: D)) { |
| 6011 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
| 6012 | llvm::FunctionType *Ty = getTypes().GetFunctionType(Info: FI); |
| 6013 | return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, |
| 6014 | IsForDefinition); |
| 6015 | } |
| 6016 | |
| 6017 | return GetAddrOfGlobalVar(D: cast<VarDecl>(Val: D), /*Ty=*/nullptr, IsForDefinition); |
| 6018 | } |
| 6019 | |
| 6020 | llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( |
| 6021 | StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, |
| 6022 | llvm::Align Alignment) { |
| 6023 | llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); |
| 6024 | llvm::GlobalVariable *OldGV = nullptr; |
| 6025 | |
| 6026 | if (GV) { |
| 6027 | // Check if the variable has the right type. |
| 6028 | if (GV->getValueType() == Ty) |
| 6029 | return GV; |
| 6030 | |
| 6031 | // Because C++ name mangling, the only way we can end up with an already |
| 6032 | // existing global with the same name is if it has been declared extern "C". |
| 6033 | assert(GV->isDeclaration() && "Declaration has wrong type!" ); |
| 6034 | OldGV = GV; |
| 6035 | } |
| 6036 | |
| 6037 | // Create a new variable. |
| 6038 | GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, |
| 6039 | Linkage, nullptr, Name); |
| 6040 | |
| 6041 | if (OldGV) { |
| 6042 | // Replace occurrences of the old variable if needed. |
| 6043 | GV->takeName(V: OldGV); |
| 6044 | |
| 6045 | if (!OldGV->use_empty()) { |
| 6046 | OldGV->replaceAllUsesWith(V: GV); |
| 6047 | } |
| 6048 | |
| 6049 | OldGV->eraseFromParent(); |
| 6050 | } |
| 6051 | |
| 6052 | if (supportsCOMDAT() && GV->isWeakForLinker() && |
| 6053 | !GV->hasAvailableExternallyLinkage()) |
| 6054 | GV->setComdat(TheModule.getOrInsertComdat(Name: GV->getName())); |
| 6055 | |
| 6056 | GV->setAlignment(Alignment); |
| 6057 | |
| 6058 | return GV; |
| 6059 | } |
| 6060 | |
| 6061 | /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the |
| 6062 | /// given global variable. If Ty is non-null and if the global doesn't exist, |
| 6063 | /// then it will be created with the specified type instead of whatever the |
| 6064 | /// normal requested type would be. If IsForDefinition is true, it is guaranteed |
| 6065 | /// that an actual global with type Ty will be returned, not conversion of a |
| 6066 | /// variable with the same mangled name but some other type. |
| 6067 | llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, |
| 6068 | llvm::Type *Ty, |
| 6069 | ForDefinition_t IsForDefinition) { |
| 6070 | assert(D->hasGlobalStorage() && "Not a global variable" ); |
| 6071 | QualType ASTTy = D->getType(); |
| 6072 | if (!Ty) |
| 6073 | Ty = getTypes().ConvertTypeForMem(T: ASTTy); |
| 6074 | |
| 6075 | StringRef MangledName = getMangledName(GD: D); |
| 6076 | return GetOrCreateLLVMGlobal(MangledName, Ty, AddrSpace: ASTTy.getAddressSpace(), D, |
| 6077 | IsForDefinition); |
| 6078 | } |
| 6079 | |
| 6080 | /// CreateRuntimeVariable - Create a new runtime global variable with the |
| 6081 | /// specified type and name. |
| 6082 | llvm::Constant * |
| 6083 | CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, |
| 6084 | StringRef Name) { |
| 6085 | LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global |
| 6086 | : LangAS::Default; |
| 6087 | auto *Ret = GetOrCreateLLVMGlobal(MangledName: Name, Ty, AddrSpace, D: nullptr); |
| 6088 | setDSOLocal(cast<llvm::GlobalValue>(Val: Ret->stripPointerCasts())); |
| 6089 | return Ret; |
| 6090 | } |
| 6091 | |
| 6092 | void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { |
| 6093 | assert(!D->getInit() && "Cannot emit definite definitions here!" ); |
| 6094 | |
| 6095 | StringRef MangledName = getMangledName(GD: D); |
| 6096 | llvm::GlobalValue *GV = GetGlobalValue(Name: MangledName); |
| 6097 | |
| 6098 | // We already have a definition, not declaration, with the same mangled name. |
| 6099 | // Emitting of declaration is not required (and actually overwrites emitted |
| 6100 | // definition). |
| 6101 | if (GV && !GV->isDeclaration()) |
| 6102 | return; |
| 6103 | |
| 6104 | // If we have not seen a reference to this variable yet, place it into the |
| 6105 | // deferred declarations table to be emitted if needed later. |
| 6106 | if (!MustBeEmitted(Global: D) && !GV) { |
| 6107 | DeferredDecls[MangledName] = D; |
| 6108 | return; |
| 6109 | } |
| 6110 | |
| 6111 | // The tentative definition is the only definition. |
| 6112 | EmitGlobalVarDefinition(D); |
| 6113 | } |
| 6114 | |
| 6115 | // Return a GlobalDecl. Use the base variants for destructors and constructors. |
| 6116 | static GlobalDecl getBaseVariantGlobalDecl(const NamedDecl *D) { |
| 6117 | if (auto const *CD = dyn_cast<const CXXConstructorDecl>(Val: D)) |
| 6118 | return GlobalDecl(CD, CXXCtorType::Ctor_Base); |
| 6119 | else if (auto const *DD = dyn_cast<const CXXDestructorDecl>(Val: D)) |
| 6120 | return GlobalDecl(DD, CXXDtorType::Dtor_Base); |
| 6121 | return GlobalDecl(D); |
| 6122 | } |
| 6123 | |
| 6124 | void CodeGenModule::EmitExternalDeclaration(const DeclaratorDecl *D) { |
| 6125 | CGDebugInfo *DI = getModuleDebugInfo(); |
| 6126 | if (!DI || !getCodeGenOpts().hasReducedDebugInfo()) |
| 6127 | return; |
| 6128 | |
| 6129 | GlobalDecl GD = getBaseVariantGlobalDecl(D); |
| 6130 | if (!GD) |
| 6131 | return; |
| 6132 | |
| 6133 | llvm::Constant *Addr = GetAddrOfGlobal(GD)->stripPointerCasts(); |
| 6134 | if (auto *GA = dyn_cast<llvm::GlobalAlias>(Val: Addr)) { |
| 6135 | DI->EmitGlobalAlias(GV: GA, Decl: GD); |
| 6136 | return; |
| 6137 | } |
| 6138 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) { |
| 6139 | DI->EmitExternalVariable( |
| 6140 | GV: cast<llvm::GlobalVariable>(Val: Addr->stripPointerCasts()), Decl: VD); |
| 6141 | } else if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) { |
| 6142 | llvm::Function *Fn = cast<llvm::Function>(Val: Addr); |
| 6143 | if (!Fn->getSubprogram()) |
| 6144 | DI->EmitFunctionDecl(GD, Loc: FD->getLocation(), FnType: FD->getType(), Fn); |
| 6145 | } |
| 6146 | } |
| 6147 | |
| 6148 | CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { |
| 6149 | return Context.toCharUnitsFromBits( |
| 6150 | BitSize: getDataLayout().getTypeStoreSizeInBits(Ty)); |
| 6151 | } |
| 6152 | |
| 6153 | LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { |
| 6154 | if (LangOpts.OpenCL) { |
| 6155 | LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; |
| 6156 | assert(AS == LangAS::opencl_global || |
| 6157 | AS == LangAS::opencl_global_device || |
| 6158 | AS == LangAS::opencl_global_host || |
| 6159 | AS == LangAS::opencl_constant || |
| 6160 | AS == LangAS::opencl_local || |
| 6161 | AS >= LangAS::FirstTargetAddressSpace); |
| 6162 | return AS; |
| 6163 | } |
| 6164 | |
| 6165 | if (LangOpts.SYCLIsDevice && |
| 6166 | (!D || D->getType().getAddressSpace() == LangAS::Default)) |
| 6167 | return LangAS::sycl_global; |
| 6168 | |
| 6169 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { |
| 6170 | if (D) { |
| 6171 | if (D->hasAttr<CUDAConstantAttr>()) |
| 6172 | return LangAS::cuda_constant; |
| 6173 | if (D->hasAttr<CUDASharedAttr>()) |
| 6174 | return LangAS::cuda_shared; |
| 6175 | if (D->hasAttr<CUDADeviceAttr>()) |
| 6176 | return LangAS::cuda_device; |
| 6177 | if (D->getType().isConstQualified()) |
| 6178 | return LangAS::cuda_constant; |
| 6179 | } |
| 6180 | return LangAS::cuda_device; |
| 6181 | } |
| 6182 | |
| 6183 | if (LangOpts.OpenMP) { |
| 6184 | LangAS AS; |
| 6185 | if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(VD: D, AS)) |
| 6186 | return AS; |
| 6187 | } |
| 6188 | return getTargetCodeGenInfo().getGlobalVarAddressSpace(CGM&: *this, D); |
| 6189 | } |
| 6190 | |
| 6191 | LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { |
| 6192 | // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. |
| 6193 | if (LangOpts.OpenCL) |
| 6194 | return LangAS::opencl_constant; |
| 6195 | if (LangOpts.SYCLIsDevice) |
| 6196 | return LangAS::sycl_global; |
| 6197 | if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) |
| 6198 | // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) |
| 6199 | // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up |
| 6200 | // with OpVariable instructions with Generic storage class which is not |
| 6201 | // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V |
| 6202 | // UniformConstant storage class is not viable as pointers to it may not be |
| 6203 | // casted to Generic pointers which are used to model HIP's "flat" pointers. |
| 6204 | return LangAS::cuda_device; |
| 6205 | if (auto AS = getTarget().getConstantAddressSpace()) |
| 6206 | return *AS; |
| 6207 | return LangAS::Default; |
| 6208 | } |
| 6209 | |
| 6210 | // In address space agnostic languages, string literals are in default address |
| 6211 | // space in AST. However, certain targets (e.g. amdgcn) request them to be |
| 6212 | // emitted in constant address space in LLVM IR. To be consistent with other |
| 6213 | // parts of AST, string literal global variables in constant address space |
| 6214 | // need to be casted to default address space before being put into address |
| 6215 | // map and referenced by other part of CodeGen. |
| 6216 | // In OpenCL, string literals are in constant address space in AST, therefore |
| 6217 | // they should not be casted to default address space. |
| 6218 | static llvm::Constant * |
| 6219 | castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, |
| 6220 | llvm::GlobalVariable *GV) { |
| 6221 | llvm::Constant *Cast = GV; |
| 6222 | if (!CGM.getLangOpts().OpenCL) { |
| 6223 | auto AS = CGM.GetGlobalConstantAddressSpace(); |
| 6224 | if (AS != LangAS::Default) |
| 6225 | Cast = CGM.performAddrSpaceCast( |
| 6226 | Src: GV, DestTy: llvm::PointerType::get( |
| 6227 | C&: CGM.getLLVMContext(), |
| 6228 | AddressSpace: CGM.getContext().getTargetAddressSpace(AS: LangAS::Default))); |
| 6229 | } |
| 6230 | return Cast; |
| 6231 | } |
| 6232 | |
| 6233 | template<typename SomeDecl> |
| 6234 | void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, |
| 6235 | llvm::GlobalValue *GV) { |
| 6236 | if (!getLangOpts().CPlusPlus) |
| 6237 | return; |
| 6238 | |
| 6239 | // Must have 'used' attribute, or else inline assembly can't rely on |
| 6240 | // the name existing. |
| 6241 | if (!D->template hasAttr<UsedAttr>()) |
| 6242 | return; |
| 6243 | |
| 6244 | // Must have internal linkage and an ordinary name. |
| 6245 | if (!D->getIdentifier() || D->getFormalLinkage() != Linkage::Internal) |
| 6246 | return; |
| 6247 | |
| 6248 | // Must be in an extern "C" context. Entities declared directly within |
| 6249 | // a record are not extern "C" even if the record is in such a context. |
| 6250 | const SomeDecl *First = D->getFirstDecl(); |
| 6251 | if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) |
| 6252 | return; |
| 6253 | |
| 6254 | // OK, this is an internal linkage entity inside an extern "C" linkage |
| 6255 | // specification. Make a note of that so we can give it the "expected" |
| 6256 | // mangled name if nothing else is using that name. |
| 6257 | std::pair<StaticExternCMap::iterator, bool> R = |
| 6258 | StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); |
| 6259 | |
| 6260 | // If we have multiple internal linkage entities with the same name |
| 6261 | // in extern "C" regions, none of them gets that name. |
| 6262 | if (!R.second) |
| 6263 | R.first->second = nullptr; |
| 6264 | } |
| 6265 | |
| 6266 | static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { |
| 6267 | if (!CGM.supportsCOMDAT()) |
| 6268 | return false; |
| 6269 | |
| 6270 | if (D.hasAttr<SelectAnyAttr>()) |
| 6271 | return true; |
| 6272 | |
| 6273 | GVALinkage Linkage; |
| 6274 | if (auto *VD = dyn_cast<VarDecl>(Val: &D)) |
| 6275 | Linkage = CGM.getContext().GetGVALinkageForVariable(VD); |
| 6276 | else |
| 6277 | Linkage = CGM.getContext().GetGVALinkageForFunction(FD: cast<FunctionDecl>(Val: &D)); |
| 6278 | |
| 6279 | switch (Linkage) { |
| 6280 | case GVA_Internal: |
| 6281 | case GVA_AvailableExternally: |
| 6282 | case GVA_StrongExternal: |
| 6283 | return false; |
| 6284 | case GVA_DiscardableODR: |
| 6285 | case GVA_StrongODR: |
| 6286 | return true; |
| 6287 | } |
| 6288 | llvm_unreachable("No such linkage" ); |
| 6289 | } |
| 6290 | |
| 6291 | bool CodeGenModule::supportsCOMDAT() const { |
| 6292 | return getTriple().supportsCOMDAT(); |
| 6293 | } |
| 6294 | |
| 6295 | void CodeGenModule::maybeSetTrivialComdat(const Decl &D, |
| 6296 | llvm::GlobalObject &GO) { |
| 6297 | if (!shouldBeInCOMDAT(CGM&: *this, D)) |
| 6298 | return; |
| 6299 | GO.setComdat(TheModule.getOrInsertComdat(Name: GO.getName())); |
| 6300 | } |
| 6301 | |
| 6302 | const ABIInfo &CodeGenModule::getABIInfo() { |
| 6303 | return getTargetCodeGenInfo().getABIInfo(); |
| 6304 | } |
| 6305 | |
| 6306 | /// Pass IsTentative as true if you want to create a tentative definition. |
| 6307 | void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, |
| 6308 | bool IsTentative) { |
| 6309 | // OpenCL global variables of sampler type are translated to function calls, |
| 6310 | // therefore no need to be translated. |
| 6311 | QualType ASTTy = D->getType(); |
| 6312 | if (getLangOpts().OpenCL && ASTTy->isSamplerT()) |
| 6313 | return; |
| 6314 | |
| 6315 | // HLSL default buffer constants will be emitted during HLSLBufferDecl codegen |
| 6316 | if (getLangOpts().HLSL && |
| 6317 | D->getType().getAddressSpace() == LangAS::hlsl_constant) |
| 6318 | return; |
| 6319 | |
| 6320 | // If this is OpenMP device, check if it is legal to emit this global |
| 6321 | // normally. |
| 6322 | if (LangOpts.OpenMPIsTargetDevice && OpenMPRuntime && |
| 6323 | OpenMPRuntime->emitTargetGlobalVariable(GD: D)) |
| 6324 | return; |
| 6325 | |
| 6326 | llvm::TrackingVH<llvm::Constant> Init; |
| 6327 | bool NeedsGlobalCtor = false; |
| 6328 | // Whether the definition of the variable is available externally. |
| 6329 | // If yes, we shouldn't emit the GloablCtor and GlobalDtor for the variable |
| 6330 | // since this is the job for its original source. |
| 6331 | bool IsDefinitionAvailableExternally = |
| 6332 | getContext().GetGVALinkageForVariable(VD: D) == GVA_AvailableExternally; |
| 6333 | bool NeedsGlobalDtor = |
| 6334 | !IsDefinitionAvailableExternally && |
| 6335 | D->needsDestruction(Ctx: getContext()) == QualType::DK_cxx_destructor; |
| 6336 | |
| 6337 | // It is helpless to emit the definition for an available_externally variable |
| 6338 | // which can't be marked as const. |
| 6339 | // We don't need to check if it needs global ctor or dtor. See the above |
| 6340 | // comment for ideas. |
| 6341 | if (IsDefinitionAvailableExternally && |
| 6342 | (!D->hasConstantInitialization() || |
| 6343 | // TODO: Update this when we have interface to check constexpr |
| 6344 | // destructor. |
| 6345 | D->needsDestruction(Ctx: getContext()) || |
| 6346 | !D->getType().isConstantStorage(Ctx: getContext(), ExcludeCtor: true, ExcludeDtor: true))) |
| 6347 | return; |
| 6348 | |
| 6349 | const VarDecl *InitDecl; |
| 6350 | const Expr *InitExpr = D->getAnyInitializer(D&: InitDecl); |
| 6351 | |
| 6352 | std::optional<ConstantEmitter> emitter; |
| 6353 | |
| 6354 | // CUDA E.2.4.1 "__shared__ variables cannot have an initialization |
| 6355 | // as part of their declaration." Sema has already checked for |
| 6356 | // error cases, so we just need to set Init to UndefValue. |
| 6357 | bool IsCUDASharedVar = |
| 6358 | getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); |
| 6359 | // Shadows of initialized device-side global variables are also left |
| 6360 | // undefined. |
| 6361 | // Managed Variables should be initialized on both host side and device side. |
| 6362 | bool IsCUDAShadowVar = |
| 6363 | !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && |
| 6364 | (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || |
| 6365 | D->hasAttr<CUDASharedAttr>()); |
| 6366 | bool IsCUDADeviceShadowVar = |
| 6367 | getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && |
| 6368 | (D->getType()->isCUDADeviceBuiltinSurfaceType() || |
| 6369 | D->getType()->isCUDADeviceBuiltinTextureType()); |
| 6370 | if (getLangOpts().CUDA && |
| 6371 | (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) { |
| 6372 | Init = llvm::UndefValue::get(T: getTypes().ConvertTypeForMem(T: ASTTy)); |
| 6373 | } else if (getLangOpts().HLSL && |
| 6374 | (D->getType()->isHLSLResourceRecord() || |
| 6375 | D->getType()->isHLSLResourceRecordArray())) { |
| 6376 | Init = llvm::PoisonValue::get(T: getTypes().ConvertType(T: ASTTy)); |
| 6377 | NeedsGlobalCtor = D->getType()->isHLSLResourceRecord() || |
| 6378 | D->getStorageClass() == SC_Static; |
| 6379 | } else if (D->hasAttr<LoaderUninitializedAttr>()) { |
| 6380 | Init = llvm::UndefValue::get(T: getTypes().ConvertTypeForMem(T: ASTTy)); |
| 6381 | } else if (!InitExpr) { |
| 6382 | // This is a tentative definition; tentative definitions are |
| 6383 | // implicitly initialized with { 0 }. |
| 6384 | // |
| 6385 | // Note that tentative definitions are only emitted at the end of |
| 6386 | // a translation unit, so they should never have incomplete |
| 6387 | // type. In addition, EmitTentativeDefinition makes sure that we |
| 6388 | // never attempt to emit a tentative definition if a real one |
| 6389 | // exists. A use may still exists, however, so we still may need |
| 6390 | // to do a RAUW. |
| 6391 | assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type" ); |
| 6392 | Init = EmitNullConstant(T: D->getType()); |
| 6393 | } else { |
| 6394 | initializedGlobalDecl = GlobalDecl(D); |
| 6395 | emitter.emplace(args&: *this); |
| 6396 | llvm::Constant *Initializer = emitter->tryEmitForInitializer(D: *InitDecl); |
| 6397 | if (!Initializer) { |
| 6398 | QualType T = InitExpr->getType(); |
| 6399 | if (D->getType()->isReferenceType()) |
| 6400 | T = D->getType(); |
| 6401 | |
| 6402 | if (getLangOpts().CPlusPlus) { |
| 6403 | Init = EmitNullConstant(T); |
| 6404 | if (!IsDefinitionAvailableExternally) |
| 6405 | NeedsGlobalCtor = true; |
| 6406 | if (InitDecl->hasFlexibleArrayInit(Ctx: getContext())) { |
| 6407 | ErrorUnsupported(D, Type: "flexible array initializer" ); |
| 6408 | // We cannot create ctor for flexible array initializer |
| 6409 | NeedsGlobalCtor = false; |
| 6410 | } |
| 6411 | } else { |
| 6412 | ErrorUnsupported(D, Type: "static initializer" ); |
| 6413 | Init = llvm::PoisonValue::get(T: getTypes().ConvertType(T)); |
| 6414 | } |
| 6415 | } else { |
| 6416 | Init = Initializer; |
| 6417 | // We don't need an initializer, so remove the entry for the delayed |
| 6418 | // initializer position (just in case this entry was delayed) if we |
| 6419 | // also don't need to register a destructor. |
| 6420 | if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) |
| 6421 | DelayedCXXInitPosition.erase(Val: D); |
| 6422 | |
| 6423 | #ifndef NDEBUG |
| 6424 | CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) + |
| 6425 | InitDecl->getFlexibleArrayInitChars(getContext()); |
| 6426 | CharUnits CstSize = CharUnits::fromQuantity( |
| 6427 | getDataLayout().getTypeAllocSize(Init->getType())); |
| 6428 | assert(VarSize == CstSize && "Emitted constant has unexpected size" ); |
| 6429 | #endif |
| 6430 | } |
| 6431 | } |
| 6432 | |
| 6433 | llvm::Type* InitType = Init->getType(); |
| 6434 | llvm::Constant *Entry = |
| 6435 | GetAddrOfGlobalVar(D, Ty: InitType, IsForDefinition: ForDefinition_t(!IsTentative)); |
| 6436 | |
| 6437 | // Strip off pointer casts if we got them. |
| 6438 | Entry = Entry->stripPointerCasts(); |
| 6439 | |
| 6440 | // Entry is now either a Function or GlobalVariable. |
| 6441 | auto *GV = dyn_cast<llvm::GlobalVariable>(Val: Entry); |
| 6442 | |
| 6443 | // We have a definition after a declaration with the wrong type. |
| 6444 | // We must make a new GlobalVariable* and update everything that used OldGV |
| 6445 | // (a declaration or tentative definition) with the new GlobalVariable* |
| 6446 | // (which will be a definition). |
| 6447 | // |
| 6448 | // This happens if there is a prototype for a global (e.g. |
| 6449 | // "extern int x[];") and then a definition of a different type (e.g. |
| 6450 | // "int x[10];"). This also happens when an initializer has a different type |
| 6451 | // from the type of the global (this happens with unions). |
| 6452 | if (!GV || GV->getValueType() != InitType || |
| 6453 | GV->getType()->getAddressSpace() != |
| 6454 | getContext().getTargetAddressSpace(AS: GetGlobalVarAddressSpace(D))) { |
| 6455 | |
| 6456 | // Move the old entry aside so that we'll create a new one. |
| 6457 | Entry->setName(StringRef()); |
| 6458 | |
| 6459 | // Make a new global with the correct type, this is now guaranteed to work. |
| 6460 | GV = cast<llvm::GlobalVariable>( |
| 6461 | Val: GetAddrOfGlobalVar(D, Ty: InitType, IsForDefinition: ForDefinition_t(!IsTentative)) |
| 6462 | ->stripPointerCasts()); |
| 6463 | |
| 6464 | // Replace all uses of the old global with the new global |
| 6465 | llvm::Constant *NewPtrForOldDecl = |
| 6466 | llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(C: GV, |
| 6467 | Ty: Entry->getType()); |
| 6468 | Entry->replaceAllUsesWith(V: NewPtrForOldDecl); |
| 6469 | |
| 6470 | // Erase the old global, since it is no longer used. |
| 6471 | cast<llvm::GlobalValue>(Val: Entry)->eraseFromParent(); |
| 6472 | } |
| 6473 | |
| 6474 | MaybeHandleStaticInExternC(D, GV); |
| 6475 | |
| 6476 | if (D->hasAttr<AnnotateAttr>()) |
| 6477 | AddGlobalAnnotations(D, GV); |
| 6478 | |
| 6479 | // Set the llvm linkage type as appropriate. |
| 6480 | llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD: D); |
| 6481 | |
| 6482 | // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on |
| 6483 | // the device. [...]" |
| 6484 | // CUDA B.2.2 "The __constant__ qualifier, optionally used together with |
| 6485 | // __device__, declares a variable that: [...] |
| 6486 | // Is accessible from all the threads within the grid and from the host |
| 6487 | // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() |
| 6488 | // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." |
| 6489 | if (LangOpts.CUDA) { |
| 6490 | if (LangOpts.CUDAIsDevice) { |
| 6491 | if (Linkage != llvm::GlobalValue::InternalLinkage && !D->isConstexpr() && |
| 6492 | !D->getType().isConstQualified() && |
| 6493 | (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || |
| 6494 | D->getType()->isCUDADeviceBuiltinSurfaceType() || |
| 6495 | D->getType()->isCUDADeviceBuiltinTextureType())) |
| 6496 | GV->setExternallyInitialized(true); |
| 6497 | } else { |
| 6498 | getCUDARuntime().internalizeDeviceSideVar(D, Linkage); |
| 6499 | } |
| 6500 | getCUDARuntime().handleVarRegistration(VD: D, Var&: *GV); |
| 6501 | } |
| 6502 | |
| 6503 | if (LangOpts.HLSL && |
| 6504 | hlsl::isInitializedByPipeline(AS: GetGlobalVarAddressSpace(D))) { |
| 6505 | // HLSL Input variables are considered to be set by the driver/pipeline, but |
| 6506 | // only visible to a single thread/wave. Push constants are also externally |
| 6507 | // initialized, but constant, hence cross-wave visibility is not relevant. |
| 6508 | GV->setExternallyInitialized(true); |
| 6509 | } else { |
| 6510 | GV->setInitializer(Init); |
| 6511 | } |
| 6512 | |
| 6513 | if (LangOpts.HLSL) |
| 6514 | getHLSLRuntime().handleGlobalVarDefinition(VD: D, Var: GV); |
| 6515 | |
| 6516 | if (emitter) |
| 6517 | emitter->finalize(global: GV); |
| 6518 | |
| 6519 | // If it is safe to mark the global 'constant', do so now. |
| 6520 | GV->setConstant((D->hasAttr<CUDAConstantAttr>() && LangOpts.CUDAIsDevice) || |
| 6521 | (!NeedsGlobalCtor && !NeedsGlobalDtor && |
| 6522 | D->getType().isConstantStorage(Ctx: getContext(), ExcludeCtor: true, ExcludeDtor: true))); |
| 6523 | |
| 6524 | // If it is in a read-only section, mark it 'constant'. |
| 6525 | if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { |
| 6526 | const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; |
| 6527 | if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) |
| 6528 | GV->setConstant(true); |
| 6529 | } |
| 6530 | |
| 6531 | CharUnits AlignVal = getContext().getDeclAlign(D); |
| 6532 | // Check for alignment specifed in an 'omp allocate' directive. |
| 6533 | if (std::optional<CharUnits> AlignValFromAllocate = |
| 6534 | getOMPAllocateAlignment(VD: D)) |
| 6535 | AlignVal = *AlignValFromAllocate; |
| 6536 | GV->setAlignment(AlignVal.getAsAlign()); |
| 6537 | |
| 6538 | // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper |
| 6539 | // function is only defined alongside the variable, not also alongside |
| 6540 | // callers. Normally, all accesses to a thread_local go through the |
| 6541 | // thread-wrapper in order to ensure initialization has occurred, underlying |
| 6542 | // variable will never be used other than the thread-wrapper, so it can be |
| 6543 | // converted to internal linkage. |
| 6544 | // |
| 6545 | // However, if the variable has the 'constinit' attribute, it _can_ be |
| 6546 | // referenced directly, without calling the thread-wrapper, so the linkage |
| 6547 | // must not be changed. |
| 6548 | // |
| 6549 | // Additionally, if the variable isn't plain external linkage, e.g. if it's |
| 6550 | // weak or linkonce, the de-duplication semantics are important to preserve, |
| 6551 | // so we don't change the linkage. |
| 6552 | if (D->getTLSKind() == VarDecl::TLS_Dynamic && |
| 6553 | Linkage == llvm::GlobalValue::ExternalLinkage && |
| 6554 | Context.getTargetInfo().getTriple().isOSDarwin() && |
| 6555 | !D->hasAttr<ConstInitAttr>()) |
| 6556 | Linkage = llvm::GlobalValue::InternalLinkage; |
| 6557 | |
| 6558 | // HLSL variables in the input or push-constant address space maps are like |
| 6559 | // memory-mapped variables. Even if they are 'static', they are externally |
| 6560 | // initialized and read/write by the hardware/driver/pipeline. |
| 6561 | if (LangOpts.HLSL && |
| 6562 | hlsl::isInitializedByPipeline(AS: GetGlobalVarAddressSpace(D))) |
| 6563 | Linkage = llvm::GlobalValue::ExternalLinkage; |
| 6564 | |
| 6565 | GV->setLinkage(Linkage); |
| 6566 | if (D->hasAttr<DLLImportAttr>()) |
| 6567 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); |
| 6568 | else if (D->hasAttr<DLLExportAttr>()) |
| 6569 | GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); |
| 6570 | else |
| 6571 | GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); |
| 6572 | |
| 6573 | if (Linkage == llvm::GlobalVariable::CommonLinkage) { |
| 6574 | // common vars aren't constant even if declared const. |
| 6575 | GV->setConstant(false); |
| 6576 | // Tentative definition of global variables may be initialized with |
| 6577 | // non-zero null pointers. In this case they should have weak linkage |
| 6578 | // since common linkage must have zero initializer and must not have |
| 6579 | // explicit section therefore cannot have non-zero initial value. |
| 6580 | if (!GV->getInitializer()->isNullValue()) |
| 6581 | GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); |
| 6582 | } |
| 6583 | |
| 6584 | setNonAliasAttributes(GD: D, GO: GV); |
| 6585 | |
| 6586 | if (D->getTLSKind() && !GV->isThreadLocal()) { |
| 6587 | if (D->getTLSKind() == VarDecl::TLS_Dynamic) |
| 6588 | CXXThreadLocals.push_back(x: D); |
| 6589 | setTLSMode(GV, D: *D); |
| 6590 | } |
| 6591 | |
| 6592 | maybeSetTrivialComdat(D: *D, GO&: *GV); |
| 6593 | |
| 6594 | // Emit the initializer function if necessary. |
| 6595 | if (NeedsGlobalCtor || NeedsGlobalDtor) |
| 6596 | EmitCXXGlobalVarDeclInitFunc(D, Addr: GV, PerformInit: NeedsGlobalCtor); |
| 6597 | |
| 6598 | SanitizerMD->reportGlobal(GV, D: *D, IsDynInit: NeedsGlobalCtor); |
| 6599 | |
| 6600 | // Emit global variable debug information. |
| 6601 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 6602 | if (getCodeGenOpts().hasReducedDebugInfo()) |
| 6603 | DI->EmitGlobalVariable(GV, Decl: D); |
| 6604 | } |
| 6605 | |
| 6606 | static bool isVarDeclStrongDefinition(const ASTContext &Context, |
| 6607 | CodeGenModule &CGM, const VarDecl *D, |
| 6608 | bool NoCommon) { |
| 6609 | // Don't give variables common linkage if -fno-common was specified unless it |
| 6610 | // was overridden by a NoCommon attribute. |
| 6611 | if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) |
| 6612 | return true; |
| 6613 | |
| 6614 | // C11 6.9.2/2: |
| 6615 | // A declaration of an identifier for an object that has file scope without |
| 6616 | // an initializer, and without a storage-class specifier or with the |
| 6617 | // storage-class specifier static, constitutes a tentative definition. |
| 6618 | if (D->getInit() || D->hasExternalStorage()) |
| 6619 | return true; |
| 6620 | |
| 6621 | // A variable cannot be both common and exist in a section. |
| 6622 | if (D->hasAttr<SectionAttr>()) |
| 6623 | return true; |
| 6624 | |
| 6625 | // A variable cannot be both common and exist in a section. |
| 6626 | // We don't try to determine which is the right section in the front-end. |
| 6627 | // If no specialized section name is applicable, it will resort to default. |
| 6628 | if (D->hasAttr<PragmaClangBSSSectionAttr>() || |
| 6629 | D->hasAttr<PragmaClangDataSectionAttr>() || |
| 6630 | D->hasAttr<PragmaClangRelroSectionAttr>() || |
| 6631 | D->hasAttr<PragmaClangRodataSectionAttr>()) |
| 6632 | return true; |
| 6633 | |
| 6634 | // Thread local vars aren't considered common linkage. |
| 6635 | if (D->getTLSKind()) |
| 6636 | return true; |
| 6637 | |
| 6638 | // Tentative definitions marked with WeakImportAttr are true definitions. |
| 6639 | if (D->hasAttr<WeakImportAttr>()) |
| 6640 | return true; |
| 6641 | |
| 6642 | // A variable cannot be both common and exist in a comdat. |
| 6643 | if (shouldBeInCOMDAT(CGM, D: *D)) |
| 6644 | return true; |
| 6645 | |
| 6646 | // Declarations with a required alignment do not have common linkage in MSVC |
| 6647 | // mode. |
| 6648 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
| 6649 | if (D->hasAttr<AlignedAttr>()) |
| 6650 | return true; |
| 6651 | QualType VarType = D->getType(); |
| 6652 | if (Context.isAlignmentRequired(T: VarType)) |
| 6653 | return true; |
| 6654 | |
| 6655 | if (const auto *RD = VarType->getAsRecordDecl()) { |
| 6656 | for (const FieldDecl *FD : RD->fields()) { |
| 6657 | if (FD->isBitField()) |
| 6658 | continue; |
| 6659 | if (FD->hasAttr<AlignedAttr>()) |
| 6660 | return true; |
| 6661 | if (Context.isAlignmentRequired(T: FD->getType())) |
| 6662 | return true; |
| 6663 | } |
| 6664 | } |
| 6665 | } |
| 6666 | |
| 6667 | // Microsoft's link.exe doesn't support alignments greater than 32 bytes for |
| 6668 | // common symbols, so symbols with greater alignment requirements cannot be |
| 6669 | // common. |
| 6670 | // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two |
| 6671 | // alignments for common symbols via the aligncomm directive, so this |
| 6672 | // restriction only applies to MSVC environments. |
| 6673 | if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && |
| 6674 | Context.getTypeAlignIfKnown(T: D->getType()) > |
| 6675 | Context.toBits(CharSize: CharUnits::fromQuantity(Quantity: 32))) |
| 6676 | return true; |
| 6677 | |
| 6678 | return false; |
| 6679 | } |
| 6680 | |
| 6681 | llvm::GlobalValue::LinkageTypes |
| 6682 | CodeGenModule::getLLVMLinkageForDeclarator(const DeclaratorDecl *D, |
| 6683 | GVALinkage Linkage) { |
| 6684 | if (Linkage == GVA_Internal) |
| 6685 | return llvm::Function::InternalLinkage; |
| 6686 | |
| 6687 | if (D->hasAttr<WeakAttr>()) |
| 6688 | return llvm::GlobalVariable::WeakAnyLinkage; |
| 6689 | |
| 6690 | if (const auto *FD = D->getAsFunction()) |
| 6691 | if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) |
| 6692 | return llvm::GlobalVariable::LinkOnceAnyLinkage; |
| 6693 | |
| 6694 | // We are guaranteed to have a strong definition somewhere else, |
| 6695 | // so we can use available_externally linkage. |
| 6696 | if (Linkage == GVA_AvailableExternally) |
| 6697 | return llvm::GlobalValue::AvailableExternallyLinkage; |
| 6698 | |
| 6699 | // Note that Apple's kernel linker doesn't support symbol |
| 6700 | // coalescing, so we need to avoid linkonce and weak linkages there. |
| 6701 | // Normally, this means we just map to internal, but for explicit |
| 6702 | // instantiations we'll map to external. |
| 6703 | |
| 6704 | // In C++, the compiler has to emit a definition in every translation unit |
| 6705 | // that references the function. We should use linkonce_odr because |
| 6706 | // a) if all references in this translation unit are optimized away, we |
| 6707 | // don't need to codegen it. b) if the function persists, it needs to be |
| 6708 | // merged with other definitions. c) C++ has the ODR, so we know the |
| 6709 | // definition is dependable. |
| 6710 | if (Linkage == GVA_DiscardableODR) |
| 6711 | return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage |
| 6712 | : llvm::Function::InternalLinkage; |
| 6713 | |
| 6714 | // An explicit instantiation of a template has weak linkage, since |
| 6715 | // explicit instantiations can occur in multiple translation units |
| 6716 | // and must all be equivalent. However, we are not allowed to |
| 6717 | // throw away these explicit instantiations. |
| 6718 | // |
| 6719 | // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, |
| 6720 | // so say that CUDA templates are either external (for kernels) or internal. |
| 6721 | // This lets llvm perform aggressive inter-procedural optimizations. For |
| 6722 | // -fgpu-rdc case, device function calls across multiple TU's are allowed, |
| 6723 | // therefore we need to follow the normal linkage paradigm. |
| 6724 | if (Linkage == GVA_StrongODR) { |
| 6725 | if (getLangOpts().AppleKext) |
| 6726 | return llvm::Function::ExternalLinkage; |
| 6727 | if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && |
| 6728 | !getLangOpts().GPURelocatableDeviceCode) |
| 6729 | return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage |
| 6730 | : llvm::Function::InternalLinkage; |
| 6731 | return llvm::Function::WeakODRLinkage; |
| 6732 | } |
| 6733 | |
| 6734 | // C++ doesn't have tentative definitions and thus cannot have common |
| 6735 | // linkage. |
| 6736 | if (!getLangOpts().CPlusPlus && isa<VarDecl>(Val: D) && |
| 6737 | !isVarDeclStrongDefinition(Context, CGM&: *this, D: cast<VarDecl>(Val: D), |
| 6738 | NoCommon: CodeGenOpts.NoCommon)) |
| 6739 | return llvm::GlobalVariable::CommonLinkage; |
| 6740 | |
| 6741 | // selectany symbols are externally visible, so use weak instead of |
| 6742 | // linkonce. MSVC optimizes away references to const selectany globals, so |
| 6743 | // all definitions should be the same and ODR linkage should be used. |
| 6744 | // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx |
| 6745 | if (D->hasAttr<SelectAnyAttr>()) |
| 6746 | return llvm::GlobalVariable::WeakODRLinkage; |
| 6747 | |
| 6748 | // Otherwise, we have strong external linkage. |
| 6749 | assert(Linkage == GVA_StrongExternal); |
| 6750 | return llvm::GlobalVariable::ExternalLinkage; |
| 6751 | } |
| 6752 | |
| 6753 | llvm::GlobalValue::LinkageTypes |
| 6754 | CodeGenModule::getLLVMLinkageVarDefinition(const VarDecl *VD) { |
| 6755 | GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); |
| 6756 | return getLLVMLinkageForDeclarator(D: VD, Linkage); |
| 6757 | } |
| 6758 | |
| 6759 | /// Replace the uses of a function that was declared with a non-proto type. |
| 6760 | /// We want to silently drop extra arguments from call sites |
| 6761 | static void replaceUsesOfNonProtoConstant(llvm::Constant *old, |
| 6762 | llvm::Function *newFn) { |
| 6763 | // Fast path. |
| 6764 | if (old->use_empty()) |
| 6765 | return; |
| 6766 | |
| 6767 | llvm::Type *newRetTy = newFn->getReturnType(); |
| 6768 | SmallVector<llvm::Value *, 4> newArgs; |
| 6769 | |
| 6770 | SmallVector<llvm::CallBase *> callSitesToBeRemovedFromParent; |
| 6771 | |
| 6772 | for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); |
| 6773 | ui != ue; ui++) { |
| 6774 | llvm::User *user = ui->getUser(); |
| 6775 | |
| 6776 | // Recognize and replace uses of bitcasts. Most calls to |
| 6777 | // unprototyped functions will use bitcasts. |
| 6778 | if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(Val: user)) { |
| 6779 | if (bitcast->getOpcode() == llvm::Instruction::BitCast) |
| 6780 | replaceUsesOfNonProtoConstant(old: bitcast, newFn); |
| 6781 | continue; |
| 6782 | } |
| 6783 | |
| 6784 | // Recognize calls to the function. |
| 6785 | llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(Val: user); |
| 6786 | if (!callSite) |
| 6787 | continue; |
| 6788 | if (!callSite->isCallee(U: &*ui)) |
| 6789 | continue; |
| 6790 | |
| 6791 | // If the return types don't match exactly, then we can't |
| 6792 | // transform this call unless it's dead. |
| 6793 | if (callSite->getType() != newRetTy && !callSite->use_empty()) |
| 6794 | continue; |
| 6795 | |
| 6796 | // Get the call site's attribute list. |
| 6797 | SmallVector<llvm::AttributeSet, 8> newArgAttrs; |
| 6798 | llvm::AttributeList oldAttrs = callSite->getAttributes(); |
| 6799 | |
| 6800 | // If the function was passed too few arguments, don't transform. |
| 6801 | unsigned newNumArgs = newFn->arg_size(); |
| 6802 | if (callSite->arg_size() < newNumArgs) |
| 6803 | continue; |
| 6804 | |
| 6805 | // If extra arguments were passed, we silently drop them. |
| 6806 | // If any of the types mismatch, we don't transform. |
| 6807 | unsigned argNo = 0; |
| 6808 | bool dontTransform = false; |
| 6809 | for (llvm::Argument &A : newFn->args()) { |
| 6810 | if (callSite->getArgOperand(i: argNo)->getType() != A.getType()) { |
| 6811 | dontTransform = true; |
| 6812 | break; |
| 6813 | } |
| 6814 | |
| 6815 | // Add any parameter attributes. |
| 6816 | newArgAttrs.push_back(Elt: oldAttrs.getParamAttrs(ArgNo: argNo)); |
| 6817 | argNo++; |
| 6818 | } |
| 6819 | if (dontTransform) |
| 6820 | continue; |
| 6821 | |
| 6822 | // Okay, we can transform this. Create the new call instruction and copy |
| 6823 | // over the required information. |
| 6824 | newArgs.append(in_start: callSite->arg_begin(), in_end: callSite->arg_begin() + argNo); |
| 6825 | |
| 6826 | // Copy over any operand bundles. |
| 6827 | SmallVector<llvm::OperandBundleDef, 1> newBundles; |
| 6828 | callSite->getOperandBundlesAsDefs(Defs&: newBundles); |
| 6829 | |
| 6830 | llvm::CallBase *newCall; |
| 6831 | if (isa<llvm::CallInst>(Val: callSite)) { |
| 6832 | newCall = llvm::CallInst::Create(Func: newFn, Args: newArgs, Bundles: newBundles, NameStr: "" , |
| 6833 | InsertBefore: callSite->getIterator()); |
| 6834 | } else { |
| 6835 | auto *oldInvoke = cast<llvm::InvokeInst>(Val: callSite); |
| 6836 | newCall = llvm::InvokeInst::Create( |
| 6837 | Func: newFn, IfNormal: oldInvoke->getNormalDest(), IfException: oldInvoke->getUnwindDest(), |
| 6838 | Args: newArgs, Bundles: newBundles, NameStr: "" , InsertBefore: callSite->getIterator()); |
| 6839 | } |
| 6840 | newArgs.clear(); // for the next iteration |
| 6841 | |
| 6842 | if (!newCall->getType()->isVoidTy()) |
| 6843 | newCall->takeName(V: callSite); |
| 6844 | newCall->setAttributes( |
| 6845 | llvm::AttributeList::get(C&: newFn->getContext(), FnAttrs: oldAttrs.getFnAttrs(), |
| 6846 | RetAttrs: oldAttrs.getRetAttrs(), ArgAttrs: newArgAttrs)); |
| 6847 | newCall->setCallingConv(callSite->getCallingConv()); |
| 6848 | |
| 6849 | // Finally, remove the old call, replacing any uses with the new one. |
| 6850 | if (!callSite->use_empty()) |
| 6851 | callSite->replaceAllUsesWith(V: newCall); |
| 6852 | |
| 6853 | // Copy debug location attached to CI. |
| 6854 | if (callSite->getDebugLoc()) |
| 6855 | newCall->setDebugLoc(callSite->getDebugLoc()); |
| 6856 | |
| 6857 | callSitesToBeRemovedFromParent.push_back(Elt: callSite); |
| 6858 | } |
| 6859 | |
| 6860 | for (auto *callSite : callSitesToBeRemovedFromParent) { |
| 6861 | callSite->eraseFromParent(); |
| 6862 | } |
| 6863 | } |
| 6864 | |
| 6865 | /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we |
| 6866 | /// implement a function with no prototype, e.g. "int foo() {}". If there are |
| 6867 | /// existing call uses of the old function in the module, this adjusts them to |
| 6868 | /// call the new function directly. |
| 6869 | /// |
| 6870 | /// This is not just a cleanup: the always_inline pass requires direct calls to |
| 6871 | /// functions to be able to inline them. If there is a bitcast in the way, it |
| 6872 | /// won't inline them. Instcombine normally deletes these calls, but it isn't |
| 6873 | /// run at -O0. |
| 6874 | static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, |
| 6875 | llvm::Function *NewFn) { |
| 6876 | // If we're redefining a global as a function, don't transform it. |
| 6877 | if (!isa<llvm::Function>(Val: Old)) return; |
| 6878 | |
| 6879 | replaceUsesOfNonProtoConstant(old: Old, newFn: NewFn); |
| 6880 | } |
| 6881 | |
| 6882 | void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { |
| 6883 | auto DK = VD->isThisDeclarationADefinition(); |
| 6884 | if ((DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) || |
| 6885 | (LangOpts.CUDA && !shouldEmitCUDAGlobalVar(Global: VD))) |
| 6886 | return; |
| 6887 | |
| 6888 | TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); |
| 6889 | // If we have a definition, this might be a deferred decl. If the |
| 6890 | // instantiation is explicit, make sure we emit it at the end. |
| 6891 | if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) |
| 6892 | GetAddrOfGlobalVar(D: VD); |
| 6893 | |
| 6894 | EmitTopLevelDecl(D: VD); |
| 6895 | } |
| 6896 | |
| 6897 | void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, |
| 6898 | llvm::GlobalValue *GV) { |
| 6899 | const auto *D = cast<FunctionDecl>(Val: GD.getDecl()); |
| 6900 | |
| 6901 | // Compute the function info and LLVM type. |
| 6902 | const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); |
| 6903 | llvm::FunctionType *Ty = getTypes().GetFunctionType(Info: FI); |
| 6904 | |
| 6905 | // Get or create the prototype for the function. |
| 6906 | if (!GV || (GV->getValueType() != Ty)) |
| 6907 | GV = cast<llvm::GlobalValue>(Val: GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, |
| 6908 | /*DontDefer=*/true, |
| 6909 | IsForDefinition: ForDefinition)); |
| 6910 | |
| 6911 | // Already emitted. |
| 6912 | if (!GV->isDeclaration()) |
| 6913 | return; |
| 6914 | |
| 6915 | // We need to set linkage and visibility on the function before |
| 6916 | // generating code for it because various parts of IR generation |
| 6917 | // want to propagate this information down (e.g. to local static |
| 6918 | // declarations). |
| 6919 | auto *Fn = cast<llvm::Function>(Val: GV); |
| 6920 | setFunctionLinkage(GD, F: Fn); |
| 6921 | |
| 6922 | if (getTriple().isOSAIX() && D->isTargetClonesMultiVersion()) |
| 6923 | Fn->setLinkage(llvm::GlobalValue::InternalLinkage); |
| 6924 | |
| 6925 | // FIXME: this is redundant with part of setFunctionDefinitionAttributes |
| 6926 | setGVProperties(GV: Fn, GD); |
| 6927 | |
| 6928 | MaybeHandleStaticInExternC(D, GV: Fn); |
| 6929 | |
| 6930 | maybeSetTrivialComdat(D: *D, GO&: *Fn); |
| 6931 | |
| 6932 | if (!tryEmitCUDADeviceInvalidFunctionBody(GD, Fn)) |
| 6933 | CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo: FI); |
| 6934 | |
| 6935 | setNonAliasAttributes(GD, GO: Fn); |
| 6936 | |
| 6937 | bool ShouldAddOptNone = !CodeGenOpts.DisableO0ImplyOptNone && |
| 6938 | (CodeGenOpts.OptimizationLevel == 0) && |
| 6939 | !D->hasAttr<MinSizeAttr>(); |
| 6940 | |
| 6941 | if (DeviceKernelAttr::isOpenCLSpelling(A: D->getAttr<DeviceKernelAttr>())) { |
| 6942 | if (GD.getKernelReferenceKind() == KernelReferenceKind::Stub && |
| 6943 | !D->hasAttr<NoInlineAttr>() && |
| 6944 | !Fn->hasFnAttribute(Kind: llvm::Attribute::NoInline) && |
| 6945 | !D->hasAttr<OptimizeNoneAttr>() && |
| 6946 | !Fn->hasFnAttribute(Kind: llvm::Attribute::OptimizeNone) && |
| 6947 | !ShouldAddOptNone) { |
| 6948 | Fn->addFnAttr(Kind: llvm::Attribute::AlwaysInline); |
| 6949 | } |
| 6950 | } |
| 6951 | |
| 6952 | SetLLVMFunctionAttributesForDefinition(D, F: Fn); |
| 6953 | |
| 6954 | // EGPR (R16-R31) requires V3 unwind info on Windows x64 because V1/V2 cannot |
| 6955 | // encode extended register numbers. Check per-function so that `target` |
| 6956 | // attribute and `nounwind`/no-unwind-table functions are respected. |
| 6957 | if (getTriple().isOSWindows() && getTriple().isX86_64()) { |
| 6958 | auto UnwindMode = CodeGenOpts.getWinX64EHUnwind(); |
| 6959 | if (UnwindMode != llvm::WinX64EHUnwindMode::Default && |
| 6960 | UnwindMode != llvm::WinX64EHUnwindMode::V3 && |
| 6961 | Fn->needsUnwindTableEntry()) { |
| 6962 | bool HasEGPR = false; |
| 6963 | if (Fn->hasFnAttribute(Kind: "target-features" )) { |
| 6964 | StringRef Feats = |
| 6965 | Fn->getFnAttribute(Kind: "target-features" ).getValueAsString(); |
| 6966 | SmallVector<StringRef, 16> Tokens; |
| 6967 | Feats.split(A&: Tokens, Separator: ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); |
| 6968 | for (StringRef Tok : Tokens) { |
| 6969 | if (Tok == "+egpr" ) |
| 6970 | HasEGPR = true; |
| 6971 | else if (Tok == "-egpr" ) |
| 6972 | HasEGPR = false; |
| 6973 | } |
| 6974 | } else { |
| 6975 | HasEGPR = Context.getTargetInfo().hasFeature(Feature: "egpr" ); |
| 6976 | } |
| 6977 | if (HasEGPR) { |
| 6978 | unsigned DiagID = Diags.getCustomDiagID( |
| 6979 | L: DiagnosticsEngine::Error, |
| 6980 | FormatString: "EGPR target feature requires unwind version 3" ); |
| 6981 | Diags.Report(Loc: D->getLocation(), DiagID); |
| 6982 | } |
| 6983 | } |
| 6984 | } |
| 6985 | |
| 6986 | auto GetPriority = [this](const auto *Attr) -> int { |
| 6987 | Expr *E = Attr->getPriority(); |
| 6988 | if (E) { |
| 6989 | return E->EvaluateKnownConstInt(Ctx: this->getContext()).getExtValue(); |
| 6990 | } |
| 6991 | return Attr->DefaultPriority; |
| 6992 | }; |
| 6993 | |
| 6994 | if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) |
| 6995 | AddGlobalCtor(Ctor: Fn, Priority: GetPriority(CA)); |
| 6996 | if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) |
| 6997 | AddGlobalDtor(Dtor: Fn, Priority: GetPriority(DA), IsDtorAttrFunc: true); |
| 6998 | if (getLangOpts().OpenMP && D->hasAttr<OMPDeclareTargetDeclAttr>()) |
| 6999 | getOpenMPRuntime().emitDeclareTargetFunction(FD: D, GV); |
| 7000 | } |
| 7001 | |
| 7002 | void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { |
| 7003 | const auto *D = cast<ValueDecl>(Val: GD.getDecl()); |
| 7004 | const AliasAttr *AA = D->getAttr<AliasAttr>(); |
| 7005 | assert(AA && "Not an alias?" ); |
| 7006 | |
| 7007 | StringRef MangledName = getMangledName(GD); |
| 7008 | |
| 7009 | if (AA->getAliasee() == MangledName) { |
| 7010 | Diags.Report(Loc: AA->getLocation(), DiagID: diag::err_cyclic_alias) << 0; |
| 7011 | return; |
| 7012 | } |
| 7013 | |
| 7014 | // If there is a definition in the module, then it wins over the alias. |
| 7015 | // This is dubious, but allow it to be safe. Just ignore the alias. |
| 7016 | llvm::GlobalValue *Entry = GetGlobalValue(Name: MangledName); |
| 7017 | if (Entry && !Entry->isDeclaration()) |
| 7018 | return; |
| 7019 | |
| 7020 | Aliases.push_back(x: GD); |
| 7021 | |
| 7022 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(T: D->getType()); |
| 7023 | |
| 7024 | // Create a reference to the named value. This ensures that it is emitted |
| 7025 | // if a deferred decl. |
| 7026 | llvm::Constant *Aliasee; |
| 7027 | llvm::GlobalValue::LinkageTypes LT; |
| 7028 | if (isa<llvm::FunctionType>(Val: DeclTy)) { |
| 7029 | Aliasee = GetOrCreateLLVMFunction(MangledName: AA->getAliasee(), Ty: DeclTy, GD, |
| 7030 | /*ForVTable=*/false); |
| 7031 | LT = getFunctionLinkage(GD); |
| 7032 | } else { |
| 7033 | Aliasee = GetOrCreateLLVMGlobal(MangledName: AA->getAliasee(), Ty: DeclTy, AddrSpace: LangAS::Default, |
| 7034 | /*D=*/nullptr); |
| 7035 | if (const auto *VD = dyn_cast<VarDecl>(Val: GD.getDecl())) |
| 7036 | LT = getLLVMLinkageVarDefinition(VD); |
| 7037 | else |
| 7038 | LT = getFunctionLinkage(GD); |
| 7039 | } |
| 7040 | |
| 7041 | // Create the new alias itself, but don't set a name yet. |
| 7042 | unsigned AS = Aliasee->getType()->getPointerAddressSpace(); |
| 7043 | auto *GA = |
| 7044 | llvm::GlobalAlias::create(Ty: DeclTy, AddressSpace: AS, Linkage: LT, Name: "" , Aliasee, Parent: &getModule()); |
| 7045 | |
| 7046 | if (Entry) { |
| 7047 | if (GA->getAliasee() == Entry) { |
| 7048 | Diags.Report(Loc: AA->getLocation(), DiagID: diag::err_cyclic_alias) << 0; |
| 7049 | return; |
| 7050 | } |
| 7051 | |
| 7052 | assert(Entry->isDeclaration()); |
| 7053 | |
| 7054 | // If there is a declaration in the module, then we had an extern followed |
| 7055 | // by the alias, as in: |
| 7056 | // extern int test6(); |
| 7057 | // ... |
| 7058 | // int test6() __attribute__((alias("test7"))); |
| 7059 | // |
| 7060 | // Remove it and replace uses of it with the alias. |
| 7061 | GA->takeName(V: Entry); |
| 7062 | |
| 7063 | Entry->replaceAllUsesWith(V: GA); |
| 7064 | Entry->eraseFromParent(); |
| 7065 | } else { |
| 7066 | GA->setName(MangledName); |
| 7067 | } |
| 7068 | |
| 7069 | // Set attributes which are particular to an alias; this is a |
| 7070 | // specialization of the attributes which may be set on a global |
| 7071 | // variable/function. |
| 7072 | if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || |
| 7073 | D->isWeakImported()) { |
| 7074 | GA->setLinkage(llvm::Function::WeakAnyLinkage); |
| 7075 | } |
| 7076 | |
| 7077 | if (const auto *VD = dyn_cast<VarDecl>(Val: D)) |
| 7078 | if (VD->getTLSKind()) |
| 7079 | setTLSMode(GV: GA, D: *VD); |
| 7080 | |
| 7081 | SetCommonAttributes(GD, GV: GA); |
| 7082 | |
| 7083 | // Emit global alias debug information. |
| 7084 | if (isa<VarDecl>(Val: D)) |
| 7085 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 7086 | DI->EmitGlobalAlias(GV: cast<llvm::GlobalValue>(Val: GA->getAliasee()->stripPointerCasts()), Decl: GD); |
| 7087 | } |
| 7088 | |
| 7089 | void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { |
| 7090 | const auto *D = cast<ValueDecl>(Val: GD.getDecl()); |
| 7091 | const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); |
| 7092 | assert(IFA && "Not an ifunc?" ); |
| 7093 | |
| 7094 | StringRef MangledName = getMangledName(GD); |
| 7095 | |
| 7096 | if (IFA->getResolver() == MangledName) { |
| 7097 | Diags.Report(Loc: IFA->getLocation(), DiagID: diag::err_cyclic_alias) << 1; |
| 7098 | return; |
| 7099 | } |
| 7100 | |
| 7101 | // Report an error if some definition overrides ifunc. |
| 7102 | llvm::GlobalValue *Entry = GetGlobalValue(Name: MangledName); |
| 7103 | if (Entry && !Entry->isDeclaration()) { |
| 7104 | GlobalDecl OtherGD; |
| 7105 | if (lookupRepresentativeDecl(MangledName, Result&: OtherGD) && |
| 7106 | DiagnosedConflictingDefinitions.insert(V: GD).second) { |
| 7107 | Diags.Report(Loc: D->getLocation(), DiagID: diag::err_duplicate_mangled_name) |
| 7108 | << MangledName; |
| 7109 | Diags.Report(Loc: OtherGD.getDecl()->getLocation(), |
| 7110 | DiagID: diag::note_previous_definition); |
| 7111 | } |
| 7112 | return; |
| 7113 | } |
| 7114 | |
| 7115 | Aliases.push_back(x: GD); |
| 7116 | |
| 7117 | // The resolver might not be visited yet. Specify a dummy non-function type to |
| 7118 | // indicate IsIncompleteFunction. Either the type is ignored (if the resolver |
| 7119 | // was emitted) or the whole function will be replaced (if the resolver has |
| 7120 | // not been emitted). |
| 7121 | llvm::Constant *Resolver = |
| 7122 | GetOrCreateLLVMFunction(MangledName: IFA->getResolver(), Ty: VoidTy, GD: {}, |
| 7123 | /*ForVTable=*/false); |
| 7124 | llvm::Type *DeclTy = getTypes().ConvertTypeForMem(T: D->getType()); |
| 7125 | unsigned AS = getTypes().getTargetAddressSpace(T: D->getType()); |
| 7126 | llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create( |
| 7127 | Ty: DeclTy, AddressSpace: AS, Linkage: llvm::Function::ExternalLinkage, Name: "" , Resolver, Parent: &getModule()); |
| 7128 | if (Entry) { |
| 7129 | if (GIF->getResolver() == Entry) { |
| 7130 | Diags.Report(Loc: IFA->getLocation(), DiagID: diag::err_cyclic_alias) << 1; |
| 7131 | return; |
| 7132 | } |
| 7133 | assert(Entry->isDeclaration()); |
| 7134 | |
| 7135 | // If there is a declaration in the module, then we had an extern followed |
| 7136 | // by the ifunc, as in: |
| 7137 | // extern int test(); |
| 7138 | // ... |
| 7139 | // int test() __attribute__((ifunc("resolver"))); |
| 7140 | // |
| 7141 | // Remove it and replace uses of it with the ifunc. |
| 7142 | GIF->takeName(V: Entry); |
| 7143 | |
| 7144 | Entry->replaceAllUsesWith(V: GIF); |
| 7145 | Entry->eraseFromParent(); |
| 7146 | } else |
| 7147 | GIF->setName(MangledName); |
| 7148 | SetCommonAttributes(GD, GV: GIF); |
| 7149 | } |
| 7150 | |
| 7151 | llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, |
| 7152 | ArrayRef<llvm::Type*> Tys) { |
| 7153 | return llvm::Intrinsic::getOrInsertDeclaration(M: &getModule(), |
| 7154 | id: (llvm::Intrinsic::ID)IID, OverloadTys: Tys); |
| 7155 | } |
| 7156 | |
| 7157 | static llvm::StringMapEntry<llvm::GlobalVariable *> & |
| 7158 | GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, |
| 7159 | const StringLiteral *Literal, bool TargetIsLSB, |
| 7160 | bool &IsUTF16, unsigned &StringLength) { |
| 7161 | StringRef String = Literal->getString(); |
| 7162 | unsigned NumBytes = String.size(); |
| 7163 | |
| 7164 | // Check for simple case. |
| 7165 | if (!Literal->containsNonAsciiOrNull()) { |
| 7166 | StringLength = NumBytes; |
| 7167 | return *Map.insert(KV: std::make_pair(x&: String, y: nullptr)).first; |
| 7168 | } |
| 7169 | |
| 7170 | // Otherwise, convert the UTF8 literals into a string of shorts. |
| 7171 | IsUTF16 = true; |
| 7172 | |
| 7173 | SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. |
| 7174 | const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); |
| 7175 | llvm::UTF16 *ToPtr = &ToBuf[0]; |
| 7176 | |
| 7177 | (void)llvm::ConvertUTF8toUTF16(sourceStart: &FromPtr, sourceEnd: FromPtr + NumBytes, targetStart: &ToPtr, |
| 7178 | targetEnd: ToPtr + NumBytes, flags: llvm::strictConversion); |
| 7179 | |
| 7180 | // ConvertUTF8toUTF16 returns the length in ToPtr. |
| 7181 | StringLength = ToPtr - &ToBuf[0]; |
| 7182 | |
| 7183 | // Add an explicit null. |
| 7184 | *ToPtr = 0; |
| 7185 | return *Map.insert(KV: std::make_pair( |
| 7186 | x: StringRef(reinterpret_cast<const char *>(ToBuf.data()), |
| 7187 | (StringLength + 1) * 2), |
| 7188 | y: nullptr)).first; |
| 7189 | } |
| 7190 | |
| 7191 | ConstantAddress |
| 7192 | CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { |
| 7193 | unsigned StringLength = 0; |
| 7194 | bool isUTF16 = false; |
| 7195 | llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = |
| 7196 | GetConstantCFStringEntry(Map&: CFConstantStringMap, Literal, |
| 7197 | TargetIsLSB: getDataLayout().isLittleEndian(), IsUTF16&: isUTF16, |
| 7198 | StringLength); |
| 7199 | |
| 7200 | if (auto *C = Entry.second) |
| 7201 | return ConstantAddress( |
| 7202 | C, C->getValueType(), CharUnits::fromQuantity(Quantity: C->getAlignment())); |
| 7203 | |
| 7204 | const ASTContext &Context = getContext(); |
| 7205 | const llvm::Triple &Triple = getTriple(); |
| 7206 | |
| 7207 | const auto CFRuntime = getLangOpts().CFRuntime; |
| 7208 | const bool IsSwiftABI = |
| 7209 | static_cast<unsigned>(CFRuntime) >= |
| 7210 | static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); |
| 7211 | const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; |
| 7212 | |
| 7213 | // If we don't already have it, get __CFConstantStringClassReference. |
| 7214 | if (!CFConstantStringClassRef) { |
| 7215 | const char *CFConstantStringClassName = "__CFConstantStringClassReference" ; |
| 7216 | llvm::Type *Ty = getTypes().ConvertType(T: getContext().IntTy); |
| 7217 | Ty = llvm::ArrayType::get(ElementType: Ty, NumElements: 0); |
| 7218 | |
| 7219 | switch (CFRuntime) { |
| 7220 | default: break; |
| 7221 | case LangOptions::CoreFoundationABI::Swift: [[fallthrough]]; |
| 7222 | case LangOptions::CoreFoundationABI::Swift5_0: |
| 7223 | CFConstantStringClassName = |
| 7224 | Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" |
| 7225 | : "$s10Foundation19_NSCFConstantStringCN" ; |
| 7226 | Ty = IntPtrTy; |
| 7227 | break; |
| 7228 | case LangOptions::CoreFoundationABI::Swift4_2: |
| 7229 | CFConstantStringClassName = |
| 7230 | Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" |
| 7231 | : "$S10Foundation19_NSCFConstantStringCN" ; |
| 7232 | Ty = IntPtrTy; |
| 7233 | break; |
| 7234 | case LangOptions::CoreFoundationABI::Swift4_1: |
| 7235 | CFConstantStringClassName = |
| 7236 | Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" |
| 7237 | : "__T010Foundation19_NSCFConstantStringCN" ; |
| 7238 | Ty = IntPtrTy; |
| 7239 | break; |
| 7240 | } |
| 7241 | |
| 7242 | llvm::Constant *C = CreateRuntimeVariable(Ty, Name: CFConstantStringClassName); |
| 7243 | |
| 7244 | if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { |
| 7245 | llvm::GlobalValue *GV = nullptr; |
| 7246 | |
| 7247 | if ((GV = dyn_cast<llvm::GlobalValue>(Val: C))) { |
| 7248 | IdentifierInfo &II = Context.Idents.get(Name: GV->getName()); |
| 7249 | TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); |
| 7250 | DeclContext *DC = TranslationUnitDecl::castToDeclContext(D: TUDecl); |
| 7251 | |
| 7252 | const VarDecl *VD = nullptr; |
| 7253 | for (const auto *Result : DC->lookup(Name: &II)) |
| 7254 | if ((VD = dyn_cast<VarDecl>(Val: Result))) |
| 7255 | break; |
| 7256 | |
| 7257 | if (Triple.isOSBinFormatELF()) { |
| 7258 | if (!VD) |
| 7259 | GV->setLinkage(llvm::GlobalValue::ExternalLinkage); |
| 7260 | } else { |
| 7261 | GV->setLinkage(llvm::GlobalValue::ExternalLinkage); |
| 7262 | if (!VD || !VD->hasAttr<DLLExportAttr>()) |
| 7263 | GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); |
| 7264 | else |
| 7265 | GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); |
| 7266 | } |
| 7267 | |
| 7268 | setDSOLocal(GV); |
| 7269 | } |
| 7270 | } |
| 7271 | |
| 7272 | // Decay array -> ptr |
| 7273 | CFConstantStringClassRef = |
| 7274 | IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) : C; |
| 7275 | } |
| 7276 | |
| 7277 | QualType CFTy = Context.getCFConstantStringType(); |
| 7278 | |
| 7279 | auto *STy = cast<llvm::StructType>(Val: getTypes().ConvertType(T: CFTy)); |
| 7280 | |
| 7281 | ConstantInitBuilder Builder(*this); |
| 7282 | auto Fields = Builder.beginStruct(structTy: STy); |
| 7283 | |
| 7284 | // Class pointer. |
| 7285 | Fields.addSignedPointer(Pointer: cast<llvm::Constant>(Val&: CFConstantStringClassRef), |
| 7286 | Schema: getCodeGenOpts().PointerAuth.ObjCIsaPointers, |
| 7287 | CalleeDecl: GlobalDecl(), CalleeType: QualType()); |
| 7288 | |
| 7289 | // Flags. |
| 7290 | if (IsSwiftABI) { |
| 7291 | Fields.addInt(intTy: IntPtrTy, value: IsSwift4_1 ? 0x05 : 0x01); |
| 7292 | Fields.addInt(intTy: Int64Ty, value: isUTF16 ? 0x07d0 : 0x07c8); |
| 7293 | } else { |
| 7294 | Fields.addInt(intTy: IntTy, value: isUTF16 ? 0x07d0 : 0x07C8); |
| 7295 | } |
| 7296 | |
| 7297 | // String pointer. |
| 7298 | llvm::Constant *C = nullptr; |
| 7299 | if (isUTF16) { |
| 7300 | auto Arr = llvm::ArrayRef( |
| 7301 | reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), |
| 7302 | Entry.first().size() / 2); |
| 7303 | C = llvm::ConstantDataArray::get(Context&: VMContext, Elts: Arr); |
| 7304 | } else { |
| 7305 | C = llvm::ConstantDataArray::getString(Context&: VMContext, Initializer: Entry.first()); |
| 7306 | } |
| 7307 | |
| 7308 | // Note: -fwritable-strings doesn't make the backing store strings of |
| 7309 | // CFStrings writable. |
| 7310 | auto *GV = |
| 7311 | new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, |
| 7312 | llvm::GlobalValue::PrivateLinkage, C, ".str" ); |
| 7313 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
| 7314 | // Don't enforce the target's minimum global alignment, since the only use |
| 7315 | // of the string is via this class initializer. |
| 7316 | CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(T: Context.ShortTy) |
| 7317 | : Context.getTypeAlignInChars(T: Context.CharTy); |
| 7318 | GV->setAlignment(Align.getAsAlign()); |
| 7319 | |
| 7320 | // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. |
| 7321 | // Without it LLVM can merge the string with a non unnamed_addr one during |
| 7322 | // LTO. Doing that changes the section it ends in, which surprises ld64. |
| 7323 | if (Triple.isOSBinFormatMachO()) |
| 7324 | GV->setSection(isUTF16 ? "__TEXT,__ustring" |
| 7325 | : "__TEXT,__cstring,cstring_literals" ); |
| 7326 | // Make sure the literal ends up in .rodata to allow for safe ICF and for |
| 7327 | // the static linker to adjust permissions to read-only later on. |
| 7328 | else if (Triple.isOSBinFormatELF()) |
| 7329 | GV->setSection(".rodata" ); |
| 7330 | |
| 7331 | // String. |
| 7332 | Fields.add(value: GV); |
| 7333 | |
| 7334 | // String length. |
| 7335 | llvm::IntegerType *LengthTy = |
| 7336 | llvm::IntegerType::get(C&: getModule().getContext(), |
| 7337 | NumBits: Context.getTargetInfo().getLongWidth()); |
| 7338 | if (IsSwiftABI) { |
| 7339 | if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || |
| 7340 | CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) |
| 7341 | LengthTy = Int32Ty; |
| 7342 | else |
| 7343 | LengthTy = IntPtrTy; |
| 7344 | } |
| 7345 | Fields.addInt(intTy: LengthTy, value: StringLength); |
| 7346 | |
| 7347 | // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is |
| 7348 | // properly aligned on 32-bit platforms. |
| 7349 | CharUnits Alignment = |
| 7350 | IsSwiftABI ? Context.toCharUnitsFromBits(BitSize: 64) : getPointerAlign(); |
| 7351 | |
| 7352 | // The struct. |
| 7353 | GV = Fields.finishAndCreateGlobal(args: "_unnamed_cfstring_" , args&: Alignment, |
| 7354 | /*isConstant=*/args: false, |
| 7355 | args: llvm::GlobalVariable::PrivateLinkage); |
| 7356 | GV->addAttribute(Kind: "objc_arc_inert" ); |
| 7357 | switch (Triple.getObjectFormat()) { |
| 7358 | case llvm::Triple::UnknownObjectFormat: |
| 7359 | llvm_unreachable("unknown file format" ); |
| 7360 | case llvm::Triple::DXContainer: |
| 7361 | case llvm::Triple::GOFF: |
| 7362 | case llvm::Triple::SPIRV: |
| 7363 | case llvm::Triple::XCOFF: |
| 7364 | llvm_unreachable("unimplemented" ); |
| 7365 | case llvm::Triple::COFF: |
| 7366 | case llvm::Triple::ELF: |
| 7367 | case llvm::Triple::Wasm: |
| 7368 | GV->setSection("cfstring" ); |
| 7369 | break; |
| 7370 | case llvm::Triple::MachO: |
| 7371 | GV->setSection("__DATA,__cfstring" ); |
| 7372 | break; |
| 7373 | } |
| 7374 | Entry.second = GV; |
| 7375 | |
| 7376 | return ConstantAddress(GV, GV->getValueType(), Alignment); |
| 7377 | } |
| 7378 | |
| 7379 | bool CodeGenModule::getExpressionLocationsEnabled() const { |
| 7380 | return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; |
| 7381 | } |
| 7382 | |
| 7383 | QualType CodeGenModule::getObjCFastEnumerationStateType() { |
| 7384 | if (ObjCFastEnumerationStateType.isNull()) { |
| 7385 | RecordDecl *D = Context.buildImplicitRecord(Name: "__objcFastEnumerationState" ); |
| 7386 | D->startDefinition(); |
| 7387 | |
| 7388 | QualType FieldTypes[] = { |
| 7389 | Context.UnsignedLongTy, Context.getPointerType(T: Context.getObjCIdType()), |
| 7390 | Context.getPointerType(T: Context.UnsignedLongTy), |
| 7391 | Context.getConstantArrayType(EltTy: Context.UnsignedLongTy, ArySize: llvm::APInt(32, 5), |
| 7392 | SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0)}; |
| 7393 | |
| 7394 | for (size_t i = 0; i < 4; ++i) { |
| 7395 | FieldDecl *Field = FieldDecl::Create(C: Context, |
| 7396 | DC: D, |
| 7397 | StartLoc: SourceLocation(), |
| 7398 | IdLoc: SourceLocation(), Id: nullptr, |
| 7399 | T: FieldTypes[i], /*TInfo=*/nullptr, |
| 7400 | /*BitWidth=*/BW: nullptr, |
| 7401 | /*Mutable=*/false, |
| 7402 | InitStyle: ICIS_NoInit); |
| 7403 | Field->setAccess(AS_public); |
| 7404 | D->addDecl(D: Field); |
| 7405 | } |
| 7406 | |
| 7407 | D->completeDefinition(); |
| 7408 | ObjCFastEnumerationStateType = Context.getCanonicalTagType(TD: D); |
| 7409 | } |
| 7410 | |
| 7411 | return ObjCFastEnumerationStateType; |
| 7412 | } |
| 7413 | |
| 7414 | llvm::Constant * |
| 7415 | CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { |
| 7416 | assert(!E->getType()->isPointerType() && "Strings are always arrays" ); |
| 7417 | |
| 7418 | // Don't emit it as the address of the string, emit the string data itself |
| 7419 | // as an inline array. |
| 7420 | if (E->getCharByteWidth() == 1) { |
| 7421 | SmallString<64> Str(E->getString()); |
| 7422 | |
| 7423 | // Resize the string to the right size, which is indicated by its type. |
| 7424 | const ConstantArrayType *CAT = Context.getAsConstantArrayType(T: E->getType()); |
| 7425 | assert(CAT && "String literal not of constant array type!" ); |
| 7426 | Str.resize(N: CAT->getZExtSize()); |
| 7427 | return llvm::ConstantDataArray::getString(Context&: VMContext, Initializer: Str, AddNull: false); |
| 7428 | } |
| 7429 | |
| 7430 | auto *AType = cast<llvm::ArrayType>(Val: getTypes().ConvertType(T: E->getType())); |
| 7431 | llvm::Type *ElemTy = AType->getElementType(); |
| 7432 | unsigned NumElements = AType->getNumElements(); |
| 7433 | |
| 7434 | // Wide strings have either 2-byte or 4-byte elements. |
| 7435 | if (ElemTy->getPrimitiveSizeInBits() == 16) { |
| 7436 | SmallVector<uint16_t, 32> Elements; |
| 7437 | Elements.reserve(N: NumElements); |
| 7438 | |
| 7439 | for(unsigned i = 0, e = E->getLength(); i != e; ++i) |
| 7440 | Elements.push_back(Elt: E->getCodeUnit(i)); |
| 7441 | Elements.resize(N: NumElements); |
| 7442 | return llvm::ConstantDataArray::get(Context&: VMContext, Elts&: Elements); |
| 7443 | } |
| 7444 | |
| 7445 | assert(ElemTy->getPrimitiveSizeInBits() == 32); |
| 7446 | SmallVector<uint32_t, 32> Elements; |
| 7447 | Elements.reserve(N: NumElements); |
| 7448 | |
| 7449 | for(unsigned i = 0, e = E->getLength(); i != e; ++i) |
| 7450 | Elements.push_back(Elt: E->getCodeUnit(i)); |
| 7451 | Elements.resize(N: NumElements); |
| 7452 | return llvm::ConstantDataArray::get(Context&: VMContext, Elts&: Elements); |
| 7453 | } |
| 7454 | |
| 7455 | static llvm::GlobalVariable * |
| 7456 | GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, |
| 7457 | CodeGenModule &CGM, StringRef GlobalName, |
| 7458 | CharUnits Alignment) { |
| 7459 | unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( |
| 7460 | AS: CGM.GetGlobalConstantAddressSpace()); |
| 7461 | |
| 7462 | llvm::Module &M = CGM.getModule(); |
| 7463 | // Create a global variable for this string |
| 7464 | auto *GV = new llvm::GlobalVariable( |
| 7465 | M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, |
| 7466 | nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); |
| 7467 | GV->setAlignment(Alignment.getAsAlign()); |
| 7468 | GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); |
| 7469 | if (GV->isWeakForLinker()) { |
| 7470 | assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals" ); |
| 7471 | GV->setComdat(M.getOrInsertComdat(Name: GV->getName())); |
| 7472 | } |
| 7473 | CGM.setDSOLocal(GV); |
| 7474 | |
| 7475 | return GV; |
| 7476 | } |
| 7477 | |
| 7478 | /// GetAddrOfConstantStringFromLiteral - Return a pointer to a |
| 7479 | /// constant array for the given string literal. |
| 7480 | ConstantAddress |
| 7481 | CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, |
| 7482 | StringRef Name) { |
| 7483 | CharUnits Alignment = |
| 7484 | getContext().getAlignOfGlobalVarInChars(T: S->getType(), /*VD=*/nullptr); |
| 7485 | |
| 7486 | llvm::Constant *C = GetConstantArrayFromStringLiteral(E: S); |
| 7487 | llvm::GlobalVariable **Entry = nullptr; |
| 7488 | if (!LangOpts.WritableStrings) { |
| 7489 | Entry = &ConstantStringMap[C]; |
| 7490 | if (auto GV = *Entry) { |
| 7491 | if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) |
| 7492 | GV->setAlignment(Alignment.getAsAlign()); |
| 7493 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(CGM&: *this, GV), |
| 7494 | GV->getValueType(), Alignment); |
| 7495 | } |
| 7496 | } |
| 7497 | |
| 7498 | SmallString<256> MangledNameBuffer; |
| 7499 | StringRef GlobalVariableName; |
| 7500 | llvm::GlobalValue::LinkageTypes LT; |
| 7501 | |
| 7502 | // Mangle the string literal if that's how the ABI merges duplicate strings. |
| 7503 | // Don't do it if they are writable, since we don't want writes in one TU to |
| 7504 | // affect strings in another. |
| 7505 | if (getCXXABI().getMangleContext().shouldMangleStringLiteral(SL: S) && |
| 7506 | !LangOpts.WritableStrings) { |
| 7507 | llvm::raw_svector_ostream Out(MangledNameBuffer); |
| 7508 | getCXXABI().getMangleContext().mangleStringLiteral(SL: S, Out); |
| 7509 | LT = llvm::GlobalValue::LinkOnceODRLinkage; |
| 7510 | GlobalVariableName = MangledNameBuffer; |
| 7511 | } else { |
| 7512 | LT = llvm::GlobalValue::PrivateLinkage; |
| 7513 | GlobalVariableName = Name; |
| 7514 | } |
| 7515 | |
| 7516 | auto GV = GenerateStringLiteral(C, LT, CGM&: *this, GlobalName: GlobalVariableName, Alignment); |
| 7517 | |
| 7518 | CGDebugInfo *DI = getModuleDebugInfo(); |
| 7519 | if (DI && getCodeGenOpts().hasReducedDebugInfo()) |
| 7520 | DI->AddStringLiteralDebugInfo(GV, S); |
| 7521 | |
| 7522 | if (Entry) |
| 7523 | *Entry = GV; |
| 7524 | |
| 7525 | SanitizerMD->reportGlobal(GV, Loc: S->getStrTokenLoc(TokNum: 0), Name: "<string literal>" ); |
| 7526 | |
| 7527 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(CGM&: *this, GV), |
| 7528 | GV->getValueType(), Alignment); |
| 7529 | } |
| 7530 | |
| 7531 | /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant |
| 7532 | /// array for the given ObjCEncodeExpr node. |
| 7533 | ConstantAddress |
| 7534 | CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { |
| 7535 | std::string Str; |
| 7536 | getContext().getObjCEncodingForType(T: E->getEncodedType(), S&: Str); |
| 7537 | |
| 7538 | return GetAddrOfConstantCString(Str); |
| 7539 | } |
| 7540 | |
| 7541 | /// GetAddrOfConstantCString - Returns a pointer to a character array containing |
| 7542 | /// the literal and a terminating '\0' character. |
| 7543 | /// The result has pointer to array type. |
| 7544 | ConstantAddress CodeGenModule::GetAddrOfConstantCString(const std::string &Str, |
| 7545 | StringRef GlobalName) { |
| 7546 | StringRef StrWithNull(Str.c_str(), Str.size() + 1); |
| 7547 | CharUnits Alignment = getContext().getAlignOfGlobalVarInChars( |
| 7548 | T: getContext().CharTy, /*VD=*/nullptr); |
| 7549 | |
| 7550 | llvm::Constant *C = |
| 7551 | llvm::ConstantDataArray::getString(Context&: getLLVMContext(), Initializer: StrWithNull, AddNull: false); |
| 7552 | |
| 7553 | // Don't share any string literals if strings aren't constant. |
| 7554 | llvm::GlobalVariable **Entry = nullptr; |
| 7555 | if (!LangOpts.WritableStrings) { |
| 7556 | Entry = &ConstantStringMap[C]; |
| 7557 | if (auto GV = *Entry) { |
| 7558 | if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) |
| 7559 | GV->setAlignment(Alignment.getAsAlign()); |
| 7560 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(CGM&: *this, GV), |
| 7561 | GV->getValueType(), Alignment); |
| 7562 | } |
| 7563 | } |
| 7564 | |
| 7565 | // Create a global variable for this. |
| 7566 | auto GV = GenerateStringLiteral(C, LT: llvm::GlobalValue::PrivateLinkage, CGM&: *this, |
| 7567 | GlobalName, Alignment); |
| 7568 | if (Entry) |
| 7569 | *Entry = GV; |
| 7570 | |
| 7571 | return ConstantAddress(castStringLiteralToDefaultAddressSpace(CGM&: *this, GV), |
| 7572 | GV->getValueType(), Alignment); |
| 7573 | } |
| 7574 | |
| 7575 | ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( |
| 7576 | const MaterializeTemporaryExpr *E, const Expr *Init) { |
| 7577 | assert((E->getStorageDuration() == SD_Static || |
| 7578 | E->getStorageDuration() == SD_Thread) && "not a global temporary" ); |
| 7579 | const auto *VD = cast<VarDecl>(Val: E->getExtendingDecl()); |
| 7580 | |
| 7581 | // Use the MaterializeTemporaryExpr's type if it has the same unqualified |
| 7582 | // base type as Init. This preserves cv-qualifiers (e.g. const from a |
| 7583 | // constexpr or const-ref binding) that skipRValueSubobjectAdjustments may |
| 7584 | // have dropped via NoOp casts, while correctly falling back to Init's type |
| 7585 | // when a real subobject adjustment changed the type (e.g. member access or |
| 7586 | // base-class cast in C++98), where E->getType() reflects the reference type, |
| 7587 | // not the actual storage type. |
| 7588 | QualType MaterializedType = Init->getType(); |
| 7589 | if (getContext().hasSameUnqualifiedType(T1: E->getType(), T2: MaterializedType)) |
| 7590 | MaterializedType = E->getType(); |
| 7591 | |
| 7592 | CharUnits Align = getContext().getTypeAlignInChars(T: MaterializedType); |
| 7593 | |
| 7594 | auto InsertResult = MaterializedGlobalTemporaryMap.insert(KV: {E, nullptr}); |
| 7595 | if (!InsertResult.second) { |
| 7596 | // We've seen this before: either we already created it or we're in the |
| 7597 | // process of doing so. |
| 7598 | if (!InsertResult.first->second) { |
| 7599 | // We recursively re-entered this function, probably during emission of |
| 7600 | // the initializer. Create a placeholder. We'll clean this up in the |
| 7601 | // outer call, at the end of this function. |
| 7602 | llvm::Type *Type = getTypes().ConvertTypeForMem(T: MaterializedType); |
| 7603 | InsertResult.first->second = new llvm::GlobalVariable( |
| 7604 | getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, |
| 7605 | nullptr); |
| 7606 | } |
| 7607 | return ConstantAddress(InsertResult.first->second, |
| 7608 | llvm::cast<llvm::GlobalVariable>( |
| 7609 | Val: InsertResult.first->second->stripPointerCasts()) |
| 7610 | ->getValueType(), |
| 7611 | Align); |
| 7612 | } |
| 7613 | |
| 7614 | // FIXME: If an externally-visible declaration extends multiple temporaries, |
| 7615 | // we need to give each temporary the same name in every translation unit (and |
| 7616 | // we also need to make the temporaries externally-visible). |
| 7617 | SmallString<256> Name; |
| 7618 | llvm::raw_svector_ostream Out(Name); |
| 7619 | getCXXABI().getMangleContext().mangleReferenceTemporary( |
| 7620 | D: VD, ManglingNumber: E->getManglingNumber(), Out); |
| 7621 | |
| 7622 | APValue *Value = nullptr; |
| 7623 | if (E->getStorageDuration() == SD_Static && VD->evaluateValue()) { |
| 7624 | // If the initializer of the extending declaration is a constant |
| 7625 | // initializer, we should have a cached constant initializer for this |
| 7626 | // temporary. Note that this might have a different value from the value |
| 7627 | // computed by evaluating the initializer if the surrounding constant |
| 7628 | // expression modifies the temporary. |
| 7629 | Value = E->getOrCreateValue(MayCreate: false); |
| 7630 | } |
| 7631 | |
| 7632 | // Try evaluating it now, it might have a constant initializer. |
| 7633 | Expr::EvalResult EvalResult; |
| 7634 | if (!Value && Init->EvaluateAsRValue(Result&: EvalResult, Ctx: getContext()) && |
| 7635 | !EvalResult.hasSideEffects()) |
| 7636 | Value = &EvalResult.Val; |
| 7637 | |
| 7638 | LangAS AddrSpace = GetGlobalVarAddressSpace(D: VD); |
| 7639 | |
| 7640 | std::optional<ConstantEmitter> emitter; |
| 7641 | llvm::Constant *InitialValue = nullptr; |
| 7642 | bool Constant = false; |
| 7643 | llvm::Type *Type; |
| 7644 | if (Value) { |
| 7645 | // The temporary has a constant initializer, use it. |
| 7646 | emitter.emplace(args&: *this); |
| 7647 | InitialValue = emitter->emitForInitializer(value: *Value, destAddrSpace: AddrSpace, |
| 7648 | destType: MaterializedType); |
| 7649 | Constant = |
| 7650 | MaterializedType.isConstantStorage(Ctx: getContext(), /*ExcludeCtor*/ Value, |
| 7651 | /*ExcludeDtor*/ false); |
| 7652 | Type = InitialValue->getType(); |
| 7653 | } else { |
| 7654 | // No initializer, the initialization will be provided when we |
| 7655 | // initialize the declaration which performed lifetime extension. |
| 7656 | Type = getTypes().ConvertTypeForMem(T: MaterializedType); |
| 7657 | } |
| 7658 | |
| 7659 | // Create a global variable for this lifetime-extended temporary. |
| 7660 | llvm::GlobalValue::LinkageTypes Linkage = getLLVMLinkageVarDefinition(VD); |
| 7661 | if (Linkage == llvm::GlobalVariable::ExternalLinkage) { |
| 7662 | const VarDecl *InitVD; |
| 7663 | if (VD->isStaticDataMember() && VD->getAnyInitializer(D&: InitVD) && |
| 7664 | isa<CXXRecordDecl>(Val: InitVD->getLexicalDeclContext())) { |
| 7665 | // Temporaries defined inside a class get linkonce_odr linkage because the |
| 7666 | // class can be defined in multiple translation units. |
| 7667 | Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; |
| 7668 | } else { |
| 7669 | // There is no need for this temporary to have external linkage if the |
| 7670 | // VarDecl has external linkage. |
| 7671 | Linkage = llvm::GlobalVariable::InternalLinkage; |
| 7672 | } |
| 7673 | } |
| 7674 | auto TargetAS = getContext().getTargetAddressSpace(AS: AddrSpace); |
| 7675 | auto *GV = new llvm::GlobalVariable( |
| 7676 | getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), |
| 7677 | /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); |
| 7678 | if (emitter) emitter->finalize(global: GV); |
| 7679 | // Don't assign dllimport or dllexport to local linkage globals. |
| 7680 | if (!llvm::GlobalValue::isLocalLinkage(Linkage)) { |
| 7681 | setGVProperties(GV, D: VD); |
| 7682 | if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) |
| 7683 | // The reference temporary should never be dllexport. |
| 7684 | GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); |
| 7685 | } |
| 7686 | GV->setAlignment(Align.getAsAlign()); |
| 7687 | if (supportsCOMDAT() && GV->isWeakForLinker()) |
| 7688 | GV->setComdat(TheModule.getOrInsertComdat(Name: GV->getName())); |
| 7689 | if (VD->getTLSKind()) |
| 7690 | setTLSMode(GV, D: *VD); |
| 7691 | llvm::Constant *CV = GV; |
| 7692 | if (AddrSpace != LangAS::Default) |
| 7693 | CV = performAddrSpaceCast( |
| 7694 | Src: GV, DestTy: llvm::PointerType::get( |
| 7695 | C&: getLLVMContext(), |
| 7696 | AddressSpace: getContext().getTargetAddressSpace(AS: LangAS::Default))); |
| 7697 | |
| 7698 | // Update the map with the new temporary. If we created a placeholder above, |
| 7699 | // replace it with the new global now. |
| 7700 | llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; |
| 7701 | if (Entry) { |
| 7702 | Entry->replaceAllUsesWith(V: CV); |
| 7703 | llvm::cast<llvm::GlobalVariable>(Val: Entry)->eraseFromParent(); |
| 7704 | } |
| 7705 | Entry = CV; |
| 7706 | |
| 7707 | return ConstantAddress(CV, Type, Align); |
| 7708 | } |
| 7709 | |
| 7710 | /// EmitObjCPropertyImplementations - Emit information for synthesized |
| 7711 | /// properties for an implementation. |
| 7712 | void CodeGenModule::EmitObjCPropertyImplementations(const |
| 7713 | ObjCImplementationDecl *D) { |
| 7714 | for (const auto *PID : D->property_impls()) { |
| 7715 | // Dynamic is just for type-checking. |
| 7716 | if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { |
| 7717 | ObjCPropertyDecl *PD = PID->getPropertyDecl(); |
| 7718 | |
| 7719 | // Determine which methods need to be implemented, some may have |
| 7720 | // been overridden. Note that ::isPropertyAccessor is not the method |
| 7721 | // we want, that just indicates if the decl came from a |
| 7722 | // property. What we want to know is if the method is defined in |
| 7723 | // this implementation. |
| 7724 | auto *Getter = PID->getGetterMethodDecl(); |
| 7725 | if (!Getter || Getter->isSynthesizedAccessorStub()) |
| 7726 | CodeGenFunction(*this).GenerateObjCGetter( |
| 7727 | IMP: const_cast<ObjCImplementationDecl *>(D), PID); |
| 7728 | auto *Setter = PID->getSetterMethodDecl(); |
| 7729 | if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) |
| 7730 | CodeGenFunction(*this).GenerateObjCSetter( |
| 7731 | IMP: const_cast<ObjCImplementationDecl *>(D), PID); |
| 7732 | } |
| 7733 | } |
| 7734 | } |
| 7735 | |
| 7736 | static bool needsDestructMethod(ObjCImplementationDecl *impl) { |
| 7737 | const ObjCInterfaceDecl *iface = impl->getClassInterface(); |
| 7738 | for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); |
| 7739 | ivar; ivar = ivar->getNextIvar()) |
| 7740 | if (ivar->getType().isDestructedType()) |
| 7741 | return true; |
| 7742 | |
| 7743 | return false; |
| 7744 | } |
| 7745 | |
| 7746 | static bool AllTrivialInitializers(CodeGenModule &CGM, |
| 7747 | ObjCImplementationDecl *D) { |
| 7748 | CodeGenFunction CGF(CGM); |
| 7749 | for (ObjCImplementationDecl::init_iterator B = D->init_begin(), |
| 7750 | E = D->init_end(); B != E; ++B) { |
| 7751 | CXXCtorInitializer *CtorInitExp = *B; |
| 7752 | Expr *Init = CtorInitExp->getInit(); |
| 7753 | if (!CGF.isTrivialInitializer(Init)) |
| 7754 | return false; |
| 7755 | } |
| 7756 | return true; |
| 7757 | } |
| 7758 | |
| 7759 | /// EmitObjCIvarInitializations - Emit information for ivar initialization |
| 7760 | /// for an implementation. |
| 7761 | void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { |
| 7762 | // We might need a .cxx_destruct even if we don't have any ivar initializers. |
| 7763 | if (needsDestructMethod(impl: D)) { |
| 7764 | const IdentifierInfo *II = &getContext().Idents.get(Name: ".cxx_destruct" ); |
| 7765 | Selector cxxSelector = getContext().Selectors.getSelector(NumArgs: 0, IIV: &II); |
| 7766 | ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( |
| 7767 | C&: getContext(), beginLoc: D->getLocation(), endLoc: D->getLocation(), SelInfo: cxxSelector, |
| 7768 | T: getContext().VoidTy, ReturnTInfo: nullptr, contextDecl: D, |
| 7769 | /*isInstance=*/true, /*isVariadic=*/false, |
| 7770 | /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, |
| 7771 | /*isImplicitlyDeclared=*/true, |
| 7772 | /*isDefined=*/false, impControl: ObjCImplementationControl::Required); |
| 7773 | D->addInstanceMethod(method: DTORMethod); |
| 7774 | CodeGenFunction(*this).GenerateObjCCtorDtorMethod(IMP: D, MD: DTORMethod, ctor: false); |
| 7775 | D->setHasDestructors(true); |
| 7776 | } |
| 7777 | |
| 7778 | // If the implementation doesn't have any ivar initializers, we don't need |
| 7779 | // a .cxx_construct. |
| 7780 | if (D->getNumIvarInitializers() == 0 || |
| 7781 | AllTrivialInitializers(CGM&: *this, D)) |
| 7782 | return; |
| 7783 | |
| 7784 | const IdentifierInfo *II = &getContext().Idents.get(Name: ".cxx_construct" ); |
| 7785 | Selector cxxSelector = getContext().Selectors.getSelector(NumArgs: 0, IIV: &II); |
| 7786 | // The constructor returns 'self'. |
| 7787 | ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( |
| 7788 | C&: getContext(), beginLoc: D->getLocation(), endLoc: D->getLocation(), SelInfo: cxxSelector, |
| 7789 | T: getContext().getObjCIdType(), ReturnTInfo: nullptr, contextDecl: D, /*isInstance=*/true, |
| 7790 | /*isVariadic=*/false, |
| 7791 | /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, |
| 7792 | /*isImplicitlyDeclared=*/true, |
| 7793 | /*isDefined=*/false, impControl: ObjCImplementationControl::Required); |
| 7794 | D->addInstanceMethod(method: CTORMethod); |
| 7795 | CodeGenFunction(*this).GenerateObjCCtorDtorMethod(IMP: D, MD: CTORMethod, ctor: true); |
| 7796 | D->setHasNonZeroConstructors(true); |
| 7797 | } |
| 7798 | |
| 7799 | // EmitLinkageSpec - Emit all declarations in a linkage spec. |
| 7800 | void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { |
| 7801 | if (LSD->getLanguage() != LinkageSpecLanguageIDs::C && |
| 7802 | LSD->getLanguage() != LinkageSpecLanguageIDs::CXX) { |
| 7803 | ErrorUnsupported(D: LSD, Type: "linkage spec" ); |
| 7804 | return; |
| 7805 | } |
| 7806 | |
| 7807 | EmitDeclContext(DC: LSD); |
| 7808 | } |
| 7809 | |
| 7810 | void CodeGenModule::EmitTopLevelStmt(const TopLevelStmtDecl *D) { |
| 7811 | // Device code should not be at top level. |
| 7812 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) |
| 7813 | return; |
| 7814 | |
| 7815 | std::unique_ptr<CodeGenFunction> &CurCGF = |
| 7816 | GlobalTopLevelStmtBlockInFlight.first; |
| 7817 | |
| 7818 | // We emitted a top-level stmt but after it there is initialization. |
| 7819 | // Stop squashing the top-level stmts into a single function. |
| 7820 | if (CurCGF && CXXGlobalInits.back() != CurCGF->CurFn) { |
| 7821 | CurCGF->FinishFunction(EndLoc: D->getEndLoc()); |
| 7822 | CurCGF = nullptr; |
| 7823 | } |
| 7824 | |
| 7825 | if (!CurCGF) { |
| 7826 | // void __stmts__N(void) |
| 7827 | // FIXME: Ask the ABI name mangler to pick a name. |
| 7828 | std::string Name = "__stmts__" + llvm::utostr(X: CXXGlobalInits.size()); |
| 7829 | FunctionArgList Args; |
| 7830 | QualType RetTy = getContext().VoidTy; |
| 7831 | const CGFunctionInfo &FnInfo = |
| 7832 | getTypes().arrangeBuiltinFunctionDeclaration(resultType: RetTy, args: Args); |
| 7833 | llvm::FunctionType *FnTy = getTypes().GetFunctionType(Info: FnInfo); |
| 7834 | llvm::Function *Fn = llvm::Function::Create( |
| 7835 | Ty: FnTy, Linkage: llvm::GlobalValue::InternalLinkage, N: Name, M: &getModule()); |
| 7836 | |
| 7837 | CurCGF.reset(p: new CodeGenFunction(*this)); |
| 7838 | GlobalTopLevelStmtBlockInFlight.second = D; |
| 7839 | CurCGF->StartFunction(GD: GlobalDecl(), RetTy, Fn, FnInfo, Args, |
| 7840 | Loc: D->getBeginLoc(), StartLoc: D->getBeginLoc()); |
| 7841 | CXXGlobalInits.push_back(x: Fn); |
| 7842 | } |
| 7843 | |
| 7844 | CurCGF->EmitStmt(S: D->getStmt()); |
| 7845 | } |
| 7846 | |
| 7847 | void CodeGenModule::EmitDeclContext(const DeclContext *DC) { |
| 7848 | for (auto *I : DC->decls()) { |
| 7849 | // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope |
| 7850 | // are themselves considered "top-level", so EmitTopLevelDecl on an |
| 7851 | // ObjCImplDecl does not recursively visit them. We need to do that in |
| 7852 | // case they're nested inside another construct (LinkageSpecDecl / |
| 7853 | // ExportDecl) that does stop them from being considered "top-level". |
| 7854 | if (auto *OID = dyn_cast<ObjCImplDecl>(Val: I)) { |
| 7855 | for (auto *M : OID->methods()) |
| 7856 | EmitTopLevelDecl(D: M); |
| 7857 | } |
| 7858 | |
| 7859 | EmitTopLevelDecl(D: I); |
| 7860 | } |
| 7861 | } |
| 7862 | |
| 7863 | /// EmitTopLevelDecl - Emit code for a single top level declaration. |
| 7864 | void CodeGenModule::EmitTopLevelDecl(Decl *D) { |
| 7865 | // Ignore dependent declarations. |
| 7866 | if (D->isTemplated()) |
| 7867 | return; |
| 7868 | |
| 7869 | // Consteval function shouldn't be emitted. |
| 7870 | if (auto *FD = dyn_cast<FunctionDecl>(Val: D); FD && FD->isImmediateFunction()) |
| 7871 | return; |
| 7872 | |
| 7873 | switch (D->getKind()) { |
| 7874 | case Decl::CXXConversion: |
| 7875 | case Decl::CXXMethod: |
| 7876 | case Decl::Function: |
| 7877 | EmitGlobal(GD: cast<FunctionDecl>(Val: D)); |
| 7878 | // Always provide some coverage mapping |
| 7879 | // even for the functions that aren't emitted. |
| 7880 | AddDeferredUnusedCoverageMapping(D); |
| 7881 | break; |
| 7882 | |
| 7883 | case Decl::CXXDeductionGuide: |
| 7884 | // Function-like, but does not result in code emission. |
| 7885 | break; |
| 7886 | |
| 7887 | case Decl::Var: |
| 7888 | case Decl::Decomposition: |
| 7889 | case Decl::VarTemplateSpecialization: |
| 7890 | EmitGlobal(GD: cast<VarDecl>(Val: D)); |
| 7891 | if (auto *DD = dyn_cast<DecompositionDecl>(Val: D)) |
| 7892 | for (auto *B : DD->flat_bindings()) |
| 7893 | if (auto *HD = B->getHoldingVar()) |
| 7894 | EmitGlobal(GD: HD); |
| 7895 | |
| 7896 | break; |
| 7897 | |
| 7898 | // Indirect fields from global anonymous structs and unions can be |
| 7899 | // ignored; only the actual variable requires IR gen support. |
| 7900 | case Decl::IndirectField: |
| 7901 | break; |
| 7902 | |
| 7903 | // C++ Decls |
| 7904 | case Decl::Namespace: |
| 7905 | EmitDeclContext(DC: cast<NamespaceDecl>(Val: D)); |
| 7906 | break; |
| 7907 | case Decl::ClassTemplateSpecialization: { |
| 7908 | const auto *Spec = cast<ClassTemplateSpecializationDecl>(Val: D); |
| 7909 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 7910 | if (Spec->getSpecializationKind() == |
| 7911 | TSK_ExplicitInstantiationDefinition && |
| 7912 | Spec->hasDefinition()) |
| 7913 | DI->completeTemplateDefinition(SD: *Spec); |
| 7914 | } [[fallthrough]]; |
| 7915 | case Decl::CXXRecord: { |
| 7916 | CXXRecordDecl *CRD = cast<CXXRecordDecl>(Val: D); |
| 7917 | if (CGDebugInfo *DI = getModuleDebugInfo()) { |
| 7918 | if (CRD->hasDefinition()) |
| 7919 | DI->EmitAndRetainType( |
| 7920 | Ty: getContext().getCanonicalTagType(TD: cast<RecordDecl>(Val: D))); |
| 7921 | if (auto *ES = D->getASTContext().getExternalSource()) |
| 7922 | if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) |
| 7923 | DI->completeUnusedClass(D: *CRD); |
| 7924 | } |
| 7925 | // Emit any static data members, they may be definitions. |
| 7926 | for (auto *I : CRD->decls()) |
| 7927 | if (isa<VarDecl>(Val: I) || isa<CXXRecordDecl>(Val: I) || isa<EnumDecl>(Val: I)) |
| 7928 | EmitTopLevelDecl(D: I); |
| 7929 | break; |
| 7930 | } |
| 7931 | // No code generation needed. |
| 7932 | case Decl::UsingShadow: |
| 7933 | case Decl::ClassTemplate: |
| 7934 | case Decl::VarTemplate: |
| 7935 | case Decl::Concept: |
| 7936 | case Decl::VarTemplatePartialSpecialization: |
| 7937 | case Decl::FunctionTemplate: |
| 7938 | case Decl::TypeAliasTemplate: |
| 7939 | case Decl::Block: |
| 7940 | case Decl::Empty: |
| 7941 | case Decl::Binding: |
| 7942 | break; |
| 7943 | case Decl::Using: // using X; [C++] |
| 7944 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 7945 | DI->EmitUsingDecl(UD: cast<UsingDecl>(Val&: *D)); |
| 7946 | break; |
| 7947 | case Decl::UsingEnum: // using enum X; [C++] |
| 7948 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 7949 | DI->EmitUsingEnumDecl(UD: cast<UsingEnumDecl>(Val&: *D)); |
| 7950 | break; |
| 7951 | case Decl::NamespaceAlias: |
| 7952 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 7953 | DI->EmitNamespaceAlias(NA: cast<NamespaceAliasDecl>(Val&: *D)); |
| 7954 | break; |
| 7955 | case Decl::UsingDirective: // using namespace X; [C++] |
| 7956 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 7957 | DI->EmitUsingDirective(UD: cast<UsingDirectiveDecl>(Val&: *D)); |
| 7958 | break; |
| 7959 | case Decl::CXXConstructor: |
| 7960 | getCXXABI().EmitCXXConstructors(D: cast<CXXConstructorDecl>(Val: D)); |
| 7961 | break; |
| 7962 | case Decl::CXXDestructor: |
| 7963 | getCXXABI().EmitCXXDestructors(D: cast<CXXDestructorDecl>(Val: D)); |
| 7964 | break; |
| 7965 | |
| 7966 | case Decl::StaticAssert: |
| 7967 | case Decl::ExplicitInstantiation: |
| 7968 | // Nothing to do. |
| 7969 | break; |
| 7970 | |
| 7971 | // Objective-C Decls |
| 7972 | |
| 7973 | // Forward declarations, no (immediate) code generation. |
| 7974 | case Decl::ObjCInterface: |
| 7975 | case Decl::ObjCCategory: |
| 7976 | break; |
| 7977 | |
| 7978 | case Decl::ObjCProtocol: { |
| 7979 | auto *Proto = cast<ObjCProtocolDecl>(Val: D); |
| 7980 | if (Proto->isThisDeclarationADefinition()) |
| 7981 | ObjCRuntime->GenerateProtocol(OPD: Proto); |
| 7982 | break; |
| 7983 | } |
| 7984 | |
| 7985 | case Decl::ObjCCategoryImpl: |
| 7986 | // Categories have properties but don't support synthesize so we |
| 7987 | // can ignore them here. |
| 7988 | ObjCRuntime->GenerateCategory(OCD: cast<ObjCCategoryImplDecl>(Val: D)); |
| 7989 | break; |
| 7990 | |
| 7991 | case Decl::ObjCImplementation: { |
| 7992 | auto *OMD = cast<ObjCImplementationDecl>(Val: D); |
| 7993 | EmitObjCPropertyImplementations(D: OMD); |
| 7994 | EmitObjCIvarInitializations(D: OMD); |
| 7995 | ObjCRuntime->GenerateClass(OID: OMD); |
| 7996 | // Emit global variable debug information. |
| 7997 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 7998 | if (getCodeGenOpts().hasReducedDebugInfo()) |
| 7999 | DI->getOrCreateInterfaceType(Ty: getContext().getObjCInterfaceType( |
| 8000 | Decl: OMD->getClassInterface()), Loc: OMD->getLocation()); |
| 8001 | break; |
| 8002 | } |
| 8003 | case Decl::ObjCMethod: { |
| 8004 | auto *OMD = cast<ObjCMethodDecl>(Val: D); |
| 8005 | // If this is not a prototype, emit the body. |
| 8006 | if (OMD->getBody()) |
| 8007 | CodeGenFunction(*this).GenerateObjCMethod(OMD); |
| 8008 | break; |
| 8009 | } |
| 8010 | case Decl::ObjCCompatibleAlias: |
| 8011 | ObjCRuntime->RegisterAlias(OAD: cast<ObjCCompatibleAliasDecl>(Val: D)); |
| 8012 | break; |
| 8013 | |
| 8014 | case Decl::PragmaComment: { |
| 8015 | const auto *PCD = cast<PragmaCommentDecl>(Val: D); |
| 8016 | switch (PCD->getCommentKind()) { |
| 8017 | case PCK_Unknown: |
| 8018 | llvm_unreachable("unexpected pragma comment kind" ); |
| 8019 | case PCK_Linker: |
| 8020 | AppendLinkerOptions(Opts: PCD->getArg()); |
| 8021 | break; |
| 8022 | case PCK_Lib: |
| 8023 | AddDependentLib(Lib: PCD->getArg()); |
| 8024 | break; |
| 8025 | case PCK_Copyright: |
| 8026 | ProcessPragmaCommentCopyright(Comment: PCD->getArg(), isFromASTFile: PCD->isFromASTFile()); |
| 8027 | break; |
| 8028 | case PCK_Compiler: |
| 8029 | case PCK_ExeStr: |
| 8030 | case PCK_User: |
| 8031 | break; // We ignore all of these. |
| 8032 | } |
| 8033 | break; |
| 8034 | } |
| 8035 | |
| 8036 | case Decl::PragmaDetectMismatch: { |
| 8037 | const auto *PDMD = cast<PragmaDetectMismatchDecl>(Val: D); |
| 8038 | AddDetectMismatch(Name: PDMD->getName(), Value: PDMD->getValue()); |
| 8039 | break; |
| 8040 | } |
| 8041 | |
| 8042 | case Decl::LinkageSpec: |
| 8043 | EmitLinkageSpec(LSD: cast<LinkageSpecDecl>(Val: D)); |
| 8044 | break; |
| 8045 | |
| 8046 | case Decl::FileScopeAsm: { |
| 8047 | // File-scope asm is ignored during device-side CUDA compilation. |
| 8048 | if (LangOpts.CUDA && LangOpts.CUDAIsDevice) |
| 8049 | break; |
| 8050 | // File-scope asm is ignored during device-side OpenMP compilation. |
| 8051 | if (LangOpts.OpenMPIsTargetDevice) |
| 8052 | break; |
| 8053 | // File-scope asm is ignored during device-side SYCL compilation. |
| 8054 | if (LangOpts.SYCLIsDevice) |
| 8055 | break; |
| 8056 | auto *AD = cast<FileScopeAsmDecl>(Val: D); |
| 8057 | getModule().appendModuleInlineAsm(Asm: AD->getAsmString()); |
| 8058 | break; |
| 8059 | } |
| 8060 | |
| 8061 | case Decl::TopLevelStmt: |
| 8062 | EmitTopLevelStmt(D: cast<TopLevelStmtDecl>(Val: D)); |
| 8063 | break; |
| 8064 | |
| 8065 | case Decl::Import: { |
| 8066 | auto *Import = cast<ImportDecl>(Val: D); |
| 8067 | |
| 8068 | // If we've already imported this module, we're done. |
| 8069 | if (!ImportedModules.insert(X: Import->getImportedModule())) |
| 8070 | break; |
| 8071 | |
| 8072 | // Emit debug information for direct imports. |
| 8073 | if (!Import->getImportedOwningModule()) { |
| 8074 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 8075 | DI->EmitImportDecl(ID: *Import); |
| 8076 | } |
| 8077 | |
| 8078 | // For C++ standard modules we are done - we will call the module |
| 8079 | // initializer for imported modules, and that will likewise call those for |
| 8080 | // any imports it has. |
| 8081 | if (CXX20ModuleInits && Import->getImportedModule() && |
| 8082 | Import->getImportedModule()->isNamedModule()) |
| 8083 | break; |
| 8084 | |
| 8085 | // For clang C++ module map modules the initializers for sub-modules are |
| 8086 | // emitted here. |
| 8087 | |
| 8088 | // Find all of the submodules and emit the module initializers. |
| 8089 | llvm::SmallPtrSet<clang::Module *, 16> Visited; |
| 8090 | SmallVector<clang::Module *, 16> Stack; |
| 8091 | Visited.insert(Ptr: Import->getImportedModule()); |
| 8092 | Stack.push_back(Elt: Import->getImportedModule()); |
| 8093 | |
| 8094 | while (!Stack.empty()) { |
| 8095 | clang::Module *Mod = Stack.pop_back_val(); |
| 8096 | if (!EmittedModuleInitializers.insert(Ptr: Mod).second) |
| 8097 | continue; |
| 8098 | |
| 8099 | for (auto *D : Context.getModuleInitializers(M: Mod)) |
| 8100 | EmitTopLevelDecl(D); |
| 8101 | |
| 8102 | // Visit the submodules of this module. |
| 8103 | for (Module *Submodule : Mod->submodules()) { |
| 8104 | // Skip explicit children; they need to be explicitly imported to emit |
| 8105 | // the initializers. |
| 8106 | if (Submodule->IsExplicit) |
| 8107 | continue; |
| 8108 | |
| 8109 | if (Visited.insert(Ptr: Submodule).second) |
| 8110 | Stack.push_back(Elt: Submodule); |
| 8111 | } |
| 8112 | } |
| 8113 | break; |
| 8114 | } |
| 8115 | |
| 8116 | case Decl::Export: |
| 8117 | EmitDeclContext(DC: cast<ExportDecl>(Val: D)); |
| 8118 | break; |
| 8119 | |
| 8120 | case Decl::OMPThreadPrivate: |
| 8121 | EmitOMPThreadPrivateDecl(D: cast<OMPThreadPrivateDecl>(Val: D)); |
| 8122 | break; |
| 8123 | |
| 8124 | case Decl::OMPAllocate: |
| 8125 | EmitOMPAllocateDecl(D: cast<OMPAllocateDecl>(Val: D)); |
| 8126 | break; |
| 8127 | |
| 8128 | case Decl::OMPDeclareReduction: |
| 8129 | EmitOMPDeclareReduction(D: cast<OMPDeclareReductionDecl>(Val: D)); |
| 8130 | break; |
| 8131 | |
| 8132 | case Decl::OMPDeclareMapper: |
| 8133 | EmitOMPDeclareMapper(D: cast<OMPDeclareMapperDecl>(Val: D)); |
| 8134 | break; |
| 8135 | |
| 8136 | case Decl::OMPRequires: |
| 8137 | EmitOMPRequiresDecl(D: cast<OMPRequiresDecl>(Val: D)); |
| 8138 | break; |
| 8139 | |
| 8140 | case Decl::Typedef: |
| 8141 | case Decl::TypeAlias: // using foo = bar; [C++11] |
| 8142 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 8143 | DI->EmitAndRetainType(Ty: getContext().getTypedefType( |
| 8144 | Keyword: ElaboratedTypeKeyword::None, /*Qualifier=*/std::nullopt, |
| 8145 | Decl: cast<TypedefNameDecl>(Val: D))); |
| 8146 | break; |
| 8147 | |
| 8148 | case Decl::Record: |
| 8149 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 8150 | if (cast<RecordDecl>(Val: D)->getDefinition()) |
| 8151 | DI->EmitAndRetainType( |
| 8152 | Ty: getContext().getCanonicalTagType(TD: cast<RecordDecl>(Val: D))); |
| 8153 | break; |
| 8154 | |
| 8155 | case Decl::Enum: |
| 8156 | if (CGDebugInfo *DI = getModuleDebugInfo()) |
| 8157 | if (cast<EnumDecl>(Val: D)->getDefinition()) |
| 8158 | DI->EmitAndRetainType( |
| 8159 | Ty: getContext().getCanonicalTagType(TD: cast<EnumDecl>(Val: D))); |
| 8160 | break; |
| 8161 | |
| 8162 | case Decl::HLSLRootSignature: |
| 8163 | getHLSLRuntime().addRootSignature(D: cast<HLSLRootSignatureDecl>(Val: D)); |
| 8164 | break; |
| 8165 | case Decl::HLSLBuffer: |
| 8166 | getHLSLRuntime().addBuffer(D: cast<HLSLBufferDecl>(Val: D)); |
| 8167 | break; |
| 8168 | |
| 8169 | case Decl::OpenACCDeclare: |
| 8170 | EmitOpenACCDeclare(D: cast<OpenACCDeclareDecl>(Val: D)); |
| 8171 | break; |
| 8172 | case Decl::OpenACCRoutine: |
| 8173 | EmitOpenACCRoutine(D: cast<OpenACCRoutineDecl>(Val: D)); |
| 8174 | break; |
| 8175 | |
| 8176 | default: |
| 8177 | // Make sure we handled everything we should, every other kind is a |
| 8178 | // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind |
| 8179 | // function. Need to recode Decl::Kind to do that easily. |
| 8180 | assert(isa<TypeDecl>(D) && "Unsupported decl kind" ); |
| 8181 | break; |
| 8182 | } |
| 8183 | } |
| 8184 | |
| 8185 | void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { |
| 8186 | // Do we need to generate coverage mapping? |
| 8187 | if (!CodeGenOpts.CoverageMapping) |
| 8188 | return; |
| 8189 | switch (D->getKind()) { |
| 8190 | case Decl::CXXConversion: |
| 8191 | case Decl::CXXMethod: |
| 8192 | case Decl::Function: |
| 8193 | case Decl::ObjCMethod: |
| 8194 | case Decl::CXXConstructor: |
| 8195 | case Decl::CXXDestructor: { |
| 8196 | if (!cast<FunctionDecl>(Val: D)->doesThisDeclarationHaveABody()) |
| 8197 | break; |
| 8198 | SourceManager &SM = getContext().getSourceManager(); |
| 8199 | if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(SpellingLoc: D->getBeginLoc())) |
| 8200 | break; |
| 8201 | if (!llvm::coverage::SystemHeadersCoverage && |
| 8202 | SM.isInSystemHeader(Loc: D->getBeginLoc())) |
| 8203 | break; |
| 8204 | DeferredEmptyCoverageMappingDecls.try_emplace(Key: D, Args: true); |
| 8205 | break; |
| 8206 | } |
| 8207 | default: |
| 8208 | break; |
| 8209 | }; |
| 8210 | } |
| 8211 | |
| 8212 | void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { |
| 8213 | // Do we need to generate coverage mapping? |
| 8214 | if (!CodeGenOpts.CoverageMapping) |
| 8215 | return; |
| 8216 | if (const auto *Fn = dyn_cast<FunctionDecl>(Val: D)) { |
| 8217 | if (Fn->isTemplateInstantiation()) |
| 8218 | ClearUnusedCoverageMapping(D: Fn->getTemplateInstantiationPattern()); |
| 8219 | } |
| 8220 | DeferredEmptyCoverageMappingDecls.insert_or_assign(Key: D, Val: false); |
| 8221 | } |
| 8222 | |
| 8223 | void CodeGenModule::EmitDeferredUnusedCoverageMappings() { |
| 8224 | // We call takeVector() here to avoid use-after-free. |
| 8225 | // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because |
| 8226 | // we deserialize function bodies to emit coverage info for them, and that |
| 8227 | // deserializes more declarations. How should we handle that case? |
| 8228 | for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { |
| 8229 | if (!Entry.second) |
| 8230 | continue; |
| 8231 | const Decl *D = Entry.first; |
| 8232 | switch (D->getKind()) { |
| 8233 | case Decl::CXXConversion: |
| 8234 | case Decl::CXXMethod: |
| 8235 | case Decl::Function: |
| 8236 | case Decl::ObjCMethod: { |
| 8237 | CodeGenPGO PGO(*this); |
| 8238 | GlobalDecl GD(cast<FunctionDecl>(Val: D)); |
| 8239 | PGO.emitEmptyCounterMapping(D, FuncName: getMangledName(GD), |
| 8240 | Linkage: getFunctionLinkage(GD)); |
| 8241 | break; |
| 8242 | } |
| 8243 | case Decl::CXXConstructor: { |
| 8244 | CodeGenPGO PGO(*this); |
| 8245 | GlobalDecl GD(cast<CXXConstructorDecl>(Val: D), Ctor_Base); |
| 8246 | PGO.emitEmptyCounterMapping(D, FuncName: getMangledName(GD), |
| 8247 | Linkage: getFunctionLinkage(GD)); |
| 8248 | break; |
| 8249 | } |
| 8250 | case Decl::CXXDestructor: { |
| 8251 | CodeGenPGO PGO(*this); |
| 8252 | GlobalDecl GD(cast<CXXDestructorDecl>(Val: D), Dtor_Base); |
| 8253 | PGO.emitEmptyCounterMapping(D, FuncName: getMangledName(GD), |
| 8254 | Linkage: getFunctionLinkage(GD)); |
| 8255 | break; |
| 8256 | } |
| 8257 | default: |
| 8258 | break; |
| 8259 | }; |
| 8260 | } |
| 8261 | } |
| 8262 | |
| 8263 | void CodeGenModule::EmitMainVoidAlias() { |
| 8264 | // In order to transition away from "__original_main" gracefully, emit an |
| 8265 | // alias for "main" in the no-argument case so that libc can detect when |
| 8266 | // new-style no-argument main is in used. |
| 8267 | if (llvm::Function *F = getModule().getFunction(Name: "main" )) { |
| 8268 | if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && |
| 8269 | F->getReturnType()->isIntegerTy(BitWidth: Context.getTargetInfo().getIntWidth())) { |
| 8270 | auto *GA = llvm::GlobalAlias::create(Name: "__main_void" , Aliasee: F); |
| 8271 | GA->setVisibility(llvm::GlobalValue::HiddenVisibility); |
| 8272 | } |
| 8273 | } |
| 8274 | } |
| 8275 | |
| 8276 | /// Turns the given pointer into a constant. |
| 8277 | static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, |
| 8278 | const void *Ptr) { |
| 8279 | uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); |
| 8280 | llvm::Type *i64 = llvm::Type::getInt64Ty(C&: Context); |
| 8281 | return llvm::ConstantInt::get(Ty: i64, V: PtrInt); |
| 8282 | } |
| 8283 | |
| 8284 | static void EmitGlobalDeclMetadata(CodeGenModule &CGM, |
| 8285 | llvm::NamedMDNode *&GlobalMetadata, |
| 8286 | GlobalDecl D, |
| 8287 | llvm::GlobalValue *Addr) { |
| 8288 | if (!GlobalMetadata) |
| 8289 | GlobalMetadata = |
| 8290 | CGM.getModule().getOrInsertNamedMetadata(Name: "clang.global.decl.ptrs" ); |
| 8291 | |
| 8292 | // TODO: should we report variant information for ctors/dtors? |
| 8293 | llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(C: Addr), |
| 8294 | llvm::ConstantAsMetadata::get(C: GetPointerConstant( |
| 8295 | Context&: CGM.getLLVMContext(), Ptr: D.getDecl()))}; |
| 8296 | GlobalMetadata->addOperand(M: llvm::MDNode::get(Context&: CGM.getLLVMContext(), MDs: Ops)); |
| 8297 | } |
| 8298 | |
| 8299 | bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, |
| 8300 | llvm::GlobalValue *CppFunc) { |
| 8301 | // Store the list of ifuncs we need to replace uses in. |
| 8302 | llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; |
| 8303 | // List of ConstantExprs that we should be able to delete when we're done |
| 8304 | // here. |
| 8305 | llvm::SmallVector<llvm::ConstantExpr *> CEs; |
| 8306 | |
| 8307 | // It isn't valid to replace the extern-C ifuncs if all we find is itself! |
| 8308 | if (Elem == CppFunc) |
| 8309 | return false; |
| 8310 | |
| 8311 | // First make sure that all users of this are ifuncs (or ifuncs via a |
| 8312 | // bitcast), and collect the list of ifuncs and CEs so we can work on them |
| 8313 | // later. |
| 8314 | for (llvm::User *User : Elem->users()) { |
| 8315 | // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an |
| 8316 | // ifunc directly. In any other case, just give up, as we don't know what we |
| 8317 | // could break by changing those. |
| 8318 | if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(Val: User)) { |
| 8319 | if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) |
| 8320 | return false; |
| 8321 | |
| 8322 | for (llvm::User *CEUser : ConstExpr->users()) { |
| 8323 | if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(Val: CEUser)) { |
| 8324 | IFuncs.push_back(Elt: IFunc); |
| 8325 | } else { |
| 8326 | return false; |
| 8327 | } |
| 8328 | } |
| 8329 | CEs.push_back(Elt: ConstExpr); |
| 8330 | } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(Val: User)) { |
| 8331 | IFuncs.push_back(Elt: IFunc); |
| 8332 | } else { |
| 8333 | // This user is one we don't know how to handle, so fail redirection. This |
| 8334 | // will result in an ifunc retaining a resolver name that will ultimately |
| 8335 | // fail to be resolved to a defined function. |
| 8336 | return false; |
| 8337 | } |
| 8338 | } |
| 8339 | |
| 8340 | // Now we know this is a valid case where we can do this alias replacement, we |
| 8341 | // need to remove all of the references to Elem (and the bitcasts!) so we can |
| 8342 | // delete it. |
| 8343 | for (llvm::GlobalIFunc *IFunc : IFuncs) |
| 8344 | IFunc->setResolver(nullptr); |
| 8345 | for (llvm::ConstantExpr *ConstExpr : CEs) |
| 8346 | ConstExpr->destroyConstant(); |
| 8347 | |
| 8348 | // We should now be out of uses for the 'old' version of this function, so we |
| 8349 | // can erase it as well. |
| 8350 | Elem->eraseFromParent(); |
| 8351 | |
| 8352 | for (llvm::GlobalIFunc *IFunc : IFuncs) { |
| 8353 | // The type of the resolver is always just a function-type that returns the |
| 8354 | // type of the IFunc, so create that here. If the type of the actual |
| 8355 | // resolver doesn't match, it just gets bitcast to the right thing. |
| 8356 | auto *ResolverTy = |
| 8357 | llvm::FunctionType::get(Result: IFunc->getType(), /*isVarArg*/ false); |
| 8358 | llvm::Constant *Resolver = GetOrCreateLLVMFunction( |
| 8359 | MangledName: CppFunc->getName(), Ty: ResolverTy, GD: {}, /*ForVTable*/ false); |
| 8360 | IFunc->setResolver(Resolver); |
| 8361 | } |
| 8362 | return true; |
| 8363 | } |
| 8364 | |
| 8365 | /// For each function which is declared within an extern "C" region and marked |
| 8366 | /// as 'used', but has internal linkage, create an alias from the unmangled |
| 8367 | /// name to the mangled name if possible. People expect to be able to refer |
| 8368 | /// to such functions with an unmangled name from inline assembly within the |
| 8369 | /// same translation unit. |
| 8370 | void CodeGenModule::EmitStaticExternCAliases() { |
| 8371 | if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) |
| 8372 | return; |
| 8373 | for (auto &I : StaticExternCValues) { |
| 8374 | const IdentifierInfo *Name = I.first; |
| 8375 | llvm::GlobalValue *Val = I.second; |
| 8376 | |
| 8377 | // If Val is null, that implies there were multiple declarations that each |
| 8378 | // had a claim to the unmangled name. In this case, generation of the alias |
| 8379 | // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. |
| 8380 | if (!Val) |
| 8381 | break; |
| 8382 | |
| 8383 | llvm::GlobalValue *ExistingElem = |
| 8384 | getModule().getNamedValue(Name: Name->getName()); |
| 8385 | |
| 8386 | // If there is either not something already by this name, or we were able to |
| 8387 | // replace all uses from IFuncs, create the alias. |
| 8388 | if (!ExistingElem || CheckAndReplaceExternCIFuncs(Elem: ExistingElem, CppFunc: Val)) |
| 8389 | addCompilerUsedGlobal(GV: llvm::GlobalAlias::create(Name: Name->getName(), Aliasee: Val)); |
| 8390 | } |
| 8391 | } |
| 8392 | |
| 8393 | bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, |
| 8394 | GlobalDecl &Result) const { |
| 8395 | auto Res = Manglings.find(Key: MangledName); |
| 8396 | if (Res == Manglings.end()) |
| 8397 | return false; |
| 8398 | Result = Res->getValue(); |
| 8399 | return true; |
| 8400 | } |
| 8401 | |
| 8402 | /// Emits metadata nodes associating all the global values in the |
| 8403 | /// current module with the Decls they came from. This is useful for |
| 8404 | /// projects using IR gen as a subroutine. |
| 8405 | /// |
| 8406 | /// Since there's currently no way to associate an MDNode directly |
| 8407 | /// with an llvm::GlobalValue, we create a global named metadata |
| 8408 | /// with the name 'clang.global.decl.ptrs'. |
| 8409 | void CodeGenModule::EmitDeclMetadata() { |
| 8410 | llvm::NamedMDNode *GlobalMetadata = nullptr; |
| 8411 | |
| 8412 | for (auto &I : MangledDeclNames) { |
| 8413 | llvm::GlobalValue *Addr = getModule().getNamedValue(Name: I.second); |
| 8414 | // Some mangled names don't necessarily have an associated GlobalValue |
| 8415 | // in this module, e.g. if we mangled it for DebugInfo. |
| 8416 | if (Addr) |
| 8417 | EmitGlobalDeclMetadata(CGM&: *this, GlobalMetadata, D: I.first, Addr); |
| 8418 | } |
| 8419 | } |
| 8420 | |
| 8421 | /// Emits metadata nodes for all the local variables in the current |
| 8422 | /// function. |
| 8423 | void CodeGenFunction::EmitDeclMetadata() { |
| 8424 | if (LocalDeclMap.empty()) return; |
| 8425 | |
| 8426 | llvm::LLVMContext &Context = getLLVMContext(); |
| 8427 | |
| 8428 | // Find the unique metadata ID for this name. |
| 8429 | unsigned DeclPtrKind = Context.getMDKindID(Name: "clang.decl.ptr" ); |
| 8430 | |
| 8431 | llvm::NamedMDNode *GlobalMetadata = nullptr; |
| 8432 | |
| 8433 | for (auto &I : LocalDeclMap) { |
| 8434 | const Decl *D = I.first; |
| 8435 | llvm::Value *Addr = I.second.emitRawPointer(CGF&: *this); |
| 8436 | if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Val: Addr)) { |
| 8437 | llvm::Value *DAddr = GetPointerConstant(Context&: getLLVMContext(), Ptr: D); |
| 8438 | Alloca->setMetadata( |
| 8439 | KindID: DeclPtrKind, Node: llvm::MDNode::get( |
| 8440 | Context, MDs: llvm::ValueAsMetadata::getConstant(C: DAddr))); |
| 8441 | } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Val: Addr)) { |
| 8442 | GlobalDecl GD = GlobalDecl(cast<VarDecl>(Val: D)); |
| 8443 | EmitGlobalDeclMetadata(CGM, GlobalMetadata, D: GD, Addr: GV); |
| 8444 | } |
| 8445 | } |
| 8446 | } |
| 8447 | |
| 8448 | void CodeGenModule::EmitVersionIdentMetadata() { |
| 8449 | llvm::NamedMDNode *IdentMetadata = |
| 8450 | TheModule.getOrInsertNamedMetadata(Name: "llvm.ident" ); |
| 8451 | std::string Version = getClangFullVersion(); |
| 8452 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
| 8453 | |
| 8454 | llvm::Metadata *IdentNode[] = {llvm::MDString::get(Context&: Ctx, Str: Version)}; |
| 8455 | IdentMetadata->addOperand(M: llvm::MDNode::get(Context&: Ctx, MDs: IdentNode)); |
| 8456 | } |
| 8457 | |
| 8458 | void CodeGenModule::EmitCommandLineMetadata() { |
| 8459 | llvm::NamedMDNode *CommandLineMetadata = |
| 8460 | TheModule.getOrInsertNamedMetadata(Name: "llvm.commandline" ); |
| 8461 | std::string CommandLine = getCodeGenOpts().RecordCommandLine; |
| 8462 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
| 8463 | |
| 8464 | llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Context&: Ctx, Str: CommandLine)}; |
| 8465 | CommandLineMetadata->addOperand(M: llvm::MDNode::get(Context&: Ctx, MDs: CommandLineNode)); |
| 8466 | } |
| 8467 | |
| 8468 | void CodeGenModule::EmitCoverageFile() { |
| 8469 | llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata(Name: "llvm.dbg.cu" ); |
| 8470 | if (!CUNode) |
| 8471 | return; |
| 8472 | |
| 8473 | llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata(Name: "llvm.gcov" ); |
| 8474 | llvm::LLVMContext &Ctx = TheModule.getContext(); |
| 8475 | auto *CoverageDataFile = |
| 8476 | llvm::MDString::get(Context&: Ctx, Str: getCodeGenOpts().CoverageDataFile); |
| 8477 | auto *CoverageNotesFile = |
| 8478 | llvm::MDString::get(Context&: Ctx, Str: getCodeGenOpts().CoverageNotesFile); |
| 8479 | for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { |
| 8480 | llvm::MDNode *CU = CUNode->getOperand(i); |
| 8481 | llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; |
| 8482 | GCov->addOperand(M: llvm::MDNode::get(Context&: Ctx, MDs: Elts)); |
| 8483 | } |
| 8484 | } |
| 8485 | |
| 8486 | llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, |
| 8487 | bool ForEH) { |
| 8488 | // Return a bogus pointer if RTTI is disabled, unless it's for EH. |
| 8489 | // FIXME: should we even be calling this method if RTTI is disabled |
| 8490 | // and it's not for EH? |
| 8491 | if (!shouldEmitRTTI(ForEH)) |
| 8492 | return llvm::Constant::getNullValue(Ty: GlobalsInt8PtrTy); |
| 8493 | |
| 8494 | if (ForEH && Ty->isObjCObjectPointerType() && |
| 8495 | LangOpts.ObjCRuntime.isGNUFamily()) |
| 8496 | return ObjCRuntime->GetEHType(T: Ty); |
| 8497 | |
| 8498 | return getCXXABI().getAddrOfRTTIDescriptor(Ty); |
| 8499 | } |
| 8500 | |
| 8501 | void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { |
| 8502 | // Do not emit threadprivates in simd-only mode. |
| 8503 | if (LangOpts.OpenMP && LangOpts.OpenMPSimd) |
| 8504 | return; |
| 8505 | for (auto RefExpr : D->varlist()) { |
| 8506 | auto *VD = cast<VarDecl>(Val: cast<DeclRefExpr>(Val: RefExpr)->getDecl()); |
| 8507 | bool PerformInit = |
| 8508 | VD->getAnyInitializer() && |
| 8509 | !VD->getAnyInitializer()->isConstantInitializer(Ctx&: getContext()); |
| 8510 | |
| 8511 | Address Addr(GetAddrOfGlobalVar(D: VD), |
| 8512 | getTypes().ConvertTypeForMem(T: VD->getType()), |
| 8513 | getContext().getDeclAlign(D: VD)); |
| 8514 | if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( |
| 8515 | VD, VDAddr: Addr, Loc: RefExpr->getBeginLoc(), PerformInit)) |
| 8516 | CXXGlobalInits.push_back(x: InitFunction); |
| 8517 | } |
| 8518 | } |
| 8519 | |
| 8520 | llvm::Metadata * |
| 8521 | CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, |
| 8522 | StringRef Suffix) { |
| 8523 | if (auto *FnType = T->getAs<FunctionProtoType>()) |
| 8524 | T = getContext().getFunctionType( |
| 8525 | ResultTy: FnType->getReturnType(), Args: FnType->getParamTypes(), |
| 8526 | EPI: FnType->getExtProtoInfo().withExceptionSpec(ESI: EST_None)); |
| 8527 | |
| 8528 | llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; |
| 8529 | if (InternalId) |
| 8530 | return InternalId; |
| 8531 | |
| 8532 | if (isExternallyVisible(L: T->getLinkage())) { |
| 8533 | std::string OutName; |
| 8534 | llvm::raw_string_ostream Out(OutName); |
| 8535 | getCXXABI().getMangleContext().mangleCanonicalTypeName( |
| 8536 | T, Out, NormalizeIntegers: getCodeGenOpts().SanitizeCfiICallNormalizeIntegers); |
| 8537 | |
| 8538 | if (getCodeGenOpts().SanitizeCfiICallNormalizeIntegers) |
| 8539 | Out << ".normalized" ; |
| 8540 | |
| 8541 | Out << Suffix; |
| 8542 | |
| 8543 | InternalId = llvm::MDString::get(Context&: getLLVMContext(), Str: Out.str()); |
| 8544 | } else { |
| 8545 | InternalId = llvm::MDNode::getDistinct(Context&: getLLVMContext(), |
| 8546 | MDs: llvm::ArrayRef<llvm::Metadata *>()); |
| 8547 | } |
| 8548 | |
| 8549 | return InternalId; |
| 8550 | } |
| 8551 | |
| 8552 | llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForFnType(QualType T) { |
| 8553 | assert(isa<FunctionType>(T)); |
| 8554 | T = GeneralizeFunctionType( |
| 8555 | Ctx&: getContext(), Ty: T, GeneralizePointers: getCodeGenOpts().SanitizeCfiICallGeneralizePointers); |
| 8556 | if (getCodeGenOpts().SanitizeCfiICallGeneralizePointers) |
| 8557 | return CreateMetadataIdentifierGeneralized(T); |
| 8558 | return CreateMetadataIdentifierForType(T); |
| 8559 | } |
| 8560 | |
| 8561 | llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { |
| 8562 | return CreateMetadataIdentifierImpl(T, Map&: MetadataIdMap, Suffix: "" ); |
| 8563 | } |
| 8564 | |
| 8565 | llvm::Metadata * |
| 8566 | CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { |
| 8567 | return CreateMetadataIdentifierImpl(T, Map&: VirtualMetadataIdMap, Suffix: ".virtual" ); |
| 8568 | } |
| 8569 | |
| 8570 | llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { |
| 8571 | return CreateMetadataIdentifierImpl(T, Map&: GeneralizedMetadataIdMap, |
| 8572 | Suffix: ".generalized" ); |
| 8573 | } |
| 8574 | |
| 8575 | /// Returns whether this module needs the "all-vtables" type identifier. |
| 8576 | bool CodeGenModule::NeedAllVtablesTypeId() const { |
| 8577 | // Returns true if at least one of vtable-based CFI checkers is enabled and |
| 8578 | // is not in the trapping mode. |
| 8579 | return ((LangOpts.Sanitize.has(K: SanitizerKind::CFIVCall) && |
| 8580 | !CodeGenOpts.SanitizeTrap.has(K: SanitizerKind::CFIVCall)) || |
| 8581 | (LangOpts.Sanitize.has(K: SanitizerKind::CFINVCall) && |
| 8582 | !CodeGenOpts.SanitizeTrap.has(K: SanitizerKind::CFINVCall)) || |
| 8583 | (LangOpts.Sanitize.has(K: SanitizerKind::CFIDerivedCast) && |
| 8584 | !CodeGenOpts.SanitizeTrap.has(K: SanitizerKind::CFIDerivedCast)) || |
| 8585 | (LangOpts.Sanitize.has(K: SanitizerKind::CFIUnrelatedCast) && |
| 8586 | !CodeGenOpts.SanitizeTrap.has(K: SanitizerKind::CFIUnrelatedCast))); |
| 8587 | } |
| 8588 | |
| 8589 | void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, |
| 8590 | CharUnits Offset, |
| 8591 | const CXXRecordDecl *RD) { |
| 8592 | CanQualType T = getContext().getCanonicalTagType(TD: RD); |
| 8593 | llvm::Metadata *MD = CreateMetadataIdentifierForType(T); |
| 8594 | VTable->addTypeMetadata(Offset: Offset.getQuantity(), TypeID: MD); |
| 8595 | |
| 8596 | if (CodeGenOpts.SanitizeCfiCrossDso) |
| 8597 | if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) |
| 8598 | VTable->addTypeMetadata(Offset: Offset.getQuantity(), |
| 8599 | TypeID: llvm::ConstantAsMetadata::get(C: CrossDsoTypeId)); |
| 8600 | |
| 8601 | if (NeedAllVtablesTypeId()) { |
| 8602 | llvm::Metadata *MD = llvm::MDString::get(Context&: getLLVMContext(), Str: "all-vtables" ); |
| 8603 | VTable->addTypeMetadata(Offset: Offset.getQuantity(), TypeID: MD); |
| 8604 | } |
| 8605 | } |
| 8606 | |
| 8607 | llvm::SanitizerStatReport &CodeGenModule::getSanStats() { |
| 8608 | if (!SanStats) |
| 8609 | SanStats = std::make_unique<llvm::SanitizerStatReport>(args: &getModule()); |
| 8610 | |
| 8611 | return *SanStats; |
| 8612 | } |
| 8613 | |
| 8614 | llvm::Value * |
| 8615 | CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, |
| 8616 | CodeGenFunction &CGF) { |
| 8617 | llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, T: E->getType()); |
| 8618 | auto *SamplerT = getOpenCLRuntime().getSamplerType(T: E->getType().getTypePtr()); |
| 8619 | auto *FTy = llvm::FunctionType::get(Result: SamplerT, Params: {C->getType()}, isVarArg: false); |
| 8620 | auto *Call = CGF.EmitRuntimeCall( |
| 8621 | callee: CreateRuntimeFunction(FTy, Name: "__translate_sampler_initializer" ), args: {C}); |
| 8622 | return Call; |
| 8623 | } |
| 8624 | |
| 8625 | CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( |
| 8626 | QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { |
| 8627 | return getNaturalTypeAlignment(T: T->getPointeeType(), BaseInfo, TBAAInfo, |
| 8628 | /* forPointeeType= */ true); |
| 8629 | } |
| 8630 | |
| 8631 | CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, |
| 8632 | LValueBaseInfo *BaseInfo, |
| 8633 | TBAAAccessInfo *TBAAInfo, |
| 8634 | bool forPointeeType) { |
| 8635 | if (TBAAInfo) |
| 8636 | *TBAAInfo = getTBAAAccessInfo(AccessType: T); |
| 8637 | |
| 8638 | // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But |
| 8639 | // that doesn't return the information we need to compute BaseInfo. |
| 8640 | |
| 8641 | // Honor alignment typedef attributes even on incomplete types. |
| 8642 | // We also honor them straight for C++ class types, even as pointees; |
| 8643 | // there's an expressivity gap here. |
| 8644 | if (auto TT = T->getAs<TypedefType>()) { |
| 8645 | if (auto Align = TT->getDecl()->getMaxAlignment()) { |
| 8646 | if (BaseInfo) |
| 8647 | *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); |
| 8648 | return getContext().toCharUnitsFromBits(BitSize: Align); |
| 8649 | } |
| 8650 | } |
| 8651 | |
| 8652 | bool AlignForArray = T->isArrayType(); |
| 8653 | |
| 8654 | // Analyze the base element type, so we don't get confused by incomplete |
| 8655 | // array types. |
| 8656 | T = getContext().getBaseElementType(QT: T); |
| 8657 | |
| 8658 | if (T->isIncompleteType()) { |
| 8659 | // We could try to replicate the logic from |
| 8660 | // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the |
| 8661 | // type is incomplete, so it's impossible to test. We could try to reuse |
| 8662 | // getTypeAlignIfKnown, but that doesn't return the information we need |
| 8663 | // to set BaseInfo. So just ignore the possibility that the alignment is |
| 8664 | // greater than one. |
| 8665 | if (BaseInfo) |
| 8666 | *BaseInfo = LValueBaseInfo(AlignmentSource::Type); |
| 8667 | return CharUnits::One(); |
| 8668 | } |
| 8669 | |
| 8670 | if (BaseInfo) |
| 8671 | *BaseInfo = LValueBaseInfo(AlignmentSource::Type); |
| 8672 | |
| 8673 | CharUnits Alignment; |
| 8674 | const CXXRecordDecl *RD; |
| 8675 | if (T.getQualifiers().hasUnaligned()) { |
| 8676 | Alignment = CharUnits::One(); |
| 8677 | } else if (forPointeeType && !AlignForArray && |
| 8678 | (RD = T->getAsCXXRecordDecl())) { |
| 8679 | // For C++ class pointees, we don't know whether we're pointing at a |
| 8680 | // base or a complete object, so we generally need to use the |
| 8681 | // non-virtual alignment. |
| 8682 | Alignment = getClassPointerAlignment(CD: RD); |
| 8683 | } else { |
| 8684 | Alignment = getContext().getTypeAlignInChars(T); |
| 8685 | } |
| 8686 | |
| 8687 | // Cap to the global maximum type alignment unless the alignment |
| 8688 | // was somehow explicit on the type. |
| 8689 | if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { |
| 8690 | if (Alignment.getQuantity() > MaxAlign && |
| 8691 | !getContext().isAlignmentRequired(T)) |
| 8692 | Alignment = CharUnits::fromQuantity(Quantity: MaxAlign); |
| 8693 | } |
| 8694 | return Alignment; |
| 8695 | } |
| 8696 | |
| 8697 | bool CodeGenModule::stopAutoInit() { |
| 8698 | unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; |
| 8699 | if (StopAfter) { |
| 8700 | // This number is positive only when -ftrivial-auto-var-init-stop-after=* is |
| 8701 | // used |
| 8702 | if (NumAutoVarInit >= StopAfter) { |
| 8703 | return true; |
| 8704 | } |
| 8705 | if (!NumAutoVarInit) { |
| 8706 | getDiags().Report(DiagID: diag::warn_trivial_auto_var_limit) |
| 8707 | << StopAfter |
| 8708 | << (getContext().getLangOpts().getTrivialAutoVarInit() == |
| 8709 | LangOptions::TrivialAutoVarInitKind::Zero |
| 8710 | ? "zero" |
| 8711 | : "pattern" ); |
| 8712 | } |
| 8713 | ++NumAutoVarInit; |
| 8714 | } |
| 8715 | return false; |
| 8716 | } |
| 8717 | |
| 8718 | void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, |
| 8719 | const Decl *D) const { |
| 8720 | // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers |
| 8721 | // postfix beginning with '.' since the symbol name can be demangled. |
| 8722 | if (LangOpts.HIP) |
| 8723 | OS << (isa<VarDecl>(Val: D) ? ".static." : ".intern." ); |
| 8724 | else |
| 8725 | OS << (isa<VarDecl>(Val: D) ? "__static__" : "__intern__" ); |
| 8726 | |
| 8727 | // If the CUID is not specified we try to generate a unique postfix. |
| 8728 | if (getLangOpts().CUID.empty()) { |
| 8729 | SourceManager &SM = getContext().getSourceManager(); |
| 8730 | PresumedLoc PLoc = SM.getPresumedLoc(Loc: D->getLocation()); |
| 8731 | assert(PLoc.isValid() && "Source location is expected to be valid." ); |
| 8732 | |
| 8733 | // Get the hash of the user defined macros. |
| 8734 | llvm::MD5 Hash; |
| 8735 | llvm::MD5::MD5Result Result; |
| 8736 | for (const auto &Arg : PreprocessorOpts.Macros) |
| 8737 | Hash.update(Str: Arg.first); |
| 8738 | Hash.final(Result); |
| 8739 | |
| 8740 | // Get the UniqueID for the file containing the decl. |
| 8741 | llvm::sys::fs::UniqueID ID; |
| 8742 | auto Status = FS->status(Path: PLoc.getFilename()); |
| 8743 | if (!Status) { |
| 8744 | PLoc = SM.getPresumedLoc(Loc: D->getLocation(), /*UseLineDirectives=*/false); |
| 8745 | assert(PLoc.isValid() && "Source location is expected to be valid." ); |
| 8746 | Status = FS->status(Path: PLoc.getFilename()); |
| 8747 | } |
| 8748 | if (!Status) { |
| 8749 | SM.getDiagnostics().Report(DiagID: diag::err_cannot_open_file) |
| 8750 | << PLoc.getFilename() << Status.getError().message(); |
| 8751 | } else { |
| 8752 | ID = Status->getUniqueID(); |
| 8753 | } |
| 8754 | OS << llvm::format(Fmt: "%x" , Vals: ID.getFile()) << llvm::format(Fmt: "%x" , Vals: ID.getDevice()) |
| 8755 | << "_" << llvm::utohexstr(X: Result.low(), /*LowerCase=*/true, /*Width=*/8); |
| 8756 | } else { |
| 8757 | OS << getContext().getCUIDHash(); |
| 8758 | } |
| 8759 | } |
| 8760 | |
| 8761 | void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) { |
| 8762 | assert(DeferredDeclsToEmit.empty() && |
| 8763 | "Should have emitted all decls deferred to emit." ); |
| 8764 | assert(NewBuilder->DeferredDecls.empty() && |
| 8765 | "Newly created module should not have deferred decls" ); |
| 8766 | NewBuilder->DeferredDecls = std::move(DeferredDecls); |
| 8767 | assert(EmittedDeferredDecls.empty() && |
| 8768 | "Still have (unmerged) EmittedDeferredDecls deferred decls" ); |
| 8769 | |
| 8770 | assert(NewBuilder->DeferredVTables.empty() && |
| 8771 | "Newly created module should not have deferred vtables" ); |
| 8772 | NewBuilder->DeferredVTables = std::move(DeferredVTables); |
| 8773 | |
| 8774 | assert(NewBuilder->EmittedVTables.empty() && |
| 8775 | "Newly created module should not have defined vtables" ); |
| 8776 | NewBuilder->EmittedVTables = std::move(EmittedVTables); |
| 8777 | |
| 8778 | assert(NewBuilder->MangledDeclNames.empty() && |
| 8779 | "Newly created module should not have mangled decl names" ); |
| 8780 | assert(NewBuilder->Manglings.empty() && |
| 8781 | "Newly created module should not have manglings" ); |
| 8782 | NewBuilder->Manglings = std::move(Manglings); |
| 8783 | |
| 8784 | NewBuilder->WeakRefReferences = std::move(WeakRefReferences); |
| 8785 | |
| 8786 | NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx); |
| 8787 | } |
| 8788 | |
| 8789 | std::string CodeGenModule::getPFPFieldName(const FieldDecl *FD) { |
| 8790 | std::string OutName; |
| 8791 | llvm::raw_string_ostream Out(OutName); |
| 8792 | getCXXABI().getMangleContext().mangleCanonicalTypeName( |
| 8793 | T: getContext().getCanonicalTagType(TD: FD->getParent()), Out, NormalizeIntegers: false); |
| 8794 | Out << "." << FD->getName(); |
| 8795 | return OutName; |
| 8796 | } |
| 8797 | |
| 8798 | bool CodeGenModule::classNeedsVectorDestructor(const CXXRecordDecl *RD) { |
| 8799 | if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts())) |
| 8800 | return false; |
| 8801 | CXXDestructorDecl *Dtor = RD->getDestructor(); |
| 8802 | // The compiler can't know if new[]/delete[] will be used outside of the DLL, |
| 8803 | // so just force vector deleting destructor emission if dllexport is present. |
| 8804 | // This matches MSVC behavior. |
| 8805 | if (Dtor && Dtor->isVirtual() && Dtor->hasAttr<DLLExportAttr>()) |
| 8806 | return true; |
| 8807 | |
| 8808 | return RequireVectorDeletingDtor.count(Ptr: RD); |
| 8809 | } |
| 8810 | |
| 8811 | void CodeGenModule::requireVectorDestructorDefinition(const CXXRecordDecl *RD) { |
| 8812 | if (!Context.getTargetInfo().emitVectorDeletingDtors(Context.getLangOpts())) |
| 8813 | return; |
| 8814 | RequireVectorDeletingDtor.insert(Ptr: RD); |
| 8815 | |
| 8816 | // To reduce code size in general case we lazily emit scalar deleting |
| 8817 | // destructor definition and an alias from vector deleting destructor to |
| 8818 | // scalar deleting destructor. It may happen that we first emitted the scalar |
| 8819 | // deleting destructor definition and the alias and then discovered that the |
| 8820 | // definition of the vector deleting destructor is required. Then we need to |
| 8821 | // remove the alias and the scalar deleting destructor and queue vector |
| 8822 | // deleting destructor body for emission. Check if that is the case. |
| 8823 | CXXDestructorDecl *DtorD = RD->getDestructor(); |
| 8824 | GlobalDecl ScalarDtorGD(DtorD, Dtor_Deleting); |
| 8825 | StringRef MangledName = getMangledName(GD: ScalarDtorGD); |
| 8826 | llvm::GlobalValue *Entry = GetGlobalValue(Name: MangledName); |
| 8827 | GlobalDecl VectorDtorGD(DtorD, Dtor_VectorDeleting); |
| 8828 | if (Entry && !Entry->isDeclaration()) { |
| 8829 | StringRef VDName = getMangledName(GD: VectorDtorGD); |
| 8830 | llvm::GlobalValue *VDEntry = GetGlobalValue(Name: VDName); |
| 8831 | // It exists and it should be an alias. |
| 8832 | assert(VDEntry && isa<llvm::GlobalAlias>(VDEntry)); |
| 8833 | auto *NewFn = llvm::Function::Create( |
| 8834 | Ty: cast<llvm::FunctionType>(Val: VDEntry->getValueType()), |
| 8835 | Linkage: llvm::Function::ExternalLinkage, N: VDName, M: &getModule()); |
| 8836 | SetFunctionAttributes(GD: VectorDtorGD, F: NewFn, /*IsIncompleteFunction*/ false, |
| 8837 | /*IsThunk*/ false); |
| 8838 | NewFn->takeName(V: VDEntry); |
| 8839 | VDEntry->replaceAllUsesWith(V: NewFn); |
| 8840 | VDEntry->eraseFromParent(); |
| 8841 | Entry->replaceAllUsesWith(V: NewFn); |
| 8842 | Entry->eraseFromParent(); |
| 8843 | } |
| 8844 | // Always add a deferred decl to emit once we confirmed that vector deleting |
| 8845 | // destructor definition is required. That helps to enforse its generation |
| 8846 | // even if destructor is only declared. |
| 8847 | addDeferredDeclToEmit(GD: VectorDtorGD); |
| 8848 | } |
| 8849 | |