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