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