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