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