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