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