Path: blob/main/contrib/llvm-project/clang/lib/Sema/Sema.cpp
35233 views
//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the actions class which performs semantic analysis and9// builds an AST out of a parse stream.10//11//===----------------------------------------------------------------------===//1213#include "UsedDeclVisitor.h"14#include "clang/AST/ASTContext.h"15#include "clang/AST/ASTDiagnostic.h"16#include "clang/AST/Decl.h"17#include "clang/AST/DeclCXX.h"18#include "clang/AST/DeclFriend.h"19#include "clang/AST/DeclObjC.h"20#include "clang/AST/Expr.h"21#include "clang/AST/ExprCXX.h"22#include "clang/AST/PrettyDeclStackTrace.h"23#include "clang/AST/StmtCXX.h"24#include "clang/Basic/DarwinSDKInfo.h"25#include "clang/Basic/DiagnosticOptions.h"26#include "clang/Basic/PartialDiagnostic.h"27#include "clang/Basic/SourceManager.h"28#include "clang/Basic/Stack.h"29#include "clang/Basic/TargetInfo.h"30#include "clang/Lex/HeaderSearch.h"31#include "clang/Lex/HeaderSearchOptions.h"32#include "clang/Lex/Preprocessor.h"33#include "clang/Sema/CXXFieldCollector.h"34#include "clang/Sema/DelayedDiagnostic.h"35#include "clang/Sema/EnterExpressionEvaluationContext.h"36#include "clang/Sema/ExternalSemaSource.h"37#include "clang/Sema/Initialization.h"38#include "clang/Sema/MultiplexExternalSemaSource.h"39#include "clang/Sema/ObjCMethodList.h"40#include "clang/Sema/RISCVIntrinsicManager.h"41#include "clang/Sema/Scope.h"42#include "clang/Sema/ScopeInfo.h"43#include "clang/Sema/SemaAMDGPU.h"44#include "clang/Sema/SemaARM.h"45#include "clang/Sema/SemaAVR.h"46#include "clang/Sema/SemaBPF.h"47#include "clang/Sema/SemaCUDA.h"48#include "clang/Sema/SemaCodeCompletion.h"49#include "clang/Sema/SemaConsumer.h"50#include "clang/Sema/SemaHLSL.h"51#include "clang/Sema/SemaHexagon.h"52#include "clang/Sema/SemaInternal.h"53#include "clang/Sema/SemaLoongArch.h"54#include "clang/Sema/SemaM68k.h"55#include "clang/Sema/SemaMIPS.h"56#include "clang/Sema/SemaMSP430.h"57#include "clang/Sema/SemaNVPTX.h"58#include "clang/Sema/SemaObjC.h"59#include "clang/Sema/SemaOpenACC.h"60#include "clang/Sema/SemaOpenCL.h"61#include "clang/Sema/SemaOpenMP.h"62#include "clang/Sema/SemaPPC.h"63#include "clang/Sema/SemaPseudoObject.h"64#include "clang/Sema/SemaRISCV.h"65#include "clang/Sema/SemaSYCL.h"66#include "clang/Sema/SemaSwift.h"67#include "clang/Sema/SemaSystemZ.h"68#include "clang/Sema/SemaWasm.h"69#include "clang/Sema/SemaX86.h"70#include "clang/Sema/TemplateDeduction.h"71#include "clang/Sema/TemplateInstCallback.h"72#include "clang/Sema/TypoCorrection.h"73#include "llvm/ADT/DenseMap.h"74#include "llvm/ADT/STLExtras.h"75#include "llvm/ADT/SmallPtrSet.h"76#include "llvm/Support/TimeProfiler.h"77#include <optional>7879using namespace clang;80using namespace sema;8182SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {83return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);84}8586ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }8788DarwinSDKInfo *89Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,90StringRef Platform) {91auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking();92if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {93Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)94<< Platform;95WarnedDarwinSDKInfoMissing = true;96}97return SDKInfo;98}99100DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() {101if (CachedDarwinSDKInfo)102return CachedDarwinSDKInfo->get();103auto SDKInfo = parseDarwinSDKInfo(104PP.getFileManager().getVirtualFileSystem(),105PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);106if (SDKInfo && *SDKInfo) {107CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));108return CachedDarwinSDKInfo->get();109}110if (!SDKInfo)111llvm::consumeError(SDKInfo.takeError());112CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();113return nullptr;114}115116IdentifierInfo *Sema::InventAbbreviatedTemplateParameterTypeName(117const IdentifierInfo *ParamName, unsigned int Index) {118std::string InventedName;119llvm::raw_string_ostream OS(InventedName);120121if (!ParamName)122OS << "auto:" << Index + 1;123else124OS << ParamName->getName() << ":auto";125126OS.flush();127return &Context.Idents.get(OS.str());128}129130PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,131const Preprocessor &PP) {132PrintingPolicy Policy = Context.getPrintingPolicy();133// In diagnostics, we print _Bool as bool if the latter is defined as the134// former.135Policy.Bool = Context.getLangOpts().Bool;136if (!Policy.Bool) {137if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {138Policy.Bool = BoolMacro->isObjectLike() &&139BoolMacro->getNumTokens() == 1 &&140BoolMacro->getReplacementToken(0).is(tok::kw__Bool);141}142}143144// Shorten the data output if needed145Policy.EntireContentsOfLargeArray = false;146147return Policy;148}149150void Sema::ActOnTranslationUnitScope(Scope *S) {151TUScope = S;152PushDeclContext(S, Context.getTranslationUnitDecl());153}154155namespace clang {156namespace sema {157158class SemaPPCallbacks : public PPCallbacks {159Sema *S = nullptr;160llvm::SmallVector<SourceLocation, 8> IncludeStack;161llvm::SmallVector<llvm::TimeTraceProfilerEntry *, 8> ProfilerStack;162163public:164void set(Sema &S) { this->S = &S; }165166void reset() { S = nullptr; }167168void FileChanged(SourceLocation Loc, FileChangeReason Reason,169SrcMgr::CharacteristicKind FileType,170FileID PrevFID) override {171if (!S)172return;173switch (Reason) {174case EnterFile: {175SourceManager &SM = S->getSourceManager();176SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));177if (IncludeLoc.isValid()) {178if (llvm::timeTraceProfilerEnabled()) {179OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getFileID(Loc));180ProfilerStack.push_back(llvm::timeTraceAsyncProfilerBegin(181"Source", FE ? FE->getName() : StringRef("<unknown>")));182}183184IncludeStack.push_back(IncludeLoc);185S->DiagnoseNonDefaultPragmaAlignPack(186Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,187IncludeLoc);188}189break;190}191case ExitFile:192if (!IncludeStack.empty()) {193if (llvm::timeTraceProfilerEnabled())194llvm::timeTraceProfilerEnd(ProfilerStack.pop_back_val());195196S->DiagnoseNonDefaultPragmaAlignPack(197Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,198IncludeStack.pop_back_val());199}200break;201default:202break;203}204}205};206207} // end namespace sema208} // end namespace clang209210const unsigned Sema::MaxAlignmentExponent;211const uint64_t Sema::MaximumAlignment;212213Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,214TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)215: SemaBase(*this), CollectStats(false), TUKind(TUKind),216CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),217Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),218SourceMgr(PP.getSourceManager()), APINotes(SourceMgr, LangOpts),219AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),220LateTemplateParser(nullptr), LateTemplateParserCleanup(nullptr),221OpaqueParser(nullptr), CurContext(nullptr), ExternalSource(nullptr),222CurScope(nullptr), Ident_super(nullptr),223AMDGPUPtr(std::make_unique<SemaAMDGPU>(*this)),224ARMPtr(std::make_unique<SemaARM>(*this)),225AVRPtr(std::make_unique<SemaAVR>(*this)),226BPFPtr(std::make_unique<SemaBPF>(*this)),227CodeCompletionPtr(228std::make_unique<SemaCodeCompletion>(*this, CodeCompleter)),229CUDAPtr(std::make_unique<SemaCUDA>(*this)),230HLSLPtr(std::make_unique<SemaHLSL>(*this)),231HexagonPtr(std::make_unique<SemaHexagon>(*this)),232LoongArchPtr(std::make_unique<SemaLoongArch>(*this)),233M68kPtr(std::make_unique<SemaM68k>(*this)),234MIPSPtr(std::make_unique<SemaMIPS>(*this)),235MSP430Ptr(std::make_unique<SemaMSP430>(*this)),236NVPTXPtr(std::make_unique<SemaNVPTX>(*this)),237ObjCPtr(std::make_unique<SemaObjC>(*this)),238OpenACCPtr(std::make_unique<SemaOpenACC>(*this)),239OpenCLPtr(std::make_unique<SemaOpenCL>(*this)),240OpenMPPtr(std::make_unique<SemaOpenMP>(*this)),241PPCPtr(std::make_unique<SemaPPC>(*this)),242PseudoObjectPtr(std::make_unique<SemaPseudoObject>(*this)),243RISCVPtr(std::make_unique<SemaRISCV>(*this)),244SYCLPtr(std::make_unique<SemaSYCL>(*this)),245SwiftPtr(std::make_unique<SemaSwift>(*this)),246SystemZPtr(std::make_unique<SemaSystemZ>(*this)),247WasmPtr(std::make_unique<SemaWasm>(*this)),248X86Ptr(std::make_unique<SemaX86>(*this)),249MSPointerToMemberRepresentationMethod(250LangOpts.getMSPointerToMemberRepresentationMethod()),251MSStructPragmaOn(false), VtorDispStack(LangOpts.getVtorDispMode()),252AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),253DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),254CodeSegStack(nullptr), StrictGuardStackCheckStack(false),255FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr),256VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),257StdCoroutineTraitsCache(nullptr), IdResolver(pp),258OriginalLexicalContext(nullptr), StdInitializerList(nullptr),259FullyCheckedComparisonCategories(260static_cast<unsigned>(ComparisonCategoryType::Last) + 1),261StdSourceLocationImplDecl(nullptr), CXXTypeInfoDecl(nullptr),262GlobalNewDeleteDeclared(false), DisableTypoCorrection(false),263TyposCorrected(0), IsBuildingRecoveryCallExpr(false), NumSFINAEErrors(0),264AccessCheckingSFINAE(false), CurrentInstantiationScope(nullptr),265InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),266ArgumentPackSubstitutionIndex(-1), SatisfactionCache(Context) {267assert(pp.TUKind == TUKind);268TUScope = nullptr;269270LoadedExternalKnownNamespaces = false;271for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)272ObjC().NSNumberLiteralMethods[I] = nullptr;273274if (getLangOpts().ObjC)275ObjC().NSAPIObj.reset(new NSAPI(Context));276277if (getLangOpts().CPlusPlus)278FieldCollector.reset(new CXXFieldCollector());279280// Tell diagnostics how to render things from the AST library.281Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);282283// This evaluation context exists to ensure that there's always at least one284// valid evaluation context available. It is never removed from the285// evaluation stack.286ExprEvalContexts.emplace_back(287ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},288nullptr, ExpressionEvaluationContextRecord::EK_Other);289290// Initialization of data sharing attributes stack for OpenMP291OpenMP().InitDataSharingAttributesStack();292293std::unique_ptr<sema::SemaPPCallbacks> Callbacks =294std::make_unique<sema::SemaPPCallbacks>();295SemaPPCallbackHandler = Callbacks.get();296PP.addPPCallbacks(std::move(Callbacks));297SemaPPCallbackHandler->set(*this);298299CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());300}301302// Anchor Sema's type info to this TU.303void Sema::anchor() {}304305void Sema::addImplicitTypedef(StringRef Name, QualType T) {306DeclarationName DN = &Context.Idents.get(Name);307if (IdResolver.begin(DN) == IdResolver.end())308PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);309}310311void Sema::Initialize() {312if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))313SC->InitializeSema(*this);314315// Tell the external Sema source about this Sema object.316if (ExternalSemaSource *ExternalSema317= dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))318ExternalSema->InitializeSema(*this);319320// This needs to happen after ExternalSemaSource::InitializeSema(this) or we321// will not be able to merge any duplicate __va_list_tag decls correctly.322VAListTagName = PP.getIdentifierInfo("__va_list_tag");323324if (!TUScope)325return;326327// Initialize predefined 128-bit integer types, if needed.328if (Context.getTargetInfo().hasInt128Type() ||329(Context.getAuxTargetInfo() &&330Context.getAuxTargetInfo()->hasInt128Type())) {331// If either of the 128-bit integer types are unavailable to name lookup,332// define them now.333DeclarationName Int128 = &Context.Idents.get("__int128_t");334if (IdResolver.begin(Int128) == IdResolver.end())335PushOnScopeChains(Context.getInt128Decl(), TUScope);336337DeclarationName UInt128 = &Context.Idents.get("__uint128_t");338if (IdResolver.begin(UInt128) == IdResolver.end())339PushOnScopeChains(Context.getUInt128Decl(), TUScope);340}341342343// Initialize predefined Objective-C types:344if (getLangOpts().ObjC) {345// If 'SEL' does not yet refer to any declarations, make it refer to the346// predefined 'SEL'.347DeclarationName SEL = &Context.Idents.get("SEL");348if (IdResolver.begin(SEL) == IdResolver.end())349PushOnScopeChains(Context.getObjCSelDecl(), TUScope);350351// If 'id' does not yet refer to any declarations, make it refer to the352// predefined 'id'.353DeclarationName Id = &Context.Idents.get("id");354if (IdResolver.begin(Id) == IdResolver.end())355PushOnScopeChains(Context.getObjCIdDecl(), TUScope);356357// Create the built-in typedef for 'Class'.358DeclarationName Class = &Context.Idents.get("Class");359if (IdResolver.begin(Class) == IdResolver.end())360PushOnScopeChains(Context.getObjCClassDecl(), TUScope);361362// Create the built-in forward declaratino for 'Protocol'.363DeclarationName Protocol = &Context.Idents.get("Protocol");364if (IdResolver.begin(Protocol) == IdResolver.end())365PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);366}367368// Create the internal type for the *StringMakeConstantString builtins.369DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");370if (IdResolver.begin(ConstantString) == IdResolver.end())371PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);372373// Initialize Microsoft "predefined C++ types".374if (getLangOpts().MSVCCompat) {375if (getLangOpts().CPlusPlus &&376IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())377PushOnScopeChains(378Context.buildImplicitRecord("type_info", TagTypeKind::Class),379TUScope);380381addImplicitTypedef("size_t", Context.getSizeType());382}383384// Initialize predefined OpenCL types and supported extensions and (optional)385// core features.386if (getLangOpts().OpenCL) {387getOpenCLOptions().addSupport(388Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());389addImplicitTypedef("sampler_t", Context.OCLSamplerTy);390addImplicitTypedef("event_t", Context.OCLEventTy);391auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();392if (OCLCompatibleVersion >= 200) {393if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {394addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);395addImplicitTypedef("queue_t", Context.OCLQueueTy);396}397if (getLangOpts().OpenCLPipes)398addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);399addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));400addImplicitTypedef("atomic_uint",401Context.getAtomicType(Context.UnsignedIntTy));402addImplicitTypedef("atomic_float",403Context.getAtomicType(Context.FloatTy));404// OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as405// 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.406addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));407408409// OpenCL v2.0 s6.13.11.6:410// - The atomic_long and atomic_ulong types are supported if the411// cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics412// extensions are supported.413// - The atomic_double type is only supported if double precision414// is supported and the cl_khr_int64_base_atomics and415// cl_khr_int64_extended_atomics extensions are supported.416// - If the device address space is 64-bits, the data types417// atomic_intptr_t, atomic_uintptr_t, atomic_size_t and418// atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and419// cl_khr_int64_extended_atomics extensions are supported.420421auto AddPointerSizeDependentTypes = [&]() {422auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());423auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());424auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());425auto AtomicPtrDiffT =426Context.getAtomicType(Context.getPointerDiffType());427addImplicitTypedef("atomic_size_t", AtomicSizeT);428addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);429addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);430addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);431};432433if (Context.getTypeSize(Context.getSizeType()) == 32) {434AddPointerSizeDependentTypes();435}436437if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {438auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);439addImplicitTypedef("atomic_half", AtomicHalfT);440}441442std::vector<QualType> Atomic64BitTypes;443if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",444getLangOpts()) &&445getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",446getLangOpts())) {447if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {448auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);449addImplicitTypedef("atomic_double", AtomicDoubleT);450Atomic64BitTypes.push_back(AtomicDoubleT);451}452auto AtomicLongT = Context.getAtomicType(Context.LongTy);453auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);454addImplicitTypedef("atomic_long", AtomicLongT);455addImplicitTypedef("atomic_ulong", AtomicULongT);456457458if (Context.getTypeSize(Context.getSizeType()) == 64) {459AddPointerSizeDependentTypes();460}461}462}463464#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \465if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \466addImplicitTypedef(#ExtType, Context.Id##Ty); \467}468#include "clang/Basic/OpenCLExtensionTypes.def"469}470471if (Context.getTargetInfo().hasAArch64SVETypes() ||472(Context.getAuxTargetInfo() &&473Context.getAuxTargetInfo()->hasAArch64SVETypes())) {474#define SVE_TYPE(Name, Id, SingletonId) \475addImplicitTypedef(Name, Context.SingletonId);476#include "clang/Basic/AArch64SVEACLETypes.def"477}478479if (Context.getTargetInfo().getTriple().isPPC64()) {480#define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \481addImplicitTypedef(#Name, Context.Id##Ty);482#include "clang/Basic/PPCTypes.def"483#define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \484addImplicitTypedef(#Name, Context.Id##Ty);485#include "clang/Basic/PPCTypes.def"486}487488if (Context.getTargetInfo().hasRISCVVTypes()) {489#define RVV_TYPE(Name, Id, SingletonId) \490addImplicitTypedef(Name, Context.SingletonId);491#include "clang/Basic/RISCVVTypes.def"492}493494if (Context.getTargetInfo().getTriple().isWasm() &&495Context.getTargetInfo().hasFeature("reference-types")) {496#define WASM_TYPE(Name, Id, SingletonId) \497addImplicitTypedef(Name, Context.SingletonId);498#include "clang/Basic/WebAssemblyReferenceTypes.def"499}500501if (Context.getTargetInfo().getTriple().isAMDGPU() ||502(Context.getAuxTargetInfo() &&503Context.getAuxTargetInfo()->getTriple().isAMDGPU())) {504#define AMDGPU_TYPE(Name, Id, SingletonId) \505addImplicitTypedef(Name, Context.SingletonId);506#include "clang/Basic/AMDGPUTypes.def"507}508509if (Context.getTargetInfo().hasBuiltinMSVaList()) {510DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");511if (IdResolver.begin(MSVaList) == IdResolver.end())512PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);513}514515DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");516if (IdResolver.begin(BuiltinVaList) == IdResolver.end())517PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);518}519520Sema::~Sema() {521assert(InstantiatingSpecializations.empty() &&522"failed to clean up an InstantiatingTemplate?");523524if (VisContext) FreeVisContext();525526// Kill all the active scopes.527for (sema::FunctionScopeInfo *FSI : FunctionScopes)528delete FSI;529530// Tell the SemaConsumer to forget about us; we're going out of scope.531if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))532SC->ForgetSema();533534// Detach from the external Sema source.535if (ExternalSemaSource *ExternalSema536= dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))537ExternalSema->ForgetSema();538539// Delete cached satisfactions.540std::vector<ConstraintSatisfaction *> Satisfactions;541Satisfactions.reserve(SatisfactionCache.size());542for (auto &Node : SatisfactionCache)543Satisfactions.push_back(&Node);544for (auto *Node : Satisfactions)545delete Node;546547threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);548549// Destroys data sharing attributes stack for OpenMP550OpenMP().DestroyDataSharingAttributesStack();551552// Detach from the PP callback handler which outlives Sema since it's owned553// by the preprocessor.554SemaPPCallbackHandler->reset();555}556557void Sema::warnStackExhausted(SourceLocation Loc) {558// Only warn about this once.559if (!WarnedStackExhausted) {560Diag(Loc, diag::warn_stack_exhausted);561WarnedStackExhausted = true;562}563}564565void Sema::runWithSufficientStackSpace(SourceLocation Loc,566llvm::function_ref<void()> Fn) {567clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn);568}569570bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,571UnavailableAttr::ImplicitReason reason) {572// If we're not in a function, it's an error.573FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);574if (!fn) return false;575576// If we're in template instantiation, it's an error.577if (inTemplateInstantiation())578return false;579580// If that function's not in a system header, it's an error.581if (!Context.getSourceManager().isInSystemHeader(loc))582return false;583584// If the function is already unavailable, it's not an error.585if (fn->hasAttr<UnavailableAttr>()) return true;586587fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));588return true;589}590591ASTMutationListener *Sema::getASTMutationListener() const {592return getASTConsumer().GetASTMutationListener();593}594595void Sema::addExternalSource(ExternalSemaSource *E) {596assert(E && "Cannot use with NULL ptr");597598if (!ExternalSource) {599ExternalSource = E;600return;601}602603if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource))604Ex->AddSource(E);605else606ExternalSource = new MultiplexExternalSemaSource(ExternalSource.get(), E);607}608609void Sema::PrintStats() const {610llvm::errs() << "\n*** Semantic Analysis Stats:\n";611llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";612613BumpAlloc.PrintStats();614AnalysisWarnings.PrintStats();615}616617void Sema::diagnoseNullableToNonnullConversion(QualType DstType,618QualType SrcType,619SourceLocation Loc) {620std::optional<NullabilityKind> ExprNullability = SrcType->getNullability();621if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&622*ExprNullability != NullabilityKind::NullableResult))623return;624625std::optional<NullabilityKind> TypeNullability = DstType->getNullability();626if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)627return;628629Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;630}631632// Generate diagnostics when adding or removing effects in a type conversion.633void Sema::diagnoseFunctionEffectConversion(QualType DstType, QualType SrcType,634SourceLocation Loc) {635const auto SrcFX = FunctionEffectsRef::get(SrcType);636const auto DstFX = FunctionEffectsRef::get(DstType);637if (SrcFX != DstFX) {638for (const auto &Diff : FunctionEffectDifferences(SrcFX, DstFX)) {639if (Diff.shouldDiagnoseConversion(SrcType, SrcFX, DstType, DstFX))640Diag(Loc, diag::warn_invalid_add_func_effects) << Diff.effectName();641}642}643}644645void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E) {646// nullptr only exists from C++11 on, so don't warn on its absence earlier.647if (!getLangOpts().CPlusPlus11)648return;649650if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)651return;652653const Expr *EStripped = E->IgnoreParenImpCasts();654if (EStripped->getType()->isNullPtrType())655return;656if (isa<GNUNullExpr>(EStripped))657return;658659if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,660E->getBeginLoc()))661return;662663// Don't diagnose the conversion from a 0 literal to a null pointer argument664// in a synthesized call to operator<=>.665if (!CodeSynthesisContexts.empty() &&666CodeSynthesisContexts.back().Kind ==667CodeSynthesisContext::RewritingOperatorAsSpaceship)668return;669670// Ignore null pointers in defaulted comparison operators.671FunctionDecl *FD = getCurFunctionDecl();672if (FD && FD->isDefaulted()) {673return;674}675676// If it is a macro from system header, and if the macro name is not "NULL",677// do not warn.678// Note that uses of "NULL" will be ignored above on systems that define it679// as __null.680SourceLocation MaybeMacroLoc = E->getBeginLoc();681if (Diags.getSuppressSystemWarnings() &&682SourceMgr.isInSystemMacro(MaybeMacroLoc) &&683!findMacroSpelling(MaybeMacroLoc, "NULL"))684return;685686Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)687<< FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");688}689690/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.691/// If there is already an implicit cast, merge into the existing one.692/// The result is of the given category.693ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,694CastKind Kind, ExprValueKind VK,695const CXXCastPath *BasePath,696CheckedConversionKind CCK) {697#ifndef NDEBUG698if (VK == VK_PRValue && !E->isPRValue()) {699switch (Kind) {700default:701llvm_unreachable(702("can't implicitly cast glvalue to prvalue with this cast "703"kind: " +704std::string(CastExpr::getCastKindName(Kind)))705.c_str());706case CK_Dependent:707case CK_LValueToRValue:708case CK_ArrayToPointerDecay:709case CK_FunctionToPointerDecay:710case CK_ToVoid:711case CK_NonAtomicToAtomic:712case CK_HLSLArrayRValue:713break;714}715}716assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&717"can't cast prvalue to glvalue");718#endif719720diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());721diagnoseZeroToNullptrConversion(Kind, E);722if (Context.hasAnyFunctionEffects() && !isCast(CCK) &&723Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)724diagnoseFunctionEffectConversion(Ty, E->getType(), E->getBeginLoc());725726QualType ExprTy = Context.getCanonicalType(E->getType());727QualType TypeTy = Context.getCanonicalType(Ty);728729if (ExprTy == TypeTy)730return E;731732if (Kind == CK_ArrayToPointerDecay) {733// C++1z [conv.array]: The temporary materialization conversion is applied.734// We also use this to fuel C++ DR1213, which applies to C++11 onwards.735if (getLangOpts().CPlusPlus && E->isPRValue()) {736// The temporary is an lvalue in C++98 and an xvalue otherwise.737ExprResult Materialized = CreateMaterializeTemporaryExpr(738E->getType(), E, !getLangOpts().CPlusPlus11);739if (Materialized.isInvalid())740return ExprError();741E = Materialized.get();742}743// C17 6.7.1p6 footnote 124: The implementation can treat any register744// declaration simply as an auto declaration. However, whether or not745// addressable storage is actually used, the address of any part of an746// object declared with storage-class specifier register cannot be747// computed, either explicitly(by use of the unary & operator as discussed748// in 6.5.3.2) or implicitly(by converting an array name to a pointer as749// discussed in 6.3.2.1).Thus, the only operator that can be applied to an750// array declared with storage-class specifier register is sizeof.751if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {752if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {753if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {754if (VD->getStorageClass() == SC_Register) {755Diag(E->getExprLoc(), diag::err_typecheck_address_of)756<< /*register variable*/ 3 << E->getSourceRange();757return ExprError();758}759}760}761}762}763764if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {765if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {766ImpCast->setType(Ty);767ImpCast->setValueKind(VK);768return E;769}770}771772return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,773CurFPFeatureOverrides());774}775776CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {777switch (ScalarTy->getScalarTypeKind()) {778case Type::STK_Bool: return CK_NoOp;779case Type::STK_CPointer: return CK_PointerToBoolean;780case Type::STK_BlockPointer: return CK_PointerToBoolean;781case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;782case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;783case Type::STK_Integral: return CK_IntegralToBoolean;784case Type::STK_Floating: return CK_FloatingToBoolean;785case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;786case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;787case Type::STK_FixedPoint: return CK_FixedPointToBoolean;788}789llvm_unreachable("unknown scalar type kind");790}791792/// Used to prune the decls of Sema's UnusedFileScopedDecls vector.793static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {794if (D->getMostRecentDecl()->isUsed())795return true;796797if (D->isExternallyVisible())798return true;799800if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {801// If this is a function template and none of its specializations is used,802// we should warn.803if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())804for (const auto *Spec : Template->specializations())805if (ShouldRemoveFromUnused(SemaRef, Spec))806return true;807808// UnusedFileScopedDecls stores the first declaration.809// The declaration may have become definition so check again.810const FunctionDecl *DeclToCheck;811if (FD->hasBody(DeclToCheck))812return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);813814// Later redecls may add new information resulting in not having to warn,815// so check again.816DeclToCheck = FD->getMostRecentDecl();817if (DeclToCheck != FD)818return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);819}820821if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {822// If a variable usable in constant expressions is referenced,823// don't warn if it isn't used: if the value of a variable is required824// for the computation of a constant expression, it doesn't make sense to825// warn even if the variable isn't odr-used. (isReferenced doesn't826// precisely reflect that, but it's a decent approximation.)827if (VD->isReferenced() &&828VD->mightBeUsableInConstantExpressions(SemaRef->Context))829return true;830831if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())832// If this is a variable template and none of its specializations is used,833// we should warn.834for (const auto *Spec : Template->specializations())835if (ShouldRemoveFromUnused(SemaRef, Spec))836return true;837838// UnusedFileScopedDecls stores the first declaration.839// The declaration may have become definition so check again.840const VarDecl *DeclToCheck = VD->getDefinition();841if (DeclToCheck)842return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);843844// Later redecls may add new information resulting in not having to warn,845// so check again.846DeclToCheck = VD->getMostRecentDecl();847if (DeclToCheck != VD)848return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);849}850851return false;852}853854static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) {855if (const auto *FD = dyn_cast<FunctionDecl>(ND))856return FD->isExternC();857return cast<VarDecl>(ND)->isExternC();858}859860/// Determine whether ND is an external-linkage function or variable whose861/// type has no linkage.862bool Sema::isExternalWithNoLinkageType(const ValueDecl *VD) const {863// Note: it's not quite enough to check whether VD has UniqueExternalLinkage,864// because we also want to catch the case where its type has VisibleNoLinkage,865// which does not affect the linkage of VD.866return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&867!isExternalFormalLinkage(VD->getType()->getLinkage()) &&868!isFunctionOrVarDeclExternC(VD);869}870871/// Obtains a sorted list of functions and variables that are undefined but872/// ODR-used.873void Sema::getUndefinedButUsed(874SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {875for (const auto &UndefinedUse : UndefinedButUsed) {876NamedDecl *ND = UndefinedUse.first;877878// Ignore attributes that have become invalid.879if (ND->isInvalidDecl()) continue;880881// __attribute__((weakref)) is basically a definition.882if (ND->hasAttr<WeakRefAttr>()) continue;883884if (isa<CXXDeductionGuideDecl>(ND))885continue;886887if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {888// An exported function will always be emitted when defined, so even if889// the function is inline, it doesn't have to be emitted in this TU. An890// imported function implies that it has been exported somewhere else.891continue;892}893894if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {895if (FD->isDefined())896continue;897if (FD->isExternallyVisible() &&898!isExternalWithNoLinkageType(FD) &&899!FD->getMostRecentDecl()->isInlined() &&900!FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())901continue;902if (FD->getBuiltinID())903continue;904} else {905const auto *VD = cast<VarDecl>(ND);906if (VD->hasDefinition() != VarDecl::DeclarationOnly)907continue;908if (VD->isExternallyVisible() &&909!isExternalWithNoLinkageType(VD) &&910!VD->getMostRecentDecl()->isInline() &&911!VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())912continue;913914// Skip VarDecls that lack formal definitions but which we know are in915// fact defined somewhere.916if (VD->isKnownToBeDefined())917continue;918}919920Undefined.push_back(std::make_pair(ND, UndefinedUse.second));921}922}923924/// checkUndefinedButUsed - Check for undefined objects with internal linkage925/// or that are inline.926static void checkUndefinedButUsed(Sema &S) {927if (S.UndefinedButUsed.empty()) return;928929// Collect all the still-undefined entities with internal linkage.930SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;931S.getUndefinedButUsed(Undefined);932S.UndefinedButUsed.clear();933if (Undefined.empty()) return;934935for (const auto &Undef : Undefined) {936ValueDecl *VD = cast<ValueDecl>(Undef.first);937SourceLocation UseLoc = Undef.second;938939if (S.isExternalWithNoLinkageType(VD)) {940// C++ [basic.link]p8:941// A type without linkage shall not be used as the type of a variable942// or function with external linkage unless943// -- the entity has C language linkage944// -- the entity is not odr-used or is defined in the same TU945//946// As an extension, accept this in cases where the type is externally947// visible, since the function or variable actually can be defined in948// another translation unit in that case.949S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())950? diag::ext_undefined_internal_type951: diag::err_undefined_internal_type)952<< isa<VarDecl>(VD) << VD;953} else if (!VD->isExternallyVisible()) {954// FIXME: We can promote this to an error. The function or variable can't955// be defined anywhere else, so the program must necessarily violate the956// one definition rule.957bool IsImplicitBase = false;958if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {959auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();960if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(961llvm::omp::TraitProperty::962implementation_extension_disable_implicit_base)) {963const auto *Func = cast<FunctionDecl>(964cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());965IsImplicitBase = BaseD->isImplicit() &&966Func->getIdentifier()->isMangledOpenMPVariantName();967}968}969if (!S.getLangOpts().OpenMP || !IsImplicitBase)970S.Diag(VD->getLocation(), diag::warn_undefined_internal)971<< isa<VarDecl>(VD) << VD;972} else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {973(void)FD;974assert(FD->getMostRecentDecl()->isInlined() &&975"used object requires definition but isn't inline or internal?");976// FIXME: This is ill-formed; we should reject.977S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;978} else {979assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&980"used var requires definition but isn't inline or internal?");981S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;982}983if (UseLoc.isValid())984S.Diag(UseLoc, diag::note_used_here);985}986}987988void Sema::LoadExternalWeakUndeclaredIdentifiers() {989if (!ExternalSource)990return;991992SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;993ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);994for (auto &WeakID : WeakIDs)995(void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);996}997998999typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;10001001/// Returns true, if all methods and nested classes of the given1002/// CXXRecordDecl are defined in this translation unit.1003///1004/// Should only be called from ActOnEndOfTranslationUnit so that all1005/// definitions are actually read.1006static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,1007RecordCompleteMap &MNCComplete) {1008RecordCompleteMap::iterator Cache = MNCComplete.find(RD);1009if (Cache != MNCComplete.end())1010return Cache->second;1011if (!RD->isCompleteDefinition())1012return false;1013bool Complete = true;1014for (DeclContext::decl_iterator I = RD->decls_begin(),1015E = RD->decls_end();1016I != E && Complete; ++I) {1017if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))1018Complete = M->isDefined() || M->isDefaulted() ||1019(M->isPureVirtual() && !isa<CXXDestructorDecl>(M));1020else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))1021// If the template function is marked as late template parsed at this1022// point, it has not been instantiated and therefore we have not1023// performed semantic analysis on it yet, so we cannot know if the type1024// can be considered complete.1025Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&1026F->getTemplatedDecl()->isDefined();1027else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {1028if (R->isInjectedClassName())1029continue;1030if (R->hasDefinition())1031Complete = MethodsAndNestedClassesComplete(R->getDefinition(),1032MNCComplete);1033else1034Complete = false;1035}1036}1037MNCComplete[RD] = Complete;1038return Complete;1039}10401041/// Returns true, if the given CXXRecordDecl is fully defined in this1042/// translation unit, i.e. all methods are defined or pure virtual and all1043/// friends, friend functions and nested classes are fully defined in this1044/// translation unit.1045///1046/// Should only be called from ActOnEndOfTranslationUnit so that all1047/// definitions are actually read.1048static bool IsRecordFullyDefined(const CXXRecordDecl *RD,1049RecordCompleteMap &RecordsComplete,1050RecordCompleteMap &MNCComplete) {1051RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);1052if (Cache != RecordsComplete.end())1053return Cache->second;1054bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);1055for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),1056E = RD->friend_end();1057I != E && Complete; ++I) {1058// Check if friend classes and methods are complete.1059if (TypeSourceInfo *TSI = (*I)->getFriendType()) {1060// Friend classes are available as the TypeSourceInfo of the FriendDecl.1061if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())1062Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);1063else1064Complete = false;1065} else {1066// Friend functions are available through the NamedDecl of FriendDecl.1067if (const FunctionDecl *FD =1068dyn_cast<FunctionDecl>((*I)->getFriendDecl()))1069Complete = FD->isDefined();1070else1071// This is a template friend, give up.1072Complete = false;1073}1074}1075RecordsComplete[RD] = Complete;1076return Complete;1077}10781079void Sema::emitAndClearUnusedLocalTypedefWarnings() {1080if (ExternalSource)1081ExternalSource->ReadUnusedLocalTypedefNameCandidates(1082UnusedLocalTypedefNameCandidates);1083for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {1084if (TD->isReferenced())1085continue;1086Diag(TD->getLocation(), diag::warn_unused_local_typedef)1087<< isa<TypeAliasDecl>(TD) << TD->getDeclName();1088}1089UnusedLocalTypedefNameCandidates.clear();1090}10911092void Sema::ActOnStartOfTranslationUnit() {1093if (getLangOpts().CPlusPlusModules &&1094getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)1095HandleStartOfHeaderUnit();1096}10971098void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {1099// No explicit actions are required at the end of the global module fragment.1100if (Kind == TUFragmentKind::Global)1101return;11021103// Transfer late parsed template instantiations over to the pending template1104// instantiation list. During normal compilation, the late template parser1105// will be installed and instantiating these templates will succeed.1106//1107// If we are building a TU prefix for serialization, it is also safe to1108// transfer these over, even though they are not parsed. The end of the TU1109// should be outside of any eager template instantiation scope, so when this1110// AST is deserialized, these templates will not be parsed until the end of1111// the combined TU.1112PendingInstantiations.insert(PendingInstantiations.end(),1113LateParsedInstantiations.begin(),1114LateParsedInstantiations.end());1115LateParsedInstantiations.clear();11161117// If DefinedUsedVTables ends up marking any virtual member functions it1118// might lead to more pending template instantiations, which we then need1119// to instantiate.1120DefineUsedVTables();11211122// C++: Perform implicit template instantiations.1123//1124// FIXME: When we perform these implicit instantiations, we do not1125// carefully keep track of the point of instantiation (C++ [temp.point]).1126// This means that name lookup that occurs within the template1127// instantiation will always happen at the end of the translation unit,1128// so it will find some names that are not required to be found. This is1129// valid, but we could do better by diagnosing if an instantiation uses a1130// name that was not visible at its first point of instantiation.1131if (ExternalSource) {1132// Load pending instantiations from the external source.1133SmallVector<PendingImplicitInstantiation, 4> Pending;1134ExternalSource->ReadPendingInstantiations(Pending);1135for (auto PII : Pending)1136if (auto Func = dyn_cast<FunctionDecl>(PII.first))1137Func->setInstantiationIsPending(true);1138PendingInstantiations.insert(PendingInstantiations.begin(),1139Pending.begin(), Pending.end());1140}11411142{1143llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");1144PerformPendingInstantiations();1145}11461147emitDeferredDiags();11481149assert(LateParsedInstantiations.empty() &&1150"end of TU template instantiation should not create more "1151"late-parsed templates");11521153// Report diagnostics for uncorrected delayed typos. Ideally all of them1154// should have been corrected by that time, but it is very hard to cover all1155// cases in practice.1156for (const auto &Typo : DelayedTypos) {1157// We pass an empty TypoCorrection to indicate no correction was performed.1158Typo.second.DiagHandler(TypoCorrection());1159}1160DelayedTypos.clear();1161}11621163void Sema::ActOnEndOfTranslationUnit() {1164assert(DelayedDiagnostics.getCurrentPool() == nullptr1165&& "reached end of translation unit with a pool attached?");11661167// If code completion is enabled, don't perform any end-of-translation-unit1168// work.1169if (PP.isCodeCompletionEnabled())1170return;11711172// Complete translation units and modules define vtables and perform implicit1173// instantiations. PCH files do not.1174if (TUKind != TU_Prefix) {1175ObjC().DiagnoseUseOfUnimplementedSelectors();11761177ActOnEndOfTranslationUnitFragment(1178!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==1179Module::PrivateModuleFragment1180? TUFragmentKind::Private1181: TUFragmentKind::Normal);11821183if (LateTemplateParserCleanup)1184LateTemplateParserCleanup(OpaqueParser);11851186CheckDelayedMemberExceptionSpecs();1187} else {1188// If we are building a TU prefix for serialization, it is safe to transfer1189// these over, even though they are not parsed. The end of the TU should be1190// outside of any eager template instantiation scope, so when this AST is1191// deserialized, these templates will not be parsed until the end of the1192// combined TU.1193PendingInstantiations.insert(PendingInstantiations.end(),1194LateParsedInstantiations.begin(),1195LateParsedInstantiations.end());1196LateParsedInstantiations.clear();11971198if (LangOpts.PCHInstantiateTemplates) {1199llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");1200PerformPendingInstantiations();1201}1202}12031204DiagnoseUnterminatedPragmaAlignPack();1205DiagnoseUnterminatedPragmaAttribute();1206OpenMP().DiagnoseUnterminatedOpenMPDeclareTarget();12071208// All delayed member exception specs should be checked or we end up accepting1209// incompatible declarations.1210assert(DelayedOverridingExceptionSpecChecks.empty());1211assert(DelayedEquivalentExceptionSpecChecks.empty());12121213// All dllexport classes should have been processed already.1214assert(DelayedDllExportClasses.empty());1215assert(DelayedDllExportMemberFunctions.empty());12161217// Remove file scoped decls that turned out to be used.1218UnusedFileScopedDecls.erase(1219std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),1220UnusedFileScopedDecls.end(),1221[this](const DeclaratorDecl *DD) {1222return ShouldRemoveFromUnused(this, DD);1223}),1224UnusedFileScopedDecls.end());12251226if (TUKind == TU_Prefix) {1227// Translation unit prefixes don't need any of the checking below.1228if (!PP.isIncrementalProcessingEnabled())1229TUScope = nullptr;1230return;1231}12321233// Check for #pragma weak identifiers that were never declared1234LoadExternalWeakUndeclaredIdentifiers();1235for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {1236if (WeakIDs.second.empty())1237continue;12381239Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),1240LookupOrdinaryName);1241if (PrevDecl != nullptr &&1242!(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))1243for (const auto &WI : WeakIDs.second)1244Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)1245<< "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction;1246else1247for (const auto &WI : WeakIDs.second)1248Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)1249<< WeakIDs.first;1250}12511252if (LangOpts.CPlusPlus11 &&1253!Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))1254CheckDelegatingCtorCycles();12551256if (!Diags.hasErrorOccurred()) {1257if (ExternalSource)1258ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);1259checkUndefinedButUsed(*this);1260}12611262// A global-module-fragment is only permitted within a module unit.1263if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==1264Module::ExplicitGlobalModuleFragment) {1265Diag(ModuleScopes.back().BeginLoc,1266diag::err_module_declaration_missing_after_global_module_introducer);1267}12681269// Now we can decide whether the modules we're building need an initializer.1270if (Module *CurrentModule = getCurrentModule();1271CurrentModule && CurrentModule->isInterfaceOrPartition()) {1272auto DoesModNeedInit = [this](Module *M) {1273if (!getASTContext().getModuleInitializers(M).empty())1274return true;1275for (auto [Exported, _] : M->Exports)1276if (Exported->isNamedModuleInterfaceHasInit())1277return true;1278for (Module *I : M->Imports)1279if (I->isNamedModuleInterfaceHasInit())1280return true;12811282return false;1283};12841285CurrentModule->NamedModuleHasInit =1286DoesModNeedInit(CurrentModule) ||1287llvm::any_of(CurrentModule->submodules(),1288[&](auto *SubM) { return DoesModNeedInit(SubM); });1289}12901291if (TUKind == TU_ClangModule) {1292// If we are building a module, resolve all of the exported declarations1293// now.1294if (Module *CurrentModule = PP.getCurrentModule()) {1295ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();12961297SmallVector<Module *, 2> Stack;1298Stack.push_back(CurrentModule);1299while (!Stack.empty()) {1300Module *Mod = Stack.pop_back_val();13011302// Resolve the exported declarations and conflicts.1303// FIXME: Actually complain, once we figure out how to teach the1304// diagnostic client to deal with complaints in the module map at this1305// point.1306ModMap.resolveExports(Mod, /*Complain=*/false);1307ModMap.resolveUses(Mod, /*Complain=*/false);1308ModMap.resolveConflicts(Mod, /*Complain=*/false);13091310// Queue the submodules, so their exports will also be resolved.1311auto SubmodulesRange = Mod->submodules();1312Stack.append(SubmodulesRange.begin(), SubmodulesRange.end());1313}1314}13151316// Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for1317// modules when they are built, not every time they are used.1318emitAndClearUnusedLocalTypedefWarnings();1319}13201321// C++ standard modules. Diagnose cases where a function is declared inline1322// in the module purview but has no definition before the end of the TU or1323// the start of a Private Module Fragment (if one is present).1324if (!PendingInlineFuncDecls.empty()) {1325for (auto *D : PendingInlineFuncDecls) {1326if (auto *FD = dyn_cast<FunctionDecl>(D)) {1327bool DefInPMF = false;1328if (auto *FDD = FD->getDefinition()) {1329DefInPMF = FDD->getOwningModule()->isPrivateModule();1330if (!DefInPMF)1331continue;1332}1333Diag(FD->getLocation(), diag::err_export_inline_not_defined)1334<< DefInPMF;1335// If we have a PMF it should be at the end of the ModuleScopes.1336if (DefInPMF &&1337ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {1338Diag(ModuleScopes.back().BeginLoc,1339diag::note_private_module_fragment);1340}1341}1342}1343PendingInlineFuncDecls.clear();1344}13451346// C99 6.9.2p2:1347// A declaration of an identifier for an object that has file1348// scope without an initializer, and without a storage-class1349// specifier or with the storage-class specifier static,1350// constitutes a tentative definition. If a translation unit1351// contains one or more tentative definitions for an identifier,1352// and the translation unit contains no external definition for1353// that identifier, then the behavior is exactly as if the1354// translation unit contains a file scope declaration of that1355// identifier, with the composite type as of the end of the1356// translation unit, with an initializer equal to 0.1357llvm::SmallSet<VarDecl *, 32> Seen;1358for (TentativeDefinitionsType::iterator1359T = TentativeDefinitions.begin(ExternalSource.get()),1360TEnd = TentativeDefinitions.end();1361T != TEnd; ++T) {1362VarDecl *VD = (*T)->getActingDefinition();13631364// If the tentative definition was completed, getActingDefinition() returns1365// null. If we've already seen this variable before, insert()'s second1366// return value is false.1367if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)1368continue;13691370if (const IncompleteArrayType *ArrayT1371= Context.getAsIncompleteArrayType(VD->getType())) {1372// Set the length of the array to 1 (C99 6.9.2p5).1373Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);1374llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);1375QualType T = Context.getConstantArrayType(1376ArrayT->getElementType(), One, nullptr, ArraySizeModifier::Normal, 0);1377VD->setType(T);1378} else if (RequireCompleteType(VD->getLocation(), VD->getType(),1379diag::err_tentative_def_incomplete_type))1380VD->setInvalidDecl();13811382// No initialization is performed for a tentative definition.1383CheckCompleteVariableDeclaration(VD);13841385// Notify the consumer that we've completed a tentative definition.1386if (!VD->isInvalidDecl())1387Consumer.CompleteTentativeDefinition(VD);1388}13891390for (auto *D : ExternalDeclarations) {1391if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())1392continue;13931394Consumer.CompleteExternalDeclaration(D);1395}13961397if (LangOpts.HLSL)1398HLSL().DiagnoseAvailabilityViolations(1399getASTContext().getTranslationUnitDecl());14001401// If there were errors, disable 'unused' warnings since they will mostly be1402// noise. Don't warn for a use from a module: either we should warn on all1403// file-scope declarations in modules or not at all, but whether the1404// declaration is used is immaterial.1405if (!Diags.hasErrorOccurred() && TUKind != TU_ClangModule) {1406// Output warning for unused file scoped decls.1407for (UnusedFileScopedDeclsType::iterator1408I = UnusedFileScopedDecls.begin(ExternalSource.get()),1409E = UnusedFileScopedDecls.end();1410I != E; ++I) {1411if (ShouldRemoveFromUnused(this, *I))1412continue;14131414if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {1415const FunctionDecl *DiagD;1416if (!FD->hasBody(DiagD))1417DiagD = FD;1418if (DiagD->isDeleted())1419continue; // Deleted functions are supposed to be unused.1420SourceRange DiagRange = DiagD->getLocation();1421if (const ASTTemplateArgumentListInfo *ASTTAL =1422DiagD->getTemplateSpecializationArgsAsWritten())1423DiagRange.setEnd(ASTTAL->RAngleLoc);1424if (DiagD->isReferenced()) {1425if (isa<CXXMethodDecl>(DiagD))1426Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)1427<< DiagD << DiagRange;1428else {1429if (FD->getStorageClass() == SC_Static &&1430!FD->isInlineSpecified() &&1431!SourceMgr.isInMainFile(1432SourceMgr.getExpansionLoc(FD->getLocation())))1433Diag(DiagD->getLocation(),1434diag::warn_unneeded_static_internal_decl)1435<< DiagD << DiagRange;1436else1437Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)1438<< /*function=*/0 << DiagD << DiagRange;1439}1440} else if (!FD->isTargetMultiVersion() ||1441FD->isTargetMultiVersionDefault()) {1442if (FD->getDescribedFunctionTemplate())1443Diag(DiagD->getLocation(), diag::warn_unused_template)1444<< /*function=*/0 << DiagD << DiagRange;1445else1446Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)1447? diag::warn_unused_member_function1448: diag::warn_unused_function)1449<< DiagD << DiagRange;1450}1451} else {1452const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();1453if (!DiagD)1454DiagD = cast<VarDecl>(*I);1455SourceRange DiagRange = DiagD->getLocation();1456if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(DiagD)) {1457if (const ASTTemplateArgumentListInfo *ASTTAL =1458VTSD->getTemplateArgsAsWritten())1459DiagRange.setEnd(ASTTAL->RAngleLoc);1460}1461if (DiagD->isReferenced()) {1462Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)1463<< /*variable=*/1 << DiagD << DiagRange;1464} else if (DiagD->getDescribedVarTemplate()) {1465Diag(DiagD->getLocation(), diag::warn_unused_template)1466<< /*variable=*/1 << DiagD << DiagRange;1467} else if (DiagD->getType().isConstQualified()) {1468const SourceManager &SM = SourceMgr;1469if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||1470!PP.getLangOpts().IsHeaderFile)1471Diag(DiagD->getLocation(), diag::warn_unused_const_variable)1472<< DiagD << DiagRange;1473} else {1474Diag(DiagD->getLocation(), diag::warn_unused_variable)1475<< DiagD << DiagRange;1476}1477}1478}14791480emitAndClearUnusedLocalTypedefWarnings();1481}14821483if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {1484// FIXME: Load additional unused private field candidates from the external1485// source.1486RecordCompleteMap RecordsComplete;1487RecordCompleteMap MNCComplete;1488for (const NamedDecl *D : UnusedPrivateFields) {1489const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());1490if (RD && !RD->isUnion() &&1491IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {1492Diag(D->getLocation(), diag::warn_unused_private_field)1493<< D->getDeclName();1494}1495}1496}14971498if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {1499if (ExternalSource)1500ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);1501for (const auto &DeletedFieldInfo : DeleteExprs) {1502for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {1503AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,1504DeleteExprLoc.second);1505}1506}1507}15081509AnalysisWarnings.IssueWarnings(Context.getTranslationUnitDecl());15101511// Check we've noticed that we're no longer parsing the initializer for every1512// variable. If we miss cases, then at best we have a performance issue and1513// at worst a rejects-valid bug.1514assert(ParsingInitForAutoVars.empty() &&1515"Didn't unmark var as having its initializer parsed");15161517if (!PP.isIncrementalProcessingEnabled())1518TUScope = nullptr;1519}152015211522//===----------------------------------------------------------------------===//1523// Helper functions.1524//===----------------------------------------------------------------------===//15251526DeclContext *Sema::getFunctionLevelDeclContext(bool AllowLambda) const {1527DeclContext *DC = CurContext;15281529while (true) {1530if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||1531isa<RequiresExprBodyDecl>(DC)) {1532DC = DC->getParent();1533} else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&1534cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&1535cast<CXXRecordDecl>(DC->getParent())->isLambda()) {1536DC = DC->getParent()->getParent();1537} else break;1538}15391540return DC;1541}15421543/// getCurFunctionDecl - If inside of a function body, this returns a pointer1544/// to the function decl for the function being parsed. If we're currently1545/// in a 'block', this returns the containing context.1546FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const {1547DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);1548return dyn_cast<FunctionDecl>(DC);1549}15501551ObjCMethodDecl *Sema::getCurMethodDecl() {1552DeclContext *DC = getFunctionLevelDeclContext();1553while (isa<RecordDecl>(DC))1554DC = DC->getParent();1555return dyn_cast<ObjCMethodDecl>(DC);1556}15571558NamedDecl *Sema::getCurFunctionOrMethodDecl() const {1559DeclContext *DC = getFunctionLevelDeclContext();1560if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))1561return cast<NamedDecl>(DC);1562return nullptr;1563}15641565LangAS Sema::getDefaultCXXMethodAddrSpace() const {1566if (getLangOpts().OpenCL)1567return getASTContext().getDefaultOpenCLPointeeAddrSpace();1568return LangAS::Default;1569}15701571void Sema::EmitCurrentDiagnostic(unsigned DiagID) {1572// FIXME: It doesn't make sense to me that DiagID is an incoming argument here1573// and yet we also use the current diag ID on the DiagnosticsEngine. This has1574// been made more painfully obvious by the refactor that introduced this1575// function, but it is possible that the incoming argument can be1576// eliminated. If it truly cannot be (for example, there is some reentrancy1577// issue I am not seeing yet), then there should at least be a clarifying1578// comment somewhere.1579if (std::optional<TemplateDeductionInfo *> Info = isSFINAEContext()) {1580switch (DiagnosticIDs::getDiagnosticSFINAEResponse(1581Diags.getCurrentDiagID())) {1582case DiagnosticIDs::SFINAE_Report:1583// We'll report the diagnostic below.1584break;15851586case DiagnosticIDs::SFINAE_SubstitutionFailure:1587// Count this failure so that we know that template argument deduction1588// has failed.1589++NumSFINAEErrors;15901591// Make a copy of this suppressed diagnostic and store it with the1592// template-deduction information.1593if (*Info && !(*Info)->hasSFINAEDiagnostic()) {1594Diagnostic DiagInfo(&Diags);1595(*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),1596PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));1597}15981599Diags.setLastDiagnosticIgnored(true);1600Diags.Clear();1601return;16021603case DiagnosticIDs::SFINAE_AccessControl: {1604// Per C++ Core Issue 1170, access control is part of SFINAE.1605// Additionally, the AccessCheckingSFINAE flag can be used to temporarily1606// make access control a part of SFINAE for the purposes of checking1607// type traits.1608if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)1609break;16101611SourceLocation Loc = Diags.getCurrentDiagLoc();16121613// Suppress this diagnostic.1614++NumSFINAEErrors;16151616// Make a copy of this suppressed diagnostic and store it with the1617// template-deduction information.1618if (*Info && !(*Info)->hasSFINAEDiagnostic()) {1619Diagnostic DiagInfo(&Diags);1620(*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),1621PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));1622}16231624Diags.setLastDiagnosticIgnored(true);1625Diags.Clear();16261627// Now the diagnostic state is clear, produce a C++98 compatibility1628// warning.1629Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);16301631// The last diagnostic which Sema produced was ignored. Suppress any1632// notes attached to it.1633Diags.setLastDiagnosticIgnored(true);1634return;1635}16361637case DiagnosticIDs::SFINAE_Suppress:1638// Make a copy of this suppressed diagnostic and store it with the1639// template-deduction information;1640if (*Info) {1641Diagnostic DiagInfo(&Diags);1642(*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),1643PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));1644}16451646// Suppress this diagnostic.1647Diags.setLastDiagnosticIgnored(true);1648Diags.Clear();1649return;1650}1651}16521653// Copy the diagnostic printing policy over the ASTContext printing policy.1654// TODO: Stop doing that. See: https://reviews.llvm.org/D45093#10902921655Context.setPrintingPolicy(getPrintingPolicy());16561657// Emit the diagnostic.1658if (!Diags.EmitCurrentDiagnostic())1659return;16601661// If this is not a note, and we're in a template instantiation1662// that is different from the last template instantiation where1663// we emitted an error, print a template instantiation1664// backtrace.1665if (!DiagnosticIDs::isBuiltinNote(DiagID))1666PrintContextStack();1667}16681669bool Sema::hasUncompilableErrorOccurred() const {1670if (getDiagnostics().hasUncompilableErrorOccurred())1671return true;1672auto *FD = dyn_cast<FunctionDecl>(CurContext);1673if (!FD)1674return false;1675auto Loc = DeviceDeferredDiags.find(FD);1676if (Loc == DeviceDeferredDiags.end())1677return false;1678for (auto PDAt : Loc->second) {1679if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))1680return true;1681}1682return false;1683}16841685// Print notes showing how we can reach FD starting from an a priori1686// known-callable function.1687static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) {1688auto FnIt = S.CUDA().DeviceKnownEmittedFns.find(FD);1689while (FnIt != S.CUDA().DeviceKnownEmittedFns.end()) {1690// Respect error limit.1691if (S.Diags.hasFatalErrorOccurred())1692return;1693DiagnosticBuilder Builder(1694S.Diags.Report(FnIt->second.Loc, diag::note_called_by));1695Builder << FnIt->second.FD;1696FnIt = S.CUDA().DeviceKnownEmittedFns.find(FnIt->second.FD);1697}1698}16991700namespace {17011702/// Helper class that emits deferred diagnostic messages if an entity directly1703/// or indirectly using the function that causes the deferred diagnostic1704/// messages is known to be emitted.1705///1706/// During parsing of AST, certain diagnostic messages are recorded as deferred1707/// diagnostics since it is unknown whether the functions containing such1708/// diagnostics will be emitted. A list of potentially emitted functions and1709/// variables that may potentially trigger emission of functions are also1710/// recorded. DeferredDiagnosticsEmitter recursively visits used functions1711/// by each function to emit deferred diagnostics.1712///1713/// During the visit, certain OpenMP directives or initializer of variables1714/// with certain OpenMP attributes will cause subsequent visiting of any1715/// functions enter a state which is called OpenMP device context in this1716/// implementation. The state is exited when the directive or initializer is1717/// exited. This state can change the emission states of subsequent uses1718/// of functions.1719///1720/// Conceptually the functions or variables to be visited form a use graph1721/// where the parent node uses the child node. At any point of the visit,1722/// the tree nodes traversed from the tree root to the current node form a use1723/// stack. The emission state of the current node depends on two factors:1724/// 1. the emission state of the root node1725/// 2. whether the current node is in OpenMP device context1726/// If the function is decided to be emitted, its contained deferred diagnostics1727/// are emitted, together with the information about the use stack.1728///1729class DeferredDiagnosticsEmitter1730: public UsedDeclVisitor<DeferredDiagnosticsEmitter> {1731public:1732typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;17331734// Whether the function is already in the current use-path.1735llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;17361737// The current use-path.1738llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;17391740// Whether the visiting of the function has been done. Done[0] is for the1741// case not in OpenMP device context. Done[1] is for the case in OpenMP1742// device context. We need two sets because diagnostics emission may be1743// different depending on whether it is in OpenMP device context.1744llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];17451746// Emission state of the root node of the current use graph.1747bool ShouldEmitRootNode;17481749// Current OpenMP device context level. It is initialized to 0 and each1750// entering of device context increases it by 1 and each exit decreases1751// it by 1. Non-zero value indicates it is currently in device context.1752unsigned InOMPDeviceContext;17531754DeferredDiagnosticsEmitter(Sema &S)1755: Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}17561757bool shouldVisitDiscardedStmt() const { return false; }17581759void VisitOMPTargetDirective(OMPTargetDirective *Node) {1760++InOMPDeviceContext;1761Inherited::VisitOMPTargetDirective(Node);1762--InOMPDeviceContext;1763}17641765void visitUsedDecl(SourceLocation Loc, Decl *D) {1766if (isa<VarDecl>(D))1767return;1768if (auto *FD = dyn_cast<FunctionDecl>(D))1769checkFunc(Loc, FD);1770else1771Inherited::visitUsedDecl(Loc, D);1772}17731774void checkVar(VarDecl *VD) {1775assert(VD->isFileVarDecl() &&1776"Should only check file-scope variables");1777if (auto *Init = VD->getInit()) {1778auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);1779bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||1780*DevTy == OMPDeclareTargetDeclAttr::DT_Any);1781if (IsDev)1782++InOMPDeviceContext;1783this->Visit(Init);1784if (IsDev)1785--InOMPDeviceContext;1786}1787}17881789void checkFunc(SourceLocation Loc, FunctionDecl *FD) {1790auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];1791FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();1792if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||1793S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))1794return;1795// Finalize analysis of OpenMP-specific constructs.1796if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&1797(ShouldEmitRootNode || InOMPDeviceContext))1798S.OpenMP().finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);1799if (Caller)1800S.CUDA().DeviceKnownEmittedFns[FD] = {Caller, Loc};1801// Always emit deferred diagnostics for the direct users. This does not1802// lead to explosion of diagnostics since each user is visited at most1803// twice.1804if (ShouldEmitRootNode || InOMPDeviceContext)1805emitDeferredDiags(FD, Caller);1806// Do not revisit a function if the function body has been completely1807// visited before.1808if (!Done.insert(FD).second)1809return;1810InUsePath.insert(FD);1811UsePath.push_back(FD);1812if (auto *S = FD->getBody()) {1813this->Visit(S);1814}1815UsePath.pop_back();1816InUsePath.erase(FD);1817}18181819void checkRecordedDecl(Decl *D) {1820if (auto *FD = dyn_cast<FunctionDecl>(D)) {1821ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==1822Sema::FunctionEmissionStatus::Emitted;1823checkFunc(SourceLocation(), FD);1824} else1825checkVar(cast<VarDecl>(D));1826}18271828// Emit any deferred diagnostics for FD1829void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {1830auto It = S.DeviceDeferredDiags.find(FD);1831if (It == S.DeviceDeferredDiags.end())1832return;1833bool HasWarningOrError = false;1834bool FirstDiag = true;1835for (PartialDiagnosticAt &PDAt : It->second) {1836// Respect error limit.1837if (S.Diags.hasFatalErrorOccurred())1838return;1839const SourceLocation &Loc = PDAt.first;1840const PartialDiagnostic &PD = PDAt.second;1841HasWarningOrError |=1842S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=1843DiagnosticsEngine::Warning;1844{1845DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));1846PD.Emit(Builder);1847}1848// Emit the note on the first diagnostic in case too many diagnostics1849// cause the note not emitted.1850if (FirstDiag && HasWarningOrError && ShowCallStack) {1851emitCallStackNotes(S, FD);1852FirstDiag = false;1853}1854}1855}1856};1857} // namespace18581859void Sema::emitDeferredDiags() {1860if (ExternalSource)1861ExternalSource->ReadDeclsToCheckForDeferredDiags(1862DeclsToCheckForDeferredDiags);18631864if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||1865DeclsToCheckForDeferredDiags.empty())1866return;18671868DeferredDiagnosticsEmitter DDE(*this);1869for (auto *D : DeclsToCheckForDeferredDiags)1870DDE.checkRecordedDecl(D);1871}18721873// In CUDA, there are some constructs which may appear in semantically-valid1874// code, but trigger errors if we ever generate code for the function in which1875// they appear. Essentially every construct you're not allowed to use on the1876// device falls into this category, because you are allowed to use these1877// constructs in a __host__ __device__ function, but only if that function is1878// never codegen'ed on the device.1879//1880// To handle semantic checking for these constructs, we keep track of the set of1881// functions we know will be emitted, either because we could tell a priori that1882// they would be emitted, or because they were transitively called by a1883// known-emitted function.1884//1885// We also keep a partial call graph of which not-known-emitted functions call1886// which other not-known-emitted functions.1887//1888// When we see something which is illegal if the current function is emitted1889// (usually by way of DiagIfDeviceCode, DiagIfHostCode, or1890// CheckCall), we first check if the current function is known-emitted. If1891// so, we immediately output the diagnostic.1892//1893// Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags1894// until we discover that the function is known-emitted, at which point we take1895// it out of this map and emit the diagnostic.18961897Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,1898unsigned DiagID,1899const FunctionDecl *Fn,1900Sema &S)1901: S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),1902ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {1903switch (K) {1904case K_Nop:1905break;1906case K_Immediate:1907case K_ImmediateWithCallStack:1908ImmediateDiag.emplace(1909ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));1910break;1911case K_Deferred:1912assert(Fn && "Must have a function to attach the deferred diag to.");1913auto &Diags = S.DeviceDeferredDiags[Fn];1914PartialDiagId.emplace(Diags.size());1915Diags.emplace_back(Loc, S.PDiag(DiagID));1916break;1917}1918}19191920Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)1921: S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),1922ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),1923PartialDiagId(D.PartialDiagId) {1924// Clean the previous diagnostics.1925D.ShowCallStack = false;1926D.ImmediateDiag.reset();1927D.PartialDiagId.reset();1928}19291930Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {1931if (ImmediateDiag) {1932// Emit our diagnostic and, if it was a warning or error, output a callstack1933// if Fn isn't a priori known-emitted.1934bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(1935DiagID, Loc) >= DiagnosticsEngine::Warning;1936ImmediateDiag.reset(); // Emit the immediate diag.1937if (IsWarningOrError && ShowCallStack)1938emitCallStackNotes(S, Fn);1939} else {1940assert((!PartialDiagId || ShowCallStack) &&1941"Must always show call stack for deferred diags.");1942}1943}19441945Sema::SemaDiagnosticBuilder1946Sema::targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD) {1947FD = FD ? FD : getCurFunctionDecl();1948if (LangOpts.OpenMP)1949return LangOpts.OpenMPIsTargetDevice1950? OpenMP().diagIfOpenMPDeviceCode(Loc, DiagID, FD)1951: OpenMP().diagIfOpenMPHostCode(Loc, DiagID, FD);1952if (getLangOpts().CUDA)1953return getLangOpts().CUDAIsDevice ? CUDA().DiagIfDeviceCode(Loc, DiagID)1954: CUDA().DiagIfHostCode(Loc, DiagID);19551956if (getLangOpts().SYCLIsDevice)1957return SYCL().DiagIfDeviceCode(Loc, DiagID);19581959return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,1960FD, *this);1961}19621963void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {1964if (isUnevaluatedContext() || Ty.isNull())1965return;19661967// The original idea behind checkTypeSupport function is that unused1968// declarations can be replaced with an array of bytes of the same size during1969// codegen, such replacement doesn't seem to be possible for types without1970// constant byte size like zero length arrays. So, do a deep check for SYCL.1971if (D && LangOpts.SYCLIsDevice) {1972llvm::DenseSet<QualType> Visited;1973SYCL().deepTypeCheckForDevice(Loc, Visited, D);1974}19751976Decl *C = cast<Decl>(getCurLexicalContext());19771978// Memcpy operations for structs containing a member with unsupported type1979// are ok, though.1980if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {1981if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&1982MD->isTrivial())1983return;19841985if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))1986if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())1987return;1988}19891990// Try to associate errors with the lexical context, if that is a function, or1991// the value declaration otherwise.1992const FunctionDecl *FD = isa<FunctionDecl>(C)1993? cast<FunctionDecl>(C)1994: dyn_cast_or_null<FunctionDecl>(D);19951996auto CheckDeviceType = [&](QualType Ty) {1997if (Ty->isDependentType())1998return;19992000if (Ty->isBitIntType()) {2001if (!Context.getTargetInfo().hasBitIntType()) {2002PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);2003if (D)2004PD << D;2005else2006PD << "expression";2007targetDiag(Loc, PD, FD)2008<< false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/2009<< Ty << Context.getTargetInfo().getTriple().str();2010}2011return;2012}20132014// Check if we are dealing with two 'long double' but with different2015// semantics.2016bool LongDoubleMismatched = false;2017if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {2018const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);2019if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&2020!Context.getTargetInfo().hasFloat128Type()) ||2021(&Sem == &llvm::APFloat::PPCDoubleDouble() &&2022!Context.getTargetInfo().hasIbm128Type()))2023LongDoubleMismatched = true;2024}20252026if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||2027(Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||2028(Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) ||2029(Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&2030!Context.getTargetInfo().hasInt128Type()) ||2031(Ty->isBFloat16Type() && !Context.getTargetInfo().hasBFloat16Type() &&2032!LangOpts.CUDAIsDevice) ||2033LongDoubleMismatched) {2034PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);2035if (D)2036PD << D;2037else2038PD << "expression";20392040if (targetDiag(Loc, PD, FD)2041<< true /*show bit size*/2042<< static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty2043<< false /*return*/ << Context.getTargetInfo().getTriple().str()) {2044if (D)2045D->setInvalidDecl();2046}2047if (D)2048targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;2049}2050};20512052auto CheckType = [&](QualType Ty, bool IsRetTy = false) {2053if (LangOpts.SYCLIsDevice ||2054(LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice) ||2055LangOpts.CUDAIsDevice)2056CheckDeviceType(Ty);20572058QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();2059const TargetInfo &TI = Context.getTargetInfo();2060if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {2061PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);2062if (D)2063PD << D;2064else2065PD << "expression";20662067if (Diag(Loc, PD, FD)2068<< false /*show bit size*/ << 0 << Ty << false /*return*/2069<< TI.getTriple().str()) {2070if (D)2071D->setInvalidDecl();2072}2073if (D)2074targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;2075}20762077bool IsDouble = UnqualTy == Context.DoubleTy;2078bool IsFloat = UnqualTy == Context.FloatTy;2079if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {2080PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);2081if (D)2082PD << D;2083else2084PD << "expression";20852086if (Diag(Loc, PD, FD)2087<< false /*show bit size*/ << 0 << Ty << true /*return*/2088<< TI.getTriple().str()) {2089if (D)2090D->setInvalidDecl();2091}2092if (D)2093targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;2094}20952096if (TI.hasRISCVVTypes() && Ty->isRVVSizelessBuiltinType() && FD) {2097llvm::StringMap<bool> CallerFeatureMap;2098Context.getFunctionFeatureMap(CallerFeatureMap, FD);2099RISCV().checkRVVTypeSupport(Ty, Loc, D, CallerFeatureMap);2100}21012102// Don't allow SVE types in functions without a SVE target.2103if (Ty->isSVESizelessBuiltinType() && FD) {2104llvm::StringMap<bool> CallerFeatureMap;2105Context.getFunctionFeatureMap(CallerFeatureMap, FD);2106if (!Builtin::evaluateRequiredTargetFeatures("sve", CallerFeatureMap)) {2107if (!Builtin::evaluateRequiredTargetFeatures("sme", CallerFeatureMap))2108Diag(Loc, diag::err_sve_vector_in_non_sve_target) << Ty;2109else if (!IsArmStreamingFunction(FD,2110/*IncludeLocallyStreaming=*/true)) {2111Diag(Loc, diag::err_sve_vector_in_non_streaming_function) << Ty;2112}2113}2114}2115};21162117CheckType(Ty);2118if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {2119for (const auto &ParamTy : FPTy->param_types())2120CheckType(ParamTy);2121CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);2122}2123if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))2124CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);2125}21262127bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {2128SourceLocation loc = locref;2129if (!loc.isMacroID()) return false;21302131// There's no good way right now to look at the intermediate2132// expansions, so just jump to the expansion location.2133loc = getSourceManager().getExpansionLoc(loc);21342135// If that's written with the name, stop here.2136SmallString<16> buffer;2137if (getPreprocessor().getSpelling(loc, buffer) == name) {2138locref = loc;2139return true;2140}2141return false;2142}21432144Scope *Sema::getScopeForContext(DeclContext *Ctx) {21452146if (!Ctx)2147return nullptr;21482149Ctx = Ctx->getPrimaryContext();2150for (Scope *S = getCurScope(); S; S = S->getParent()) {2151// Ignore scopes that cannot have declarations. This is important for2152// out-of-line definitions of static class members.2153if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))2154if (DeclContext *Entity = S->getEntity())2155if (Ctx == Entity->getPrimaryContext())2156return S;2157}21582159return nullptr;2160}21612162/// Enter a new function scope2163void Sema::PushFunctionScope() {2164if (FunctionScopes.empty() && CachedFunctionScope) {2165// Use CachedFunctionScope to avoid allocating memory when possible.2166CachedFunctionScope->Clear();2167FunctionScopes.push_back(CachedFunctionScope.release());2168} else {2169FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));2170}2171if (LangOpts.OpenMP)2172OpenMP().pushOpenMPFunctionRegion();2173}21742175void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {2176FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),2177BlockScope, Block));2178CapturingFunctionScopes++;2179}21802181LambdaScopeInfo *Sema::PushLambdaScope() {2182LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());2183FunctionScopes.push_back(LSI);2184CapturingFunctionScopes++;2185return LSI;2186}21872188void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {2189if (LambdaScopeInfo *const LSI = getCurLambda()) {2190LSI->AutoTemplateParameterDepth = Depth;2191return;2192}2193llvm_unreachable(2194"Remove assertion if intentionally called in a non-lambda context.");2195}21962197// Check that the type of the VarDecl has an accessible copy constructor and2198// resolve its destructor's exception specification.2199// This also performs initialization of block variables when they are moved2200// to the heap. It uses the same rules as applicable for implicit moves2201// according to the C++ standard in effect ([class.copy.elision]p3).2202static void checkEscapingByref(VarDecl *VD, Sema &S) {2203QualType T = VD->getType();2204EnterExpressionEvaluationContext scope(2205S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);2206SourceLocation Loc = VD->getLocation();2207Expr *VarRef =2208new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);2209ExprResult Result;2210auto IE = InitializedEntity::InitializeBlock(Loc, T);2211if (S.getLangOpts().CPlusPlus23) {2212auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,2213VK_XValue, FPOptionsOverride());2214Result = S.PerformCopyInitialization(IE, SourceLocation(), E);2215} else {2216Result = S.PerformMoveOrCopyInitialization(2217IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible},2218VarRef);2219}22202221if (!Result.isInvalid()) {2222Result = S.MaybeCreateExprWithCleanups(Result);2223Expr *Init = Result.getAs<Expr>();2224S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));2225}22262227// The destructor's exception specification is needed when IRGen generates2228// block copy/destroy functions. Resolve it here.2229if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())2230if (CXXDestructorDecl *DD = RD->getDestructor()) {2231auto *FPT = DD->getType()->castAs<FunctionProtoType>();2232S.ResolveExceptionSpec(Loc, FPT);2233}2234}22352236static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {2237// Set the EscapingByref flag of __block variables captured by2238// escaping blocks.2239for (const BlockDecl *BD : FSI.Blocks) {2240for (const BlockDecl::Capture &BC : BD->captures()) {2241VarDecl *VD = BC.getVariable();2242if (VD->hasAttr<BlocksAttr>()) {2243// Nothing to do if this is a __block variable captured by a2244// non-escaping block.2245if (BD->doesNotEscape())2246continue;2247VD->setEscapingByref();2248}2249// Check whether the captured variable is or contains an object of2250// non-trivial C union type.2251QualType CapType = BC.getVariable()->getType();2252if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||2253CapType.hasNonTrivialToPrimitiveCopyCUnion())2254S.checkNonTrivialCUnion(BC.getVariable()->getType(),2255BD->getCaretLocation(),2256Sema::NTCUC_BlockCapture,2257Sema::NTCUK_Destruct|Sema::NTCUK_Copy);2258}2259}22602261for (VarDecl *VD : FSI.ByrefBlockVars) {2262// __block variables might require us to capture a copy-initializer.2263if (!VD->isEscapingByref())2264continue;2265// It's currently invalid to ever have a __block variable with an2266// array type; should we diagnose that here?2267// Regardless, we don't want to ignore array nesting when2268// constructing this copy.2269if (VD->getType()->isStructureOrClassType())2270checkEscapingByref(VD, S);2271}2272}22732274Sema::PoppedFunctionScopePtr2275Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,2276const Decl *D, QualType BlockType) {2277assert(!FunctionScopes.empty() && "mismatched push/pop!");22782279markEscapingByrefs(*FunctionScopes.back(), *this);22802281PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),2282PoppedFunctionScopeDeleter(this));22832284if (LangOpts.OpenMP)2285OpenMP().popOpenMPFunctionRegion(Scope.get());22862287// Issue any analysis-based warnings.2288if (WP && D)2289AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);2290else2291for (const auto &PUD : Scope->PossiblyUnreachableDiags)2292Diag(PUD.Loc, PUD.PD);22932294return Scope;2295}22962297void Sema::PoppedFunctionScopeDeleter::2298operator()(sema::FunctionScopeInfo *Scope) const {2299if (!Scope->isPlainFunction())2300Self->CapturingFunctionScopes--;2301// Stash the function scope for later reuse if it's for a normal function.2302if (Scope->isPlainFunction() && !Self->CachedFunctionScope)2303Self->CachedFunctionScope.reset(Scope);2304else2305delete Scope;2306}23072308void Sema::PushCompoundScope(bool IsStmtExpr) {2309getCurFunction()->CompoundScopes.push_back(2310CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));2311}23122313void Sema::PopCompoundScope() {2314FunctionScopeInfo *CurFunction = getCurFunction();2315assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");23162317CurFunction->CompoundScopes.pop_back();2318}23192320bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {2321return getCurFunction()->hasUnrecoverableErrorOccurred();2322}23232324void Sema::setFunctionHasBranchIntoScope() {2325if (!FunctionScopes.empty())2326FunctionScopes.back()->setHasBranchIntoScope();2327}23282329void Sema::setFunctionHasBranchProtectedScope() {2330if (!FunctionScopes.empty())2331FunctionScopes.back()->setHasBranchProtectedScope();2332}23332334void Sema::setFunctionHasIndirectGoto() {2335if (!FunctionScopes.empty())2336FunctionScopes.back()->setHasIndirectGoto();2337}23382339void Sema::setFunctionHasMustTail() {2340if (!FunctionScopes.empty())2341FunctionScopes.back()->setHasMustTail();2342}23432344BlockScopeInfo *Sema::getCurBlock() {2345if (FunctionScopes.empty())2346return nullptr;23472348auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());2349if (CurBSI && CurBSI->TheDecl &&2350!CurBSI->TheDecl->Encloses(CurContext)) {2351// We have switched contexts due to template instantiation.2352assert(!CodeSynthesisContexts.empty());2353return nullptr;2354}23552356return CurBSI;2357}23582359FunctionScopeInfo *Sema::getEnclosingFunction() const {2360if (FunctionScopes.empty())2361return nullptr;23622363for (int e = FunctionScopes.size() - 1; e >= 0; --e) {2364if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))2365continue;2366return FunctionScopes[e];2367}2368return nullptr;2369}23702371LambdaScopeInfo *Sema::getEnclosingLambda() const {2372for (auto *Scope : llvm::reverse(FunctionScopes)) {2373if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {2374if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&2375LSI->AfterParameterList) {2376// We have switched contexts due to template instantiation.2377// FIXME: We should swap out the FunctionScopes during code synthesis2378// so that we don't need to check for this.2379assert(!CodeSynthesisContexts.empty());2380return nullptr;2381}2382return LSI;2383}2384}2385return nullptr;2386}23872388LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {2389if (FunctionScopes.empty())2390return nullptr;23912392auto I = FunctionScopes.rbegin();2393if (IgnoreNonLambdaCapturingScope) {2394auto E = FunctionScopes.rend();2395while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))2396++I;2397if (I == E)2398return nullptr;2399}2400auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);2401if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&2402!CurLSI->Lambda->Encloses(CurContext) && CurLSI->AfterParameterList) {2403// We have switched contexts due to template instantiation.2404assert(!CodeSynthesisContexts.empty());2405return nullptr;2406}24072408return CurLSI;2409}24102411// We have a generic lambda if we parsed auto parameters, or we have2412// an associated template parameter list.2413LambdaScopeInfo *Sema::getCurGenericLambda() {2414if (LambdaScopeInfo *LSI = getCurLambda()) {2415return (LSI->TemplateParams.size() ||2416LSI->GLTemplateParameterList) ? LSI : nullptr;2417}2418return nullptr;2419}242024212422void Sema::ActOnComment(SourceRange Comment) {2423if (!LangOpts.RetainCommentsFromSystemHeaders &&2424SourceMgr.isInSystemHeader(Comment.getBegin()))2425return;2426RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);2427if (RC.isAlmostTrailingComment() || RC.hasUnsupportedSplice(SourceMgr)) {2428SourceRange MagicMarkerRange(Comment.getBegin(),2429Comment.getBegin().getLocWithOffset(3));2430StringRef MagicMarkerText;2431switch (RC.getKind()) {2432case RawComment::RCK_OrdinaryBCPL:2433MagicMarkerText = "///<";2434break;2435case RawComment::RCK_OrdinaryC:2436MagicMarkerText = "/**<";2437break;2438case RawComment::RCK_Invalid:2439// FIXME: are there other scenarios that could produce an invalid2440// raw comment here?2441Diag(Comment.getBegin(), diag::warn_splice_in_doxygen_comment);2442return;2443default:2444llvm_unreachable("if this is an almost Doxygen comment, "2445"it should be ordinary");2446}2447Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<2448FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);2449}2450Context.addComment(RC);2451}24522453// Pin this vtable to this file.2454ExternalSemaSource::~ExternalSemaSource() {}2455char ExternalSemaSource::ID;24562457void ExternalSemaSource::ReadMethodPool(Selector Sel) { }2458void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }24592460void ExternalSemaSource::ReadKnownNamespaces(2461SmallVectorImpl<NamespaceDecl *> &Namespaces) {2462}24632464void ExternalSemaSource::ReadUndefinedButUsed(2465llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}24662467void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<2468FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}24692470bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,2471UnresolvedSetImpl &OverloadSet) {2472ZeroArgCallReturnTy = QualType();2473OverloadSet.clear();24742475const OverloadExpr *Overloads = nullptr;2476bool IsMemExpr = false;2477if (E.getType() == Context.OverloadTy) {2478OverloadExpr::FindResult FR = OverloadExpr::find(&E);24792480// Ignore overloads that are pointer-to-member constants.2481if (FR.HasFormOfMemberPointer)2482return false;24832484Overloads = FR.Expression;2485} else if (E.getType() == Context.BoundMemberTy) {2486Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());2487IsMemExpr = true;2488}24892490bool Ambiguous = false;2491bool IsMV = false;24922493if (Overloads) {2494for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),2495DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {2496OverloadSet.addDecl(*it);24972498// Check whether the function is a non-template, non-member which takes no2499// arguments.2500if (IsMemExpr)2501continue;2502if (const FunctionDecl *OverloadDecl2503= dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {2504if (OverloadDecl->getMinRequiredArguments() == 0) {2505if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&2506(!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||2507OverloadDecl->isCPUSpecificMultiVersion()))) {2508ZeroArgCallReturnTy = QualType();2509Ambiguous = true;2510} else {2511ZeroArgCallReturnTy = OverloadDecl->getReturnType();2512IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||2513OverloadDecl->isCPUSpecificMultiVersion();2514}2515}2516}2517}25182519// If it's not a member, use better machinery to try to resolve the call2520if (!IsMemExpr)2521return !ZeroArgCallReturnTy.isNull();2522}25232524// Attempt to call the member with no arguments - this will correctly handle2525// member templates with defaults/deduction of template arguments, overloads2526// with default arguments, etc.2527if (IsMemExpr && !E.isTypeDependent()) {2528Sema::TentativeAnalysisScope Trap(*this);2529ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),2530std::nullopt, SourceLocation());2531if (R.isUsable()) {2532ZeroArgCallReturnTy = R.get()->getType();2533return true;2534}2535return false;2536}25372538if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {2539if (const auto *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {2540if (Fun->getMinRequiredArguments() == 0)2541ZeroArgCallReturnTy = Fun->getReturnType();2542return true;2543}2544}25452546// We don't have an expression that's convenient to get a FunctionDecl from,2547// but we can at least check if the type is "function of 0 arguments".2548QualType ExprTy = E.getType();2549const FunctionType *FunTy = nullptr;2550QualType PointeeTy = ExprTy->getPointeeType();2551if (!PointeeTy.isNull())2552FunTy = PointeeTy->getAs<FunctionType>();2553if (!FunTy)2554FunTy = ExprTy->getAs<FunctionType>();25552556if (const auto *FPT = dyn_cast_if_present<FunctionProtoType>(FunTy)) {2557if (FPT->getNumParams() == 0)2558ZeroArgCallReturnTy = FunTy->getReturnType();2559return true;2560}2561return false;2562}25632564/// Give notes for a set of overloads.2565///2566/// A companion to tryExprAsCall. In cases when the name that the programmer2567/// wrote was an overloaded function, we may be able to make some guesses about2568/// plausible overloads based on their return types; such guesses can be handed2569/// off to this method to be emitted as notes.2570///2571/// \param Overloads - The overloads to note.2572/// \param FinalNoteLoc - If we've suppressed printing some overloads due to2573/// -fshow-overloads=best, this is the location to attach to the note about too2574/// many candidates. Typically this will be the location of the original2575/// ill-formed expression.2576static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,2577const SourceLocation FinalNoteLoc) {2578unsigned ShownOverloads = 0;2579unsigned SuppressedOverloads = 0;2580for (UnresolvedSetImpl::iterator It = Overloads.begin(),2581DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {2582if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {2583++SuppressedOverloads;2584continue;2585}25862587const NamedDecl *Fn = (*It)->getUnderlyingDecl();2588// Don't print overloads for non-default multiversioned functions.2589if (const auto *FD = Fn->getAsFunction()) {2590if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&2591!FD->getAttr<TargetAttr>()->isDefaultVersion())2592continue;2593if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&2594!FD->getAttr<TargetVersionAttr>()->isDefaultVersion())2595continue;2596}2597S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);2598++ShownOverloads;2599}26002601S.Diags.overloadCandidatesShown(ShownOverloads);26022603if (SuppressedOverloads)2604S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)2605<< SuppressedOverloads;2606}26072608static void notePlausibleOverloads(Sema &S, SourceLocation Loc,2609const UnresolvedSetImpl &Overloads,2610bool (*IsPlausibleResult)(QualType)) {2611if (!IsPlausibleResult)2612return noteOverloads(S, Overloads, Loc);26132614UnresolvedSet<2> PlausibleOverloads;2615for (OverloadExpr::decls_iterator It = Overloads.begin(),2616DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {2617const auto *OverloadDecl = cast<FunctionDecl>(*It);2618QualType OverloadResultTy = OverloadDecl->getReturnType();2619if (IsPlausibleResult(OverloadResultTy))2620PlausibleOverloads.addDecl(It.getDecl());2621}2622noteOverloads(S, PlausibleOverloads, Loc);2623}26242625/// Determine whether the given expression can be called by just2626/// putting parentheses after it. Notably, expressions with unary2627/// operators can't be because the unary operator will start parsing2628/// outside the call.2629static bool IsCallableWithAppend(const Expr *E) {2630E = E->IgnoreImplicit();2631return (!isa<CStyleCastExpr>(E) &&2632!isa<UnaryOperator>(E) &&2633!isa<BinaryOperator>(E) &&2634!isa<CXXOperatorCallExpr>(E));2635}26362637static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {2638if (const auto *UO = dyn_cast<UnaryOperator>(E))2639E = UO->getSubExpr();26402641if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {2642if (ULE->getNumDecls() == 0)2643return false;26442645const NamedDecl *ND = *ULE->decls_begin();2646if (const auto *FD = dyn_cast<FunctionDecl>(ND))2647return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();2648}2649return false;2650}26512652bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,2653bool ForceComplain,2654bool (*IsPlausibleResult)(QualType)) {2655SourceLocation Loc = E.get()->getExprLoc();2656SourceRange Range = E.get()->getSourceRange();2657UnresolvedSet<4> Overloads;26582659// If this is a SFINAE context, don't try anything that might trigger ADL2660// prematurely.2661if (!isSFINAEContext()) {2662QualType ZeroArgCallTy;2663if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&2664!ZeroArgCallTy.isNull() &&2665(!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {2666// At this point, we know E is potentially callable with 02667// arguments and that it returns something of a reasonable type,2668// so we can emit a fixit and carry on pretending that E was2669// actually a CallExpr.2670SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());2671bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());2672Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range2673<< (IsCallableWithAppend(E.get())2674? FixItHint::CreateInsertion(ParenInsertionLoc,2675"()")2676: FixItHint());2677if (!IsMV)2678notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);26792680// FIXME: Try this before emitting the fixit, and suppress diagnostics2681// while doing so.2682E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), std::nullopt,2683Range.getEnd().getLocWithOffset(1));2684return true;2685}2686}2687if (!ForceComplain) return false;26882689bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());2690Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;2691if (!IsMV)2692notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);2693E = ExprError();2694return true;2695}26962697IdentifierInfo *Sema::getSuperIdentifier() const {2698if (!Ident_super)2699Ident_super = &Context.Idents.get("super");2700return Ident_super;2701}27022703void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,2704CapturedRegionKind K,2705unsigned OpenMPCaptureLevel) {2706auto *CSI = new CapturedRegionScopeInfo(2707getDiagnostics(), S, CD, RD, CD->getContextParam(), K,2708(getLangOpts().OpenMP && K == CR_OpenMP)2709? OpenMP().getOpenMPNestingLevel()2710: 0,2711OpenMPCaptureLevel);2712CSI->ReturnType = Context.VoidTy;2713FunctionScopes.push_back(CSI);2714CapturingFunctionScopes++;2715}27162717CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {2718if (FunctionScopes.empty())2719return nullptr;27202721return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());2722}27232724const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &2725Sema::getMismatchingDeleteExpressions() const {2726return DeleteExprs;2727}27282729Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S)2730: S(S), OldFPFeaturesState(S.CurFPFeatures),2731OldOverrides(S.FpPragmaStack.CurrentValue),2732OldEvalMethod(S.PP.getCurrentFPEvalMethod()),2733OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}27342735Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {2736S.CurFPFeatures = OldFPFeaturesState;2737S.FpPragmaStack.CurrentValue = OldOverrides;2738S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);2739}27402741bool Sema::isDeclaratorFunctionLike(Declarator &D) {2742assert(D.getCXXScopeSpec().isSet() &&2743"can only be called for qualified names");27442745auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),2746LookupOrdinaryName, forRedeclarationInCurContext());2747DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(),2748!D.getDeclSpec().isFriendSpecified());2749if (!DC)2750return false;27512752LookupQualifiedName(LR, DC);2753bool Result = llvm::all_of(LR, [](Decl *Dcl) {2754if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {2755ND = ND->getUnderlyingDecl();2756return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||2757isa<UsingDecl>(ND);2758}2759return false;2760});2761return Result;2762}27632764FunctionEffectDifferences::FunctionEffectDifferences(2765const FunctionEffectsRef &Old, const FunctionEffectsRef &New) {27662767FunctionEffectsRef::iterator POld = Old.begin();2768FunctionEffectsRef::iterator OldEnd = Old.end();2769FunctionEffectsRef::iterator PNew = New.begin();2770FunctionEffectsRef::iterator NewEnd = New.end();27712772while (true) {2773int cmp = 0;2774if (POld == OldEnd) {2775if (PNew == NewEnd)2776break;2777cmp = 1;2778} else if (PNew == NewEnd)2779cmp = -1;2780else {2781FunctionEffectWithCondition Old = *POld;2782FunctionEffectWithCondition New = *PNew;2783if (Old.Effect.kind() < New.Effect.kind())2784cmp = -1;2785else if (New.Effect.kind() < Old.Effect.kind())2786cmp = 1;2787else {2788cmp = 0;2789if (Old.Cond.getCondition() != New.Cond.getCondition()) {2790// FIXME: Cases where the expressions are equivalent but2791// don't have the same identity.2792push_back(FunctionEffectDiff{2793Old.Effect.kind(), FunctionEffectDiff::Kind::ConditionMismatch,2794Old, New});2795}2796}2797}27982799if (cmp < 0) {2800// removal2801FunctionEffectWithCondition Old = *POld;2802push_back(FunctionEffectDiff{2803Old.Effect.kind(), FunctionEffectDiff::Kind::Removed, Old, {}});2804++POld;2805} else if (cmp > 0) {2806// addition2807FunctionEffectWithCondition New = *PNew;2808push_back(FunctionEffectDiff{2809New.Effect.kind(), FunctionEffectDiff::Kind::Added, {}, New});2810++PNew;2811} else {2812++POld;2813++PNew;2814}2815}2816}28172818bool FunctionEffectDiff::shouldDiagnoseConversion(2819QualType SrcType, const FunctionEffectsRef &SrcFX, QualType DstType,2820const FunctionEffectsRef &DstFX) const {28212822switch (EffectKind) {2823case FunctionEffect::Kind::NonAllocating:2824// nonallocating can't be added (spoofed) during a conversion, unless we2825// have nonblocking.2826if (DiffKind == Kind::Added) {2827for (const auto &CFE : SrcFX) {2828if (CFE.Effect.kind() == FunctionEffect::Kind::NonBlocking)2829return false;2830}2831}2832[[fallthrough]];2833case FunctionEffect::Kind::NonBlocking:2834// nonblocking can't be added (spoofed) during a conversion.2835switch (DiffKind) {2836case Kind::Added:2837return true;2838case Kind::Removed:2839return false;2840case Kind::ConditionMismatch:2841// FIXME: Condition mismatches are too coarse right now -- expressions2842// which are equivalent but don't have the same identity are detected as2843// mismatches. We're going to diagnose those anyhow until expression2844// matching is better.2845return true;2846}2847case FunctionEffect::Kind::Blocking:2848case FunctionEffect::Kind::Allocating:2849return false;2850case FunctionEffect::Kind::None:2851break;2852}2853llvm_unreachable("unknown effect kind");2854}28552856bool FunctionEffectDiff::shouldDiagnoseRedeclaration(2857const FunctionDecl &OldFunction, const FunctionEffectsRef &OldFX,2858const FunctionDecl &NewFunction, const FunctionEffectsRef &NewFX) const {2859switch (EffectKind) {2860case FunctionEffect::Kind::NonAllocating:2861case FunctionEffect::Kind::NonBlocking:2862// nonblocking/nonallocating can't be removed in a redeclaration.2863switch (DiffKind) {2864case Kind::Added:2865return false; // No diagnostic.2866case Kind::Removed:2867return true; // Issue diagnostic.2868case Kind::ConditionMismatch:2869// All these forms of mismatches are diagnosed.2870return true;2871}2872case FunctionEffect::Kind::Blocking:2873case FunctionEffect::Kind::Allocating:2874return false;2875case FunctionEffect::Kind::None:2876break;2877}2878llvm_unreachable("unknown effect kind");2879}28802881FunctionEffectDiff::OverrideResult2882FunctionEffectDiff::shouldDiagnoseMethodOverride(2883const CXXMethodDecl &OldMethod, const FunctionEffectsRef &OldFX,2884const CXXMethodDecl &NewMethod, const FunctionEffectsRef &NewFX) const {2885switch (EffectKind) {2886case FunctionEffect::Kind::NonAllocating:2887case FunctionEffect::Kind::NonBlocking:2888switch (DiffKind) {28892890// If added on an override, that's fine and not diagnosed.2891case Kind::Added:2892return OverrideResult::NoAction;28932894// If missing from an override (removed), propagate from base to derived.2895case Kind::Removed:2896return OverrideResult::Merge;28972898// If there's a mismatch involving the effect's polarity or condition,2899// issue a warning.2900case Kind::ConditionMismatch:2901return OverrideResult::Warn;2902}29032904case FunctionEffect::Kind::Blocking:2905case FunctionEffect::Kind::Allocating:2906return OverrideResult::NoAction;29072908case FunctionEffect::Kind::None:2909break;2910}2911llvm_unreachable("unknown effect kind");2912}291329142915