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 = Target.parseTargetAttr(Attr->getFeaturesStr()); 1337 llvm::sort(Info.Features, [&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.CPU.empty()) { 1349 IsFirst = false; 1350 Out << "arch_" << Info.CPU; 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 = 2175 Target.parseTargetAttr(TD->getFeaturesStr()); 2176 if (!ParsedAttr.CPU.empty() && 2177 getTarget().isValidCPUName(ParsedAttr.CPU)) { 2178 TargetCPU = ParsedAttr.CPU; 2179 TuneCPU = ""; // Clear the tune CPU. 2180 } 2181 if (!ParsedAttr.Tune.empty() && 2182 getTarget().isValidCPUName(ParsedAttr.Tune)) 2183 TuneCPU = ParsedAttr.Tune; 2184 } 2185 2186 if (SD) { 2187 // Apply the given CPU name as the 'tune-cpu' so that the optimizer can 2188 // favor this processor. 2189 TuneCPU = getTarget().getCPUSpecificTuneName( 2190 SD->getCPUName(GD.getMultiVersionIndex())->getName()); 2191 } 2192 } else { 2193 // Otherwise just add the existing target cpu and target features to the 2194 // function. 2195 Features = getTarget().getTargetOpts().Features; 2196 } 2197 2198 if (!TargetCPU.empty()) { 2199 Attrs.addAttribute("target-cpu", TargetCPU); 2200 AddedAttr = true; 2201 } 2202 if (!TuneCPU.empty()) { 2203 Attrs.addAttribute("tune-cpu", TuneCPU); 2204 AddedAttr = true; 2205 } 2206 if (!Features.empty()) { 2207 llvm::sort(Features); 2208 Attrs.addAttribute("target-features", llvm::join(Features, ",")); 2209 AddedAttr = true; 2210 } 2211 2212 return AddedAttr; 2213 } 2214 2215 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 2216 llvm::GlobalObject *GO) { 2217 const Decl *D = GD.getDecl(); 2218 SetCommonAttributes(GD, GO); 2219 2220 if (D) { 2221 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 2222 if (D->hasAttr<RetainAttr>()) 2223 addUsedGlobal(GV); 2224 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 2225 GV->addAttribute("bss-section", SA->getName()); 2226 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 2227 GV->addAttribute("data-section", SA->getName()); 2228 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 2229 GV->addAttribute("rodata-section", SA->getName()); 2230 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 2231 GV->addAttribute("relro-section", SA->getName()); 2232 } 2233 2234 if (auto *F = dyn_cast<llvm::Function>(GO)) { 2235 if (D->hasAttr<RetainAttr>()) 2236 addUsedGlobal(F); 2237 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 2238 if (!D->getAttr<SectionAttr>()) 2239 F->addFnAttr("implicit-section-name", SA->getName()); 2240 2241 llvm::AttrBuilder Attrs(F->getContext()); 2242 if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 2243 // We know that GetCPUAndFeaturesAttributes will always have the 2244 // newest set, since it has the newest possible FunctionDecl, so the 2245 // new ones should replace the old. 2246 llvm::AttributeMask RemoveAttrs; 2247 RemoveAttrs.addAttribute("target-cpu"); 2248 RemoveAttrs.addAttribute("target-features"); 2249 RemoveAttrs.addAttribute("tune-cpu"); 2250 F->removeFnAttrs(RemoveAttrs); 2251 F->addFnAttrs(Attrs); 2252 } 2253 } 2254 2255 if (const auto *CSA = D->getAttr<CodeSegAttr>()) 2256 GO->setSection(CSA->getName()); 2257 else if (const auto *SA = D->getAttr<SectionAttr>()) 2258 GO->setSection(SA->getName()); 2259 } 2260 2261 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 2262 } 2263 2264 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 2265 llvm::Function *F, 2266 const CGFunctionInfo &FI) { 2267 const Decl *D = GD.getDecl(); 2268 SetLLVMFunctionAttributes(GD, FI, F, /*IsThunk=*/false); 2269 SetLLVMFunctionAttributesForDefinition(D, F); 2270 2271 F->setLinkage(llvm::Function::InternalLinkage); 2272 2273 setNonAliasAttributes(GD, F); 2274 } 2275 2276 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 2277 // Set linkage and visibility in case we never see a definition. 2278 LinkageInfo LV = ND->getLinkageAndVisibility(); 2279 // Don't set internal linkage on declarations. 2280 // "extern_weak" is overloaded in LLVM; we probably should have 2281 // separate linkage types for this. 2282 if (isExternallyVisible(LV.getLinkage()) && 2283 (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 2284 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 2285 } 2286 2287 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 2288 llvm::Function *F) { 2289 // Only if we are checking indirect calls. 2290 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 2291 return; 2292 2293 // Non-static class methods are handled via vtable or member function pointer 2294 // checks elsewhere. 2295 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2296 return; 2297 2298 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 2299 F->addTypeMetadata(0, MD); 2300 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 2301 2302 // Emit a hash-based bit set entry for cross-DSO calls. 2303 if (CodeGenOpts.SanitizeCfiCrossDso) 2304 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 2305 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 2306 } 2307 2308 void CodeGenModule::setKCFIType(const FunctionDecl *FD, llvm::Function *F) { 2309 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 2310 return; 2311 2312 llvm::LLVMContext &Ctx = F->getContext(); 2313 llvm::MDBuilder MDB(Ctx); 2314 F->setMetadata(llvm::LLVMContext::MD_kcfi_type, 2315 llvm::MDNode::get( 2316 Ctx, MDB.createConstant(CreateKCFITypeId(FD->getType())))); 2317 } 2318 2319 static bool allowKCFIIdentifier(StringRef Name) { 2320 // KCFI type identifier constants are only necessary for external assembly 2321 // functions, which means it's safe to skip unusual names. Subset of 2322 // MCAsmInfo::isAcceptableChar() and MCAsmInfoXCOFF::isAcceptableChar(). 2323 return llvm::all_of(Name, [](const char &C) { 2324 return llvm::isAlnum(C) || C == '_' || C == '.'; 2325 }); 2326 } 2327 2328 void CodeGenModule::finalizeKCFITypes() { 2329 llvm::Module &M = getModule(); 2330 for (auto &F : M.functions()) { 2331 // Remove KCFI type metadata from non-address-taken local functions. 2332 bool AddressTaken = F.hasAddressTaken(); 2333 if (!AddressTaken && F.hasLocalLinkage()) 2334 F.eraseMetadata(llvm::LLVMContext::MD_kcfi_type); 2335 2336 // Generate a constant with the expected KCFI type identifier for all 2337 // address-taken function declarations to support annotating indirectly 2338 // called assembly functions. 2339 if (!AddressTaken || !F.isDeclaration()) 2340 continue; 2341 2342 const llvm::ConstantInt *Type; 2343 if (const llvm::MDNode *MD = F.getMetadata(llvm::LLVMContext::MD_kcfi_type)) 2344 Type = llvm::mdconst::extract<llvm::ConstantInt>(MD->getOperand(0)); 2345 else 2346 continue; 2347 2348 StringRef Name = F.getName(); 2349 if (!allowKCFIIdentifier(Name)) 2350 continue; 2351 2352 std::string Asm = (".weak __kcfi_typeid_" + Name + "\n.set __kcfi_typeid_" + 2353 Name + ", " + Twine(Type->getZExtValue()) + "\n") 2354 .str(); 2355 M.appendModuleInlineAsm(Asm); 2356 } 2357 } 2358 2359 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 2360 bool IsIncompleteFunction, 2361 bool IsThunk) { 2362 2363 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 2364 // If this is an intrinsic function, set the function's attributes 2365 // to the intrinsic's attributes. 2366 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 2367 return; 2368 } 2369 2370 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 2371 2372 if (!IsIncompleteFunction) 2373 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F, 2374 IsThunk); 2375 2376 // Add the Returned attribute for "this", except for iOS 5 and earlier 2377 // where substantial code, including the libstdc++ dylib, was compiled with 2378 // GCC and does not actually return "this". 2379 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 2380 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 2381 assert(!F->arg_empty() && 2382 F->arg_begin()->getType() 2383 ->canLosslesslyBitCastTo(F->getReturnType()) && 2384 "unexpected this return"); 2385 F->addParamAttr(0, llvm::Attribute::Returned); 2386 } 2387 2388 // Only a few attributes are set on declarations; these may later be 2389 // overridden by a definition. 2390 2391 setLinkageForGV(F, FD); 2392 setGVProperties(F, FD); 2393 2394 // Setup target-specific attributes. 2395 if (!IsIncompleteFunction && F->isDeclaration()) 2396 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 2397 2398 if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 2399 F->setSection(CSA->getName()); 2400 else if (const auto *SA = FD->getAttr<SectionAttr>()) 2401 F->setSection(SA->getName()); 2402 2403 if (const auto *EA = FD->getAttr<ErrorAttr>()) { 2404 if (EA->isError()) 2405 F->addFnAttr("dontcall-error", EA->getUserDiagnostic()); 2406 else if (EA->isWarning()) 2407 F->addFnAttr("dontcall-warn", EA->getUserDiagnostic()); 2408 } 2409 2410 // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2411 if (FD->isInlineBuiltinDeclaration()) { 2412 const FunctionDecl *FDBody; 2413 bool HasBody = FD->hasBody(FDBody); 2414 (void)HasBody; 2415 assert(HasBody && "Inline builtin declarations should always have an " 2416 "available body!"); 2417 if (shouldEmitFunction(FDBody)) 2418 F->addFnAttr(llvm::Attribute::NoBuiltin); 2419 } 2420 2421 if (FD->isReplaceableGlobalAllocationFunction()) { 2422 // A replaceable global allocation function does not act like a builtin by 2423 // default, only if it is invoked by a new-expression or delete-expression. 2424 F->addFnAttr(llvm::Attribute::NoBuiltin); 2425 } 2426 2427 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 2428 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2429 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 2430 if (MD->isVirtual()) 2431 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2432 2433 // Don't emit entries for function declarations in the cross-DSO mode. This 2434 // is handled with better precision by the receiving DSO. But if jump tables 2435 // are non-canonical then we need type metadata in order to produce the local 2436 // jump table. 2437 if (!CodeGenOpts.SanitizeCfiCrossDso || 2438 !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 2439 CreateFunctionTypeMetadataForIcall(FD, F); 2440 2441 if (LangOpts.Sanitize.has(SanitizerKind::KCFI)) 2442 setKCFIType(FD, F); 2443 2444 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 2445 getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 2446 2447 if (CodeGenOpts.InlineMaxStackSize != UINT_MAX) 2448 F->addFnAttr("inline-max-stacksize", llvm::utostr(CodeGenOpts.InlineMaxStackSize)); 2449 2450 if (const auto *CB = FD->getAttr<CallbackAttr>()) { 2451 // Annotate the callback behavior as metadata: 2452 // - The callback callee (as argument number). 2453 // - The callback payloads (as argument numbers). 2454 llvm::LLVMContext &Ctx = F->getContext(); 2455 llvm::MDBuilder MDB(Ctx); 2456 2457 // The payload indices are all but the first one in the encoding. The first 2458 // identifies the callback callee. 2459 int CalleeIdx = *CB->encoding_begin(); 2460 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 2461 F->addMetadata(llvm::LLVMContext::MD_callback, 2462 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2463 CalleeIdx, PayloadIndices, 2464 /* VarArgsArePassed */ false)})); 2465 } 2466 } 2467 2468 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2469 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2470 "Only globals with definition can force usage."); 2471 LLVMUsed.emplace_back(GV); 2472 } 2473 2474 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 2475 assert(!GV->isDeclaration() && 2476 "Only globals with definition can force usage."); 2477 LLVMCompilerUsed.emplace_back(GV); 2478 } 2479 2480 void CodeGenModule::addUsedOrCompilerUsedGlobal(llvm::GlobalValue *GV) { 2481 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2482 "Only globals with definition can force usage."); 2483 if (getTriple().isOSBinFormatELF()) 2484 LLVMCompilerUsed.emplace_back(GV); 2485 else 2486 LLVMUsed.emplace_back(GV); 2487 } 2488 2489 static void emitUsed(CodeGenModule &CGM, StringRef Name, 2490 std::vector<llvm::WeakTrackingVH> &List) { 2491 // Don't create llvm.used if there is no need. 2492 if (List.empty()) 2493 return; 2494 2495 // Convert List to what ConstantArray needs. 2496 SmallVector<llvm::Constant*, 8> UsedArray; 2497 UsedArray.resize(List.size()); 2498 for (unsigned i = 0, e = List.size(); i != e; ++i) { 2499 UsedArray[i] = 2500 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2501 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2502 } 2503 2504 if (UsedArray.empty()) 2505 return; 2506 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2507 2508 auto *GV = new llvm::GlobalVariable( 2509 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2510 llvm::ConstantArray::get(ATy, UsedArray), Name); 2511 2512 GV->setSection("llvm.metadata"); 2513 } 2514 2515 void CodeGenModule::emitLLVMUsed() { 2516 emitUsed(*this, "llvm.used", LLVMUsed); 2517 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2518 } 2519 2520 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2521 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2522 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2523 } 2524 2525 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2526 llvm::SmallString<32> Opt; 2527 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2528 if (Opt.empty()) 2529 return; 2530 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2531 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2532 } 2533 2534 void CodeGenModule::AddDependentLib(StringRef Lib) { 2535 auto &C = getLLVMContext(); 2536 if (getTarget().getTriple().isOSBinFormatELF()) { 2537 ELFDependentLibraries.push_back( 2538 llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2539 return; 2540 } 2541 2542 llvm::SmallString<24> Opt; 2543 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2544 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2545 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2546 } 2547 2548 /// Add link options implied by the given module, including modules 2549 /// it depends on, using a postorder walk. 2550 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2551 SmallVectorImpl<llvm::MDNode *> &Metadata, 2552 llvm::SmallPtrSet<Module *, 16> &Visited) { 2553 // Import this module's parent. 2554 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2555 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2556 } 2557 2558 // Import this module's dependencies. 2559 for (Module *Import : llvm::reverse(Mod->Imports)) { 2560 if (Visited.insert(Import).second) 2561 addLinkOptionsPostorder(CGM, Import, Metadata, Visited); 2562 } 2563 2564 // Add linker options to link against the libraries/frameworks 2565 // described by this module. 2566 llvm::LLVMContext &Context = CGM.getLLVMContext(); 2567 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 2568 2569 // For modules that use export_as for linking, use that module 2570 // name instead. 2571 if (Mod->UseExportAsModuleLinkName) 2572 return; 2573 2574 for (const Module::LinkLibrary &LL : llvm::reverse(Mod->LinkLibraries)) { 2575 // Link against a framework. Frameworks are currently Darwin only, so we 2576 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2577 if (LL.IsFramework) { 2578 llvm::Metadata *Args[2] = {llvm::MDString::get(Context, "-framework"), 2579 llvm::MDString::get(Context, LL.Library)}; 2580 2581 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2582 continue; 2583 } 2584 2585 // Link against a library. 2586 if (IsELF) { 2587 llvm::Metadata *Args[2] = { 2588 llvm::MDString::get(Context, "lib"), 2589 llvm::MDString::get(Context, LL.Library), 2590 }; 2591 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2592 } else { 2593 llvm::SmallString<24> Opt; 2594 CGM.getTargetCodeGenInfo().getDependentLibraryOption(LL.Library, Opt); 2595 auto *OptString = llvm::MDString::get(Context, Opt); 2596 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2597 } 2598 } 2599 } 2600 2601 void CodeGenModule::EmitModuleInitializers(clang::Module *Primary) { 2602 // Emit the initializers in the order that sub-modules appear in the 2603 // source, first Global Module Fragments, if present. 2604 if (auto GMF = Primary->getGlobalModuleFragment()) { 2605 for (Decl *D : getContext().getModuleInitializers(GMF)) { 2606 if (isa<ImportDecl>(D)) 2607 continue; 2608 assert(isa<VarDecl>(D) && "GMF initializer decl is not a var?"); 2609 EmitTopLevelDecl(D); 2610 } 2611 } 2612 // Second any associated with the module, itself. 2613 for (Decl *D : getContext().getModuleInitializers(Primary)) { 2614 // Skip import decls, the inits for those are called explicitly. 2615 if (isa<ImportDecl>(D)) 2616 continue; 2617 EmitTopLevelDecl(D); 2618 } 2619 // Third any associated with the Privat eMOdule Fragment, if present. 2620 if (auto PMF = Primary->getPrivateModuleFragment()) { 2621 for (Decl *D : getContext().getModuleInitializers(PMF)) { 2622 assert(isa<VarDecl>(D) && "PMF initializer decl is not a var?"); 2623 EmitTopLevelDecl(D); 2624 } 2625 } 2626 } 2627 2628 void CodeGenModule::EmitModuleLinkOptions() { 2629 // Collect the set of all of the modules we want to visit to emit link 2630 // options, which is essentially the imported modules and all of their 2631 // non-explicit child modules. 2632 llvm::SetVector<clang::Module *> LinkModules; 2633 llvm::SmallPtrSet<clang::Module *, 16> Visited; 2634 SmallVector<clang::Module *, 16> Stack; 2635 2636 // Seed the stack with imported modules. 2637 for (Module *M : ImportedModules) { 2638 // Do not add any link flags when an implementation TU of a module imports 2639 // a header of that same module. 2640 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 2641 !getLangOpts().isCompilingModule()) 2642 continue; 2643 if (Visited.insert(M).second) 2644 Stack.push_back(M); 2645 } 2646 2647 // Find all of the modules to import, making a little effort to prune 2648 // non-leaf modules. 2649 while (!Stack.empty()) { 2650 clang::Module *Mod = Stack.pop_back_val(); 2651 2652 bool AnyChildren = false; 2653 2654 // Visit the submodules of this module. 2655 for (const auto &SM : Mod->submodules()) { 2656 // Skip explicit children; they need to be explicitly imported to be 2657 // linked against. 2658 if (SM->IsExplicit) 2659 continue; 2660 2661 if (Visited.insert(SM).second) { 2662 Stack.push_back(SM); 2663 AnyChildren = true; 2664 } 2665 } 2666 2667 // We didn't find any children, so add this module to the list of 2668 // modules to link against. 2669 if (!AnyChildren) { 2670 LinkModules.insert(Mod); 2671 } 2672 } 2673 2674 // Add link options for all of the imported modules in reverse topological 2675 // order. We don't do anything to try to order import link flags with respect 2676 // to linker options inserted by things like #pragma comment(). 2677 SmallVector<llvm::MDNode *, 16> MetadataArgs; 2678 Visited.clear(); 2679 for (Module *M : LinkModules) 2680 if (Visited.insert(M).second) 2681 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 2682 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 2683 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 2684 2685 // Add the linker options metadata flag. 2686 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 2687 for (auto *MD : LinkerOptionsMetadata) 2688 NMD->addOperand(MD); 2689 } 2690 2691 void CodeGenModule::EmitDeferred() { 2692 // Emit deferred declare target declarations. 2693 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 2694 getOpenMPRuntime().emitDeferredTargetDecls(); 2695 2696 // Emit code for any potentially referenced deferred decls. Since a 2697 // previously unused static decl may become used during the generation of code 2698 // for a static function, iterate until no changes are made. 2699 2700 if (!DeferredVTables.empty()) { 2701 EmitDeferredVTables(); 2702 2703 // Emitting a vtable doesn't directly cause more vtables to 2704 // become deferred, although it can cause functions to be 2705 // emitted that then need those vtables. 2706 assert(DeferredVTables.empty()); 2707 } 2708 2709 // Emit CUDA/HIP static device variables referenced by host code only. 2710 // Note we should not clear CUDADeviceVarODRUsedByHost since it is still 2711 // needed for further handling. 2712 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) 2713 llvm::append_range(DeferredDeclsToEmit, 2714 getContext().CUDADeviceVarODRUsedByHost); 2715 2716 // Stop if we're out of both deferred vtables and deferred declarations. 2717 if (DeferredDeclsToEmit.empty()) 2718 return; 2719 2720 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 2721 // work, it will not interfere with this. 2722 std::vector<GlobalDecl> CurDeclsToEmit; 2723 CurDeclsToEmit.swap(DeferredDeclsToEmit); 2724 2725 for (GlobalDecl &D : CurDeclsToEmit) { 2726 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 2727 // to get GlobalValue with exactly the type we need, not something that 2728 // might had been created for another decl with the same mangled name but 2729 // different type. 2730 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 2731 GetAddrOfGlobal(D, ForDefinition)); 2732 2733 // In case of different address spaces, we may still get a cast, even with 2734 // IsForDefinition equal to true. Query mangled names table to get 2735 // GlobalValue. 2736 if (!GV) 2737 GV = GetGlobalValue(getMangledName(D)); 2738 2739 // Make sure GetGlobalValue returned non-null. 2740 assert(GV); 2741 2742 // Check to see if we've already emitted this. This is necessary 2743 // for a couple of reasons: first, decls can end up in the 2744 // deferred-decls queue multiple times, and second, decls can end 2745 // up with definitions in unusual ways (e.g. by an extern inline 2746 // function acquiring a strong function redefinition). Just 2747 // ignore these cases. 2748 if (!GV->isDeclaration()) 2749 continue; 2750 2751 // If this is OpenMP, check if it is legal to emit this global normally. 2752 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2753 continue; 2754 2755 // Otherwise, emit the definition and move on to the next one. 2756 EmitGlobalDefinition(D, GV); 2757 2758 // If we found out that we need to emit more decls, do that recursively. 2759 // This has the advantage that the decls are emitted in a DFS and related 2760 // ones are close together, which is convenient for testing. 2761 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 2762 EmitDeferred(); 2763 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 2764 } 2765 } 2766 } 2767 2768 void CodeGenModule::EmitVTablesOpportunistically() { 2769 // Try to emit external vtables as available_externally if they have emitted 2770 // all inlined virtual functions. It runs after EmitDeferred() and therefore 2771 // is not allowed to create new references to things that need to be emitted 2772 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 2773 2774 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 2775 && "Only emit opportunistic vtables with optimizations"); 2776 2777 for (const CXXRecordDecl *RD : OpportunisticVTables) { 2778 assert(getVTables().isVTableExternal(RD) && 2779 "This queue should only contain external vtables"); 2780 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 2781 VTables.GenerateClassData(RD); 2782 } 2783 OpportunisticVTables.clear(); 2784 } 2785 2786 void CodeGenModule::EmitGlobalAnnotations() { 2787 if (Annotations.empty()) 2788 return; 2789 2790 // Create a new global variable for the ConstantStruct in the Module. 2791 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 2792 Annotations[0]->getType(), Annotations.size()), Annotations); 2793 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 2794 llvm::GlobalValue::AppendingLinkage, 2795 Array, "llvm.global.annotations"); 2796 gv->setSection(AnnotationSection); 2797 } 2798 2799 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 2800 llvm::Constant *&AStr = AnnotationStrings[Str]; 2801 if (AStr) 2802 return AStr; 2803 2804 // Not found yet, create a new global. 2805 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2806 auto *gv = 2807 new llvm::GlobalVariable(getModule(), s->getType(), true, 2808 llvm::GlobalValue::PrivateLinkage, s, ".str"); 2809 gv->setSection(AnnotationSection); 2810 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2811 AStr = gv; 2812 return gv; 2813 } 2814 2815 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 2816 SourceManager &SM = getContext().getSourceManager(); 2817 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2818 if (PLoc.isValid()) 2819 return EmitAnnotationString(PLoc.getFilename()); 2820 return EmitAnnotationString(SM.getBufferName(Loc)); 2821 } 2822 2823 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 2824 SourceManager &SM = getContext().getSourceManager(); 2825 PresumedLoc PLoc = SM.getPresumedLoc(L); 2826 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 2827 SM.getExpansionLineNumber(L); 2828 return llvm::ConstantInt::get(Int32Ty, LineNo); 2829 } 2830 2831 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 2832 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 2833 if (Exprs.empty()) 2834 return llvm::ConstantPointerNull::get(GlobalsInt8PtrTy); 2835 2836 llvm::FoldingSetNodeID ID; 2837 for (Expr *E : Exprs) { 2838 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 2839 } 2840 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 2841 if (Lookup) 2842 return Lookup; 2843 2844 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 2845 LLVMArgs.reserve(Exprs.size()); 2846 ConstantEmitter ConstEmiter(*this); 2847 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 2848 const auto *CE = cast<clang::ConstantExpr>(E); 2849 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 2850 CE->getType()); 2851 }); 2852 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 2853 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 2854 llvm::GlobalValue::PrivateLinkage, Struct, 2855 ".args"); 2856 GV->setSection(AnnotationSection); 2857 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2858 auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, GlobalsInt8PtrTy); 2859 2860 Lookup = Bitcasted; 2861 return Bitcasted; 2862 } 2863 2864 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 2865 const AnnotateAttr *AA, 2866 SourceLocation L) { 2867 // Get the globals for file name, annotation, and the line number. 2868 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 2869 *UnitGV = EmitAnnotationUnit(L), 2870 *LineNoCst = EmitAnnotationLineNo(L), 2871 *Args = EmitAnnotationArgs(AA); 2872 2873 llvm::Constant *GVInGlobalsAS = GV; 2874 if (GV->getAddressSpace() != 2875 getDataLayout().getDefaultGlobalsAddressSpace()) { 2876 GVInGlobalsAS = llvm::ConstantExpr::getAddrSpaceCast( 2877 GV, GV->getValueType()->getPointerTo( 2878 getDataLayout().getDefaultGlobalsAddressSpace())); 2879 } 2880 2881 // Create the ConstantStruct for the global annotation. 2882 llvm::Constant *Fields[] = { 2883 llvm::ConstantExpr::getBitCast(GVInGlobalsAS, GlobalsInt8PtrTy), 2884 llvm::ConstantExpr::getBitCast(AnnoGV, GlobalsInt8PtrTy), 2885 llvm::ConstantExpr::getBitCast(UnitGV, GlobalsInt8PtrTy), 2886 LineNoCst, 2887 Args, 2888 }; 2889 return llvm::ConstantStruct::getAnon(Fields); 2890 } 2891 2892 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 2893 llvm::GlobalValue *GV) { 2894 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2895 // Get the struct elements for these annotations. 2896 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2897 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 2898 } 2899 2900 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, llvm::Function *Fn, 2901 SourceLocation Loc) const { 2902 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2903 // NoSanitize by function name. 2904 if (NoSanitizeL.containsFunction(Kind, Fn->getName())) 2905 return true; 2906 // NoSanitize by location. Check "mainfile" prefix. 2907 auto &SM = Context.getSourceManager(); 2908 const FileEntry &MainFile = *SM.getFileEntryForID(SM.getMainFileID()); 2909 if (NoSanitizeL.containsMainFile(Kind, MainFile.getName())) 2910 return true; 2911 2912 // Check "src" prefix. 2913 if (Loc.isValid()) 2914 return NoSanitizeL.containsLocation(Kind, Loc); 2915 // If location is unknown, this may be a compiler-generated function. Assume 2916 // it's located in the main file. 2917 return NoSanitizeL.containsFile(Kind, MainFile.getName()); 2918 } 2919 2920 bool CodeGenModule::isInNoSanitizeList(SanitizerMask Kind, 2921 llvm::GlobalVariable *GV, 2922 SourceLocation Loc, QualType Ty, 2923 StringRef Category) const { 2924 const auto &NoSanitizeL = getContext().getNoSanitizeList(); 2925 if (NoSanitizeL.containsGlobal(Kind, GV->getName(), Category)) 2926 return true; 2927 auto &SM = Context.getSourceManager(); 2928 if (NoSanitizeL.containsMainFile( 2929 Kind, SM.getFileEntryForID(SM.getMainFileID())->getName(), Category)) 2930 return true; 2931 if (NoSanitizeL.containsLocation(Kind, Loc, Category)) 2932 return true; 2933 2934 // Check global type. 2935 if (!Ty.isNull()) { 2936 // Drill down the array types: if global variable of a fixed type is 2937 // not sanitized, we also don't instrument arrays of them. 2938 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 2939 Ty = AT->getElementType(); 2940 Ty = Ty.getCanonicalType().getUnqualifiedType(); 2941 // Only record types (classes, structs etc.) are ignored. 2942 if (Ty->isRecordType()) { 2943 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 2944 if (NoSanitizeL.containsType(Kind, TypeStr, Category)) 2945 return true; 2946 } 2947 } 2948 return false; 2949 } 2950 2951 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 2952 StringRef Category) const { 2953 const auto &XRayFilter = getContext().getXRayFilter(); 2954 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 2955 auto Attr = ImbueAttr::NONE; 2956 if (Loc.isValid()) 2957 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 2958 if (Attr == ImbueAttr::NONE) 2959 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 2960 switch (Attr) { 2961 case ImbueAttr::NONE: 2962 return false; 2963 case ImbueAttr::ALWAYS: 2964 Fn->addFnAttr("function-instrument", "xray-always"); 2965 break; 2966 case ImbueAttr::ALWAYS_ARG1: 2967 Fn->addFnAttr("function-instrument", "xray-always"); 2968 Fn->addFnAttr("xray-log-args", "1"); 2969 break; 2970 case ImbueAttr::NEVER: 2971 Fn->addFnAttr("function-instrument", "xray-never"); 2972 break; 2973 } 2974 return true; 2975 } 2976 2977 ProfileList::ExclusionType 2978 CodeGenModule::isFunctionBlockedByProfileList(llvm::Function *Fn, 2979 SourceLocation Loc) const { 2980 const auto &ProfileList = getContext().getProfileList(); 2981 // If the profile list is empty, then instrument everything. 2982 if (ProfileList.isEmpty()) 2983 return ProfileList::Allow; 2984 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 2985 // First, check the function name. 2986 if (auto V = ProfileList.isFunctionExcluded(Fn->getName(), Kind)) 2987 return *V; 2988 // Next, check the source location. 2989 if (Loc.isValid()) 2990 if (auto V = ProfileList.isLocationExcluded(Loc, Kind)) 2991 return *V; 2992 // If location is unknown, this may be a compiler-generated function. Assume 2993 // it's located in the main file. 2994 auto &SM = Context.getSourceManager(); 2995 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) 2996 if (auto V = ProfileList.isFileExcluded(MainFile->getName(), Kind)) 2997 return *V; 2998 return ProfileList.getDefault(Kind); 2999 } 3000 3001 ProfileList::ExclusionType 3002 CodeGenModule::isFunctionBlockedFromProfileInstr(llvm::Function *Fn, 3003 SourceLocation Loc) const { 3004 auto V = isFunctionBlockedByProfileList(Fn, Loc); 3005 if (V != ProfileList::Allow) 3006 return V; 3007 3008 auto NumGroups = getCodeGenOpts().ProfileTotalFunctionGroups; 3009 if (NumGroups > 1) { 3010 auto Group = llvm::crc32(arrayRefFromStringRef(Fn->getName())) % NumGroups; 3011 if (Group != getCodeGenOpts().ProfileSelectedFunctionGroup) 3012 return ProfileList::Skip; 3013 } 3014 return ProfileList::Allow; 3015 } 3016 3017 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 3018 // Never defer when EmitAllDecls is specified. 3019 if (LangOpts.EmitAllDecls) 3020 return true; 3021 3022 if (CodeGenOpts.KeepStaticConsts) { 3023 const auto *VD = dyn_cast<VarDecl>(Global); 3024 if (VD && VD->getType().isConstQualified() && 3025 VD->getStorageDuration() == SD_Static) 3026 return true; 3027 } 3028 3029 return getContext().DeclMustBeEmitted(Global); 3030 } 3031 3032 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 3033 // In OpenMP 5.0 variables and function may be marked as 3034 // device_type(host/nohost) and we should not emit them eagerly unless we sure 3035 // that they must be emitted on the host/device. To be sure we need to have 3036 // seen a declare target with an explicit mentioning of the function, we know 3037 // we have if the level of the declare target attribute is -1. Note that we 3038 // check somewhere else if we should emit this at all. 3039 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd) { 3040 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 3041 OMPDeclareTargetDeclAttr::getActiveAttr(Global); 3042 if (!ActiveAttr || (*ActiveAttr)->getLevel() != (unsigned)-1) 3043 return false; 3044 } 3045 3046 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3047 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 3048 // Implicit template instantiations may change linkage if they are later 3049 // explicitly instantiated, so they should not be emitted eagerly. 3050 return false; 3051 } 3052 if (const auto *VD = dyn_cast<VarDecl>(Global)) { 3053 if (Context.getInlineVariableDefinitionKind(VD) == 3054 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 3055 // A definition of an inline constexpr static data member may change 3056 // linkage later if it's redeclared outside the class. 3057 return false; 3058 if (CXX20ModuleInits && VD->getOwningModule() && 3059 !VD->getOwningModule()->isModuleMapModule()) { 3060 // For CXX20, module-owned initializers need to be deferred, since it is 3061 // not known at this point if they will be run for the current module or 3062 // as part of the initializer for an imported one. 3063 return false; 3064 } 3065 } 3066 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 3067 // codegen for global variables, because they may be marked as threadprivate. 3068 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 3069 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 3070 !isTypeConstant(Global->getType(), false) && 3071 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 3072 return false; 3073 3074 return true; 3075 } 3076 3077 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 3078 StringRef Name = getMangledName(GD); 3079 3080 // The UUID descriptor should be pointer aligned. 3081 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 3082 3083 // Look for an existing global. 3084 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 3085 return ConstantAddress(GV, GV->getValueType(), Alignment); 3086 3087 ConstantEmitter Emitter(*this); 3088 llvm::Constant *Init; 3089 3090 APValue &V = GD->getAsAPValue(); 3091 if (!V.isAbsent()) { 3092 // If possible, emit the APValue version of the initializer. In particular, 3093 // this gets the type of the constant right. 3094 Init = Emitter.emitForInitializer( 3095 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 3096 } else { 3097 // As a fallback, directly construct the constant. 3098 // FIXME: This may get padding wrong under esoteric struct layout rules. 3099 // MSVC appears to create a complete type 'struct __s_GUID' that it 3100 // presumably uses to represent these constants. 3101 MSGuidDecl::Parts Parts = GD->getParts(); 3102 llvm::Constant *Fields[4] = { 3103 llvm::ConstantInt::get(Int32Ty, Parts.Part1), 3104 llvm::ConstantInt::get(Int16Ty, Parts.Part2), 3105 llvm::ConstantInt::get(Int16Ty, Parts.Part3), 3106 llvm::ConstantDataArray::getRaw( 3107 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 3108 Int8Ty)}; 3109 Init = llvm::ConstantStruct::getAnon(Fields); 3110 } 3111 3112 auto *GV = new llvm::GlobalVariable( 3113 getModule(), Init->getType(), 3114 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 3115 if (supportsCOMDAT()) 3116 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3117 setDSOLocal(GV); 3118 3119 if (!V.isAbsent()) { 3120 Emitter.finalize(GV); 3121 return ConstantAddress(GV, GV->getValueType(), Alignment); 3122 } 3123 3124 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 3125 llvm::Constant *Addr = llvm::ConstantExpr::getBitCast( 3126 GV, Ty->getPointerTo(GV->getAddressSpace())); 3127 return ConstantAddress(Addr, Ty, Alignment); 3128 } 3129 3130 ConstantAddress CodeGenModule::GetAddrOfUnnamedGlobalConstantDecl( 3131 const UnnamedGlobalConstantDecl *GCD) { 3132 CharUnits Alignment = getContext().getTypeAlignInChars(GCD->getType()); 3133 3134 llvm::GlobalVariable **Entry = nullptr; 3135 Entry = &UnnamedGlobalConstantDeclMap[GCD]; 3136 if (*Entry) 3137 return ConstantAddress(*Entry, (*Entry)->getValueType(), Alignment); 3138 3139 ConstantEmitter Emitter(*this); 3140 llvm::Constant *Init; 3141 3142 const APValue &V = GCD->getValue(); 3143 3144 assert(!V.isAbsent()); 3145 Init = Emitter.emitForInitializer(V, GCD->getType().getAddressSpace(), 3146 GCD->getType()); 3147 3148 auto *GV = new llvm::GlobalVariable(getModule(), Init->getType(), 3149 /*isConstant=*/true, 3150 llvm::GlobalValue::PrivateLinkage, Init, 3151 ".constant"); 3152 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 3153 GV->setAlignment(Alignment.getAsAlign()); 3154 3155 Emitter.finalize(GV); 3156 3157 *Entry = GV; 3158 return ConstantAddress(GV, GV->getValueType(), Alignment); 3159 } 3160 3161 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 3162 const TemplateParamObjectDecl *TPO) { 3163 StringRef Name = getMangledName(TPO); 3164 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 3165 3166 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 3167 return ConstantAddress(GV, GV->getValueType(), Alignment); 3168 3169 ConstantEmitter Emitter(*this); 3170 llvm::Constant *Init = Emitter.emitForInitializer( 3171 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 3172 3173 if (!Init) { 3174 ErrorUnsupported(TPO, "template parameter object"); 3175 return ConstantAddress::invalid(); 3176 } 3177 3178 auto *GV = new llvm::GlobalVariable( 3179 getModule(), Init->getType(), 3180 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 3181 if (supportsCOMDAT()) 3182 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3183 Emitter.finalize(GV); 3184 3185 return ConstantAddress(GV, GV->getValueType(), Alignment); 3186 } 3187 3188 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 3189 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 3190 assert(AA && "No alias?"); 3191 3192 CharUnits Alignment = getContext().getDeclAlign(VD); 3193 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 3194 3195 // See if there is already something with the target's name in the module. 3196 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 3197 if (Entry) { 3198 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 3199 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 3200 return ConstantAddress(Ptr, DeclTy, Alignment); 3201 } 3202 3203 llvm::Constant *Aliasee; 3204 if (isa<llvm::FunctionType>(DeclTy)) 3205 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 3206 GlobalDecl(cast<FunctionDecl>(VD)), 3207 /*ForVTable=*/false); 3208 else 3209 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 3210 nullptr); 3211 3212 auto *F = cast<llvm::GlobalValue>(Aliasee); 3213 F->setLinkage(llvm::Function::ExternalWeakLinkage); 3214 WeakRefReferences.insert(F); 3215 3216 return ConstantAddress(Aliasee, DeclTy, Alignment); 3217 } 3218 3219 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 3220 const auto *Global = cast<ValueDecl>(GD.getDecl()); 3221 3222 // Weak references don't produce any output by themselves. 3223 if (Global->hasAttr<WeakRefAttr>()) 3224 return; 3225 3226 // If this is an alias definition (which otherwise looks like a declaration) 3227 // emit it now. 3228 if (Global->hasAttr<AliasAttr>()) 3229 return EmitAliasDefinition(GD); 3230 3231 // IFunc like an alias whose value is resolved at runtime by calling resolver. 3232 if (Global->hasAttr<IFuncAttr>()) 3233 return emitIFuncDefinition(GD); 3234 3235 // If this is a cpu_dispatch multiversion function, emit the resolver. 3236 if (Global->hasAttr<CPUDispatchAttr>()) 3237 return emitCPUDispatchDefinition(GD); 3238 3239 // If this is CUDA, be selective about which declarations we emit. 3240 if (LangOpts.CUDA) { 3241 if (LangOpts.CUDAIsDevice) { 3242 if (!Global->hasAttr<CUDADeviceAttr>() && 3243 !Global->hasAttr<CUDAGlobalAttr>() && 3244 !Global->hasAttr<CUDAConstantAttr>() && 3245 !Global->hasAttr<CUDASharedAttr>() && 3246 !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 3247 !Global->getType()->isCUDADeviceBuiltinTextureType()) 3248 return; 3249 } else { 3250 // We need to emit host-side 'shadows' for all global 3251 // device-side variables because the CUDA runtime needs their 3252 // size and host-side address in order to provide access to 3253 // their device-side incarnations. 3254 3255 // So device-only functions are the only things we skip. 3256 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 3257 Global->hasAttr<CUDADeviceAttr>()) 3258 return; 3259 3260 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 3261 "Expected Variable or Function"); 3262 } 3263 } 3264 3265 if (LangOpts.OpenMP) { 3266 // If this is OpenMP, check if it is legal to emit this global normally. 3267 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 3268 return; 3269 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 3270 if (MustBeEmitted(Global)) 3271 EmitOMPDeclareReduction(DRD); 3272 return; 3273 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 3274 if (MustBeEmitted(Global)) 3275 EmitOMPDeclareMapper(DMD); 3276 return; 3277 } 3278 } 3279 3280 // Ignore declarations, they will be emitted on their first use. 3281 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 3282 // Forward declarations are emitted lazily on first use. 3283 if (!FD->doesThisDeclarationHaveABody()) { 3284 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 3285 return; 3286 3287 StringRef MangledName = getMangledName(GD); 3288 3289 // Compute the function info and LLVM type. 3290 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3291 llvm::Type *Ty = getTypes().GetFunctionType(FI); 3292 3293 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 3294 /*DontDefer=*/false); 3295 return; 3296 } 3297 } else { 3298 const auto *VD = cast<VarDecl>(Global); 3299 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 3300 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 3301 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 3302 if (LangOpts.OpenMP) { 3303 // Emit declaration of the must-be-emitted declare target variable. 3304 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3305 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 3306 bool UnifiedMemoryEnabled = 3307 getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 3308 if (*Res == OMPDeclareTargetDeclAttr::MT_To && 3309 !UnifiedMemoryEnabled) { 3310 (void)GetAddrOfGlobalVar(VD); 3311 } else { 3312 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 3313 (*Res == OMPDeclareTargetDeclAttr::MT_To && 3314 UnifiedMemoryEnabled)) && 3315 "Link clause or to clause with unified memory expected."); 3316 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 3317 } 3318 3319 return; 3320 } 3321 } 3322 // If this declaration may have caused an inline variable definition to 3323 // change linkage, make sure that it's emitted. 3324 if (Context.getInlineVariableDefinitionKind(VD) == 3325 ASTContext::InlineVariableDefinitionKind::Strong) 3326 GetAddrOfGlobalVar(VD); 3327 return; 3328 } 3329 } 3330 3331 // Defer code generation to first use when possible, e.g. if this is an inline 3332 // function. If the global must always be emitted, do it eagerly if possible 3333 // to benefit from cache locality. 3334 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 3335 // Emit the definition if it can't be deferred. 3336 EmitGlobalDefinition(GD); 3337 return; 3338 } 3339 3340 // If we're deferring emission of a C++ variable with an 3341 // initializer, remember the order in which it appeared in the file. 3342 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 3343 cast<VarDecl>(Global)->hasInit()) { 3344 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 3345 CXXGlobalInits.push_back(nullptr); 3346 } 3347 3348 StringRef MangledName = getMangledName(GD); 3349 if (GetGlobalValue(MangledName) != nullptr) { 3350 // The value has already been used and should therefore be emitted. 3351 addDeferredDeclToEmit(GD); 3352 } else if (MustBeEmitted(Global)) { 3353 // The value must be emitted, but cannot be emitted eagerly. 3354 assert(!MayBeEmittedEagerly(Global)); 3355 addDeferredDeclToEmit(GD); 3356 EmittedDeferredDecls[MangledName] = GD; 3357 } else { 3358 // Otherwise, remember that we saw a deferred decl with this name. The 3359 // first use of the mangled name will cause it to move into 3360 // DeferredDeclsToEmit. 3361 DeferredDecls[MangledName] = GD; 3362 } 3363 } 3364 3365 // Check if T is a class type with a destructor that's not dllimport. 3366 static bool HasNonDllImportDtor(QualType T) { 3367 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 3368 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 3369 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 3370 return true; 3371 3372 return false; 3373 } 3374 3375 namespace { 3376 struct FunctionIsDirectlyRecursive 3377 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 3378 const StringRef Name; 3379 const Builtin::Context &BI; 3380 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 3381 : Name(N), BI(C) {} 3382 3383 bool VisitCallExpr(const CallExpr *E) { 3384 const FunctionDecl *FD = E->getDirectCallee(); 3385 if (!FD) 3386 return false; 3387 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3388 if (Attr && Name == Attr->getLabel()) 3389 return true; 3390 unsigned BuiltinID = FD->getBuiltinID(); 3391 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 3392 return false; 3393 StringRef BuiltinName = BI.getName(BuiltinID); 3394 if (BuiltinName.startswith("__builtin_") && 3395 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 3396 return true; 3397 } 3398 return false; 3399 } 3400 3401 bool VisitStmt(const Stmt *S) { 3402 for (const Stmt *Child : S->children()) 3403 if (Child && this->Visit(Child)) 3404 return true; 3405 return false; 3406 } 3407 }; 3408 3409 // Make sure we're not referencing non-imported vars or functions. 3410 struct DLLImportFunctionVisitor 3411 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 3412 bool SafeToInline = true; 3413 3414 bool shouldVisitImplicitCode() const { return true; } 3415 3416 bool VisitVarDecl(VarDecl *VD) { 3417 if (VD->getTLSKind()) { 3418 // A thread-local variable cannot be imported. 3419 SafeToInline = false; 3420 return SafeToInline; 3421 } 3422 3423 // A variable definition might imply a destructor call. 3424 if (VD->isThisDeclarationADefinition()) 3425 SafeToInline = !HasNonDllImportDtor(VD->getType()); 3426 3427 return SafeToInline; 3428 } 3429 3430 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 3431 if (const auto *D = E->getTemporary()->getDestructor()) 3432 SafeToInline = D->hasAttr<DLLImportAttr>(); 3433 return SafeToInline; 3434 } 3435 3436 bool VisitDeclRefExpr(DeclRefExpr *E) { 3437 ValueDecl *VD = E->getDecl(); 3438 if (isa<FunctionDecl>(VD)) 3439 SafeToInline = VD->hasAttr<DLLImportAttr>(); 3440 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 3441 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 3442 return SafeToInline; 3443 } 3444 3445 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 3446 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 3447 return SafeToInline; 3448 } 3449 3450 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 3451 CXXMethodDecl *M = E->getMethodDecl(); 3452 if (!M) { 3453 // Call through a pointer to member function. This is safe to inline. 3454 SafeToInline = true; 3455 } else { 3456 SafeToInline = M->hasAttr<DLLImportAttr>(); 3457 } 3458 return SafeToInline; 3459 } 3460 3461 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 3462 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 3463 return SafeToInline; 3464 } 3465 3466 bool VisitCXXNewExpr(CXXNewExpr *E) { 3467 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 3468 return SafeToInline; 3469 } 3470 }; 3471 } 3472 3473 // isTriviallyRecursive - Check if this function calls another 3474 // decl that, because of the asm attribute or the other decl being a builtin, 3475 // ends up pointing to itself. 3476 bool 3477 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 3478 StringRef Name; 3479 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 3480 // asm labels are a special kind of mangling we have to support. 3481 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 3482 if (!Attr) 3483 return false; 3484 Name = Attr->getLabel(); 3485 } else { 3486 Name = FD->getName(); 3487 } 3488 3489 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 3490 const Stmt *Body = FD->getBody(); 3491 return Body ? Walker.Visit(Body) : false; 3492 } 3493 3494 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 3495 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 3496 return true; 3497 const auto *F = cast<FunctionDecl>(GD.getDecl()); 3498 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 3499 return false; 3500 3501 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 3502 // Check whether it would be safe to inline this dllimport function. 3503 DLLImportFunctionVisitor Visitor; 3504 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 3505 if (!Visitor.SafeToInline) 3506 return false; 3507 3508 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 3509 // Implicit destructor invocations aren't captured in the AST, so the 3510 // check above can't see them. Check for them manually here. 3511 for (const Decl *Member : Dtor->getParent()->decls()) 3512 if (isa<FieldDecl>(Member)) 3513 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 3514 return false; 3515 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 3516 if (HasNonDllImportDtor(B.getType())) 3517 return false; 3518 } 3519 } 3520 3521 // Inline builtins declaration must be emitted. They often are fortified 3522 // functions. 3523 if (F->isInlineBuiltinDeclaration()) 3524 return true; 3525 3526 // PR9614. Avoid cases where the source code is lying to us. An available 3527 // externally function should have an equivalent function somewhere else, 3528 // but a function that calls itself through asm label/`__builtin_` trickery is 3529 // clearly not equivalent to the real implementation. 3530 // This happens in glibc's btowc and in some configure checks. 3531 return !isTriviallyRecursive(F); 3532 } 3533 3534 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 3535 return CodeGenOpts.OptimizationLevel > 0; 3536 } 3537 3538 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 3539 llvm::GlobalValue *GV) { 3540 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3541 3542 if (FD->isCPUSpecificMultiVersion()) { 3543 auto *Spec = FD->getAttr<CPUSpecificAttr>(); 3544 for (unsigned I = 0; I < Spec->cpus_size(); ++I) 3545 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3546 } else if (FD->isTargetClonesMultiVersion()) { 3547 auto *Clone = FD->getAttr<TargetClonesAttr>(); 3548 for (unsigned I = 0; I < Clone->featuresStrs_size(); ++I) 3549 if (Clone->isFirstOfVersion(I)) 3550 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3551 // Ensure that the resolver function is also emitted. 3552 GetOrCreateMultiVersionResolver(GD); 3553 } else 3554 EmitGlobalFunctionDefinition(GD, GV); 3555 } 3556 3557 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 3558 const auto *D = cast<ValueDecl>(GD.getDecl()); 3559 3560 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 3561 Context.getSourceManager(), 3562 "Generating code for declaration"); 3563 3564 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3565 // At -O0, don't generate IR for functions with available_externally 3566 // linkage. 3567 if (!shouldEmitFunction(GD)) 3568 return; 3569 3570 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 3571 std::string Name; 3572 llvm::raw_string_ostream OS(Name); 3573 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 3574 /*Qualified=*/true); 3575 return Name; 3576 }); 3577 3578 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 3579 // Make sure to emit the definition(s) before we emit the thunks. 3580 // This is necessary for the generation of certain thunks. 3581 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 3582 ABI->emitCXXStructor(GD); 3583 else if (FD->isMultiVersion()) 3584 EmitMultiVersionFunctionDefinition(GD, GV); 3585 else 3586 EmitGlobalFunctionDefinition(GD, GV); 3587 3588 if (Method->isVirtual()) 3589 getVTables().EmitThunks(GD); 3590 3591 return; 3592 } 3593 3594 if (FD->isMultiVersion()) 3595 return EmitMultiVersionFunctionDefinition(GD, GV); 3596 return EmitGlobalFunctionDefinition(GD, GV); 3597 } 3598 3599 if (const auto *VD = dyn_cast<VarDecl>(D)) 3600 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 3601 3602 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 3603 } 3604 3605 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3606 llvm::Function *NewFn); 3607 3608 static unsigned 3609 TargetMVPriority(const TargetInfo &TI, 3610 const CodeGenFunction::MultiVersionResolverOption &RO) { 3611 unsigned Priority = 0; 3612 for (StringRef Feat : RO.Conditions.Features) 3613 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 3614 3615 if (!RO.Conditions.Architecture.empty()) 3616 Priority = std::max( 3617 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 3618 return Priority; 3619 } 3620 3621 // Multiversion functions should be at most 'WeakODRLinkage' so that a different 3622 // TU can forward declare the function without causing problems. Particularly 3623 // in the cases of CPUDispatch, this causes issues. This also makes sure we 3624 // work with internal linkage functions, so that the same function name can be 3625 // used with internal linkage in multiple TUs. 3626 llvm::GlobalValue::LinkageTypes getMultiversionLinkage(CodeGenModule &CGM, 3627 GlobalDecl GD) { 3628 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3629 if (FD->getFormalLinkage() == InternalLinkage) 3630 return llvm::GlobalValue::InternalLinkage; 3631 return llvm::GlobalValue::WeakODRLinkage; 3632 } 3633 3634 void CodeGenModule::emitMultiVersionFunctions() { 3635 std::vector<GlobalDecl> MVFuncsToEmit; 3636 MultiVersionFuncs.swap(MVFuncsToEmit); 3637 for (GlobalDecl GD : MVFuncsToEmit) { 3638 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3639 assert(FD && "Expected a FunctionDecl"); 3640 3641 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3642 if (FD->isTargetMultiVersion()) { 3643 getContext().forEachMultiversionedFunctionVersion( 3644 FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 3645 GlobalDecl CurGD{ 3646 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 3647 StringRef MangledName = getMangledName(CurGD); 3648 llvm::Constant *Func = GetGlobalValue(MangledName); 3649 if (!Func) { 3650 if (CurFD->isDefined()) { 3651 EmitGlobalFunctionDefinition(CurGD, nullptr); 3652 Func = GetGlobalValue(MangledName); 3653 } else { 3654 const CGFunctionInfo &FI = 3655 getTypes().arrangeGlobalDeclaration(GD); 3656 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3657 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 3658 /*DontDefer=*/false, ForDefinition); 3659 } 3660 assert(Func && "This should have just been created"); 3661 } 3662 3663 const auto *TA = CurFD->getAttr<TargetAttr>(); 3664 llvm::SmallVector<StringRef, 8> Feats; 3665 TA->getAddedFeatures(Feats); 3666 3667 Options.emplace_back(cast<llvm::Function>(Func), 3668 TA->getArchitecture(), Feats); 3669 }); 3670 } else if (FD->isTargetClonesMultiVersion()) { 3671 const auto *TC = FD->getAttr<TargetClonesAttr>(); 3672 for (unsigned VersionIndex = 0; VersionIndex < TC->featuresStrs_size(); 3673 ++VersionIndex) { 3674 if (!TC->isFirstOfVersion(VersionIndex)) 3675 continue; 3676 GlobalDecl CurGD{(FD->isDefined() ? FD->getDefinition() : FD), 3677 VersionIndex}; 3678 StringRef Version = TC->getFeatureStr(VersionIndex); 3679 StringRef MangledName = getMangledName(CurGD); 3680 llvm::Constant *Func = GetGlobalValue(MangledName); 3681 if (!Func) { 3682 if (FD->isDefined()) { 3683 EmitGlobalFunctionDefinition(CurGD, nullptr); 3684 Func = GetGlobalValue(MangledName); 3685 } else { 3686 const CGFunctionInfo &FI = 3687 getTypes().arrangeGlobalDeclaration(CurGD); 3688 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3689 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 3690 /*DontDefer=*/false, ForDefinition); 3691 } 3692 assert(Func && "This should have just been created"); 3693 } 3694 3695 StringRef Architecture; 3696 llvm::SmallVector<StringRef, 1> Feature; 3697 3698 if (Version.startswith("arch=")) 3699 Architecture = Version.drop_front(sizeof("arch=") - 1); 3700 else if (Version != "default") 3701 Feature.push_back(Version); 3702 3703 Options.emplace_back(cast<llvm::Function>(Func), Architecture, Feature); 3704 } 3705 } else { 3706 assert(0 && "Expected a target or target_clones multiversion function"); 3707 continue; 3708 } 3709 3710 llvm::Constant *ResolverConstant = GetOrCreateMultiVersionResolver(GD); 3711 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(ResolverConstant)) 3712 ResolverConstant = IFunc->getResolver(); 3713 llvm::Function *ResolverFunc = cast<llvm::Function>(ResolverConstant); 3714 3715 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3716 3717 if (supportsCOMDAT()) 3718 ResolverFunc->setComdat( 3719 getModule().getOrInsertComdat(ResolverFunc->getName())); 3720 3721 const TargetInfo &TI = getTarget(); 3722 llvm::stable_sort( 3723 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 3724 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3725 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 3726 }); 3727 CodeGenFunction CGF(*this); 3728 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3729 } 3730 3731 // Ensure that any additions to the deferred decls list caused by emitting a 3732 // variant are emitted. This can happen when the variant itself is inline and 3733 // calls a function without linkage. 3734 if (!MVFuncsToEmit.empty()) 3735 EmitDeferred(); 3736 3737 // Ensure that any additions to the multiversion funcs list from either the 3738 // deferred decls or the multiversion functions themselves are emitted. 3739 if (!MultiVersionFuncs.empty()) 3740 emitMultiVersionFunctions(); 3741 } 3742 3743 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 3744 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3745 assert(FD && "Not a FunctionDecl?"); 3746 assert(FD->isCPUDispatchMultiVersion() && "Not a multiversion function?"); 3747 const auto *DD = FD->getAttr<CPUDispatchAttr>(); 3748 assert(DD && "Not a cpu_dispatch Function?"); 3749 3750 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3751 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 3752 3753 StringRef ResolverName = getMangledName(GD); 3754 UpdateMultiVersionNames(GD, FD, ResolverName); 3755 3756 llvm::Type *ResolverType; 3757 GlobalDecl ResolverGD; 3758 if (getTarget().supportsIFunc()) { 3759 ResolverType = llvm::FunctionType::get( 3760 llvm::PointerType::get(DeclTy, 3761 Context.getTargetAddressSpace(FD->getType())), 3762 false); 3763 } 3764 else { 3765 ResolverType = DeclTy; 3766 ResolverGD = GD; 3767 } 3768 3769 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 3770 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 3771 ResolverFunc->setLinkage(getMultiversionLinkage(*this, GD)); 3772 if (supportsCOMDAT()) 3773 ResolverFunc->setComdat( 3774 getModule().getOrInsertComdat(ResolverFunc->getName())); 3775 3776 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3777 const TargetInfo &Target = getTarget(); 3778 unsigned Index = 0; 3779 for (const IdentifierInfo *II : DD->cpus()) { 3780 // Get the name of the target function so we can look it up/create it. 3781 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 3782 getCPUSpecificMangling(*this, II->getName()); 3783 3784 llvm::Constant *Func = GetGlobalValue(MangledName); 3785 3786 if (!Func) { 3787 GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 3788 if (ExistingDecl.getDecl() && 3789 ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 3790 EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 3791 Func = GetGlobalValue(MangledName); 3792 } else { 3793 if (!ExistingDecl.getDecl()) 3794 ExistingDecl = GD.getWithMultiVersionIndex(Index); 3795 3796 Func = GetOrCreateLLVMFunction( 3797 MangledName, DeclTy, ExistingDecl, 3798 /*ForVTable=*/false, /*DontDefer=*/true, 3799 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 3800 } 3801 } 3802 3803 llvm::SmallVector<StringRef, 32> Features; 3804 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 3805 llvm::transform(Features, Features.begin(), 3806 [](StringRef Str) { return Str.substr(1); }); 3807 llvm::erase_if(Features, [&Target](StringRef Feat) { 3808 return !Target.validateCpuSupports(Feat); 3809 }); 3810 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 3811 ++Index; 3812 } 3813 3814 llvm::stable_sort( 3815 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 3816 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3817 return llvm::X86::getCpuSupportsMask(LHS.Conditions.Features) > 3818 llvm::X86::getCpuSupportsMask(RHS.Conditions.Features); 3819 }); 3820 3821 // If the list contains multiple 'default' versions, such as when it contains 3822 // 'pentium' and 'generic', don't emit the call to the generic one (since we 3823 // always run on at least a 'pentium'). We do this by deleting the 'least 3824 // advanced' (read, lowest mangling letter). 3825 while (Options.size() > 1 && 3826 llvm::X86::getCpuSupportsMask( 3827 (Options.end() - 2)->Conditions.Features) == 0) { 3828 StringRef LHSName = (Options.end() - 2)->Function->getName(); 3829 StringRef RHSName = (Options.end() - 1)->Function->getName(); 3830 if (LHSName.compare(RHSName) < 0) 3831 Options.erase(Options.end() - 2); 3832 else 3833 Options.erase(Options.end() - 1); 3834 } 3835 3836 CodeGenFunction CGF(*this); 3837 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3838 3839 if (getTarget().supportsIFunc()) { 3840 llvm::GlobalValue::LinkageTypes Linkage = getMultiversionLinkage(*this, GD); 3841 auto *IFunc = cast<llvm::GlobalValue>(GetOrCreateMultiVersionResolver(GD)); 3842 3843 // Fix up function declarations that were created for cpu_specific before 3844 // cpu_dispatch was known 3845 if (!isa<llvm::GlobalIFunc>(IFunc)) { 3846 assert(cast<llvm::Function>(IFunc)->isDeclaration()); 3847 auto *GI = llvm::GlobalIFunc::create(DeclTy, 0, Linkage, "", ResolverFunc, 3848 &getModule()); 3849 GI->takeName(IFunc); 3850 IFunc->replaceAllUsesWith(GI); 3851 IFunc->eraseFromParent(); 3852 IFunc = GI; 3853 } 3854 3855 std::string AliasName = getMangledNameImpl( 3856 *this, GD, FD, /*OmitMultiVersionMangling=*/true); 3857 llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 3858 if (!AliasFunc) { 3859 auto *GA = llvm::GlobalAlias::create(DeclTy, 0, Linkage, AliasName, IFunc, 3860 &getModule()); 3861 SetCommonAttributes(GD, GA); 3862 } 3863 } 3864 } 3865 3866 /// If a dispatcher for the specified mangled name is not in the module, create 3867 /// and return an llvm Function with the specified type. 3868 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(GlobalDecl GD) { 3869 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3870 assert(FD && "Not a FunctionDecl?"); 3871 3872 std::string MangledName = 3873 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 3874 3875 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 3876 // a separate resolver). 3877 std::string ResolverName = MangledName; 3878 if (getTarget().supportsIFunc()) 3879 ResolverName += ".ifunc"; 3880 else if (FD->isTargetMultiVersion()) 3881 ResolverName += ".resolver"; 3882 3883 // If the resolver has already been created, just return it. 3884 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 3885 return ResolverGV; 3886 3887 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3888 llvm::FunctionType *DeclTy = getTypes().GetFunctionType(FI); 3889 3890 // The resolver needs to be created. For target and target_clones, defer 3891 // creation until the end of the TU. 3892 if (FD->isTargetMultiVersion() || FD->isTargetClonesMultiVersion()) 3893 MultiVersionFuncs.push_back(GD); 3894 3895 // For cpu_specific, don't create an ifunc yet because we don't know if the 3896 // cpu_dispatch will be emitted in this translation unit. 3897 if (getTarget().supportsIFunc() && !FD->isCPUSpecificMultiVersion()) { 3898 llvm::Type *ResolverType = llvm::FunctionType::get( 3899 llvm::PointerType::get( 3900 DeclTy, getContext().getTargetAddressSpace(FD->getType())), 3901 false); 3902 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3903 MangledName + ".resolver", ResolverType, GlobalDecl{}, 3904 /*ForVTable=*/false); 3905 llvm::GlobalIFunc *GIF = 3906 llvm::GlobalIFunc::create(DeclTy, 0, getMultiversionLinkage(*this, GD), 3907 "", Resolver, &getModule()); 3908 GIF->setName(ResolverName); 3909 SetCommonAttributes(FD, GIF); 3910 3911 return GIF; 3912 } 3913 3914 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3915 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 3916 assert(isa<llvm::GlobalValue>(Resolver) && 3917 "Resolver should be created for the first time"); 3918 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 3919 return Resolver; 3920 } 3921 3922 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 3923 /// module, create and return an llvm Function with the specified type. If there 3924 /// is something in the module with the specified name, return it potentially 3925 /// bitcasted to the right type. 3926 /// 3927 /// If D is non-null, it specifies a decl that correspond to this. This is used 3928 /// to set the attributes on the function when it is first created. 3929 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 3930 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 3931 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 3932 ForDefinition_t IsForDefinition) { 3933 const Decl *D = GD.getDecl(); 3934 3935 // Any attempts to use a MultiVersion function should result in retrieving 3936 // the iFunc instead. Name Mangling will handle the rest of the changes. 3937 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 3938 // For the device mark the function as one that should be emitted. 3939 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 3940 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 3941 !DontDefer && !IsForDefinition) { 3942 if (const FunctionDecl *FDDef = FD->getDefinition()) { 3943 GlobalDecl GDDef; 3944 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 3945 GDDef = GlobalDecl(CD, GD.getCtorType()); 3946 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 3947 GDDef = GlobalDecl(DD, GD.getDtorType()); 3948 else 3949 GDDef = GlobalDecl(FDDef); 3950 EmitGlobal(GDDef); 3951 } 3952 } 3953 3954 if (FD->isMultiVersion()) { 3955 UpdateMultiVersionNames(GD, FD, MangledName); 3956 if (!IsForDefinition) 3957 return GetOrCreateMultiVersionResolver(GD); 3958 } 3959 } 3960 3961 // Lookup the entry, lazily creating it if necessary. 3962 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3963 if (Entry) { 3964 if (WeakRefReferences.erase(Entry)) { 3965 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 3966 if (FD && !FD->hasAttr<WeakAttr>()) 3967 Entry->setLinkage(llvm::Function::ExternalLinkage); 3968 } 3969 3970 // Handle dropped DLL attributes. 3971 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 3972 !shouldMapVisibilityToDLLExport(cast_or_null<NamedDecl>(D))) { 3973 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3974 setDSOLocal(Entry); 3975 } 3976 3977 // If there are two attempts to define the same mangled name, issue an 3978 // error. 3979 if (IsForDefinition && !Entry->isDeclaration()) { 3980 GlobalDecl OtherGD; 3981 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 3982 // to make sure that we issue an error only once. 3983 if (lookupRepresentativeDecl(MangledName, OtherGD) && 3984 (GD.getCanonicalDecl().getDecl() != 3985 OtherGD.getCanonicalDecl().getDecl()) && 3986 DiagnosedConflictingDefinitions.insert(GD).second) { 3987 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3988 << MangledName; 3989 getDiags().Report(OtherGD.getDecl()->getLocation(), 3990 diag::note_previous_definition); 3991 } 3992 } 3993 3994 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 3995 (Entry->getValueType() == Ty)) { 3996 return Entry; 3997 } 3998 3999 // Make sure the result is of the correct type. 4000 // (If function is requested for a definition, we always need to create a new 4001 // function, not just return a bitcast.) 4002 if (!IsForDefinition) 4003 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 4004 } 4005 4006 // This function doesn't have a complete type (for example, the return 4007 // type is an incomplete struct). Use a fake type instead, and make 4008 // sure not to try to set attributes. 4009 bool IsIncompleteFunction = false; 4010 4011 llvm::FunctionType *FTy; 4012 if (isa<llvm::FunctionType>(Ty)) { 4013 FTy = cast<llvm::FunctionType>(Ty); 4014 } else { 4015 FTy = llvm::FunctionType::get(VoidTy, false); 4016 IsIncompleteFunction = true; 4017 } 4018 4019 llvm::Function *F = 4020 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 4021 Entry ? StringRef() : MangledName, &getModule()); 4022 4023 // If we already created a function with the same mangled name (but different 4024 // type) before, take its name and add it to the list of functions to be 4025 // replaced with F at the end of CodeGen. 4026 // 4027 // This happens if there is a prototype for a function (e.g. "int f()") and 4028 // then a definition of a different type (e.g. "int f(int x)"). 4029 if (Entry) { 4030 F->takeName(Entry); 4031 4032 // This might be an implementation of a function without a prototype, in 4033 // which case, try to do special replacement of calls which match the new 4034 // prototype. The really key thing here is that we also potentially drop 4035 // arguments from the call site so as to make a direct call, which makes the 4036 // inliner happier and suppresses a number of optimizer warnings (!) about 4037 // dropping arguments. 4038 if (!Entry->use_empty()) { 4039 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 4040 Entry->removeDeadConstantUsers(); 4041 } 4042 4043 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 4044 F, Entry->getValueType()->getPointerTo()); 4045 addGlobalValReplacement(Entry, BC); 4046 } 4047 4048 assert(F->getName() == MangledName && "name was uniqued!"); 4049 if (D) 4050 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 4051 if (ExtraAttrs.hasFnAttrs()) { 4052 llvm::AttrBuilder B(F->getContext(), ExtraAttrs.getFnAttrs()); 4053 F->addFnAttrs(B); 4054 } 4055 4056 if (!DontDefer) { 4057 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 4058 // each other bottoming out with the base dtor. Therefore we emit non-base 4059 // dtors on usage, even if there is no dtor definition in the TU. 4060 if (isa_and_nonnull<CXXDestructorDecl>(D) && 4061 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 4062 GD.getDtorType())) 4063 addDeferredDeclToEmit(GD); 4064 4065 // This is the first use or definition of a mangled name. If there is a 4066 // deferred decl with this name, remember that we need to emit it at the end 4067 // of the file. 4068 auto DDI = DeferredDecls.find(MangledName); 4069 if (DDI != DeferredDecls.end()) { 4070 // Move the potentially referenced deferred decl to the 4071 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 4072 // don't need it anymore). 4073 addDeferredDeclToEmit(DDI->second); 4074 EmittedDeferredDecls[DDI->first] = DDI->second; 4075 DeferredDecls.erase(DDI); 4076 4077 // Otherwise, there are cases we have to worry about where we're 4078 // using a declaration for which we must emit a definition but where 4079 // we might not find a top-level definition: 4080 // - member functions defined inline in their classes 4081 // - friend functions defined inline in some class 4082 // - special member functions with implicit definitions 4083 // If we ever change our AST traversal to walk into class methods, 4084 // this will be unnecessary. 4085 // 4086 // We also don't emit a definition for a function if it's going to be an 4087 // entry in a vtable, unless it's already marked as used. 4088 } else if (getLangOpts().CPlusPlus && D) { 4089 // Look for a declaration that's lexically in a record. 4090 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 4091 FD = FD->getPreviousDecl()) { 4092 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 4093 if (FD->doesThisDeclarationHaveABody()) { 4094 addDeferredDeclToEmit(GD.getWithDecl(FD)); 4095 break; 4096 } 4097 } 4098 } 4099 } 4100 } 4101 4102 // Make sure the result is of the requested type. 4103 if (!IsIncompleteFunction) { 4104 assert(F->getFunctionType() == Ty); 4105 return F; 4106 } 4107 4108 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 4109 return llvm::ConstantExpr::getBitCast(F, PTy); 4110 } 4111 4112 /// GetAddrOfFunction - Return the address of the given function. If Ty is 4113 /// non-null, then this function will use the specified type if it has to 4114 /// create it (this occurs when we see a definition of the function). 4115 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 4116 llvm::Type *Ty, 4117 bool ForVTable, 4118 bool DontDefer, 4119 ForDefinition_t IsForDefinition) { 4120 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 4121 "consteval function should never be emitted"); 4122 // If there was no specific requested type, just convert it now. 4123 if (!Ty) { 4124 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 4125 Ty = getTypes().ConvertType(FD->getType()); 4126 } 4127 4128 // Devirtualized destructor calls may come through here instead of via 4129 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 4130 // of the complete destructor when necessary. 4131 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 4132 if (getTarget().getCXXABI().isMicrosoft() && 4133 GD.getDtorType() == Dtor_Complete && 4134 DD->getParent()->getNumVBases() == 0) 4135 GD = GlobalDecl(DD, Dtor_Base); 4136 } 4137 4138 StringRef MangledName = getMangledName(GD); 4139 auto *F = GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 4140 /*IsThunk=*/false, llvm::AttributeList(), 4141 IsForDefinition); 4142 // Returns kernel handle for HIP kernel stub function. 4143 if (LangOpts.CUDA && !LangOpts.CUDAIsDevice && 4144 cast<FunctionDecl>(GD.getDecl())->hasAttr<CUDAGlobalAttr>()) { 4145 auto *Handle = getCUDARuntime().getKernelHandle( 4146 cast<llvm::Function>(F->stripPointerCasts()), GD); 4147 if (IsForDefinition) 4148 return F; 4149 return llvm::ConstantExpr::getBitCast(Handle, Ty->getPointerTo()); 4150 } 4151 return F; 4152 } 4153 4154 llvm::Constant *CodeGenModule::GetFunctionStart(const ValueDecl *Decl) { 4155 llvm::GlobalValue *F = 4156 cast<llvm::GlobalValue>(GetAddrOfFunction(Decl)->stripPointerCasts()); 4157 4158 return llvm::ConstantExpr::getBitCast(llvm::NoCFIValue::get(F), 4159 llvm::Type::getInt8PtrTy(VMContext)); 4160 } 4161 4162 static const FunctionDecl * 4163 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 4164 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 4165 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 4166 4167 IdentifierInfo &CII = C.Idents.get(Name); 4168 for (const auto *Result : DC->lookup(&CII)) 4169 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4170 return FD; 4171 4172 if (!C.getLangOpts().CPlusPlus) 4173 return nullptr; 4174 4175 // Demangle the premangled name from getTerminateFn() 4176 IdentifierInfo &CXXII = 4177 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 4178 ? C.Idents.get("terminate") 4179 : C.Idents.get(Name); 4180 4181 for (const auto &N : {"__cxxabiv1", "std"}) { 4182 IdentifierInfo &NS = C.Idents.get(N); 4183 for (const auto *Result : DC->lookup(&NS)) { 4184 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 4185 if (auto *LSD = dyn_cast<LinkageSpecDecl>(Result)) 4186 for (const auto *Result : LSD->lookup(&NS)) 4187 if ((ND = dyn_cast<NamespaceDecl>(Result))) 4188 break; 4189 4190 if (ND) 4191 for (const auto *Result : ND->lookup(&CXXII)) 4192 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 4193 return FD; 4194 } 4195 } 4196 4197 return nullptr; 4198 } 4199 4200 /// CreateRuntimeFunction - Create a new runtime function with the specified 4201 /// type and name. 4202 llvm::FunctionCallee 4203 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 4204 llvm::AttributeList ExtraAttrs, bool Local, 4205 bool AssumeConvergent) { 4206 if (AssumeConvergent) { 4207 ExtraAttrs = 4208 ExtraAttrs.addFnAttribute(VMContext, llvm::Attribute::Convergent); 4209 } 4210 4211 llvm::Constant *C = 4212 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 4213 /*DontDefer=*/false, /*IsThunk=*/false, 4214 ExtraAttrs); 4215 4216 if (auto *F = dyn_cast<llvm::Function>(C)) { 4217 if (F->empty()) { 4218 F->setCallingConv(getRuntimeCC()); 4219 4220 // In Windows Itanium environments, try to mark runtime functions 4221 // dllimport. For Mingw and MSVC, don't. We don't really know if the user 4222 // will link their standard library statically or dynamically. Marking 4223 // functions imported when they are not imported can cause linker errors 4224 // and warnings. 4225 if (!Local && getTriple().isWindowsItaniumEnvironment() && 4226 !getCodeGenOpts().LTOVisibilityPublicStd) { 4227 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 4228 if (!FD || FD->hasAttr<DLLImportAttr>()) { 4229 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4230 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 4231 } 4232 } 4233 setDSOLocal(F); 4234 } 4235 } 4236 4237 return {FTy, C}; 4238 } 4239 4240 /// isTypeConstant - Determine whether an object of this type can be emitted 4241 /// as a constant. 4242 /// 4243 /// If ExcludeCtor is true, the duration when the object's constructor runs 4244 /// will not be considered. The caller will need to verify that the object is 4245 /// not written to during its construction. 4246 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 4247 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 4248 return false; 4249 4250 if (Context.getLangOpts().CPlusPlus) { 4251 if (const CXXRecordDecl *Record 4252 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 4253 return ExcludeCtor && !Record->hasMutableFields() && 4254 Record->hasTrivialDestructor(); 4255 } 4256 4257 return true; 4258 } 4259 4260 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 4261 /// create and return an llvm GlobalVariable with the specified type and address 4262 /// space. If there is something in the module with the specified name, return 4263 /// it potentially bitcasted to the right type. 4264 /// 4265 /// If D is non-null, it specifies a decl that correspond to this. This is used 4266 /// to set the attributes on the global when it is first created. 4267 /// 4268 /// If IsForDefinition is true, it is guaranteed that an actual global with 4269 /// type Ty will be returned, not conversion of a variable with the same 4270 /// mangled name but some other type. 4271 llvm::Constant * 4272 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, llvm::Type *Ty, 4273 LangAS AddrSpace, const VarDecl *D, 4274 ForDefinition_t IsForDefinition) { 4275 // Lookup the entry, lazily creating it if necessary. 4276 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4277 unsigned TargetAS = getContext().getTargetAddressSpace(AddrSpace); 4278 if (Entry) { 4279 if (WeakRefReferences.erase(Entry)) { 4280 if (D && !D->hasAttr<WeakAttr>()) 4281 Entry->setLinkage(llvm::Function::ExternalLinkage); 4282 } 4283 4284 // Handle dropped DLL attributes. 4285 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>() && 4286 !shouldMapVisibilityToDLLExport(D)) 4287 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 4288 4289 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 4290 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 4291 4292 if (Entry->getValueType() == Ty && Entry->getAddressSpace() == TargetAS) 4293 return Entry; 4294 4295 // If there are two attempts to define the same mangled name, issue an 4296 // error. 4297 if (IsForDefinition && !Entry->isDeclaration()) { 4298 GlobalDecl OtherGD; 4299 const VarDecl *OtherD; 4300 4301 // Check that D is not yet in DiagnosedConflictingDefinitions is required 4302 // to make sure that we issue an error only once. 4303 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 4304 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 4305 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 4306 OtherD->hasInit() && 4307 DiagnosedConflictingDefinitions.insert(D).second) { 4308 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 4309 << MangledName; 4310 getDiags().Report(OtherGD.getDecl()->getLocation(), 4311 diag::note_previous_definition); 4312 } 4313 } 4314 4315 // Make sure the result is of the correct type. 4316 if (Entry->getType()->getAddressSpace() != TargetAS) { 4317 return llvm::ConstantExpr::getAddrSpaceCast(Entry, 4318 Ty->getPointerTo(TargetAS)); 4319 } 4320 4321 // (If global is requested for a definition, we always need to create a new 4322 // global, not just return a bitcast.) 4323 if (!IsForDefinition) 4324 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo(TargetAS)); 4325 } 4326 4327 auto DAddrSpace = GetGlobalVarAddressSpace(D); 4328 4329 auto *GV = new llvm::GlobalVariable( 4330 getModule(), Ty, false, llvm::GlobalValue::ExternalLinkage, nullptr, 4331 MangledName, nullptr, llvm::GlobalVariable::NotThreadLocal, 4332 getContext().getTargetAddressSpace(DAddrSpace)); 4333 4334 // If we already created a global with the same mangled name (but different 4335 // type) before, take its name and remove it from its parent. 4336 if (Entry) { 4337 GV->takeName(Entry); 4338 4339 if (!Entry->use_empty()) { 4340 llvm::Constant *NewPtrForOldDecl = 4341 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 4342 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4343 } 4344 4345 Entry->eraseFromParent(); 4346 } 4347 4348 // This is the first use or definition of a mangled name. If there is a 4349 // deferred decl with this name, remember that we need to emit it at the end 4350 // of the file. 4351 auto DDI = DeferredDecls.find(MangledName); 4352 if (DDI != DeferredDecls.end()) { 4353 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 4354 // list, and remove it from DeferredDecls (since we don't need it anymore). 4355 addDeferredDeclToEmit(DDI->second); 4356 EmittedDeferredDecls[DDI->first] = DDI->second; 4357 DeferredDecls.erase(DDI); 4358 } 4359 4360 // Handle things which are present even on external declarations. 4361 if (D) { 4362 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 4363 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 4364 4365 // FIXME: This code is overly simple and should be merged with other global 4366 // handling. 4367 GV->setConstant(isTypeConstant(D->getType(), false)); 4368 4369 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4370 4371 setLinkageForGV(GV, D); 4372 4373 if (D->getTLSKind()) { 4374 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4375 CXXThreadLocals.push_back(D); 4376 setTLSMode(GV, *D); 4377 } 4378 4379 setGVProperties(GV, D); 4380 4381 // If required by the ABI, treat declarations of static data members with 4382 // inline initializers as definitions. 4383 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 4384 EmitGlobalVarDefinition(D); 4385 } 4386 4387 // Emit section information for extern variables. 4388 if (D->hasExternalStorage()) { 4389 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 4390 GV->setSection(SA->getName()); 4391 } 4392 4393 // Handle XCore specific ABI requirements. 4394 if (getTriple().getArch() == llvm::Triple::xcore && 4395 D->getLanguageLinkage() == CLanguageLinkage && 4396 D->getType().isConstant(Context) && 4397 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 4398 GV->setSection(".cp.rodata"); 4399 4400 // Check if we a have a const declaration with an initializer, we may be 4401 // able to emit it as available_externally to expose it's value to the 4402 // optimizer. 4403 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 4404 D->getType().isConstQualified() && !GV->hasInitializer() && 4405 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 4406 const auto *Record = 4407 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 4408 bool HasMutableFields = Record && Record->hasMutableFields(); 4409 if (!HasMutableFields) { 4410 const VarDecl *InitDecl; 4411 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4412 if (InitExpr) { 4413 ConstantEmitter emitter(*this); 4414 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 4415 if (Init) { 4416 auto *InitType = Init->getType(); 4417 if (GV->getValueType() != InitType) { 4418 // The type of the initializer does not match the definition. 4419 // This happens when an initializer has a different type from 4420 // the type of the global (because of padding at the end of a 4421 // structure for instance). 4422 GV->setName(StringRef()); 4423 // Make a new global with the correct type, this is now guaranteed 4424 // to work. 4425 auto *NewGV = cast<llvm::GlobalVariable>( 4426 GetAddrOfGlobalVar(D, InitType, IsForDefinition) 4427 ->stripPointerCasts()); 4428 4429 // Erase the old global, since it is no longer used. 4430 GV->eraseFromParent(); 4431 GV = NewGV; 4432 } else { 4433 GV->setInitializer(Init); 4434 GV->setConstant(true); 4435 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 4436 } 4437 emitter.finalize(GV); 4438 } 4439 } 4440 } 4441 } 4442 } 4443 4444 if (GV->isDeclaration()) { 4445 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 4446 // External HIP managed variables needed to be recorded for transformation 4447 // in both device and host compilations. 4448 if (getLangOpts().CUDA && D && D->hasAttr<HIPManagedAttr>() && 4449 D->hasExternalStorage()) 4450 getCUDARuntime().handleVarRegistration(D, *GV); 4451 } 4452 4453 if (D) 4454 SanitizerMD->reportGlobal(GV, *D); 4455 4456 LangAS ExpectedAS = 4457 D ? D->getType().getAddressSpace() 4458 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 4459 assert(getContext().getTargetAddressSpace(ExpectedAS) == TargetAS); 4460 if (DAddrSpace != ExpectedAS) { 4461 return getTargetCodeGenInfo().performAddrSpaceCast( 4462 *this, GV, DAddrSpace, ExpectedAS, Ty->getPointerTo(TargetAS)); 4463 } 4464 4465 return GV; 4466 } 4467 4468 llvm::Constant * 4469 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 4470 const Decl *D = GD.getDecl(); 4471 4472 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 4473 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 4474 /*DontDefer=*/false, IsForDefinition); 4475 4476 if (isa<CXXMethodDecl>(D)) { 4477 auto FInfo = 4478 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 4479 auto Ty = getTypes().GetFunctionType(*FInfo); 4480 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4481 IsForDefinition); 4482 } 4483 4484 if (isa<FunctionDecl>(D)) { 4485 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4486 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4487 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 4488 IsForDefinition); 4489 } 4490 4491 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 4492 } 4493 4494 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 4495 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 4496 unsigned Alignment) { 4497 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 4498 llvm::GlobalVariable *OldGV = nullptr; 4499 4500 if (GV) { 4501 // Check if the variable has the right type. 4502 if (GV->getValueType() == Ty) 4503 return GV; 4504 4505 // Because C++ name mangling, the only way we can end up with an already 4506 // existing global with the same name is if it has been declared extern "C". 4507 assert(GV->isDeclaration() && "Declaration has wrong type!"); 4508 OldGV = GV; 4509 } 4510 4511 // Create a new variable. 4512 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 4513 Linkage, nullptr, Name); 4514 4515 if (OldGV) { 4516 // Replace occurrences of the old variable if needed. 4517 GV->takeName(OldGV); 4518 4519 if (!OldGV->use_empty()) { 4520 llvm::Constant *NewPtrForOldDecl = 4521 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 4522 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 4523 } 4524 4525 OldGV->eraseFromParent(); 4526 } 4527 4528 if (supportsCOMDAT() && GV->isWeakForLinker() && 4529 !GV->hasAvailableExternallyLinkage()) 4530 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 4531 4532 GV->setAlignment(llvm::MaybeAlign(Alignment)); 4533 4534 return GV; 4535 } 4536 4537 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 4538 /// given global variable. If Ty is non-null and if the global doesn't exist, 4539 /// then it will be created with the specified type instead of whatever the 4540 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 4541 /// that an actual global with type Ty will be returned, not conversion of a 4542 /// variable with the same mangled name but some other type. 4543 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 4544 llvm::Type *Ty, 4545 ForDefinition_t IsForDefinition) { 4546 assert(D->hasGlobalStorage() && "Not a global variable"); 4547 QualType ASTTy = D->getType(); 4548 if (!Ty) 4549 Ty = getTypes().ConvertTypeForMem(ASTTy); 4550 4551 StringRef MangledName = getMangledName(D); 4552 return GetOrCreateLLVMGlobal(MangledName, Ty, ASTTy.getAddressSpace(), D, 4553 IsForDefinition); 4554 } 4555 4556 /// CreateRuntimeVariable - Create a new runtime global variable with the 4557 /// specified type and name. 4558 llvm::Constant * 4559 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 4560 StringRef Name) { 4561 LangAS AddrSpace = getContext().getLangOpts().OpenCL ? LangAS::opencl_global 4562 : LangAS::Default; 4563 auto *Ret = GetOrCreateLLVMGlobal(Name, Ty, AddrSpace, nullptr); 4564 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 4565 return Ret; 4566 } 4567 4568 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 4569 assert(!D->getInit() && "Cannot emit definite definitions here!"); 4570 4571 StringRef MangledName = getMangledName(D); 4572 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 4573 4574 // We already have a definition, not declaration, with the same mangled name. 4575 // Emitting of declaration is not required (and actually overwrites emitted 4576 // definition). 4577 if (GV && !GV->isDeclaration()) 4578 return; 4579 4580 // If we have not seen a reference to this variable yet, place it into the 4581 // deferred declarations table to be emitted if needed later. 4582 if (!MustBeEmitted(D) && !GV) { 4583 DeferredDecls[MangledName] = D; 4584 return; 4585 } 4586 4587 // The tentative definition is the only definition. 4588 EmitGlobalVarDefinition(D); 4589 } 4590 4591 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 4592 EmitExternalVarDeclaration(D); 4593 } 4594 4595 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 4596 return Context.toCharUnitsFromBits( 4597 getDataLayout().getTypeStoreSizeInBits(Ty)); 4598 } 4599 4600 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 4601 if (LangOpts.OpenCL) { 4602 LangAS AS = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 4603 assert(AS == LangAS::opencl_global || 4604 AS == LangAS::opencl_global_device || 4605 AS == LangAS::opencl_global_host || 4606 AS == LangAS::opencl_constant || 4607 AS == LangAS::opencl_local || 4608 AS >= LangAS::FirstTargetAddressSpace); 4609 return AS; 4610 } 4611 4612 if (LangOpts.SYCLIsDevice && 4613 (!D || D->getType().getAddressSpace() == LangAS::Default)) 4614 return LangAS::sycl_global; 4615 4616 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 4617 if (D && D->hasAttr<CUDAConstantAttr>()) 4618 return LangAS::cuda_constant; 4619 else if (D && D->hasAttr<CUDASharedAttr>()) 4620 return LangAS::cuda_shared; 4621 else if (D && D->hasAttr<CUDADeviceAttr>()) 4622 return LangAS::cuda_device; 4623 else if (D && D->getType().isConstQualified()) 4624 return LangAS::cuda_constant; 4625 else 4626 return LangAS::cuda_device; 4627 } 4628 4629 if (LangOpts.OpenMP) { 4630 LangAS AS; 4631 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 4632 return AS; 4633 } 4634 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 4635 } 4636 4637 LangAS CodeGenModule::GetGlobalConstantAddressSpace() const { 4638 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 4639 if (LangOpts.OpenCL) 4640 return LangAS::opencl_constant; 4641 if (LangOpts.SYCLIsDevice) 4642 return LangAS::sycl_global; 4643 if (LangOpts.HIP && LangOpts.CUDAIsDevice && getTriple().isSPIRV()) 4644 // For HIPSPV map literals to cuda_device (maps to CrossWorkGroup in SPIR-V) 4645 // instead of default AS (maps to Generic in SPIR-V). Otherwise, we end up 4646 // with OpVariable instructions with Generic storage class which is not 4647 // allowed (SPIR-V V1.6 s3.42.8). Also, mapping literals to SPIR-V 4648 // UniformConstant storage class is not viable as pointers to it may not be 4649 // casted to Generic pointers which are used to model HIP's "flat" pointers. 4650 return LangAS::cuda_device; 4651 if (auto AS = getTarget().getConstantAddressSpace()) 4652 return *AS; 4653 return LangAS::Default; 4654 } 4655 4656 // In address space agnostic languages, string literals are in default address 4657 // space in AST. However, certain targets (e.g. amdgcn) request them to be 4658 // emitted in constant address space in LLVM IR. To be consistent with other 4659 // parts of AST, string literal global variables in constant address space 4660 // need to be casted to default address space before being put into address 4661 // map and referenced by other part of CodeGen. 4662 // In OpenCL, string literals are in constant address space in AST, therefore 4663 // they should not be casted to default address space. 4664 static llvm::Constant * 4665 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 4666 llvm::GlobalVariable *GV) { 4667 llvm::Constant *Cast = GV; 4668 if (!CGM.getLangOpts().OpenCL) { 4669 auto AS = CGM.GetGlobalConstantAddressSpace(); 4670 if (AS != LangAS::Default) 4671 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4672 CGM, GV, AS, LangAS::Default, 4673 GV->getValueType()->getPointerTo( 4674 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 4675 } 4676 return Cast; 4677 } 4678 4679 template<typename SomeDecl> 4680 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 4681 llvm::GlobalValue *GV) { 4682 if (!getLangOpts().CPlusPlus) 4683 return; 4684 4685 // Must have 'used' attribute, or else inline assembly can't rely on 4686 // the name existing. 4687 if (!D->template hasAttr<UsedAttr>()) 4688 return; 4689 4690 // Must have internal linkage and an ordinary name. 4691 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 4692 return; 4693 4694 // Must be in an extern "C" context. Entities declared directly within 4695 // a record are not extern "C" even if the record is in such a context. 4696 const SomeDecl *First = D->getFirstDecl(); 4697 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 4698 return; 4699 4700 // OK, this is an internal linkage entity inside an extern "C" linkage 4701 // specification. Make a note of that so we can give it the "expected" 4702 // mangled name if nothing else is using that name. 4703 std::pair<StaticExternCMap::iterator, bool> R = 4704 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 4705 4706 // If we have multiple internal linkage entities with the same name 4707 // in extern "C" regions, none of them gets that name. 4708 if (!R.second) 4709 R.first->second = nullptr; 4710 } 4711 4712 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 4713 if (!CGM.supportsCOMDAT()) 4714 return false; 4715 4716 if (D.hasAttr<SelectAnyAttr>()) 4717 return true; 4718 4719 GVALinkage Linkage; 4720 if (auto *VD = dyn_cast<VarDecl>(&D)) 4721 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 4722 else 4723 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 4724 4725 switch (Linkage) { 4726 case GVA_Internal: 4727 case GVA_AvailableExternally: 4728 case GVA_StrongExternal: 4729 return false; 4730 case GVA_DiscardableODR: 4731 case GVA_StrongODR: 4732 return true; 4733 } 4734 llvm_unreachable("No such linkage"); 4735 } 4736 4737 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 4738 llvm::GlobalObject &GO) { 4739 if (!shouldBeInCOMDAT(*this, D)) 4740 return; 4741 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 4742 } 4743 4744 /// Pass IsTentative as true if you want to create a tentative definition. 4745 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 4746 bool IsTentative) { 4747 // OpenCL global variables of sampler type are translated to function calls, 4748 // therefore no need to be translated. 4749 QualType ASTTy = D->getType(); 4750 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 4751 return; 4752 4753 // If this is OpenMP device, check if it is legal to emit this global 4754 // normally. 4755 if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 4756 OpenMPRuntime->emitTargetGlobalVariable(D)) 4757 return; 4758 4759 llvm::TrackingVH<llvm::Constant> Init; 4760 bool NeedsGlobalCtor = false; 4761 bool NeedsGlobalDtor = 4762 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 4763 4764 const VarDecl *InitDecl; 4765 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 4766 4767 Optional<ConstantEmitter> emitter; 4768 4769 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 4770 // as part of their declaration." Sema has already checked for 4771 // error cases, so we just need to set Init to UndefValue. 4772 bool IsCUDASharedVar = 4773 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 4774 // Shadows of initialized device-side global variables are also left 4775 // undefined. 4776 // Managed Variables should be initialized on both host side and device side. 4777 bool IsCUDAShadowVar = 4778 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4779 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 4780 D->hasAttr<CUDASharedAttr>()); 4781 bool IsCUDADeviceShadowVar = 4782 getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4783 (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4784 D->getType()->isCUDADeviceBuiltinTextureType()); 4785 if (getLangOpts().CUDA && 4786 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 4787 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4788 else if (D->hasAttr<LoaderUninitializedAttr>()) 4789 Init = llvm::UndefValue::get(getTypes().ConvertTypeForMem(ASTTy)); 4790 else if (!InitExpr) { 4791 // This is a tentative definition; tentative definitions are 4792 // implicitly initialized with { 0 }. 4793 // 4794 // Note that tentative definitions are only emitted at the end of 4795 // a translation unit, so they should never have incomplete 4796 // type. In addition, EmitTentativeDefinition makes sure that we 4797 // never attempt to emit a tentative definition if a real one 4798 // exists. A use may still exists, however, so we still may need 4799 // to do a RAUW. 4800 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 4801 Init = EmitNullConstant(D->getType()); 4802 } else { 4803 initializedGlobalDecl = GlobalDecl(D); 4804 emitter.emplace(*this); 4805 llvm::Constant *Initializer = emitter->tryEmitForInitializer(*InitDecl); 4806 if (!Initializer) { 4807 QualType T = InitExpr->getType(); 4808 if (D->getType()->isReferenceType()) 4809 T = D->getType(); 4810 4811 if (getLangOpts().CPlusPlus) { 4812 if (InitDecl->hasFlexibleArrayInit(getContext())) 4813 ErrorUnsupported(D, "flexible array initializer"); 4814 Init = EmitNullConstant(T); 4815 NeedsGlobalCtor = true; 4816 } else { 4817 ErrorUnsupported(D, "static initializer"); 4818 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 4819 } 4820 } else { 4821 Init = Initializer; 4822 // We don't need an initializer, so remove the entry for the delayed 4823 // initializer position (just in case this entry was delayed) if we 4824 // also don't need to register a destructor. 4825 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 4826 DelayedCXXInitPosition.erase(D); 4827 4828 #ifndef NDEBUG 4829 CharUnits VarSize = getContext().getTypeSizeInChars(ASTTy) + 4830 InitDecl->getFlexibleArrayInitChars(getContext()); 4831 CharUnits CstSize = CharUnits::fromQuantity( 4832 getDataLayout().getTypeAllocSize(Init->getType())); 4833 assert(VarSize == CstSize && "Emitted constant has unexpected size"); 4834 #endif 4835 } 4836 } 4837 4838 llvm::Type* InitType = Init->getType(); 4839 llvm::Constant *Entry = 4840 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 4841 4842 // Strip off pointer casts if we got them. 4843 Entry = Entry->stripPointerCasts(); 4844 4845 // Entry is now either a Function or GlobalVariable. 4846 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 4847 4848 // We have a definition after a declaration with the wrong type. 4849 // We must make a new GlobalVariable* and update everything that used OldGV 4850 // (a declaration or tentative definition) with the new GlobalVariable* 4851 // (which will be a definition). 4852 // 4853 // This happens if there is a prototype for a global (e.g. 4854 // "extern int x[];") and then a definition of a different type (e.g. 4855 // "int x[10];"). This also happens when an initializer has a different type 4856 // from the type of the global (this happens with unions). 4857 if (!GV || GV->getValueType() != InitType || 4858 GV->getType()->getAddressSpace() != 4859 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 4860 4861 // Move the old entry aside so that we'll create a new one. 4862 Entry->setName(StringRef()); 4863 4864 // Make a new global with the correct type, this is now guaranteed to work. 4865 GV = cast<llvm::GlobalVariable>( 4866 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4867 ->stripPointerCasts()); 4868 4869 // Replace all uses of the old global with the new global 4870 llvm::Constant *NewPtrForOldDecl = 4871 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, 4872 Entry->getType()); 4873 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4874 4875 // Erase the old global, since it is no longer used. 4876 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 4877 } 4878 4879 MaybeHandleStaticInExternC(D, GV); 4880 4881 if (D->hasAttr<AnnotateAttr>()) 4882 AddGlobalAnnotations(D, GV); 4883 4884 // Set the llvm linkage type as appropriate. 4885 llvm::GlobalValue::LinkageTypes Linkage = 4886 getLLVMLinkageVarDefinition(D, GV->isConstant()); 4887 4888 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 4889 // the device. [...]" 4890 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 4891 // __device__, declares a variable that: [...] 4892 // Is accessible from all the threads within the grid and from the host 4893 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 4894 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 4895 if (GV && LangOpts.CUDA) { 4896 if (LangOpts.CUDAIsDevice) { 4897 if (Linkage != llvm::GlobalValue::InternalLinkage && 4898 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() || 4899 D->getType()->isCUDADeviceBuiltinSurfaceType() || 4900 D->getType()->isCUDADeviceBuiltinTextureType())) 4901 GV->setExternallyInitialized(true); 4902 } else { 4903 getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 4904 } 4905 getCUDARuntime().handleVarRegistration(D, *GV); 4906 } 4907 4908 GV->setInitializer(Init); 4909 if (emitter) 4910 emitter->finalize(GV); 4911 4912 // If it is safe to mark the global 'constant', do so now. 4913 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4914 isTypeConstant(D->getType(), true)); 4915 4916 // If it is in a read-only section, mark it 'constant'. 4917 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4918 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 4919 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 4920 GV->setConstant(true); 4921 } 4922 4923 CharUnits AlignVal = getContext().getDeclAlign(D); 4924 // Check for alignment specifed in an 'omp allocate' directive. 4925 if (llvm::Optional<CharUnits> AlignValFromAllocate = 4926 getOMPAllocateAlignment(D)) 4927 AlignVal = *AlignValFromAllocate; 4928 GV->setAlignment(AlignVal.getAsAlign()); 4929 4930 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 4931 // function is only defined alongside the variable, not also alongside 4932 // callers. Normally, all accesses to a thread_local go through the 4933 // thread-wrapper in order to ensure initialization has occurred, underlying 4934 // variable will never be used other than the thread-wrapper, so it can be 4935 // converted to internal linkage. 4936 // 4937 // However, if the variable has the 'constinit' attribute, it _can_ be 4938 // referenced directly, without calling the thread-wrapper, so the linkage 4939 // must not be changed. 4940 // 4941 // Additionally, if the variable isn't plain external linkage, e.g. if it's 4942 // weak or linkonce, the de-duplication semantics are important to preserve, 4943 // so we don't change the linkage. 4944 if (D->getTLSKind() == VarDecl::TLS_Dynamic && 4945 Linkage == llvm::GlobalValue::ExternalLinkage && 4946 Context.getTargetInfo().getTriple().isOSDarwin() && 4947 !D->hasAttr<ConstInitAttr>()) 4948 Linkage = llvm::GlobalValue::InternalLinkage; 4949 4950 GV->setLinkage(Linkage); 4951 if (D->hasAttr<DLLImportAttr>()) 4952 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 4953 else if (D->hasAttr<DLLExportAttr>()) 4954 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 4955 else 4956 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 4957 4958 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 4959 // common vars aren't constant even if declared const. 4960 GV->setConstant(false); 4961 // Tentative definition of global variables may be initialized with 4962 // non-zero null pointers. In this case they should have weak linkage 4963 // since common linkage must have zero initializer and must not have 4964 // explicit section therefore cannot have non-zero initial value. 4965 if (!GV->getInitializer()->isNullValue()) 4966 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 4967 } 4968 4969 setNonAliasAttributes(D, GV); 4970 4971 if (D->getTLSKind() && !GV->isThreadLocal()) { 4972 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4973 CXXThreadLocals.push_back(D); 4974 setTLSMode(GV, *D); 4975 } 4976 4977 maybeSetTrivialComdat(*D, *GV); 4978 4979 // Emit the initializer function if necessary. 4980 if (NeedsGlobalCtor || NeedsGlobalDtor) 4981 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 4982 4983 SanitizerMD->reportGlobal(GV, *D, NeedsGlobalCtor); 4984 4985 // Emit global variable debug information. 4986 if (CGDebugInfo *DI = getModuleDebugInfo()) 4987 if (getCodeGenOpts().hasReducedDebugInfo()) 4988 DI->EmitGlobalVariable(GV, D); 4989 } 4990 4991 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 4992 if (CGDebugInfo *DI = getModuleDebugInfo()) 4993 if (getCodeGenOpts().hasReducedDebugInfo()) { 4994 QualType ASTTy = D->getType(); 4995 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 4996 llvm::Constant *GV = 4997 GetOrCreateLLVMGlobal(D->getName(), Ty, ASTTy.getAddressSpace(), D); 4998 DI->EmitExternalVariable( 4999 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 5000 } 5001 } 5002 5003 static bool isVarDeclStrongDefinition(const ASTContext &Context, 5004 CodeGenModule &CGM, const VarDecl *D, 5005 bool NoCommon) { 5006 // Don't give variables common linkage if -fno-common was specified unless it 5007 // was overridden by a NoCommon attribute. 5008 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 5009 return true; 5010 5011 // C11 6.9.2/2: 5012 // A declaration of an identifier for an object that has file scope without 5013 // an initializer, and without a storage-class specifier or with the 5014 // storage-class specifier static, constitutes a tentative definition. 5015 if (D->getInit() || D->hasExternalStorage()) 5016 return true; 5017 5018 // A variable cannot be both common and exist in a section. 5019 if (D->hasAttr<SectionAttr>()) 5020 return true; 5021 5022 // A variable cannot be both common and exist in a section. 5023 // We don't try to determine which is the right section in the front-end. 5024 // If no specialized section name is applicable, it will resort to default. 5025 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 5026 D->hasAttr<PragmaClangDataSectionAttr>() || 5027 D->hasAttr<PragmaClangRelroSectionAttr>() || 5028 D->hasAttr<PragmaClangRodataSectionAttr>()) 5029 return true; 5030 5031 // Thread local vars aren't considered common linkage. 5032 if (D->getTLSKind()) 5033 return true; 5034 5035 // Tentative definitions marked with WeakImportAttr are true definitions. 5036 if (D->hasAttr<WeakImportAttr>()) 5037 return true; 5038 5039 // A variable cannot be both common and exist in a comdat. 5040 if (shouldBeInCOMDAT(CGM, *D)) 5041 return true; 5042 5043 // Declarations with a required alignment do not have common linkage in MSVC 5044 // mode. 5045 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5046 if (D->hasAttr<AlignedAttr>()) 5047 return true; 5048 QualType VarType = D->getType(); 5049 if (Context.isAlignmentRequired(VarType)) 5050 return true; 5051 5052 if (const auto *RT = VarType->getAs<RecordType>()) { 5053 const RecordDecl *RD = RT->getDecl(); 5054 for (const FieldDecl *FD : RD->fields()) { 5055 if (FD->isBitField()) 5056 continue; 5057 if (FD->hasAttr<AlignedAttr>()) 5058 return true; 5059 if (Context.isAlignmentRequired(FD->getType())) 5060 return true; 5061 } 5062 } 5063 } 5064 5065 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 5066 // common symbols, so symbols with greater alignment requirements cannot be 5067 // common. 5068 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 5069 // alignments for common symbols via the aligncomm directive, so this 5070 // restriction only applies to MSVC environments. 5071 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 5072 Context.getTypeAlignIfKnown(D->getType()) > 5073 Context.toBits(CharUnits::fromQuantity(32))) 5074 return true; 5075 5076 return false; 5077 } 5078 5079 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 5080 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 5081 if (Linkage == GVA_Internal) 5082 return llvm::Function::InternalLinkage; 5083 5084 if (D->hasAttr<WeakAttr>()) 5085 return llvm::GlobalVariable::WeakAnyLinkage; 5086 5087 if (const auto *FD = D->getAsFunction()) 5088 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 5089 return llvm::GlobalVariable::LinkOnceAnyLinkage; 5090 5091 // We are guaranteed to have a strong definition somewhere else, 5092 // so we can use available_externally linkage. 5093 if (Linkage == GVA_AvailableExternally) 5094 return llvm::GlobalValue::AvailableExternallyLinkage; 5095 5096 // Note that Apple's kernel linker doesn't support symbol 5097 // coalescing, so we need to avoid linkonce and weak linkages there. 5098 // Normally, this means we just map to internal, but for explicit 5099 // instantiations we'll map to external. 5100 5101 // In C++, the compiler has to emit a definition in every translation unit 5102 // that references the function. We should use linkonce_odr because 5103 // a) if all references in this translation unit are optimized away, we 5104 // don't need to codegen it. b) if the function persists, it needs to be 5105 // merged with other definitions. c) C++ has the ODR, so we know the 5106 // definition is dependable. 5107 if (Linkage == GVA_DiscardableODR) 5108 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 5109 : llvm::Function::InternalLinkage; 5110 5111 // An explicit instantiation of a template has weak linkage, since 5112 // explicit instantiations can occur in multiple translation units 5113 // and must all be equivalent. However, we are not allowed to 5114 // throw away these explicit instantiations. 5115 // 5116 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 5117 // so say that CUDA templates are either external (for kernels) or internal. 5118 // This lets llvm perform aggressive inter-procedural optimizations. For 5119 // -fgpu-rdc case, device function calls across multiple TU's are allowed, 5120 // therefore we need to follow the normal linkage paradigm. 5121 if (Linkage == GVA_StrongODR) { 5122 if (getLangOpts().AppleKext) 5123 return llvm::Function::ExternalLinkage; 5124 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 5125 !getLangOpts().GPURelocatableDeviceCode) 5126 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 5127 : llvm::Function::InternalLinkage; 5128 return llvm::Function::WeakODRLinkage; 5129 } 5130 5131 // C++ doesn't have tentative definitions and thus cannot have common 5132 // linkage. 5133 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 5134 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 5135 CodeGenOpts.NoCommon)) 5136 return llvm::GlobalVariable::CommonLinkage; 5137 5138 // selectany symbols are externally visible, so use weak instead of 5139 // linkonce. MSVC optimizes away references to const selectany globals, so 5140 // all definitions should be the same and ODR linkage should be used. 5141 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 5142 if (D->hasAttr<SelectAnyAttr>()) 5143 return llvm::GlobalVariable::WeakODRLinkage; 5144 5145 // Otherwise, we have strong external linkage. 5146 assert(Linkage == GVA_StrongExternal); 5147 return llvm::GlobalVariable::ExternalLinkage; 5148 } 5149 5150 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 5151 const VarDecl *VD, bool IsConstant) { 5152 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 5153 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 5154 } 5155 5156 /// Replace the uses of a function that was declared with a non-proto type. 5157 /// We want to silently drop extra arguments from call sites 5158 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 5159 llvm::Function *newFn) { 5160 // Fast path. 5161 if (old->use_empty()) return; 5162 5163 llvm::Type *newRetTy = newFn->getReturnType(); 5164 SmallVector<llvm::Value*, 4> newArgs; 5165 5166 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 5167 ui != ue; ) { 5168 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 5169 llvm::User *user = use->getUser(); 5170 5171 // Recognize and replace uses of bitcasts. Most calls to 5172 // unprototyped functions will use bitcasts. 5173 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 5174 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 5175 replaceUsesOfNonProtoConstant(bitcast, newFn); 5176 continue; 5177 } 5178 5179 // Recognize calls to the function. 5180 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 5181 if (!callSite) continue; 5182 if (!callSite->isCallee(&*use)) 5183 continue; 5184 5185 // If the return types don't match exactly, then we can't 5186 // transform this call unless it's dead. 5187 if (callSite->getType() != newRetTy && !callSite->use_empty()) 5188 continue; 5189 5190 // Get the call site's attribute list. 5191 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 5192 llvm::AttributeList oldAttrs = callSite->getAttributes(); 5193 5194 // If the function was passed too few arguments, don't transform. 5195 unsigned newNumArgs = newFn->arg_size(); 5196 if (callSite->arg_size() < newNumArgs) 5197 continue; 5198 5199 // If extra arguments were passed, we silently drop them. 5200 // If any of the types mismatch, we don't transform. 5201 unsigned argNo = 0; 5202 bool dontTransform = false; 5203 for (llvm::Argument &A : newFn->args()) { 5204 if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 5205 dontTransform = true; 5206 break; 5207 } 5208 5209 // Add any parameter attributes. 5210 newArgAttrs.push_back(oldAttrs.getParamAttrs(argNo)); 5211 argNo++; 5212 } 5213 if (dontTransform) 5214 continue; 5215 5216 // Okay, we can transform this. Create the new call instruction and copy 5217 // over the required information. 5218 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 5219 5220 // Copy over any operand bundles. 5221 SmallVector<llvm::OperandBundleDef, 1> newBundles; 5222 callSite->getOperandBundlesAsDefs(newBundles); 5223 5224 llvm::CallBase *newCall; 5225 if (isa<llvm::CallInst>(callSite)) { 5226 newCall = 5227 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 5228 } else { 5229 auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 5230 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 5231 oldInvoke->getUnwindDest(), newArgs, 5232 newBundles, "", callSite); 5233 } 5234 newArgs.clear(); // for the next iteration 5235 5236 if (!newCall->getType()->isVoidTy()) 5237 newCall->takeName(callSite); 5238 newCall->setAttributes( 5239 llvm::AttributeList::get(newFn->getContext(), oldAttrs.getFnAttrs(), 5240 oldAttrs.getRetAttrs(), newArgAttrs)); 5241 newCall->setCallingConv(callSite->getCallingConv()); 5242 5243 // Finally, remove the old call, replacing any uses with the new one. 5244 if (!callSite->use_empty()) 5245 callSite->replaceAllUsesWith(newCall); 5246 5247 // Copy debug location attached to CI. 5248 if (callSite->getDebugLoc()) 5249 newCall->setDebugLoc(callSite->getDebugLoc()); 5250 5251 callSite->eraseFromParent(); 5252 } 5253 } 5254 5255 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 5256 /// implement a function with no prototype, e.g. "int foo() {}". If there are 5257 /// existing call uses of the old function in the module, this adjusts them to 5258 /// call the new function directly. 5259 /// 5260 /// This is not just a cleanup: the always_inline pass requires direct calls to 5261 /// functions to be able to inline them. If there is a bitcast in the way, it 5262 /// won't inline them. Instcombine normally deletes these calls, but it isn't 5263 /// run at -O0. 5264 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 5265 llvm::Function *NewFn) { 5266 // If we're redefining a global as a function, don't transform it. 5267 if (!isa<llvm::Function>(Old)) return; 5268 5269 replaceUsesOfNonProtoConstant(Old, NewFn); 5270 } 5271 5272 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 5273 auto DK = VD->isThisDeclarationADefinition(); 5274 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 5275 return; 5276 5277 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 5278 // If we have a definition, this might be a deferred decl. If the 5279 // instantiation is explicit, make sure we emit it at the end. 5280 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 5281 GetAddrOfGlobalVar(VD); 5282 5283 EmitTopLevelDecl(VD); 5284 } 5285 5286 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 5287 llvm::GlobalValue *GV) { 5288 const auto *D = cast<FunctionDecl>(GD.getDecl()); 5289 5290 // Compute the function info and LLVM type. 5291 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 5292 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 5293 5294 // Get or create the prototype for the function. 5295 if (!GV || (GV->getValueType() != Ty)) 5296 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 5297 /*DontDefer=*/true, 5298 ForDefinition)); 5299 5300 // Already emitted. 5301 if (!GV->isDeclaration()) 5302 return; 5303 5304 // We need to set linkage and visibility on the function before 5305 // generating code for it because various parts of IR generation 5306 // want to propagate this information down (e.g. to local static 5307 // declarations). 5308 auto *Fn = cast<llvm::Function>(GV); 5309 setFunctionLinkage(GD, Fn); 5310 5311 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 5312 setGVProperties(Fn, GD); 5313 5314 MaybeHandleStaticInExternC(D, Fn); 5315 5316 maybeSetTrivialComdat(*D, *Fn); 5317 5318 // Set CodeGen attributes that represent floating point environment. 5319 setLLVMFunctionFEnvAttributes(D, Fn); 5320 5321 CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 5322 5323 setNonAliasAttributes(GD, Fn); 5324 SetLLVMFunctionAttributesForDefinition(D, Fn); 5325 5326 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 5327 AddGlobalCtor(Fn, CA->getPriority()); 5328 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 5329 AddGlobalDtor(Fn, DA->getPriority(), true); 5330 if (D->hasAttr<AnnotateAttr>()) 5331 AddGlobalAnnotations(D, Fn); 5332 } 5333 5334 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 5335 const auto *D = cast<ValueDecl>(GD.getDecl()); 5336 const AliasAttr *AA = D->getAttr<AliasAttr>(); 5337 assert(AA && "Not an alias?"); 5338 5339 StringRef MangledName = getMangledName(GD); 5340 5341 if (AA->getAliasee() == MangledName) { 5342 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5343 return; 5344 } 5345 5346 // If there is a definition in the module, then it wins over the alias. 5347 // This is dubious, but allow it to be safe. Just ignore the alias. 5348 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5349 if (Entry && !Entry->isDeclaration()) 5350 return; 5351 5352 Aliases.push_back(GD); 5353 5354 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5355 5356 // Create a reference to the named value. This ensures that it is emitted 5357 // if a deferred decl. 5358 llvm::Constant *Aliasee; 5359 llvm::GlobalValue::LinkageTypes LT; 5360 if (isa<llvm::FunctionType>(DeclTy)) { 5361 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 5362 /*ForVTable=*/false); 5363 LT = getFunctionLinkage(GD); 5364 } else { 5365 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), DeclTy, LangAS::Default, 5366 /*D=*/nullptr); 5367 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 5368 LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified()); 5369 else 5370 LT = getFunctionLinkage(GD); 5371 } 5372 5373 // Create the new alias itself, but don't set a name yet. 5374 unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 5375 auto *GA = 5376 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 5377 5378 if (Entry) { 5379 if (GA->getAliasee() == Entry) { 5380 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 5381 return; 5382 } 5383 5384 assert(Entry->isDeclaration()); 5385 5386 // If there is a declaration in the module, then we had an extern followed 5387 // by the alias, as in: 5388 // extern int test6(); 5389 // ... 5390 // int test6() __attribute__((alias("test7"))); 5391 // 5392 // Remove it and replace uses of it with the alias. 5393 GA->takeName(Entry); 5394 5395 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 5396 Entry->getType())); 5397 Entry->eraseFromParent(); 5398 } else { 5399 GA->setName(MangledName); 5400 } 5401 5402 // Set attributes which are particular to an alias; this is a 5403 // specialization of the attributes which may be set on a global 5404 // variable/function. 5405 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 5406 D->isWeakImported()) { 5407 GA->setLinkage(llvm::Function::WeakAnyLinkage); 5408 } 5409 5410 if (const auto *VD = dyn_cast<VarDecl>(D)) 5411 if (VD->getTLSKind()) 5412 setTLSMode(GA, *VD); 5413 5414 SetCommonAttributes(GD, GA); 5415 5416 // Emit global alias debug information. 5417 if (isa<VarDecl>(D)) 5418 if (CGDebugInfo *DI = getModuleDebugInfo()) 5419 DI->EmitGlobalAlias(cast<llvm::GlobalValue>(GA->getAliasee()->stripPointerCasts()), GD); 5420 } 5421 5422 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 5423 const auto *D = cast<ValueDecl>(GD.getDecl()); 5424 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 5425 assert(IFA && "Not an ifunc?"); 5426 5427 StringRef MangledName = getMangledName(GD); 5428 5429 if (IFA->getResolver() == MangledName) { 5430 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5431 return; 5432 } 5433 5434 // Report an error if some definition overrides ifunc. 5435 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 5436 if (Entry && !Entry->isDeclaration()) { 5437 GlobalDecl OtherGD; 5438 if (lookupRepresentativeDecl(MangledName, OtherGD) && 5439 DiagnosedConflictingDefinitions.insert(GD).second) { 5440 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 5441 << MangledName; 5442 Diags.Report(OtherGD.getDecl()->getLocation(), 5443 diag::note_previous_definition); 5444 } 5445 return; 5446 } 5447 5448 Aliases.push_back(GD); 5449 5450 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 5451 llvm::Type *ResolverTy = llvm::GlobalIFunc::getResolverFunctionType(DeclTy); 5452 llvm::Constant *Resolver = 5453 GetOrCreateLLVMFunction(IFA->getResolver(), ResolverTy, {}, 5454 /*ForVTable=*/false); 5455 llvm::GlobalIFunc *GIF = 5456 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 5457 "", Resolver, &getModule()); 5458 if (Entry) { 5459 if (GIF->getResolver() == Entry) { 5460 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 5461 return; 5462 } 5463 assert(Entry->isDeclaration()); 5464 5465 // If there is a declaration in the module, then we had an extern followed 5466 // by the ifunc, as in: 5467 // extern int test(); 5468 // ... 5469 // int test() __attribute__((ifunc("resolver"))); 5470 // 5471 // Remove it and replace uses of it with the ifunc. 5472 GIF->takeName(Entry); 5473 5474 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 5475 Entry->getType())); 5476 Entry->eraseFromParent(); 5477 } else 5478 GIF->setName(MangledName); 5479 5480 SetCommonAttributes(GD, GIF); 5481 } 5482 5483 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 5484 ArrayRef<llvm::Type*> Tys) { 5485 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 5486 Tys); 5487 } 5488 5489 static llvm::StringMapEntry<llvm::GlobalVariable *> & 5490 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 5491 const StringLiteral *Literal, bool TargetIsLSB, 5492 bool &IsUTF16, unsigned &StringLength) { 5493 StringRef String = Literal->getString(); 5494 unsigned NumBytes = String.size(); 5495 5496 // Check for simple case. 5497 if (!Literal->containsNonAsciiOrNull()) { 5498 StringLength = NumBytes; 5499 return *Map.insert(std::make_pair(String, nullptr)).first; 5500 } 5501 5502 // Otherwise, convert the UTF8 literals into a string of shorts. 5503 IsUTF16 = true; 5504 5505 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 5506 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5507 llvm::UTF16 *ToPtr = &ToBuf[0]; 5508 5509 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5510 ToPtr + NumBytes, llvm::strictConversion); 5511 5512 // ConvertUTF8toUTF16 returns the length in ToPtr. 5513 StringLength = ToPtr - &ToBuf[0]; 5514 5515 // Add an explicit null. 5516 *ToPtr = 0; 5517 return *Map.insert(std::make_pair( 5518 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 5519 (StringLength + 1) * 2), 5520 nullptr)).first; 5521 } 5522 5523 ConstantAddress 5524 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 5525 unsigned StringLength = 0; 5526 bool isUTF16 = false; 5527 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 5528 GetConstantCFStringEntry(CFConstantStringMap, Literal, 5529 getDataLayout().isLittleEndian(), isUTF16, 5530 StringLength); 5531 5532 if (auto *C = Entry.second) 5533 return ConstantAddress( 5534 C, C->getValueType(), CharUnits::fromQuantity(C->getAlignment())); 5535 5536 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 5537 llvm::Constant *Zeros[] = { Zero, Zero }; 5538 5539 const ASTContext &Context = getContext(); 5540 const llvm::Triple &Triple = getTriple(); 5541 5542 const auto CFRuntime = getLangOpts().CFRuntime; 5543 const bool IsSwiftABI = 5544 static_cast<unsigned>(CFRuntime) >= 5545 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 5546 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 5547 5548 // If we don't already have it, get __CFConstantStringClassReference. 5549 if (!CFConstantStringClassRef) { 5550 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 5551 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 5552 Ty = llvm::ArrayType::get(Ty, 0); 5553 5554 switch (CFRuntime) { 5555 default: break; 5556 case LangOptions::CoreFoundationABI::Swift: [[fallthrough]]; 5557 case LangOptions::CoreFoundationABI::Swift5_0: 5558 CFConstantStringClassName = 5559 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 5560 : "$s10Foundation19_NSCFConstantStringCN"; 5561 Ty = IntPtrTy; 5562 break; 5563 case LangOptions::CoreFoundationABI::Swift4_2: 5564 CFConstantStringClassName = 5565 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 5566 : "$S10Foundation19_NSCFConstantStringCN"; 5567 Ty = IntPtrTy; 5568 break; 5569 case LangOptions::CoreFoundationABI::Swift4_1: 5570 CFConstantStringClassName = 5571 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 5572 : "__T010Foundation19_NSCFConstantStringCN"; 5573 Ty = IntPtrTy; 5574 break; 5575 } 5576 5577 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 5578 5579 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 5580 llvm::GlobalValue *GV = nullptr; 5581 5582 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 5583 IdentifierInfo &II = Context.Idents.get(GV->getName()); 5584 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 5585 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 5586 5587 const VarDecl *VD = nullptr; 5588 for (const auto *Result : DC->lookup(&II)) 5589 if ((VD = dyn_cast<VarDecl>(Result))) 5590 break; 5591 5592 if (Triple.isOSBinFormatELF()) { 5593 if (!VD) 5594 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5595 } else { 5596 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 5597 if (!VD || !VD->hasAttr<DLLExportAttr>()) 5598 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 5599 else 5600 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 5601 } 5602 5603 setDSOLocal(GV); 5604 } 5605 } 5606 5607 // Decay array -> ptr 5608 CFConstantStringClassRef = 5609 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 5610 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 5611 } 5612 5613 QualType CFTy = Context.getCFConstantStringType(); 5614 5615 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 5616 5617 ConstantInitBuilder Builder(*this); 5618 auto Fields = Builder.beginStruct(STy); 5619 5620 // Class pointer. 5621 Fields.add(cast<llvm::Constant>(CFConstantStringClassRef)); 5622 5623 // Flags. 5624 if (IsSwiftABI) { 5625 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 5626 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 5627 } else { 5628 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 5629 } 5630 5631 // String pointer. 5632 llvm::Constant *C = nullptr; 5633 if (isUTF16) { 5634 auto Arr = llvm::makeArrayRef( 5635 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 5636 Entry.first().size() / 2); 5637 C = llvm::ConstantDataArray::get(VMContext, Arr); 5638 } else { 5639 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 5640 } 5641 5642 // Note: -fwritable-strings doesn't make the backing store strings of 5643 // CFStrings writable. (See <rdar://problem/10657500>) 5644 auto *GV = 5645 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 5646 llvm::GlobalValue::PrivateLinkage, C, ".str"); 5647 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5648 // Don't enforce the target's minimum global alignment, since the only use 5649 // of the string is via this class initializer. 5650 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 5651 : Context.getTypeAlignInChars(Context.CharTy); 5652 GV->setAlignment(Align.getAsAlign()); 5653 5654 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 5655 // Without it LLVM can merge the string with a non unnamed_addr one during 5656 // LTO. Doing that changes the section it ends in, which surprises ld64. 5657 if (Triple.isOSBinFormatMachO()) 5658 GV->setSection(isUTF16 ? "__TEXT,__ustring" 5659 : "__TEXT,__cstring,cstring_literals"); 5660 // Make sure the literal ends up in .rodata to allow for safe ICF and for 5661 // the static linker to adjust permissions to read-only later on. 5662 else if (Triple.isOSBinFormatELF()) 5663 GV->setSection(".rodata"); 5664 5665 // String. 5666 llvm::Constant *Str = 5667 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 5668 5669 if (isUTF16) 5670 // Cast the UTF16 string to the correct type. 5671 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 5672 Fields.add(Str); 5673 5674 // String length. 5675 llvm::IntegerType *LengthTy = 5676 llvm::IntegerType::get(getModule().getContext(), 5677 Context.getTargetInfo().getLongWidth()); 5678 if (IsSwiftABI) { 5679 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 5680 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 5681 LengthTy = Int32Ty; 5682 else 5683 LengthTy = IntPtrTy; 5684 } 5685 Fields.addInt(LengthTy, StringLength); 5686 5687 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 5688 // properly aligned on 32-bit platforms. 5689 CharUnits Alignment = 5690 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 5691 5692 // The struct. 5693 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 5694 /*isConstant=*/false, 5695 llvm::GlobalVariable::PrivateLinkage); 5696 GV->addAttribute("objc_arc_inert"); 5697 switch (Triple.getObjectFormat()) { 5698 case llvm::Triple::UnknownObjectFormat: 5699 llvm_unreachable("unknown file format"); 5700 case llvm::Triple::DXContainer: 5701 case llvm::Triple::GOFF: 5702 case llvm::Triple::SPIRV: 5703 case llvm::Triple::XCOFF: 5704 llvm_unreachable("unimplemented"); 5705 case llvm::Triple::COFF: 5706 case llvm::Triple::ELF: 5707 case llvm::Triple::Wasm: 5708 GV->setSection("cfstring"); 5709 break; 5710 case llvm::Triple::MachO: 5711 GV->setSection("__DATA,__cfstring"); 5712 break; 5713 } 5714 Entry.second = GV; 5715 5716 return ConstantAddress(GV, GV->getValueType(), Alignment); 5717 } 5718 5719 bool CodeGenModule::getExpressionLocationsEnabled() const { 5720 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 5721 } 5722 5723 QualType CodeGenModule::getObjCFastEnumerationStateType() { 5724 if (ObjCFastEnumerationStateType.isNull()) { 5725 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 5726 D->startDefinition(); 5727 5728 QualType FieldTypes[] = { 5729 Context.UnsignedLongTy, 5730 Context.getPointerType(Context.getObjCIdType()), 5731 Context.getPointerType(Context.UnsignedLongTy), 5732 Context.getConstantArrayType(Context.UnsignedLongTy, 5733 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 5734 }; 5735 5736 for (size_t i = 0; i < 4; ++i) { 5737 FieldDecl *Field = FieldDecl::Create(Context, 5738 D, 5739 SourceLocation(), 5740 SourceLocation(), nullptr, 5741 FieldTypes[i], /*TInfo=*/nullptr, 5742 /*BitWidth=*/nullptr, 5743 /*Mutable=*/false, 5744 ICIS_NoInit); 5745 Field->setAccess(AS_public); 5746 D->addDecl(Field); 5747 } 5748 5749 D->completeDefinition(); 5750 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 5751 } 5752 5753 return ObjCFastEnumerationStateType; 5754 } 5755 5756 llvm::Constant * 5757 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 5758 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 5759 5760 // Don't emit it as the address of the string, emit the string data itself 5761 // as an inline array. 5762 if (E->getCharByteWidth() == 1) { 5763 SmallString<64> Str(E->getString()); 5764 5765 // Resize the string to the right size, which is indicated by its type. 5766 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 5767 Str.resize(CAT->getSize().getZExtValue()); 5768 return llvm::ConstantDataArray::getString(VMContext, Str, false); 5769 } 5770 5771 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 5772 llvm::Type *ElemTy = AType->getElementType(); 5773 unsigned NumElements = AType->getNumElements(); 5774 5775 // Wide strings have either 2-byte or 4-byte elements. 5776 if (ElemTy->getPrimitiveSizeInBits() == 16) { 5777 SmallVector<uint16_t, 32> Elements; 5778 Elements.reserve(NumElements); 5779 5780 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5781 Elements.push_back(E->getCodeUnit(i)); 5782 Elements.resize(NumElements); 5783 return llvm::ConstantDataArray::get(VMContext, Elements); 5784 } 5785 5786 assert(ElemTy->getPrimitiveSizeInBits() == 32); 5787 SmallVector<uint32_t, 32> Elements; 5788 Elements.reserve(NumElements); 5789 5790 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5791 Elements.push_back(E->getCodeUnit(i)); 5792 Elements.resize(NumElements); 5793 return llvm::ConstantDataArray::get(VMContext, Elements); 5794 } 5795 5796 static llvm::GlobalVariable * 5797 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 5798 CodeGenModule &CGM, StringRef GlobalName, 5799 CharUnits Alignment) { 5800 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5801 CGM.GetGlobalConstantAddressSpace()); 5802 5803 llvm::Module &M = CGM.getModule(); 5804 // Create a global variable for this string 5805 auto *GV = new llvm::GlobalVariable( 5806 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 5807 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5808 GV->setAlignment(Alignment.getAsAlign()); 5809 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5810 if (GV->isWeakForLinker()) { 5811 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 5812 GV->setComdat(M.getOrInsertComdat(GV->getName())); 5813 } 5814 CGM.setDSOLocal(GV); 5815 5816 return GV; 5817 } 5818 5819 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 5820 /// constant array for the given string literal. 5821 ConstantAddress 5822 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 5823 StringRef Name) { 5824 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 5825 5826 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 5827 llvm::GlobalVariable **Entry = nullptr; 5828 if (!LangOpts.WritableStrings) { 5829 Entry = &ConstantStringMap[C]; 5830 if (auto GV = *Entry) { 5831 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5832 GV->setAlignment(Alignment.getAsAlign()); 5833 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5834 GV->getValueType(), Alignment); 5835 } 5836 } 5837 5838 SmallString<256> MangledNameBuffer; 5839 StringRef GlobalVariableName; 5840 llvm::GlobalValue::LinkageTypes LT; 5841 5842 // Mangle the string literal if that's how the ABI merges duplicate strings. 5843 // Don't do it if they are writable, since we don't want writes in one TU to 5844 // affect strings in another. 5845 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 5846 !LangOpts.WritableStrings) { 5847 llvm::raw_svector_ostream Out(MangledNameBuffer); 5848 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 5849 LT = llvm::GlobalValue::LinkOnceODRLinkage; 5850 GlobalVariableName = MangledNameBuffer; 5851 } else { 5852 LT = llvm::GlobalValue::PrivateLinkage; 5853 GlobalVariableName = Name; 5854 } 5855 5856 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 5857 5858 CGDebugInfo *DI = getModuleDebugInfo(); 5859 if (DI && getCodeGenOpts().hasReducedDebugInfo()) 5860 DI->AddStringLiteralDebugInfo(GV, S); 5861 5862 if (Entry) 5863 *Entry = GV; 5864 5865 SanitizerMD->reportGlobal(GV, S->getStrTokenLoc(0), "<string literal>"); 5866 5867 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5868 GV->getValueType(), Alignment); 5869 } 5870 5871 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 5872 /// array for the given ObjCEncodeExpr node. 5873 ConstantAddress 5874 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 5875 std::string Str; 5876 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 5877 5878 return GetAddrOfConstantCString(Str); 5879 } 5880 5881 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 5882 /// the literal and a terminating '\0' character. 5883 /// The result has pointer to array type. 5884 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 5885 const std::string &Str, const char *GlobalName) { 5886 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 5887 CharUnits Alignment = 5888 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 5889 5890 llvm::Constant *C = 5891 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 5892 5893 // Don't share any string literals if strings aren't constant. 5894 llvm::GlobalVariable **Entry = nullptr; 5895 if (!LangOpts.WritableStrings) { 5896 Entry = &ConstantStringMap[C]; 5897 if (auto GV = *Entry) { 5898 if (uint64_t(Alignment.getQuantity()) > GV->getAlignment()) 5899 GV->setAlignment(Alignment.getAsAlign()); 5900 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5901 GV->getValueType(), Alignment); 5902 } 5903 } 5904 5905 // Get the default prefix if a name wasn't specified. 5906 if (!GlobalName) 5907 GlobalName = ".str"; 5908 // Create a global variable for this. 5909 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 5910 GlobalName, Alignment); 5911 if (Entry) 5912 *Entry = GV; 5913 5914 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5915 GV->getValueType(), Alignment); 5916 } 5917 5918 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 5919 const MaterializeTemporaryExpr *E, const Expr *Init) { 5920 assert((E->getStorageDuration() == SD_Static || 5921 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 5922 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 5923 5924 // If we're not materializing a subobject of the temporary, keep the 5925 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 5926 QualType MaterializedType = Init->getType(); 5927 if (Init == E->getSubExpr()) 5928 MaterializedType = E->getType(); 5929 5930 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 5931 5932 auto InsertResult = MaterializedGlobalTemporaryMap.insert({E, nullptr}); 5933 if (!InsertResult.second) { 5934 // We've seen this before: either we already created it or we're in the 5935 // process of doing so. 5936 if (!InsertResult.first->second) { 5937 // We recursively re-entered this function, probably during emission of 5938 // the initializer. Create a placeholder. We'll clean this up in the 5939 // outer call, at the end of this function. 5940 llvm::Type *Type = getTypes().ConvertTypeForMem(MaterializedType); 5941 InsertResult.first->second = new llvm::GlobalVariable( 5942 getModule(), Type, false, llvm::GlobalVariable::InternalLinkage, 5943 nullptr); 5944 } 5945 return ConstantAddress(InsertResult.first->second, 5946 llvm::cast<llvm::GlobalVariable>( 5947 InsertResult.first->second->stripPointerCasts()) 5948 ->getValueType(), 5949 Align); 5950 } 5951 5952 // FIXME: If an externally-visible declaration extends multiple temporaries, 5953 // we need to give each temporary the same name in every translation unit (and 5954 // we also need to make the temporaries externally-visible). 5955 SmallString<256> Name; 5956 llvm::raw_svector_ostream Out(Name); 5957 getCXXABI().getMangleContext().mangleReferenceTemporary( 5958 VD, E->getManglingNumber(), Out); 5959 5960 APValue *Value = nullptr; 5961 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5962 // If the initializer of the extending declaration is a constant 5963 // initializer, we should have a cached constant initializer for this 5964 // temporary. Note that this might have a different value from the value 5965 // computed by evaluating the initializer if the surrounding constant 5966 // expression modifies the temporary. 5967 Value = E->getOrCreateValue(false); 5968 } 5969 5970 // Try evaluating it now, it might have a constant initializer. 5971 Expr::EvalResult EvalResult; 5972 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 5973 !EvalResult.hasSideEffects()) 5974 Value = &EvalResult.Val; 5975 5976 LangAS AddrSpace = 5977 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 5978 5979 Optional<ConstantEmitter> emitter; 5980 llvm::Constant *InitialValue = nullptr; 5981 bool Constant = false; 5982 llvm::Type *Type; 5983 if (Value) { 5984 // The temporary has a constant initializer, use it. 5985 emitter.emplace(*this); 5986 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 5987 MaterializedType); 5988 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 5989 Type = InitialValue->getType(); 5990 } else { 5991 // No initializer, the initialization will be provided when we 5992 // initialize the declaration which performed lifetime extension. 5993 Type = getTypes().ConvertTypeForMem(MaterializedType); 5994 } 5995 5996 // Create a global variable for this lifetime-extended temporary. 5997 llvm::GlobalValue::LinkageTypes Linkage = 5998 getLLVMLinkageVarDefinition(VD, Constant); 5999 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 6000 const VarDecl *InitVD; 6001 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 6002 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 6003 // Temporaries defined inside a class get linkonce_odr linkage because the 6004 // class can be defined in multiple translation units. 6005 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 6006 } else { 6007 // There is no need for this temporary to have external linkage if the 6008 // VarDecl has external linkage. 6009 Linkage = llvm::GlobalVariable::InternalLinkage; 6010 } 6011 } 6012 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 6013 auto *GV = new llvm::GlobalVariable( 6014 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 6015 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 6016 if (emitter) emitter->finalize(GV); 6017 // Don't assign dllimport or dllexport to local linkage globals. 6018 if (!llvm::GlobalValue::isLocalLinkage(Linkage)) { 6019 setGVProperties(GV, VD); 6020 if (GV->getDLLStorageClass() == llvm::GlobalVariable::DLLExportStorageClass) 6021 // The reference temporary should never be dllexport. 6022 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 6023 } 6024 GV->setAlignment(Align.getAsAlign()); 6025 if (supportsCOMDAT() && GV->isWeakForLinker()) 6026 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 6027 if (VD->getTLSKind()) 6028 setTLSMode(GV, *VD); 6029 llvm::Constant *CV = GV; 6030 if (AddrSpace != LangAS::Default) 6031 CV = getTargetCodeGenInfo().performAddrSpaceCast( 6032 *this, GV, AddrSpace, LangAS::Default, 6033 Type->getPointerTo( 6034 getContext().getTargetAddressSpace(LangAS::Default))); 6035 6036 // Update the map with the new temporary. If we created a placeholder above, 6037 // replace it with the new global now. 6038 llvm::Constant *&Entry = MaterializedGlobalTemporaryMap[E]; 6039 if (Entry) { 6040 Entry->replaceAllUsesWith( 6041 llvm::ConstantExpr::getBitCast(CV, Entry->getType())); 6042 llvm::cast<llvm::GlobalVariable>(Entry)->eraseFromParent(); 6043 } 6044 Entry = CV; 6045 6046 return ConstantAddress(CV, Type, Align); 6047 } 6048 6049 /// EmitObjCPropertyImplementations - Emit information for synthesized 6050 /// properties for an implementation. 6051 void CodeGenModule::EmitObjCPropertyImplementations(const 6052 ObjCImplementationDecl *D) { 6053 for (const auto *PID : D->property_impls()) { 6054 // Dynamic is just for type-checking. 6055 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 6056 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 6057 6058 // Determine which methods need to be implemented, some may have 6059 // been overridden. Note that ::isPropertyAccessor is not the method 6060 // we want, that just indicates if the decl came from a 6061 // property. What we want to know is if the method is defined in 6062 // this implementation. 6063 auto *Getter = PID->getGetterMethodDecl(); 6064 if (!Getter || Getter->isSynthesizedAccessorStub()) 6065 CodeGenFunction(*this).GenerateObjCGetter( 6066 const_cast<ObjCImplementationDecl *>(D), PID); 6067 auto *Setter = PID->getSetterMethodDecl(); 6068 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 6069 CodeGenFunction(*this).GenerateObjCSetter( 6070 const_cast<ObjCImplementationDecl *>(D), PID); 6071 } 6072 } 6073 } 6074 6075 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 6076 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 6077 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 6078 ivar; ivar = ivar->getNextIvar()) 6079 if (ivar->getType().isDestructedType()) 6080 return true; 6081 6082 return false; 6083 } 6084 6085 static bool AllTrivialInitializers(CodeGenModule &CGM, 6086 ObjCImplementationDecl *D) { 6087 CodeGenFunction CGF(CGM); 6088 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 6089 E = D->init_end(); B != E; ++B) { 6090 CXXCtorInitializer *CtorInitExp = *B; 6091 Expr *Init = CtorInitExp->getInit(); 6092 if (!CGF.isTrivialInitializer(Init)) 6093 return false; 6094 } 6095 return true; 6096 } 6097 6098 /// EmitObjCIvarInitializations - Emit information for ivar initialization 6099 /// for an implementation. 6100 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 6101 // We might need a .cxx_destruct even if we don't have any ivar initializers. 6102 if (needsDestructMethod(D)) { 6103 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 6104 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6105 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 6106 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6107 getContext().VoidTy, nullptr, D, 6108 /*isInstance=*/true, /*isVariadic=*/false, 6109 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6110 /*isImplicitlyDeclared=*/true, 6111 /*isDefined=*/false, ObjCMethodDecl::Required); 6112 D->addInstanceMethod(DTORMethod); 6113 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 6114 D->setHasDestructors(true); 6115 } 6116 6117 // If the implementation doesn't have any ivar initializers, we don't need 6118 // a .cxx_construct. 6119 if (D->getNumIvarInitializers() == 0 || 6120 AllTrivialInitializers(*this, D)) 6121 return; 6122 6123 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 6124 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 6125 // The constructor returns 'self'. 6126 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 6127 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 6128 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 6129 /*isVariadic=*/false, 6130 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 6131 /*isImplicitlyDeclared=*/true, 6132 /*isDefined=*/false, ObjCMethodDecl::Required); 6133 D->addInstanceMethod(CTORMethod); 6134 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 6135 D->setHasNonZeroConstructors(true); 6136 } 6137 6138 // EmitLinkageSpec - Emit all declarations in a linkage spec. 6139 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 6140 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 6141 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 6142 ErrorUnsupported(LSD, "linkage spec"); 6143 return; 6144 } 6145 6146 EmitDeclContext(LSD); 6147 } 6148 6149 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 6150 for (auto *I : DC->decls()) { 6151 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 6152 // are themselves considered "top-level", so EmitTopLevelDecl on an 6153 // ObjCImplDecl does not recursively visit them. We need to do that in 6154 // case they're nested inside another construct (LinkageSpecDecl / 6155 // ExportDecl) that does stop them from being considered "top-level". 6156 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 6157 for (auto *M : OID->methods()) 6158 EmitTopLevelDecl(M); 6159 } 6160 6161 EmitTopLevelDecl(I); 6162 } 6163 } 6164 6165 /// EmitTopLevelDecl - Emit code for a single top level declaration. 6166 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 6167 // Ignore dependent declarations. 6168 if (D->isTemplated()) 6169 return; 6170 6171 // Consteval function shouldn't be emitted. 6172 if (auto *FD = dyn_cast<FunctionDecl>(D)) 6173 if (FD->isConsteval()) 6174 return; 6175 6176 switch (D->getKind()) { 6177 case Decl::CXXConversion: 6178 case Decl::CXXMethod: 6179 case Decl::Function: 6180 EmitGlobal(cast<FunctionDecl>(D)); 6181 // Always provide some coverage mapping 6182 // even for the functions that aren't emitted. 6183 AddDeferredUnusedCoverageMapping(D); 6184 break; 6185 6186 case Decl::CXXDeductionGuide: 6187 // Function-like, but does not result in code emission. 6188 break; 6189 6190 case Decl::Var: 6191 case Decl::Decomposition: 6192 case Decl::VarTemplateSpecialization: 6193 EmitGlobal(cast<VarDecl>(D)); 6194 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 6195 for (auto *B : DD->bindings()) 6196 if (auto *HD = B->getHoldingVar()) 6197 EmitGlobal(HD); 6198 break; 6199 6200 // Indirect fields from global anonymous structs and unions can be 6201 // ignored; only the actual variable requires IR gen support. 6202 case Decl::IndirectField: 6203 break; 6204 6205 // C++ Decls 6206 case Decl::Namespace: 6207 EmitDeclContext(cast<NamespaceDecl>(D)); 6208 break; 6209 case Decl::ClassTemplateSpecialization: { 6210 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 6211 if (CGDebugInfo *DI = getModuleDebugInfo()) 6212 if (Spec->getSpecializationKind() == 6213 TSK_ExplicitInstantiationDefinition && 6214 Spec->hasDefinition()) 6215 DI->completeTemplateDefinition(*Spec); 6216 } [[fallthrough]]; 6217 case Decl::CXXRecord: { 6218 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 6219 if (CGDebugInfo *DI = getModuleDebugInfo()) { 6220 if (CRD->hasDefinition()) 6221 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6222 if (auto *ES = D->getASTContext().getExternalSource()) 6223 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 6224 DI->completeUnusedClass(*CRD); 6225 } 6226 // Emit any static data members, they may be definitions. 6227 for (auto *I : CRD->decls()) 6228 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 6229 EmitTopLevelDecl(I); 6230 break; 6231 } 6232 // No code generation needed. 6233 case Decl::UsingShadow: 6234 case Decl::ClassTemplate: 6235 case Decl::VarTemplate: 6236 case Decl::Concept: 6237 case Decl::VarTemplatePartialSpecialization: 6238 case Decl::FunctionTemplate: 6239 case Decl::TypeAliasTemplate: 6240 case Decl::Block: 6241 case Decl::Empty: 6242 case Decl::Binding: 6243 break; 6244 case Decl::Using: // using X; [C++] 6245 if (CGDebugInfo *DI = getModuleDebugInfo()) 6246 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 6247 break; 6248 case Decl::UsingEnum: // using enum X; [C++] 6249 if (CGDebugInfo *DI = getModuleDebugInfo()) 6250 DI->EmitUsingEnumDecl(cast<UsingEnumDecl>(*D)); 6251 break; 6252 case Decl::NamespaceAlias: 6253 if (CGDebugInfo *DI = getModuleDebugInfo()) 6254 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 6255 break; 6256 case Decl::UsingDirective: // using namespace X; [C++] 6257 if (CGDebugInfo *DI = getModuleDebugInfo()) 6258 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 6259 break; 6260 case Decl::CXXConstructor: 6261 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 6262 break; 6263 case Decl::CXXDestructor: 6264 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 6265 break; 6266 6267 case Decl::StaticAssert: 6268 // Nothing to do. 6269 break; 6270 6271 // Objective-C Decls 6272 6273 // Forward declarations, no (immediate) code generation. 6274 case Decl::ObjCInterface: 6275 case Decl::ObjCCategory: 6276 break; 6277 6278 case Decl::ObjCProtocol: { 6279 auto *Proto = cast<ObjCProtocolDecl>(D); 6280 if (Proto->isThisDeclarationADefinition()) 6281 ObjCRuntime->GenerateProtocol(Proto); 6282 break; 6283 } 6284 6285 case Decl::ObjCCategoryImpl: 6286 // Categories have properties but don't support synthesize so we 6287 // can ignore them here. 6288 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 6289 break; 6290 6291 case Decl::ObjCImplementation: { 6292 auto *OMD = cast<ObjCImplementationDecl>(D); 6293 EmitObjCPropertyImplementations(OMD); 6294 EmitObjCIvarInitializations(OMD); 6295 ObjCRuntime->GenerateClass(OMD); 6296 // Emit global variable debug information. 6297 if (CGDebugInfo *DI = getModuleDebugInfo()) 6298 if (getCodeGenOpts().hasReducedDebugInfo()) 6299 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 6300 OMD->getClassInterface()), OMD->getLocation()); 6301 break; 6302 } 6303 case Decl::ObjCMethod: { 6304 auto *OMD = cast<ObjCMethodDecl>(D); 6305 // If this is not a prototype, emit the body. 6306 if (OMD->getBody()) 6307 CodeGenFunction(*this).GenerateObjCMethod(OMD); 6308 break; 6309 } 6310 case Decl::ObjCCompatibleAlias: 6311 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 6312 break; 6313 6314 case Decl::PragmaComment: { 6315 const auto *PCD = cast<PragmaCommentDecl>(D); 6316 switch (PCD->getCommentKind()) { 6317 case PCK_Unknown: 6318 llvm_unreachable("unexpected pragma comment kind"); 6319 case PCK_Linker: 6320 AppendLinkerOptions(PCD->getArg()); 6321 break; 6322 case PCK_Lib: 6323 AddDependentLib(PCD->getArg()); 6324 break; 6325 case PCK_Compiler: 6326 case PCK_ExeStr: 6327 case PCK_User: 6328 break; // We ignore all of these. 6329 } 6330 break; 6331 } 6332 6333 case Decl::PragmaDetectMismatch: { 6334 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 6335 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 6336 break; 6337 } 6338 6339 case Decl::LinkageSpec: 6340 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 6341 break; 6342 6343 case Decl::FileScopeAsm: { 6344 // File-scope asm is ignored during device-side CUDA compilation. 6345 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 6346 break; 6347 // File-scope asm is ignored during device-side OpenMP compilation. 6348 if (LangOpts.OpenMPIsDevice) 6349 break; 6350 // File-scope asm is ignored during device-side SYCL compilation. 6351 if (LangOpts.SYCLIsDevice) 6352 break; 6353 auto *AD = cast<FileScopeAsmDecl>(D); 6354 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 6355 break; 6356 } 6357 6358 case Decl::Import: { 6359 auto *Import = cast<ImportDecl>(D); 6360 6361 // If we've already imported this module, we're done. 6362 if (!ImportedModules.insert(Import->getImportedModule())) 6363 break; 6364 6365 // Emit debug information for direct imports. 6366 if (!Import->getImportedOwningModule()) { 6367 if (CGDebugInfo *DI = getModuleDebugInfo()) 6368 DI->EmitImportDecl(*Import); 6369 } 6370 6371 // For C++ standard modules we are done - we will call the module 6372 // initializer for imported modules, and that will likewise call those for 6373 // any imports it has. 6374 if (CXX20ModuleInits && Import->getImportedOwningModule() && 6375 !Import->getImportedOwningModule()->isModuleMapModule()) 6376 break; 6377 6378 // For clang C++ module map modules the initializers for sub-modules are 6379 // emitted here. 6380 6381 // Find all of the submodules and emit the module initializers. 6382 llvm::SmallPtrSet<clang::Module *, 16> Visited; 6383 SmallVector<clang::Module *, 16> Stack; 6384 Visited.insert(Import->getImportedModule()); 6385 Stack.push_back(Import->getImportedModule()); 6386 6387 while (!Stack.empty()) { 6388 clang::Module *Mod = Stack.pop_back_val(); 6389 if (!EmittedModuleInitializers.insert(Mod).second) 6390 continue; 6391 6392 for (auto *D : Context.getModuleInitializers(Mod)) 6393 EmitTopLevelDecl(D); 6394 6395 // Visit the submodules of this module. 6396 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 6397 SubEnd = Mod->submodule_end(); 6398 Sub != SubEnd; ++Sub) { 6399 // Skip explicit children; they need to be explicitly imported to emit 6400 // the initializers. 6401 if ((*Sub)->IsExplicit) 6402 continue; 6403 6404 if (Visited.insert(*Sub).second) 6405 Stack.push_back(*Sub); 6406 } 6407 } 6408 break; 6409 } 6410 6411 case Decl::Export: 6412 EmitDeclContext(cast<ExportDecl>(D)); 6413 break; 6414 6415 case Decl::OMPThreadPrivate: 6416 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 6417 break; 6418 6419 case Decl::OMPAllocate: 6420 EmitOMPAllocateDecl(cast<OMPAllocateDecl>(D)); 6421 break; 6422 6423 case Decl::OMPDeclareReduction: 6424 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 6425 break; 6426 6427 case Decl::OMPDeclareMapper: 6428 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 6429 break; 6430 6431 case Decl::OMPRequires: 6432 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 6433 break; 6434 6435 case Decl::Typedef: 6436 case Decl::TypeAlias: // using foo = bar; [C++11] 6437 if (CGDebugInfo *DI = getModuleDebugInfo()) 6438 DI->EmitAndRetainType( 6439 getContext().getTypedefType(cast<TypedefNameDecl>(D))); 6440 break; 6441 6442 case Decl::Record: 6443 if (CGDebugInfo *DI = getModuleDebugInfo()) 6444 if (cast<RecordDecl>(D)->getDefinition()) 6445 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 6446 break; 6447 6448 case Decl::Enum: 6449 if (CGDebugInfo *DI = getModuleDebugInfo()) 6450 if (cast<EnumDecl>(D)->getDefinition()) 6451 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 6452 break; 6453 6454 default: 6455 // Make sure we handled everything we should, every other kind is a 6456 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 6457 // function. Need to recode Decl::Kind to do that easily. 6458 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 6459 break; 6460 } 6461 } 6462 6463 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 6464 // Do we need to generate coverage mapping? 6465 if (!CodeGenOpts.CoverageMapping) 6466 return; 6467 switch (D->getKind()) { 6468 case Decl::CXXConversion: 6469 case Decl::CXXMethod: 6470 case Decl::Function: 6471 case Decl::ObjCMethod: 6472 case Decl::CXXConstructor: 6473 case Decl::CXXDestructor: { 6474 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 6475 break; 6476 SourceManager &SM = getContext().getSourceManager(); 6477 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 6478 break; 6479 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6480 if (I == DeferredEmptyCoverageMappingDecls.end()) 6481 DeferredEmptyCoverageMappingDecls[D] = true; 6482 break; 6483 } 6484 default: 6485 break; 6486 }; 6487 } 6488 6489 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 6490 // Do we need to generate coverage mapping? 6491 if (!CodeGenOpts.CoverageMapping) 6492 return; 6493 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 6494 if (Fn->isTemplateInstantiation()) 6495 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 6496 } 6497 auto I = DeferredEmptyCoverageMappingDecls.find(D); 6498 if (I == DeferredEmptyCoverageMappingDecls.end()) 6499 DeferredEmptyCoverageMappingDecls[D] = false; 6500 else 6501 I->second = false; 6502 } 6503 6504 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 6505 // We call takeVector() here to avoid use-after-free. 6506 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 6507 // we deserialize function bodies to emit coverage info for them, and that 6508 // deserializes more declarations. How should we handle that case? 6509 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 6510 if (!Entry.second) 6511 continue; 6512 const Decl *D = Entry.first; 6513 switch (D->getKind()) { 6514 case Decl::CXXConversion: 6515 case Decl::CXXMethod: 6516 case Decl::Function: 6517 case Decl::ObjCMethod: { 6518 CodeGenPGO PGO(*this); 6519 GlobalDecl GD(cast<FunctionDecl>(D)); 6520 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6521 getFunctionLinkage(GD)); 6522 break; 6523 } 6524 case Decl::CXXConstructor: { 6525 CodeGenPGO PGO(*this); 6526 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 6527 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6528 getFunctionLinkage(GD)); 6529 break; 6530 } 6531 case Decl::CXXDestructor: { 6532 CodeGenPGO PGO(*this); 6533 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 6534 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 6535 getFunctionLinkage(GD)); 6536 break; 6537 } 6538 default: 6539 break; 6540 }; 6541 } 6542 } 6543 6544 void CodeGenModule::EmitMainVoidAlias() { 6545 // In order to transition away from "__original_main" gracefully, emit an 6546 // alias for "main" in the no-argument case so that libc can detect when 6547 // new-style no-argument main is in used. 6548 if (llvm::Function *F = getModule().getFunction("main")) { 6549 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 6550 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) { 6551 auto *GA = llvm::GlobalAlias::create("__main_void", F); 6552 GA->setVisibility(llvm::GlobalValue::HiddenVisibility); 6553 } 6554 } 6555 } 6556 6557 /// Turns the given pointer into a constant. 6558 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 6559 const void *Ptr) { 6560 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 6561 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 6562 return llvm::ConstantInt::get(i64, PtrInt); 6563 } 6564 6565 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 6566 llvm::NamedMDNode *&GlobalMetadata, 6567 GlobalDecl D, 6568 llvm::GlobalValue *Addr) { 6569 if (!GlobalMetadata) 6570 GlobalMetadata = 6571 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 6572 6573 // TODO: should we report variant information for ctors/dtors? 6574 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 6575 llvm::ConstantAsMetadata::get(GetPointerConstant( 6576 CGM.getLLVMContext(), D.getDecl()))}; 6577 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 6578 } 6579 6580 bool CodeGenModule::CheckAndReplaceExternCIFuncs(llvm::GlobalValue *Elem, 6581 llvm::GlobalValue *CppFunc) { 6582 // Store the list of ifuncs we need to replace uses in. 6583 llvm::SmallVector<llvm::GlobalIFunc *> IFuncs; 6584 // List of ConstantExprs that we should be able to delete when we're done 6585 // here. 6586 llvm::SmallVector<llvm::ConstantExpr *> CEs; 6587 6588 // It isn't valid to replace the extern-C ifuncs if all we find is itself! 6589 if (Elem == CppFunc) 6590 return false; 6591 6592 // First make sure that all users of this are ifuncs (or ifuncs via a 6593 // bitcast), and collect the list of ifuncs and CEs so we can work on them 6594 // later. 6595 for (llvm::User *User : Elem->users()) { 6596 // Users can either be a bitcast ConstExpr that is used by the ifuncs, OR an 6597 // ifunc directly. In any other case, just give up, as we don't know what we 6598 // could break by changing those. 6599 if (auto *ConstExpr = dyn_cast<llvm::ConstantExpr>(User)) { 6600 if (ConstExpr->getOpcode() != llvm::Instruction::BitCast) 6601 return false; 6602 6603 for (llvm::User *CEUser : ConstExpr->users()) { 6604 if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(CEUser)) { 6605 IFuncs.push_back(IFunc); 6606 } else { 6607 return false; 6608 } 6609 } 6610 CEs.push_back(ConstExpr); 6611 } else if (auto *IFunc = dyn_cast<llvm::GlobalIFunc>(User)) { 6612 IFuncs.push_back(IFunc); 6613 } else { 6614 // This user is one we don't know how to handle, so fail redirection. This 6615 // will result in an ifunc retaining a resolver name that will ultimately 6616 // fail to be resolved to a defined function. 6617 return false; 6618 } 6619 } 6620 6621 // Now we know this is a valid case where we can do this alias replacement, we 6622 // need to remove all of the references to Elem (and the bitcasts!) so we can 6623 // delete it. 6624 for (llvm::GlobalIFunc *IFunc : IFuncs) 6625 IFunc->setResolver(nullptr); 6626 for (llvm::ConstantExpr *ConstExpr : CEs) 6627 ConstExpr->destroyConstant(); 6628 6629 // We should now be out of uses for the 'old' version of this function, so we 6630 // can erase it as well. 6631 Elem->eraseFromParent(); 6632 6633 for (llvm::GlobalIFunc *IFunc : IFuncs) { 6634 // The type of the resolver is always just a function-type that returns the 6635 // type of the IFunc, so create that here. If the type of the actual 6636 // resolver doesn't match, it just gets bitcast to the right thing. 6637 auto *ResolverTy = 6638 llvm::FunctionType::get(IFunc->getType(), /*isVarArg*/ false); 6639 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 6640 CppFunc->getName(), ResolverTy, {}, /*ForVTable*/ false); 6641 IFunc->setResolver(Resolver); 6642 } 6643 return true; 6644 } 6645 6646 /// For each function which is declared within an extern "C" region and marked 6647 /// as 'used', but has internal linkage, create an alias from the unmangled 6648 /// name to the mangled name if possible. People expect to be able to refer 6649 /// to such functions with an unmangled name from inline assembly within the 6650 /// same translation unit. 6651 void CodeGenModule::EmitStaticExternCAliases() { 6652 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 6653 return; 6654 for (auto &I : StaticExternCValues) { 6655 IdentifierInfo *Name = I.first; 6656 llvm::GlobalValue *Val = I.second; 6657 6658 // If Val is null, that implies there were multiple declarations that each 6659 // had a claim to the unmangled name. In this case, generation of the alias 6660 // is suppressed. See CodeGenModule::MaybeHandleStaticInExternC. 6661 if (!Val) 6662 break; 6663 6664 llvm::GlobalValue *ExistingElem = 6665 getModule().getNamedValue(Name->getName()); 6666 6667 // If there is either not something already by this name, or we were able to 6668 // replace all uses from IFuncs, create the alias. 6669 if (!ExistingElem || CheckAndReplaceExternCIFuncs(ExistingElem, Val)) 6670 addCompilerUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 6671 } 6672 } 6673 6674 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 6675 GlobalDecl &Result) const { 6676 auto Res = Manglings.find(MangledName); 6677 if (Res == Manglings.end()) 6678 return false; 6679 Result = Res->getValue(); 6680 return true; 6681 } 6682 6683 /// Emits metadata nodes associating all the global values in the 6684 /// current module with the Decls they came from. This is useful for 6685 /// projects using IR gen as a subroutine. 6686 /// 6687 /// Since there's currently no way to associate an MDNode directly 6688 /// with an llvm::GlobalValue, we create a global named metadata 6689 /// with the name 'clang.global.decl.ptrs'. 6690 void CodeGenModule::EmitDeclMetadata() { 6691 llvm::NamedMDNode *GlobalMetadata = nullptr; 6692 6693 for (auto &I : MangledDeclNames) { 6694 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 6695 // Some mangled names don't necessarily have an associated GlobalValue 6696 // in this module, e.g. if we mangled it for DebugInfo. 6697 if (Addr) 6698 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 6699 } 6700 } 6701 6702 /// Emits metadata nodes for all the local variables in the current 6703 /// function. 6704 void CodeGenFunction::EmitDeclMetadata() { 6705 if (LocalDeclMap.empty()) return; 6706 6707 llvm::LLVMContext &Context = getLLVMContext(); 6708 6709 // Find the unique metadata ID for this name. 6710 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 6711 6712 llvm::NamedMDNode *GlobalMetadata = nullptr; 6713 6714 for (auto &I : LocalDeclMap) { 6715 const Decl *D = I.first; 6716 llvm::Value *Addr = I.second.getPointer(); 6717 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 6718 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 6719 Alloca->setMetadata( 6720 DeclPtrKind, llvm::MDNode::get( 6721 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 6722 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 6723 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 6724 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 6725 } 6726 } 6727 } 6728 6729 void CodeGenModule::EmitVersionIdentMetadata() { 6730 llvm::NamedMDNode *IdentMetadata = 6731 TheModule.getOrInsertNamedMetadata("llvm.ident"); 6732 std::string Version = getClangFullVersion(); 6733 llvm::LLVMContext &Ctx = TheModule.getContext(); 6734 6735 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 6736 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 6737 } 6738 6739 void CodeGenModule::EmitCommandLineMetadata() { 6740 llvm::NamedMDNode *CommandLineMetadata = 6741 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 6742 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 6743 llvm::LLVMContext &Ctx = TheModule.getContext(); 6744 6745 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 6746 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 6747 } 6748 6749 void CodeGenModule::EmitCoverageFile() { 6750 if (getCodeGenOpts().CoverageDataFile.empty() && 6751 getCodeGenOpts().CoverageNotesFile.empty()) 6752 return; 6753 6754 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 6755 if (!CUNode) 6756 return; 6757 6758 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 6759 llvm::LLVMContext &Ctx = TheModule.getContext(); 6760 auto *CoverageDataFile = 6761 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 6762 auto *CoverageNotesFile = 6763 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 6764 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 6765 llvm::MDNode *CU = CUNode->getOperand(i); 6766 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 6767 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 6768 } 6769 } 6770 6771 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 6772 bool ForEH) { 6773 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 6774 // FIXME: should we even be calling this method if RTTI is disabled 6775 // and it's not for EH? 6776 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 6777 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 6778 getTriple().isNVPTX())) 6779 return llvm::Constant::getNullValue(Int8PtrTy); 6780 6781 if (ForEH && Ty->isObjCObjectPointerType() && 6782 LangOpts.ObjCRuntime.isGNUFamily()) 6783 return ObjCRuntime->GetEHType(Ty); 6784 6785 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 6786 } 6787 6788 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 6789 // Do not emit threadprivates in simd-only mode. 6790 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 6791 return; 6792 for (auto RefExpr : D->varlists()) { 6793 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 6794 bool PerformInit = 6795 VD->getAnyInitializer() && 6796 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 6797 /*ForRef=*/false); 6798 6799 Address Addr(GetAddrOfGlobalVar(VD), 6800 getTypes().ConvertTypeForMem(VD->getType()), 6801 getContext().getDeclAlign(VD)); 6802 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 6803 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 6804 CXXGlobalInits.push_back(InitFunction); 6805 } 6806 } 6807 6808 llvm::Metadata * 6809 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 6810 StringRef Suffix) { 6811 if (auto *FnType = T->getAs<FunctionProtoType>()) 6812 T = getContext().getFunctionType( 6813 FnType->getReturnType(), FnType->getParamTypes(), 6814 FnType->getExtProtoInfo().withExceptionSpec(EST_None)); 6815 6816 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 6817 if (InternalId) 6818 return InternalId; 6819 6820 if (isExternallyVisible(T->getLinkage())) { 6821 std::string OutName; 6822 llvm::raw_string_ostream Out(OutName); 6823 getCXXABI().getMangleContext().mangleTypeName(T, Out); 6824 Out << Suffix; 6825 6826 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 6827 } else { 6828 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 6829 llvm::ArrayRef<llvm::Metadata *>()); 6830 } 6831 6832 return InternalId; 6833 } 6834 6835 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 6836 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 6837 } 6838 6839 llvm::Metadata * 6840 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 6841 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 6842 } 6843 6844 // Generalize pointer types to a void pointer with the qualifiers of the 6845 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 6846 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 6847 // 'void *'. 6848 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 6849 if (!Ty->isPointerType()) 6850 return Ty; 6851 6852 return Ctx.getPointerType( 6853 QualType(Ctx.VoidTy).withCVRQualifiers( 6854 Ty->getPointeeType().getCVRQualifiers())); 6855 } 6856 6857 // Apply type generalization to a FunctionType's return and argument types 6858 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 6859 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 6860 SmallVector<QualType, 8> GeneralizedParams; 6861 for (auto &Param : FnType->param_types()) 6862 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 6863 6864 return Ctx.getFunctionType( 6865 GeneralizeType(Ctx, FnType->getReturnType()), 6866 GeneralizedParams, FnType->getExtProtoInfo()); 6867 } 6868 6869 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 6870 return Ctx.getFunctionNoProtoType( 6871 GeneralizeType(Ctx, FnType->getReturnType())); 6872 6873 llvm_unreachable("Encountered unknown FunctionType"); 6874 } 6875 6876 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 6877 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 6878 GeneralizedMetadataIdMap, ".generalized"); 6879 } 6880 6881 /// Returns whether this module needs the "all-vtables" type identifier. 6882 bool CodeGenModule::NeedAllVtablesTypeId() const { 6883 // Returns true if at least one of vtable-based CFI checkers is enabled and 6884 // is not in the trapping mode. 6885 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 6886 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 6887 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 6888 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 6889 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 6890 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 6891 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 6892 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 6893 } 6894 6895 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 6896 CharUnits Offset, 6897 const CXXRecordDecl *RD) { 6898 llvm::Metadata *MD = 6899 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 6900 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6901 6902 if (CodeGenOpts.SanitizeCfiCrossDso) 6903 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 6904 VTable->addTypeMetadata(Offset.getQuantity(), 6905 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 6906 6907 if (NeedAllVtablesTypeId()) { 6908 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 6909 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6910 } 6911 } 6912 6913 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 6914 if (!SanStats) 6915 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 6916 6917 return *SanStats; 6918 } 6919 6920 llvm::Value * 6921 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 6922 CodeGenFunction &CGF) { 6923 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 6924 auto *SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 6925 auto *FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 6926 auto *Call = CGF.EmitRuntimeCall( 6927 CreateRuntimeFunction(FTy, "__translate_sampler_initializer"), {C}); 6928 return Call; 6929 } 6930 6931 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 6932 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 6933 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 6934 /* forPointeeType= */ true); 6935 } 6936 6937 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 6938 LValueBaseInfo *BaseInfo, 6939 TBAAAccessInfo *TBAAInfo, 6940 bool forPointeeType) { 6941 if (TBAAInfo) 6942 *TBAAInfo = getTBAAAccessInfo(T); 6943 6944 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 6945 // that doesn't return the information we need to compute BaseInfo. 6946 6947 // Honor alignment typedef attributes even on incomplete types. 6948 // We also honor them straight for C++ class types, even as pointees; 6949 // there's an expressivity gap here. 6950 if (auto TT = T->getAs<TypedefType>()) { 6951 if (auto Align = TT->getDecl()->getMaxAlignment()) { 6952 if (BaseInfo) 6953 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 6954 return getContext().toCharUnitsFromBits(Align); 6955 } 6956 } 6957 6958 bool AlignForArray = T->isArrayType(); 6959 6960 // Analyze the base element type, so we don't get confused by incomplete 6961 // array types. 6962 T = getContext().getBaseElementType(T); 6963 6964 if (T->isIncompleteType()) { 6965 // We could try to replicate the logic from 6966 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 6967 // type is incomplete, so it's impossible to test. We could try to reuse 6968 // getTypeAlignIfKnown, but that doesn't return the information we need 6969 // to set BaseInfo. So just ignore the possibility that the alignment is 6970 // greater than one. 6971 if (BaseInfo) 6972 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6973 return CharUnits::One(); 6974 } 6975 6976 if (BaseInfo) 6977 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6978 6979 CharUnits Alignment; 6980 const CXXRecordDecl *RD; 6981 if (T.getQualifiers().hasUnaligned()) { 6982 Alignment = CharUnits::One(); 6983 } else if (forPointeeType && !AlignForArray && 6984 (RD = T->getAsCXXRecordDecl())) { 6985 // For C++ class pointees, we don't know whether we're pointing at a 6986 // base or a complete object, so we generally need to use the 6987 // non-virtual alignment. 6988 Alignment = getClassPointerAlignment(RD); 6989 } else { 6990 Alignment = getContext().getTypeAlignInChars(T); 6991 } 6992 6993 // Cap to the global maximum type alignment unless the alignment 6994 // was somehow explicit on the type. 6995 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 6996 if (Alignment.getQuantity() > MaxAlign && 6997 !getContext().isAlignmentRequired(T)) 6998 Alignment = CharUnits::fromQuantity(MaxAlign); 6999 } 7000 return Alignment; 7001 } 7002 7003 bool CodeGenModule::stopAutoInit() { 7004 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 7005 if (StopAfter) { 7006 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 7007 // used 7008 if (NumAutoVarInit >= StopAfter) { 7009 return true; 7010 } 7011 if (!NumAutoVarInit) { 7012 unsigned DiagID = getDiags().getCustomDiagID( 7013 DiagnosticsEngine::Warning, 7014 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 7015 "number of times ftrivial-auto-var-init=%1 gets applied."); 7016 getDiags().Report(DiagID) 7017 << StopAfter 7018 << (getContext().getLangOpts().getTrivialAutoVarInit() == 7019 LangOptions::TrivialAutoVarInitKind::Zero 7020 ? "zero" 7021 : "pattern"); 7022 } 7023 ++NumAutoVarInit; 7024 } 7025 return false; 7026 } 7027 7028 void CodeGenModule::printPostfixForExternalizedDecl(llvm::raw_ostream &OS, 7029 const Decl *D) const { 7030 // ptxas does not allow '.' in symbol names. On the other hand, HIP prefers 7031 // postfix beginning with '.' since the symbol name can be demangled. 7032 if (LangOpts.HIP) 7033 OS << (isa<VarDecl>(D) ? ".static." : ".intern."); 7034 else 7035 OS << (isa<VarDecl>(D) ? "__static__" : "__intern__"); 7036 7037 // If the CUID is not specified we try to generate a unique postfix. 7038 if (getLangOpts().CUID.empty()) { 7039 SourceManager &SM = getContext().getSourceManager(); 7040 PresumedLoc PLoc = SM.getPresumedLoc(D->getLocation()); 7041 assert(PLoc.isValid() && "Source location is expected to be valid."); 7042 7043 // Get the hash of the user defined macros. 7044 llvm::MD5 Hash; 7045 llvm::MD5::MD5Result Result; 7046 for (const auto &Arg : PreprocessorOpts.Macros) 7047 Hash.update(Arg.first); 7048 Hash.final(Result); 7049 7050 // Get the UniqueID for the file containing the decl. 7051 llvm::sys::fs::UniqueID ID; 7052 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) { 7053 PLoc = SM.getPresumedLoc(D->getLocation(), /*UseLineDirectives=*/false); 7054 assert(PLoc.isValid() && "Source location is expected to be valid."); 7055 if (auto EC = llvm::sys::fs::getUniqueID(PLoc.getFilename(), ID)) 7056 SM.getDiagnostics().Report(diag::err_cannot_open_file) 7057 << PLoc.getFilename() << EC.message(); 7058 } 7059 OS << llvm::format("%x", ID.getFile()) << llvm::format("%x", ID.getDevice()) 7060 << "_" << llvm::utohexstr(Result.low(), /*LowerCase=*/true, /*Width=*/8); 7061 } else { 7062 OS << getContext().getCUIDHash(); 7063 } 7064 } 7065 7066 void CodeGenModule::moveLazyEmissionStates(CodeGenModule *NewBuilder) { 7067 assert(DeferredDeclsToEmit.empty() && 7068 "Should have emitted all decls deferred to emit."); 7069 assert(NewBuilder->DeferredDecls.empty() && 7070 "Newly created module should not have deferred decls"); 7071 NewBuilder->DeferredDecls = std::move(DeferredDecls); 7072 7073 assert(NewBuilder->DeferredVTables.empty() && 7074 "Newly created module should not have deferred vtables"); 7075 NewBuilder->DeferredVTables = std::move(DeferredVTables); 7076 7077 assert(NewBuilder->MangledDeclNames.empty() && 7078 "Newly created module should not have mangled decl names"); 7079 assert(NewBuilder->Manglings.empty() && 7080 "Newly created module should not have manglings"); 7081 NewBuilder->Manglings = std::move(Manglings); 7082 7083 assert(WeakRefReferences.empty() && "Not all WeakRefRefs have been applied"); 7084 NewBuilder->WeakRefReferences = std::move(WeakRefReferences); 7085 7086 NewBuilder->TBAA = std::move(TBAA); 7087 7088 assert(NewBuilder->EmittedDeferredDecls.empty() && 7089 "Still have (unmerged) EmittedDeferredDecls deferred decls"); 7090 7091 NewBuilder->EmittedDeferredDecls = std::move(EmittedDeferredDecls); 7092 7093 NewBuilder->ABI->MangleCtx = std::move(ABI->MangleCtx); 7094 } 7095