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