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