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