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