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