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