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