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