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