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