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