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