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