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