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