[lld][WebAssembly] Add `--table-base` setting
[llvm-project.git] / clang / lib / Sema / Sema.cpp
blobfaf375fb8fab3e73a514cef4228e37d22ea2731a
1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the actions class which performs semantic analysis and
10 // builds an AST out of a parse stream.
12 //===----------------------------------------------------------------------===//
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclFriend.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/AST/PrettyDeclStackTrace.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/Basic/DarwinSDKInfo.h"
26 #include "clang/Basic/DiagnosticOptions.h"
27 #include "clang/Basic/PartialDiagnostic.h"
28 #include "clang/Basic/SourceManager.h"
29 #include "clang/Basic/Stack.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h"
32 #include "clang/Lex/HeaderSearchOptions.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/CXXFieldCollector.h"
35 #include "clang/Sema/DelayedDiagnostic.h"
36 #include "clang/Sema/EnterExpressionEvaluationContext.h"
37 #include "clang/Sema/ExternalSemaSource.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/MultiplexExternalSemaSource.h"
40 #include "clang/Sema/ObjCMethodList.h"
41 #include "clang/Sema/RISCVIntrinsicManager.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaConsumer.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/TemplateDeduction.h"
47 #include "clang/Sema/TemplateInstCallback.h"
48 #include "clang/Sema/TypoCorrection.h"
49 #include "llvm/ADT/DenseMap.h"
50 #include "llvm/ADT/STLExtras.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/Support/TimeProfiler.h"
53 #include <optional>
55 using namespace clang;
56 using namespace sema;
58 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
59 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
62 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
64 DarwinSDKInfo *
65 Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
66 StringRef Platform) {
67 auto *SDKInfo = getDarwinSDKInfoForAvailabilityChecking();
68 if (!SDKInfo && !WarnedDarwinSDKInfoMissing) {
69 Diag(Loc, diag::warn_missing_sdksettings_for_availability_checking)
70 << Platform;
71 WarnedDarwinSDKInfoMissing = true;
73 return SDKInfo;
76 DarwinSDKInfo *Sema::getDarwinSDKInfoForAvailabilityChecking() {
77 if (CachedDarwinSDKInfo)
78 return CachedDarwinSDKInfo->get();
79 auto SDKInfo = parseDarwinSDKInfo(
80 PP.getFileManager().getVirtualFileSystem(),
81 PP.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot);
82 if (SDKInfo && *SDKInfo) {
83 CachedDarwinSDKInfo = std::make_unique<DarwinSDKInfo>(std::move(**SDKInfo));
84 return CachedDarwinSDKInfo->get();
86 if (!SDKInfo)
87 llvm::consumeError(SDKInfo.takeError());
88 CachedDarwinSDKInfo = std::unique_ptr<DarwinSDKInfo>();
89 return nullptr;
92 IdentifierInfo *
93 Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
94 unsigned int Index) {
95 std::string InventedName;
96 llvm::raw_string_ostream OS(InventedName);
98 if (!ParamName)
99 OS << "auto:" << Index + 1;
100 else
101 OS << ParamName->getName() << ":auto";
103 OS.flush();
104 return &Context.Idents.get(OS.str());
107 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
108 const Preprocessor &PP) {
109 PrintingPolicy Policy = Context.getPrintingPolicy();
110 // In diagnostics, we print _Bool as bool if the latter is defined as the
111 // former.
112 Policy.Bool = Context.getLangOpts().Bool;
113 if (!Policy.Bool) {
114 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
115 Policy.Bool = BoolMacro->isObjectLike() &&
116 BoolMacro->getNumTokens() == 1 &&
117 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
121 // Shorten the data output if needed
122 Policy.EntireContentsOfLargeArray = false;
124 return Policy;
127 void Sema::ActOnTranslationUnitScope(Scope *S) {
128 TUScope = S;
129 PushDeclContext(S, Context.getTranslationUnitDecl());
132 namespace clang {
133 namespace sema {
135 class SemaPPCallbacks : public PPCallbacks {
136 Sema *S = nullptr;
137 llvm::SmallVector<SourceLocation, 8> IncludeStack;
139 public:
140 void set(Sema &S) { this->S = &S; }
142 void reset() { S = nullptr; }
144 void FileChanged(SourceLocation Loc, FileChangeReason Reason,
145 SrcMgr::CharacteristicKind FileType,
146 FileID PrevFID) override {
147 if (!S)
148 return;
149 switch (Reason) {
150 case EnterFile: {
151 SourceManager &SM = S->getSourceManager();
152 SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
153 if (IncludeLoc.isValid()) {
154 if (llvm::timeTraceProfilerEnabled()) {
155 const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
156 llvm::timeTraceProfilerBegin(
157 "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
160 IncludeStack.push_back(IncludeLoc);
161 S->DiagnoseNonDefaultPragmaAlignPack(
162 Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude,
163 IncludeLoc);
165 break;
167 case ExitFile:
168 if (!IncludeStack.empty()) {
169 if (llvm::timeTraceProfilerEnabled())
170 llvm::timeTraceProfilerEnd();
172 S->DiagnoseNonDefaultPragmaAlignPack(
173 Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit,
174 IncludeStack.pop_back_val());
176 break;
177 default:
178 break;
183 } // end namespace sema
184 } // end namespace clang
186 const unsigned Sema::MaxAlignmentExponent;
187 const uint64_t Sema::MaximumAlignment;
189 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
190 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
191 : ExternalSource(nullptr), CurFPFeatures(pp.getLangOpts()),
192 LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
193 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
194 CollectStats(false), CodeCompleter(CodeCompleter), CurContext(nullptr),
195 OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
196 MSPointerToMemberRepresentationMethod(
197 LangOpts.getMSPointerToMemberRepresentationMethod()),
198 VtorDispStack(LangOpts.getVtorDispMode()),
199 AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack)),
200 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
201 CodeSegStack(nullptr), StrictGuardStackCheckStack(false),
202 FpPragmaStack(FPOptionsOverride()), CurInitSeg(nullptr),
203 VisContext(nullptr), PragmaAttributeCurrentTargetDecl(nullptr),
204 IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr),
205 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
206 StdInitializerList(nullptr), StdCoroutineTraitsCache(nullptr),
207 CXXTypeInfoDecl(nullptr), StdSourceLocationImplDecl(nullptr),
208 NSNumberDecl(nullptr), NSValueDecl(nullptr), NSStringDecl(nullptr),
209 StringWithUTF8StringMethod(nullptr),
210 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
211 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
212 DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
213 TUKind(TUKind), NumSFINAEErrors(0),
214 FullyCheckedComparisonCategories(
215 static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
216 SatisfactionCache(Context), AccessCheckingSFINAE(false),
217 InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
218 ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
219 DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
220 ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
221 CurScope(nullptr), Ident_super(nullptr) {
222 assert(pp.TUKind == TUKind);
223 TUScope = nullptr;
224 isConstantEvaluatedOverride = false;
226 LoadedExternalKnownNamespaces = false;
227 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
228 NSNumberLiteralMethods[I] = nullptr;
230 if (getLangOpts().ObjC)
231 NSAPIObj.reset(new NSAPI(Context));
233 if (getLangOpts().CPlusPlus)
234 FieldCollector.reset(new CXXFieldCollector());
236 // Tell diagnostics how to render things from the AST library.
237 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
239 // This evaluation context exists to ensure that there's always at least one
240 // valid evaluation context available. It is never removed from the
241 // evaluation stack.
242 ExprEvalContexts.emplace_back(
243 ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
244 nullptr, ExpressionEvaluationContextRecord::EK_Other);
246 // Initialization of data sharing attributes stack for OpenMP
247 InitDataSharingAttributesStack();
249 std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
250 std::make_unique<sema::SemaPPCallbacks>();
251 SemaPPCallbackHandler = Callbacks.get();
252 PP.addPPCallbacks(std::move(Callbacks));
253 SemaPPCallbackHandler->set(*this);
255 CurFPFeatures.setFPEvalMethod(PP.getCurrentFPEvalMethod());
258 // Anchor Sema's type info to this TU.
259 void Sema::anchor() {}
261 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
262 DeclarationName DN = &Context.Idents.get(Name);
263 if (IdResolver.begin(DN) == IdResolver.end())
264 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
267 void Sema::Initialize() {
268 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
269 SC->InitializeSema(*this);
271 // Tell the external Sema source about this Sema object.
272 if (ExternalSemaSource *ExternalSema
273 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
274 ExternalSema->InitializeSema(*this);
276 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
277 // will not be able to merge any duplicate __va_list_tag decls correctly.
278 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
280 if (!TUScope)
281 return;
283 // Initialize predefined 128-bit integer types, if needed.
284 if (Context.getTargetInfo().hasInt128Type() ||
285 (Context.getAuxTargetInfo() &&
286 Context.getAuxTargetInfo()->hasInt128Type())) {
287 // If either of the 128-bit integer types are unavailable to name lookup,
288 // define them now.
289 DeclarationName Int128 = &Context.Idents.get("__int128_t");
290 if (IdResolver.begin(Int128) == IdResolver.end())
291 PushOnScopeChains(Context.getInt128Decl(), TUScope);
293 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
294 if (IdResolver.begin(UInt128) == IdResolver.end())
295 PushOnScopeChains(Context.getUInt128Decl(), TUScope);
299 // Initialize predefined Objective-C types:
300 if (getLangOpts().ObjC) {
301 // If 'SEL' does not yet refer to any declarations, make it refer to the
302 // predefined 'SEL'.
303 DeclarationName SEL = &Context.Idents.get("SEL");
304 if (IdResolver.begin(SEL) == IdResolver.end())
305 PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
307 // If 'id' does not yet refer to any declarations, make it refer to the
308 // predefined 'id'.
309 DeclarationName Id = &Context.Idents.get("id");
310 if (IdResolver.begin(Id) == IdResolver.end())
311 PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
313 // Create the built-in typedef for 'Class'.
314 DeclarationName Class = &Context.Idents.get("Class");
315 if (IdResolver.begin(Class) == IdResolver.end())
316 PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
318 // Create the built-in forward declaratino for 'Protocol'.
319 DeclarationName Protocol = &Context.Idents.get("Protocol");
320 if (IdResolver.begin(Protocol) == IdResolver.end())
321 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
324 // Create the internal type for the *StringMakeConstantString builtins.
325 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
326 if (IdResolver.begin(ConstantString) == IdResolver.end())
327 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
329 // Initialize Microsoft "predefined C++ types".
330 if (getLangOpts().MSVCCompat) {
331 if (getLangOpts().CPlusPlus &&
332 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
333 PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
334 TUScope);
336 addImplicitTypedef("size_t", Context.getSizeType());
339 // Initialize predefined OpenCL types and supported extensions and (optional)
340 // core features.
341 if (getLangOpts().OpenCL) {
342 getOpenCLOptions().addSupport(
343 Context.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
344 addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
345 addImplicitTypedef("event_t", Context.OCLEventTy);
346 auto OCLCompatibleVersion = getLangOpts().getOpenCLCompatibleVersion();
347 if (OCLCompatibleVersion >= 200) {
348 if (getLangOpts().OpenCLCPlusPlus || getLangOpts().Blocks) {
349 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
350 addImplicitTypedef("queue_t", Context.OCLQueueTy);
352 if (getLangOpts().OpenCLPipes)
353 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
354 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
355 addImplicitTypedef("atomic_uint",
356 Context.getAtomicType(Context.UnsignedIntTy));
357 addImplicitTypedef("atomic_float",
358 Context.getAtomicType(Context.FloatTy));
359 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
360 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
361 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
364 // OpenCL v2.0 s6.13.11.6:
365 // - The atomic_long and atomic_ulong types are supported if the
366 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
367 // extensions are supported.
368 // - The atomic_double type is only supported if double precision
369 // is supported and the cl_khr_int64_base_atomics and
370 // cl_khr_int64_extended_atomics extensions are supported.
371 // - If the device address space is 64-bits, the data types
372 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
373 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
374 // cl_khr_int64_extended_atomics extensions are supported.
376 auto AddPointerSizeDependentTypes = [&]() {
377 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
378 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
379 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
380 auto AtomicPtrDiffT =
381 Context.getAtomicType(Context.getPointerDiffType());
382 addImplicitTypedef("atomic_size_t", AtomicSizeT);
383 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
384 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
385 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
388 if (Context.getTypeSize(Context.getSizeType()) == 32) {
389 AddPointerSizeDependentTypes();
392 if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
393 auto AtomicHalfT = Context.getAtomicType(Context.HalfTy);
394 addImplicitTypedef("atomic_half", AtomicHalfT);
397 std::vector<QualType> Atomic64BitTypes;
398 if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
399 getLangOpts()) &&
400 getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
401 getLangOpts())) {
402 if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
403 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
404 addImplicitTypedef("atomic_double", AtomicDoubleT);
405 Atomic64BitTypes.push_back(AtomicDoubleT);
407 auto AtomicLongT = Context.getAtomicType(Context.LongTy);
408 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
409 addImplicitTypedef("atomic_long", AtomicLongT);
410 addImplicitTypedef("atomic_ulong", AtomicULongT);
413 if (Context.getTypeSize(Context.getSizeType()) == 64) {
414 AddPointerSizeDependentTypes();
419 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
420 if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \
421 addImplicitTypedef(#ExtType, Context.Id##Ty); \
423 #include "clang/Basic/OpenCLExtensionTypes.def"
426 if (Context.getTargetInfo().hasAArch64SVETypes()) {
427 #define SVE_TYPE(Name, Id, SingletonId) \
428 addImplicitTypedef(Name, Context.SingletonId);
429 #include "clang/Basic/AArch64SVEACLETypes.def"
432 if (Context.getTargetInfo().getTriple().isPPC64()) {
433 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
434 addImplicitTypedef(#Name, Context.Id##Ty);
435 #include "clang/Basic/PPCTypes.def"
436 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
437 addImplicitTypedef(#Name, Context.Id##Ty);
438 #include "clang/Basic/PPCTypes.def"
441 if (Context.getTargetInfo().hasRISCVVTypes()) {
442 #define RVV_TYPE(Name, Id, SingletonId) \
443 addImplicitTypedef(Name, Context.SingletonId);
444 #include "clang/Basic/RISCVVTypes.def"
447 if (Context.getTargetInfo().getTriple().isWasm() &&
448 Context.getTargetInfo().hasFeature("reference-types")) {
449 #define WASM_TYPE(Name, Id, SingletonId) \
450 addImplicitTypedef(Name, Context.SingletonId);
451 #include "clang/Basic/WebAssemblyReferenceTypes.def"
454 if (Context.getTargetInfo().hasBuiltinMSVaList()) {
455 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
456 if (IdResolver.begin(MSVaList) == IdResolver.end())
457 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
460 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
461 if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
462 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
465 Sema::~Sema() {
466 assert(InstantiatingSpecializations.empty() &&
467 "failed to clean up an InstantiatingTemplate?");
469 if (VisContext) FreeVisContext();
471 // Kill all the active scopes.
472 for (sema::FunctionScopeInfo *FSI : FunctionScopes)
473 delete FSI;
475 // Tell the SemaConsumer to forget about us; we're going out of scope.
476 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
477 SC->ForgetSema();
479 // Detach from the external Sema source.
480 if (ExternalSemaSource *ExternalSema
481 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
482 ExternalSema->ForgetSema();
484 // Delete cached satisfactions.
485 std::vector<ConstraintSatisfaction *> Satisfactions;
486 Satisfactions.reserve(Satisfactions.size());
487 for (auto &Node : SatisfactionCache)
488 Satisfactions.push_back(&Node);
489 for (auto *Node : Satisfactions)
490 delete Node;
492 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
494 // Destroys data sharing attributes stack for OpenMP
495 DestroyDataSharingAttributesStack();
497 // Detach from the PP callback handler which outlives Sema since it's owned
498 // by the preprocessor.
499 SemaPPCallbackHandler->reset();
502 void Sema::warnStackExhausted(SourceLocation Loc) {
503 // Only warn about this once.
504 if (!WarnedStackExhausted) {
505 Diag(Loc, diag::warn_stack_exhausted);
506 WarnedStackExhausted = true;
510 void Sema::runWithSufficientStackSpace(SourceLocation Loc,
511 llvm::function_ref<void()> Fn) {
512 clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn);
515 /// makeUnavailableInSystemHeader - There is an error in the current
516 /// context. If we're still in a system header, and we can plausibly
517 /// make the relevant declaration unavailable instead of erroring, do
518 /// so and return true.
519 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
520 UnavailableAttr::ImplicitReason reason) {
521 // If we're not in a function, it's an error.
522 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
523 if (!fn) return false;
525 // If we're in template instantiation, it's an error.
526 if (inTemplateInstantiation())
527 return false;
529 // If that function's not in a system header, it's an error.
530 if (!Context.getSourceManager().isInSystemHeader(loc))
531 return false;
533 // If the function is already unavailable, it's not an error.
534 if (fn->hasAttr<UnavailableAttr>()) return true;
536 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
537 return true;
540 ASTMutationListener *Sema::getASTMutationListener() const {
541 return getASTConsumer().GetASTMutationListener();
544 ///Registers an external source. If an external source already exists,
545 /// creates a multiplex external source and appends to it.
547 ///\param[in] E - A non-null external sema source.
549 void Sema::addExternalSource(ExternalSemaSource *E) {
550 assert(E && "Cannot use with NULL ptr");
552 if (!ExternalSource) {
553 ExternalSource = E;
554 return;
557 if (auto *Ex = dyn_cast<MultiplexExternalSemaSource>(ExternalSource))
558 Ex->AddSource(E);
559 else
560 ExternalSource = new MultiplexExternalSemaSource(ExternalSource.get(), E);
563 /// Print out statistics about the semantic analysis.
564 void Sema::PrintStats() const {
565 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
566 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
568 BumpAlloc.PrintStats();
569 AnalysisWarnings.PrintStats();
572 void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
573 QualType SrcType,
574 SourceLocation Loc) {
575 std::optional<NullabilityKind> ExprNullability = SrcType->getNullability();
576 if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
577 *ExprNullability != NullabilityKind::NullableResult))
578 return;
580 std::optional<NullabilityKind> TypeNullability = DstType->getNullability();
581 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
582 return;
584 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
587 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E) {
588 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
589 if (!getLangOpts().CPlusPlus11)
590 return;
592 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
593 return;
594 if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
595 return;
597 if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
598 E->getBeginLoc()))
599 return;
601 // Don't diagnose the conversion from a 0 literal to a null pointer argument
602 // in a synthesized call to operator<=>.
603 if (!CodeSynthesisContexts.empty() &&
604 CodeSynthesisContexts.back().Kind ==
605 CodeSynthesisContext::RewritingOperatorAsSpaceship)
606 return;
608 // Ignore null pointers in defaulted comparison operators.
609 FunctionDecl *FD = getCurFunctionDecl();
610 if (FD && FD->isDefaulted()) {
611 return;
614 // If it is a macro from system header, and if the macro name is not "NULL",
615 // do not warn.
616 SourceLocation MaybeMacroLoc = E->getBeginLoc();
617 if (Diags.getSuppressSystemWarnings() &&
618 SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
619 !findMacroSpelling(MaybeMacroLoc, "NULL"))
620 return;
622 Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
623 << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
626 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
627 /// If there is already an implicit cast, merge into the existing one.
628 /// The result is of the given category.
629 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
630 CastKind Kind, ExprValueKind VK,
631 const CXXCastPath *BasePath,
632 CheckedConversionKind CCK) {
633 #ifndef NDEBUG
634 if (VK == VK_PRValue && !E->isPRValue()) {
635 switch (Kind) {
636 default:
637 llvm_unreachable(
638 ("can't implicitly cast glvalue to prvalue with this cast "
639 "kind: " +
640 std::string(CastExpr::getCastKindName(Kind)))
641 .c_str());
642 case CK_Dependent:
643 case CK_LValueToRValue:
644 case CK_ArrayToPointerDecay:
645 case CK_FunctionToPointerDecay:
646 case CK_ToVoid:
647 case CK_NonAtomicToAtomic:
648 break;
651 assert((VK == VK_PRValue || Kind == CK_Dependent || !E->isPRValue()) &&
652 "can't cast prvalue to glvalue");
653 #endif
655 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
656 diagnoseZeroToNullptrConversion(Kind, E);
658 QualType ExprTy = Context.getCanonicalType(E->getType());
659 QualType TypeTy = Context.getCanonicalType(Ty);
661 if (ExprTy == TypeTy)
662 return E;
664 if (Kind == CK_ArrayToPointerDecay) {
665 // C++1z [conv.array]: The temporary materialization conversion is applied.
666 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
667 if (getLangOpts().CPlusPlus && E->isPRValue()) {
668 // The temporary is an lvalue in C++98 and an xvalue otherwise.
669 ExprResult Materialized = CreateMaterializeTemporaryExpr(
670 E->getType(), E, !getLangOpts().CPlusPlus11);
671 if (Materialized.isInvalid())
672 return ExprError();
673 E = Materialized.get();
675 // C17 6.7.1p6 footnote 124: The implementation can treat any register
676 // declaration simply as an auto declaration. However, whether or not
677 // addressable storage is actually used, the address of any part of an
678 // object declared with storage-class specifier register cannot be
679 // computed, either explicitly(by use of the unary & operator as discussed
680 // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
681 // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
682 // array declared with storage-class specifier register is sizeof.
683 if (VK == VK_PRValue && !getLangOpts().CPlusPlus && !E->isPRValue()) {
684 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
685 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
686 if (VD->getStorageClass() == SC_Register) {
687 Diag(E->getExprLoc(), diag::err_typecheck_address_of)
688 << /*register variable*/ 3 << E->getSourceRange();
689 return ExprError();
696 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
697 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
698 ImpCast->setType(Ty);
699 ImpCast->setValueKind(VK);
700 return E;
704 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
705 CurFPFeatureOverrides());
708 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
709 /// to the conversion from scalar type ScalarTy to the Boolean type.
710 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
711 switch (ScalarTy->getScalarTypeKind()) {
712 case Type::STK_Bool: return CK_NoOp;
713 case Type::STK_CPointer: return CK_PointerToBoolean;
714 case Type::STK_BlockPointer: return CK_PointerToBoolean;
715 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
716 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
717 case Type::STK_Integral: return CK_IntegralToBoolean;
718 case Type::STK_Floating: return CK_FloatingToBoolean;
719 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
720 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
721 case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
723 llvm_unreachable("unknown scalar type kind");
726 /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
727 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
728 if (D->getMostRecentDecl()->isUsed())
729 return true;
731 if (D->isExternallyVisible())
732 return true;
734 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
735 // If this is a function template and none of its specializations is used,
736 // we should warn.
737 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
738 for (const auto *Spec : Template->specializations())
739 if (ShouldRemoveFromUnused(SemaRef, Spec))
740 return true;
742 // UnusedFileScopedDecls stores the first declaration.
743 // The declaration may have become definition so check again.
744 const FunctionDecl *DeclToCheck;
745 if (FD->hasBody(DeclToCheck))
746 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
748 // Later redecls may add new information resulting in not having to warn,
749 // so check again.
750 DeclToCheck = FD->getMostRecentDecl();
751 if (DeclToCheck != FD)
752 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
755 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
756 // If a variable usable in constant expressions is referenced,
757 // don't warn if it isn't used: if the value of a variable is required
758 // for the computation of a constant expression, it doesn't make sense to
759 // warn even if the variable isn't odr-used. (isReferenced doesn't
760 // precisely reflect that, but it's a decent approximation.)
761 if (VD->isReferenced() &&
762 VD->mightBeUsableInConstantExpressions(SemaRef->Context))
763 return true;
765 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
766 // If this is a variable template and none of its specializations is used,
767 // we should warn.
768 for (const auto *Spec : Template->specializations())
769 if (ShouldRemoveFromUnused(SemaRef, Spec))
770 return true;
772 // UnusedFileScopedDecls stores the first declaration.
773 // The declaration may have become definition so check again.
774 const VarDecl *DeclToCheck = VD->getDefinition();
775 if (DeclToCheck)
776 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
778 // Later redecls may add new information resulting in not having to warn,
779 // so check again.
780 DeclToCheck = VD->getMostRecentDecl();
781 if (DeclToCheck != VD)
782 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
785 return false;
788 static bool isFunctionOrVarDeclExternC(const NamedDecl *ND) {
789 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
790 return FD->isExternC();
791 return cast<VarDecl>(ND)->isExternC();
794 /// Determine whether ND is an external-linkage function or variable whose
795 /// type has no linkage.
796 bool Sema::isExternalWithNoLinkageType(const ValueDecl *VD) const {
797 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
798 // because we also want to catch the case where its type has VisibleNoLinkage,
799 // which does not affect the linkage of VD.
800 return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
801 !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
802 !isFunctionOrVarDeclExternC(VD);
805 /// Obtains a sorted list of functions and variables that are undefined but
806 /// ODR-used.
807 void Sema::getUndefinedButUsed(
808 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
809 for (const auto &UndefinedUse : UndefinedButUsed) {
810 NamedDecl *ND = UndefinedUse.first;
812 // Ignore attributes that have become invalid.
813 if (ND->isInvalidDecl()) continue;
815 // __attribute__((weakref)) is basically a definition.
816 if (ND->hasAttr<WeakRefAttr>()) continue;
818 if (isa<CXXDeductionGuideDecl>(ND))
819 continue;
821 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
822 // An exported function will always be emitted when defined, so even if
823 // the function is inline, it doesn't have to be emitted in this TU. An
824 // imported function implies that it has been exported somewhere else.
825 continue;
828 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
829 if (FD->isDefined())
830 continue;
831 if (FD->isExternallyVisible() &&
832 !isExternalWithNoLinkageType(FD) &&
833 !FD->getMostRecentDecl()->isInlined() &&
834 !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
835 continue;
836 if (FD->getBuiltinID())
837 continue;
838 } else {
839 const auto *VD = cast<VarDecl>(ND);
840 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
841 continue;
842 if (VD->isExternallyVisible() &&
843 !isExternalWithNoLinkageType(VD) &&
844 !VD->getMostRecentDecl()->isInline() &&
845 !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
846 continue;
848 // Skip VarDecls that lack formal definitions but which we know are in
849 // fact defined somewhere.
850 if (VD->isKnownToBeDefined())
851 continue;
854 Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
858 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
859 /// or that are inline.
860 static void checkUndefinedButUsed(Sema &S) {
861 if (S.UndefinedButUsed.empty()) return;
863 // Collect all the still-undefined entities with internal linkage.
864 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
865 S.getUndefinedButUsed(Undefined);
866 if (Undefined.empty()) return;
868 for (const auto &Undef : Undefined) {
869 ValueDecl *VD = cast<ValueDecl>(Undef.first);
870 SourceLocation UseLoc = Undef.second;
872 if (S.isExternalWithNoLinkageType(VD)) {
873 // C++ [basic.link]p8:
874 // A type without linkage shall not be used as the type of a variable
875 // or function with external linkage unless
876 // -- the entity has C language linkage
877 // -- the entity is not odr-used or is defined in the same TU
879 // As an extension, accept this in cases where the type is externally
880 // visible, since the function or variable actually can be defined in
881 // another translation unit in that case.
882 S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
883 ? diag::ext_undefined_internal_type
884 : diag::err_undefined_internal_type)
885 << isa<VarDecl>(VD) << VD;
886 } else if (!VD->isExternallyVisible()) {
887 // FIXME: We can promote this to an error. The function or variable can't
888 // be defined anywhere else, so the program must necessarily violate the
889 // one definition rule.
890 bool IsImplicitBase = false;
891 if (const auto *BaseD = dyn_cast<FunctionDecl>(VD)) {
892 auto *DVAttr = BaseD->getAttr<OMPDeclareVariantAttr>();
893 if (DVAttr && !DVAttr->getTraitInfo().isExtensionActive(
894 llvm::omp::TraitProperty::
895 implementation_extension_disable_implicit_base)) {
896 const auto *Func = cast<FunctionDecl>(
897 cast<DeclRefExpr>(DVAttr->getVariantFuncRef())->getDecl());
898 IsImplicitBase = BaseD->isImplicit() &&
899 Func->getIdentifier()->isMangledOpenMPVariantName();
902 if (!S.getLangOpts().OpenMP || !IsImplicitBase)
903 S.Diag(VD->getLocation(), diag::warn_undefined_internal)
904 << isa<VarDecl>(VD) << VD;
905 } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
906 (void)FD;
907 assert(FD->getMostRecentDecl()->isInlined() &&
908 "used object requires definition but isn't inline or internal?");
909 // FIXME: This is ill-formed; we should reject.
910 S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
911 } else {
912 assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
913 "used var requires definition but isn't inline or internal?");
914 S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
916 if (UseLoc.isValid())
917 S.Diag(UseLoc, diag::note_used_here);
920 S.UndefinedButUsed.clear();
923 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
924 if (!ExternalSource)
925 return;
927 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
928 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
929 for (auto &WeakID : WeakIDs)
930 (void)WeakUndeclaredIdentifiers[WeakID.first].insert(WeakID.second);
934 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
936 /// Returns true, if all methods and nested classes of the given
937 /// CXXRecordDecl are defined in this translation unit.
939 /// Should only be called from ActOnEndOfTranslationUnit so that all
940 /// definitions are actually read.
941 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
942 RecordCompleteMap &MNCComplete) {
943 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
944 if (Cache != MNCComplete.end())
945 return Cache->second;
946 if (!RD->isCompleteDefinition())
947 return false;
948 bool Complete = true;
949 for (DeclContext::decl_iterator I = RD->decls_begin(),
950 E = RD->decls_end();
951 I != E && Complete; ++I) {
952 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
953 Complete = M->isDefined() || M->isDefaulted() ||
954 (M->isPure() && !isa<CXXDestructorDecl>(M));
955 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
956 // If the template function is marked as late template parsed at this
957 // point, it has not been instantiated and therefore we have not
958 // performed semantic analysis on it yet, so we cannot know if the type
959 // can be considered complete.
960 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
961 F->getTemplatedDecl()->isDefined();
962 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
963 if (R->isInjectedClassName())
964 continue;
965 if (R->hasDefinition())
966 Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
967 MNCComplete);
968 else
969 Complete = false;
972 MNCComplete[RD] = Complete;
973 return Complete;
976 /// Returns true, if the given CXXRecordDecl is fully defined in this
977 /// translation unit, i.e. all methods are defined or pure virtual and all
978 /// friends, friend functions and nested classes are fully defined in this
979 /// translation unit.
981 /// Should only be called from ActOnEndOfTranslationUnit so that all
982 /// definitions are actually read.
983 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
984 RecordCompleteMap &RecordsComplete,
985 RecordCompleteMap &MNCComplete) {
986 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
987 if (Cache != RecordsComplete.end())
988 return Cache->second;
989 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
990 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
991 E = RD->friend_end();
992 I != E && Complete; ++I) {
993 // Check if friend classes and methods are complete.
994 if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
995 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
996 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
997 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
998 else
999 Complete = false;
1000 } else {
1001 // Friend functions are available through the NamedDecl of FriendDecl.
1002 if (const FunctionDecl *FD =
1003 dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
1004 Complete = FD->isDefined();
1005 else
1006 // This is a template friend, give up.
1007 Complete = false;
1010 RecordsComplete[RD] = Complete;
1011 return Complete;
1014 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
1015 if (ExternalSource)
1016 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
1017 UnusedLocalTypedefNameCandidates);
1018 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
1019 if (TD->isReferenced())
1020 continue;
1021 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
1022 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
1024 UnusedLocalTypedefNameCandidates.clear();
1027 /// This is called before the very first declaration in the translation unit
1028 /// is parsed. Note that the ASTContext may have already injected some
1029 /// declarations.
1030 void Sema::ActOnStartOfTranslationUnit() {
1031 if (getLangOpts().CPlusPlusModules &&
1032 getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit)
1033 HandleStartOfHeaderUnit();
1036 void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
1037 // No explicit actions are required at the end of the global module fragment.
1038 if (Kind == TUFragmentKind::Global)
1039 return;
1041 // Transfer late parsed template instantiations over to the pending template
1042 // instantiation list. During normal compilation, the late template parser
1043 // will be installed and instantiating these templates will succeed.
1045 // If we are building a TU prefix for serialization, it is also safe to
1046 // transfer these over, even though they are not parsed. The end of the TU
1047 // should be outside of any eager template instantiation scope, so when this
1048 // AST is deserialized, these templates will not be parsed until the end of
1049 // the combined TU.
1050 PendingInstantiations.insert(PendingInstantiations.end(),
1051 LateParsedInstantiations.begin(),
1052 LateParsedInstantiations.end());
1053 LateParsedInstantiations.clear();
1055 // If DefinedUsedVTables ends up marking any virtual member functions it
1056 // might lead to more pending template instantiations, which we then need
1057 // to instantiate.
1058 DefineUsedVTables();
1060 // C++: Perform implicit template instantiations.
1062 // FIXME: When we perform these implicit instantiations, we do not
1063 // carefully keep track of the point of instantiation (C++ [temp.point]).
1064 // This means that name lookup that occurs within the template
1065 // instantiation will always happen at the end of the translation unit,
1066 // so it will find some names that are not required to be found. This is
1067 // valid, but we could do better by diagnosing if an instantiation uses a
1068 // name that was not visible at its first point of instantiation.
1069 if (ExternalSource) {
1070 // Load pending instantiations from the external source.
1071 SmallVector<PendingImplicitInstantiation, 4> Pending;
1072 ExternalSource->ReadPendingInstantiations(Pending);
1073 for (auto PII : Pending)
1074 if (auto Func = dyn_cast<FunctionDecl>(PII.first))
1075 Func->setInstantiationIsPending(true);
1076 PendingInstantiations.insert(PendingInstantiations.begin(),
1077 Pending.begin(), Pending.end());
1081 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1082 PerformPendingInstantiations();
1085 emitDeferredDiags();
1087 assert(LateParsedInstantiations.empty() &&
1088 "end of TU template instantiation should not create more "
1089 "late-parsed templates");
1091 // Report diagnostics for uncorrected delayed typos. Ideally all of them
1092 // should have been corrected by that time, but it is very hard to cover all
1093 // cases in practice.
1094 for (const auto &Typo : DelayedTypos) {
1095 // We pass an empty TypoCorrection to indicate no correction was performed.
1096 Typo.second.DiagHandler(TypoCorrection());
1098 DelayedTypos.clear();
1101 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1102 /// translation unit when EOF is reached and all but the top-level scope is
1103 /// popped.
1104 void Sema::ActOnEndOfTranslationUnit() {
1105 assert(DelayedDiagnostics.getCurrentPool() == nullptr
1106 && "reached end of translation unit with a pool attached?");
1108 // If code completion is enabled, don't perform any end-of-translation-unit
1109 // work.
1110 if (PP.isCodeCompletionEnabled())
1111 return;
1113 // Complete translation units and modules define vtables and perform implicit
1114 // instantiations. PCH files do not.
1115 if (TUKind != TU_Prefix) {
1116 DiagnoseUseOfUnimplementedSelectors();
1118 ActOnEndOfTranslationUnitFragment(
1119 !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1120 Module::PrivateModuleFragment
1121 ? TUFragmentKind::Private
1122 : TUFragmentKind::Normal);
1124 if (LateTemplateParserCleanup)
1125 LateTemplateParserCleanup(OpaqueParser);
1127 CheckDelayedMemberExceptionSpecs();
1128 } else {
1129 // If we are building a TU prefix for serialization, it is safe to transfer
1130 // these over, even though they are not parsed. The end of the TU should be
1131 // outside of any eager template instantiation scope, so when this AST is
1132 // deserialized, these templates will not be parsed until the end of the
1133 // combined TU.
1134 PendingInstantiations.insert(PendingInstantiations.end(),
1135 LateParsedInstantiations.begin(),
1136 LateParsedInstantiations.end());
1137 LateParsedInstantiations.clear();
1139 if (LangOpts.PCHInstantiateTemplates) {
1140 llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1141 PerformPendingInstantiations();
1145 DiagnoseUnterminatedPragmaAlignPack();
1146 DiagnoseUnterminatedPragmaAttribute();
1147 DiagnoseUnterminatedOpenMPDeclareTarget();
1149 // All delayed member exception specs should be checked or we end up accepting
1150 // incompatible declarations.
1151 assert(DelayedOverridingExceptionSpecChecks.empty());
1152 assert(DelayedEquivalentExceptionSpecChecks.empty());
1154 // All dllexport classes should have been processed already.
1155 assert(DelayedDllExportClasses.empty());
1156 assert(DelayedDllExportMemberFunctions.empty());
1158 // Remove file scoped decls that turned out to be used.
1159 UnusedFileScopedDecls.erase(
1160 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1161 UnusedFileScopedDecls.end(),
1162 [this](const DeclaratorDecl *DD) {
1163 return ShouldRemoveFromUnused(this, DD);
1165 UnusedFileScopedDecls.end());
1167 if (TUKind == TU_Prefix) {
1168 // Translation unit prefixes don't need any of the checking below.
1169 if (!PP.isIncrementalProcessingEnabled())
1170 TUScope = nullptr;
1171 return;
1174 // Check for #pragma weak identifiers that were never declared
1175 LoadExternalWeakUndeclaredIdentifiers();
1176 for (const auto &WeakIDs : WeakUndeclaredIdentifiers) {
1177 if (WeakIDs.second.empty())
1178 continue;
1180 Decl *PrevDecl = LookupSingleName(TUScope, WeakIDs.first, SourceLocation(),
1181 LookupOrdinaryName);
1182 if (PrevDecl != nullptr &&
1183 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1184 for (const auto &WI : WeakIDs.second)
1185 Diag(WI.getLocation(), diag::warn_attribute_wrong_decl_type)
1186 << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction;
1187 else
1188 for (const auto &WI : WeakIDs.second)
1189 Diag(WI.getLocation(), diag::warn_weak_identifier_undeclared)
1190 << WeakIDs.first;
1193 if (LangOpts.CPlusPlus11 &&
1194 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
1195 CheckDelegatingCtorCycles();
1197 if (!Diags.hasErrorOccurred()) {
1198 if (ExternalSource)
1199 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1200 checkUndefinedButUsed(*this);
1203 // A global-module-fragment is only permitted within a module unit.
1204 bool DiagnosedMissingModuleDeclaration = false;
1205 if (!ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1206 Module::ExplicitGlobalModuleFragment) {
1207 Diag(ModuleScopes.back().BeginLoc,
1208 diag::err_module_declaration_missing_after_global_module_introducer);
1209 DiagnosedMissingModuleDeclaration = true;
1212 if (TUKind == TU_Module) {
1213 // If we are building a module interface unit, we need to have seen the
1214 // module declaration by now.
1215 if (getLangOpts().getCompilingModule() ==
1216 LangOptions::CMK_ModuleInterface &&
1217 !isCurrentModulePurview() && !DiagnosedMissingModuleDeclaration) {
1218 // FIXME: Make a better guess as to where to put the module declaration.
1219 Diag(getSourceManager().getLocForStartOfFile(
1220 getSourceManager().getMainFileID()),
1221 diag::err_module_declaration_missing);
1224 // If we are building a module, resolve all of the exported declarations
1225 // now.
1226 if (Module *CurrentModule = PP.getCurrentModule()) {
1227 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1229 SmallVector<Module *, 2> Stack;
1230 Stack.push_back(CurrentModule);
1231 while (!Stack.empty()) {
1232 Module *Mod = Stack.pop_back_val();
1234 // Resolve the exported declarations and conflicts.
1235 // FIXME: Actually complain, once we figure out how to teach the
1236 // diagnostic client to deal with complaints in the module map at this
1237 // point.
1238 ModMap.resolveExports(Mod, /*Complain=*/false);
1239 ModMap.resolveUses(Mod, /*Complain=*/false);
1240 ModMap.resolveConflicts(Mod, /*Complain=*/false);
1242 // Queue the submodules, so their exports will also be resolved.
1243 auto SubmodulesRange = Mod->submodules();
1244 Stack.append(SubmodulesRange.begin(), SubmodulesRange.end());
1248 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1249 // modules when they are built, not every time they are used.
1250 emitAndClearUnusedLocalTypedefWarnings();
1253 // C++ standard modules. Diagnose cases where a function is declared inline
1254 // in the module purview but has no definition before the end of the TU or
1255 // the start of a Private Module Fragment (if one is present).
1256 if (!PendingInlineFuncDecls.empty()) {
1257 for (auto *D : PendingInlineFuncDecls) {
1258 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1259 bool DefInPMF = false;
1260 if (auto *FDD = FD->getDefinition()) {
1261 assert(FDD->getOwningModule() &&
1262 FDD->getOwningModule()->isModulePurview());
1263 DefInPMF = FDD->getOwningModule()->isPrivateModule();
1264 if (!DefInPMF)
1265 continue;
1267 Diag(FD->getLocation(), diag::err_export_inline_not_defined)
1268 << DefInPMF;
1269 // If we have a PMF it should be at the end of the ModuleScopes.
1270 if (DefInPMF &&
1271 ModuleScopes.back().Module->Kind == Module::PrivateModuleFragment) {
1272 Diag(ModuleScopes.back().BeginLoc,
1273 diag::note_private_module_fragment);
1277 PendingInlineFuncDecls.clear();
1280 // C99 6.9.2p2:
1281 // A declaration of an identifier for an object that has file
1282 // scope without an initializer, and without a storage-class
1283 // specifier or with the storage-class specifier static,
1284 // constitutes a tentative definition. If a translation unit
1285 // contains one or more tentative definitions for an identifier,
1286 // and the translation unit contains no external definition for
1287 // that identifier, then the behavior is exactly as if the
1288 // translation unit contains a file scope declaration of that
1289 // identifier, with the composite type as of the end of the
1290 // translation unit, with an initializer equal to 0.
1291 llvm::SmallSet<VarDecl *, 32> Seen;
1292 for (TentativeDefinitionsType::iterator
1293 T = TentativeDefinitions.begin(ExternalSource.get()),
1294 TEnd = TentativeDefinitions.end();
1295 T != TEnd; ++T) {
1296 VarDecl *VD = (*T)->getActingDefinition();
1298 // If the tentative definition was completed, getActingDefinition() returns
1299 // null. If we've already seen this variable before, insert()'s second
1300 // return value is false.
1301 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
1302 continue;
1304 if (const IncompleteArrayType *ArrayT
1305 = Context.getAsIncompleteArrayType(VD->getType())) {
1306 // Set the length of the array to 1 (C99 6.9.2p5).
1307 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1308 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1309 QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One,
1310 nullptr, ArrayType::Normal, 0);
1311 VD->setType(T);
1312 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1313 diag::err_tentative_def_incomplete_type))
1314 VD->setInvalidDecl();
1316 // No initialization is performed for a tentative definition.
1317 CheckCompleteVariableDeclaration(VD);
1319 // Notify the consumer that we've completed a tentative definition.
1320 if (!VD->isInvalidDecl())
1321 Consumer.CompleteTentativeDefinition(VD);
1324 for (auto *D : ExternalDeclarations) {
1325 if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1326 continue;
1328 Consumer.CompleteExternalDeclaration(D);
1331 // If there were errors, disable 'unused' warnings since they will mostly be
1332 // noise. Don't warn for a use from a module: either we should warn on all
1333 // file-scope declarations in modules or not at all, but whether the
1334 // declaration is used is immaterial.
1335 if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
1336 // Output warning for unused file scoped decls.
1337 for (UnusedFileScopedDeclsType::iterator
1338 I = UnusedFileScopedDecls.begin(ExternalSource.get()),
1339 E = UnusedFileScopedDecls.end();
1340 I != E; ++I) {
1341 if (ShouldRemoveFromUnused(this, *I))
1342 continue;
1344 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1345 const FunctionDecl *DiagD;
1346 if (!FD->hasBody(DiagD))
1347 DiagD = FD;
1348 if (DiagD->isDeleted())
1349 continue; // Deleted functions are supposed to be unused.
1350 SourceRange DiagRange = DiagD->getLocation();
1351 if (const ASTTemplateArgumentListInfo *ASTTAL =
1352 DiagD->getTemplateSpecializationArgsAsWritten())
1353 DiagRange.setEnd(ASTTAL->RAngleLoc);
1354 if (DiagD->isReferenced()) {
1355 if (isa<CXXMethodDecl>(DiagD))
1356 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1357 << DiagD << DiagRange;
1358 else {
1359 if (FD->getStorageClass() == SC_Static &&
1360 !FD->isInlineSpecified() &&
1361 !SourceMgr.isInMainFile(
1362 SourceMgr.getExpansionLoc(FD->getLocation())))
1363 Diag(DiagD->getLocation(),
1364 diag::warn_unneeded_static_internal_decl)
1365 << DiagD << DiagRange;
1366 else
1367 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1368 << /*function=*/0 << DiagD << DiagRange;
1370 } else {
1371 if (FD->getDescribedFunctionTemplate())
1372 Diag(DiagD->getLocation(), diag::warn_unused_template)
1373 << /*function=*/0 << DiagD << DiagRange;
1374 else
1375 Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1376 ? diag::warn_unused_member_function
1377 : diag::warn_unused_function)
1378 << DiagD << DiagRange;
1380 } else {
1381 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1382 if (!DiagD)
1383 DiagD = cast<VarDecl>(*I);
1384 SourceRange DiagRange = DiagD->getLocation();
1385 if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(DiagD)) {
1386 if (const ASTTemplateArgumentListInfo *ASTTAL =
1387 VTSD->getTemplateArgsInfo())
1388 DiagRange.setEnd(ASTTAL->RAngleLoc);
1390 if (DiagD->isReferenced()) {
1391 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1392 << /*variable=*/1 << DiagD << DiagRange;
1393 } else if (DiagD->getDescribedVarTemplate()) {
1394 Diag(DiagD->getLocation(), diag::warn_unused_template)
1395 << /*variable=*/1 << DiagD << DiagRange;
1396 } else if (DiagD->getType().isConstQualified()) {
1397 const SourceManager &SM = SourceMgr;
1398 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1399 !PP.getLangOpts().IsHeaderFile)
1400 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1401 << DiagD << DiagRange;
1402 } else {
1403 Diag(DiagD->getLocation(), diag::warn_unused_variable)
1404 << DiagD << DiagRange;
1409 emitAndClearUnusedLocalTypedefWarnings();
1412 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1413 // FIXME: Load additional unused private field candidates from the external
1414 // source.
1415 RecordCompleteMap RecordsComplete;
1416 RecordCompleteMap MNCComplete;
1417 for (const NamedDecl *D : UnusedPrivateFields) {
1418 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1419 if (RD && !RD->isUnion() &&
1420 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1421 Diag(D->getLocation(), diag::warn_unused_private_field)
1422 << D->getDeclName();
1427 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1428 if (ExternalSource)
1429 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1430 for (const auto &DeletedFieldInfo : DeleteExprs) {
1431 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1432 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1433 DeleteExprLoc.second);
1438 AnalysisWarnings.IssueWarnings(Context.getTranslationUnitDecl());
1440 // Check we've noticed that we're no longer parsing the initializer for every
1441 // variable. If we miss cases, then at best we have a performance issue and
1442 // at worst a rejects-valid bug.
1443 assert(ParsingInitForAutoVars.empty() &&
1444 "Didn't unmark var as having its initializer parsed");
1446 if (!PP.isIncrementalProcessingEnabled())
1447 TUScope = nullptr;
1451 //===----------------------------------------------------------------------===//
1452 // Helper functions.
1453 //===----------------------------------------------------------------------===//
1455 DeclContext *Sema::getFunctionLevelDeclContext(bool AllowLambda) const {
1456 DeclContext *DC = CurContext;
1458 while (true) {
1459 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
1460 isa<RequiresExprBodyDecl>(DC)) {
1461 DC = DC->getParent();
1462 } else if (!AllowLambda && isa<CXXMethodDecl>(DC) &&
1463 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1464 cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1465 DC = DC->getParent()->getParent();
1466 } else break;
1469 return DC;
1472 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1473 /// to the function decl for the function being parsed. If we're currently
1474 /// in a 'block', this returns the containing context.
1475 FunctionDecl *Sema::getCurFunctionDecl(bool AllowLambda) const {
1476 DeclContext *DC = getFunctionLevelDeclContext(AllowLambda);
1477 return dyn_cast<FunctionDecl>(DC);
1480 ObjCMethodDecl *Sema::getCurMethodDecl() {
1481 DeclContext *DC = getFunctionLevelDeclContext();
1482 while (isa<RecordDecl>(DC))
1483 DC = DC->getParent();
1484 return dyn_cast<ObjCMethodDecl>(DC);
1487 NamedDecl *Sema::getCurFunctionOrMethodDecl() const {
1488 DeclContext *DC = getFunctionLevelDeclContext();
1489 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1490 return cast<NamedDecl>(DC);
1491 return nullptr;
1494 Decl *Sema::getCurLocalScopeDecl() {
1495 if (const BlockScopeInfo *BSI = getCurBlock())
1496 return BSI->TheDecl;
1497 if (const LambdaScopeInfo *LSI = getCurLambda())
1498 return LSI->CallOperator;
1499 if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
1500 return CSI->TheCapturedDecl;
1501 if (NamedDecl *ND = getCurFunctionOrMethodDecl())
1502 return ND;
1503 return nullptr;
1506 LangAS Sema::getDefaultCXXMethodAddrSpace() const {
1507 if (getLangOpts().OpenCL)
1508 return getASTContext().getDefaultOpenCLPointeeAddrSpace();
1509 return LangAS::Default;
1512 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1513 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1514 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1515 // been made more painfully obvious by the refactor that introduced this
1516 // function, but it is possible that the incoming argument can be
1517 // eliminated. If it truly cannot be (for example, there is some reentrancy
1518 // issue I am not seeing yet), then there should at least be a clarifying
1519 // comment somewhere.
1520 if (std::optional<TemplateDeductionInfo *> Info = isSFINAEContext()) {
1521 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1522 Diags.getCurrentDiagID())) {
1523 case DiagnosticIDs::SFINAE_Report:
1524 // We'll report the diagnostic below.
1525 break;
1527 case DiagnosticIDs::SFINAE_SubstitutionFailure:
1528 // Count this failure so that we know that template argument deduction
1529 // has failed.
1530 ++NumSFINAEErrors;
1532 // Make a copy of this suppressed diagnostic and store it with the
1533 // template-deduction information.
1534 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1535 Diagnostic DiagInfo(&Diags);
1536 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1537 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1540 Diags.setLastDiagnosticIgnored(true);
1541 Diags.Clear();
1542 return;
1544 case DiagnosticIDs::SFINAE_AccessControl: {
1545 // Per C++ Core Issue 1170, access control is part of SFINAE.
1546 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1547 // make access control a part of SFINAE for the purposes of checking
1548 // type traits.
1549 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
1550 break;
1552 SourceLocation Loc = Diags.getCurrentDiagLoc();
1554 // Suppress this diagnostic.
1555 ++NumSFINAEErrors;
1557 // Make a copy of this suppressed diagnostic and store it with the
1558 // template-deduction information.
1559 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1560 Diagnostic DiagInfo(&Diags);
1561 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1562 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1565 Diags.setLastDiagnosticIgnored(true);
1566 Diags.Clear();
1568 // Now the diagnostic state is clear, produce a C++98 compatibility
1569 // warning.
1570 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1572 // The last diagnostic which Sema produced was ignored. Suppress any
1573 // notes attached to it.
1574 Diags.setLastDiagnosticIgnored(true);
1575 return;
1578 case DiagnosticIDs::SFINAE_Suppress:
1579 // Make a copy of this suppressed diagnostic and store it with the
1580 // template-deduction information;
1581 if (*Info) {
1582 Diagnostic DiagInfo(&Diags);
1583 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1584 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1587 // Suppress this diagnostic.
1588 Diags.setLastDiagnosticIgnored(true);
1589 Diags.Clear();
1590 return;
1594 // Copy the diagnostic printing policy over the ASTContext printing policy.
1595 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
1596 Context.setPrintingPolicy(getPrintingPolicy());
1598 // Emit the diagnostic.
1599 if (!Diags.EmitCurrentDiagnostic())
1600 return;
1602 // If this is not a note, and we're in a template instantiation
1603 // that is different from the last template instantiation where
1604 // we emitted an error, print a template instantiation
1605 // backtrace.
1606 if (!DiagnosticIDs::isBuiltinNote(DiagID))
1607 PrintContextStack();
1610 Sema::SemaDiagnosticBuilder
1611 Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
1612 return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
1615 bool Sema::hasUncompilableErrorOccurred() const {
1616 if (getDiagnostics().hasUncompilableErrorOccurred())
1617 return true;
1618 auto *FD = dyn_cast<FunctionDecl>(CurContext);
1619 if (!FD)
1620 return false;
1621 auto Loc = DeviceDeferredDiags.find(FD);
1622 if (Loc == DeviceDeferredDiags.end())
1623 return false;
1624 for (auto PDAt : Loc->second) {
1625 if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
1626 return true;
1628 return false;
1631 // Print notes showing how we can reach FD starting from an a priori
1632 // known-callable function.
1633 static void emitCallStackNotes(Sema &S, const FunctionDecl *FD) {
1634 auto FnIt = S.DeviceKnownEmittedFns.find(FD);
1635 while (FnIt != S.DeviceKnownEmittedFns.end()) {
1636 // Respect error limit.
1637 if (S.Diags.hasFatalErrorOccurred())
1638 return;
1639 DiagnosticBuilder Builder(
1640 S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1641 Builder << FnIt->second.FD;
1642 FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
1646 namespace {
1648 /// Helper class that emits deferred diagnostic messages if an entity directly
1649 /// or indirectly using the function that causes the deferred diagnostic
1650 /// messages is known to be emitted.
1652 /// During parsing of AST, certain diagnostic messages are recorded as deferred
1653 /// diagnostics since it is unknown whether the functions containing such
1654 /// diagnostics will be emitted. A list of potentially emitted functions and
1655 /// variables that may potentially trigger emission of functions are also
1656 /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1657 /// by each function to emit deferred diagnostics.
1659 /// During the visit, certain OpenMP directives or initializer of variables
1660 /// with certain OpenMP attributes will cause subsequent visiting of any
1661 /// functions enter a state which is called OpenMP device context in this
1662 /// implementation. The state is exited when the directive or initializer is
1663 /// exited. This state can change the emission states of subsequent uses
1664 /// of functions.
1666 /// Conceptually the functions or variables to be visited form a use graph
1667 /// where the parent node uses the child node. At any point of the visit,
1668 /// the tree nodes traversed from the tree root to the current node form a use
1669 /// stack. The emission state of the current node depends on two factors:
1670 /// 1. the emission state of the root node
1671 /// 2. whether the current node is in OpenMP device context
1672 /// If the function is decided to be emitted, its contained deferred diagnostics
1673 /// are emitted, together with the information about the use stack.
1675 class DeferredDiagnosticsEmitter
1676 : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1677 public:
1678 typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1680 // Whether the function is already in the current use-path.
1681 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1683 // The current use-path.
1684 llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1686 // Whether the visiting of the function has been done. Done[0] is for the
1687 // case not in OpenMP device context. Done[1] is for the case in OpenMP
1688 // device context. We need two sets because diagnostics emission may be
1689 // different depending on whether it is in OpenMP device context.
1690 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
1692 // Emission state of the root node of the current use graph.
1693 bool ShouldEmitRootNode;
1695 // Current OpenMP device context level. It is initialized to 0 and each
1696 // entering of device context increases it by 1 and each exit decreases
1697 // it by 1. Non-zero value indicates it is currently in device context.
1698 unsigned InOMPDeviceContext;
1700 DeferredDiagnosticsEmitter(Sema &S)
1701 : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1703 bool shouldVisitDiscardedStmt() const { return false; }
1705 void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1706 ++InOMPDeviceContext;
1707 Inherited::VisitOMPTargetDirective(Node);
1708 --InOMPDeviceContext;
1711 void visitUsedDecl(SourceLocation Loc, Decl *D) {
1712 if (isa<VarDecl>(D))
1713 return;
1714 if (auto *FD = dyn_cast<FunctionDecl>(D))
1715 checkFunc(Loc, FD);
1716 else
1717 Inherited::visitUsedDecl(Loc, D);
1720 void checkVar(VarDecl *VD) {
1721 assert(VD->isFileVarDecl() &&
1722 "Should only check file-scope variables");
1723 if (auto *Init = VD->getInit()) {
1724 auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1725 bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
1726 *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1727 if (IsDev)
1728 ++InOMPDeviceContext;
1729 this->Visit(Init);
1730 if (IsDev)
1731 --InOMPDeviceContext;
1735 void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1736 auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
1737 FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
1738 if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
1739 S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
1740 return;
1741 // Finalize analysis of OpenMP-specific constructs.
1742 if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
1743 (ShouldEmitRootNode || InOMPDeviceContext))
1744 S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1745 if (Caller)
1746 S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
1747 // Always emit deferred diagnostics for the direct users. This does not
1748 // lead to explosion of diagnostics since each user is visited at most
1749 // twice.
1750 if (ShouldEmitRootNode || InOMPDeviceContext)
1751 emitDeferredDiags(FD, Caller);
1752 // Do not revisit a function if the function body has been completely
1753 // visited before.
1754 if (!Done.insert(FD).second)
1755 return;
1756 InUsePath.insert(FD);
1757 UsePath.push_back(FD);
1758 if (auto *S = FD->getBody()) {
1759 this->Visit(S);
1761 UsePath.pop_back();
1762 InUsePath.erase(FD);
1765 void checkRecordedDecl(Decl *D) {
1766 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1767 ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1768 Sema::FunctionEmissionStatus::Emitted;
1769 checkFunc(SourceLocation(), FD);
1770 } else
1771 checkVar(cast<VarDecl>(D));
1774 // Emit any deferred diagnostics for FD
1775 void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
1776 auto It = S.DeviceDeferredDiags.find(FD);
1777 if (It == S.DeviceDeferredDiags.end())
1778 return;
1779 bool HasWarningOrError = false;
1780 bool FirstDiag = true;
1781 for (PartialDiagnosticAt &PDAt : It->second) {
1782 // Respect error limit.
1783 if (S.Diags.hasFatalErrorOccurred())
1784 return;
1785 const SourceLocation &Loc = PDAt.first;
1786 const PartialDiagnostic &PD = PDAt.second;
1787 HasWarningOrError |=
1788 S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
1789 DiagnosticsEngine::Warning;
1791 DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1792 PD.Emit(Builder);
1794 // Emit the note on the first diagnostic in case too many diagnostics
1795 // cause the note not emitted.
1796 if (FirstDiag && HasWarningOrError && ShowCallStack) {
1797 emitCallStackNotes(S, FD);
1798 FirstDiag = false;
1803 } // namespace
1805 void Sema::emitDeferredDiags() {
1806 if (ExternalSource)
1807 ExternalSource->ReadDeclsToCheckForDeferredDiags(
1808 DeclsToCheckForDeferredDiags);
1810 if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
1811 DeclsToCheckForDeferredDiags.empty())
1812 return;
1814 DeferredDiagnosticsEmitter DDE(*this);
1815 for (auto *D : DeclsToCheckForDeferredDiags)
1816 DDE.checkRecordedDecl(D);
1819 // In CUDA, there are some constructs which may appear in semantically-valid
1820 // code, but trigger errors if we ever generate code for the function in which
1821 // they appear. Essentially every construct you're not allowed to use on the
1822 // device falls into this category, because you are allowed to use these
1823 // constructs in a __host__ __device__ function, but only if that function is
1824 // never codegen'ed on the device.
1826 // To handle semantic checking for these constructs, we keep track of the set of
1827 // functions we know will be emitted, either because we could tell a priori that
1828 // they would be emitted, or because they were transitively called by a
1829 // known-emitted function.
1831 // We also keep a partial call graph of which not-known-emitted functions call
1832 // which other not-known-emitted functions.
1834 // When we see something which is illegal if the current function is emitted
1835 // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1836 // CheckCUDACall), we first check if the current function is known-emitted. If
1837 // so, we immediately output the diagnostic.
1839 // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
1840 // until we discover that the function is known-emitted, at which point we take
1841 // it out of this map and emit the diagnostic.
1843 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
1844 unsigned DiagID,
1845 const FunctionDecl *Fn,
1846 Sema &S)
1847 : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1848 ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1849 switch (K) {
1850 case K_Nop:
1851 break;
1852 case K_Immediate:
1853 case K_ImmediateWithCallStack:
1854 ImmediateDiag.emplace(
1855 ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
1856 break;
1857 case K_Deferred:
1858 assert(Fn && "Must have a function to attach the deferred diag to.");
1859 auto &Diags = S.DeviceDeferredDiags[Fn];
1860 PartialDiagId.emplace(Diags.size());
1861 Diags.emplace_back(Loc, S.PDiag(DiagID));
1862 break;
1866 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
1867 : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1868 ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1869 PartialDiagId(D.PartialDiagId) {
1870 // Clean the previous diagnostics.
1871 D.ShowCallStack = false;
1872 D.ImmediateDiag.reset();
1873 D.PartialDiagId.reset();
1876 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
1877 if (ImmediateDiag) {
1878 // Emit our diagnostic and, if it was a warning or error, output a callstack
1879 // if Fn isn't a priori known-emitted.
1880 bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1881 DiagID, Loc) >= DiagnosticsEngine::Warning;
1882 ImmediateDiag.reset(); // Emit the immediate diag.
1883 if (IsWarningOrError && ShowCallStack)
1884 emitCallStackNotes(S, Fn);
1885 } else {
1886 assert((!PartialDiagId || ShowCallStack) &&
1887 "Must always show call stack for deferred diags.");
1891 Sema::SemaDiagnosticBuilder
1892 Sema::targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD) {
1893 FD = FD ? FD : getCurFunctionDecl();
1894 if (LangOpts.OpenMP)
1895 return LangOpts.OpenMPIsTargetDevice
1896 ? diagIfOpenMPDeviceCode(Loc, DiagID, FD)
1897 : diagIfOpenMPHostCode(Loc, DiagID, FD);
1898 if (getLangOpts().CUDA)
1899 return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
1900 : CUDADiagIfHostCode(Loc, DiagID);
1902 if (getLangOpts().SYCLIsDevice)
1903 return SYCLDiagIfDeviceCode(Loc, DiagID);
1905 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
1906 FD, *this);
1909 Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID,
1910 bool DeferHint) {
1911 bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
1912 bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag &&
1913 DiagnosticIDs::isDeferrable(DiagID) &&
1914 (DeferHint || DeferDiags || !IsError);
1915 auto SetIsLastErrorImmediate = [&](bool Flag) {
1916 if (IsError)
1917 IsLastErrorImmediate = Flag;
1919 if (!ShouldDefer) {
1920 SetIsLastErrorImmediate(true);
1921 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc,
1922 DiagID, getCurFunctionDecl(), *this);
1925 SemaDiagnosticBuilder DB = getLangOpts().CUDAIsDevice
1926 ? CUDADiagIfDeviceCode(Loc, DiagID)
1927 : CUDADiagIfHostCode(Loc, DiagID);
1928 SetIsLastErrorImmediate(DB.isImmediate());
1929 return DB;
1932 void Sema::checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D) {
1933 if (isUnevaluatedContext() || Ty.isNull())
1934 return;
1936 // The original idea behind checkTypeSupport function is that unused
1937 // declarations can be replaced with an array of bytes of the same size during
1938 // codegen, such replacement doesn't seem to be possible for types without
1939 // constant byte size like zero length arrays. So, do a deep check for SYCL.
1940 if (D && LangOpts.SYCLIsDevice) {
1941 llvm::DenseSet<QualType> Visited;
1942 deepTypeCheckForSYCLDevice(Loc, Visited, D);
1945 Decl *C = cast<Decl>(getCurLexicalContext());
1947 // Memcpy operations for structs containing a member with unsupported type
1948 // are ok, though.
1949 if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
1950 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
1951 MD->isTrivial())
1952 return;
1954 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
1955 if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
1956 return;
1959 // Try to associate errors with the lexical context, if that is a function, or
1960 // the value declaration otherwise.
1961 const FunctionDecl *FD = isa<FunctionDecl>(C)
1962 ? cast<FunctionDecl>(C)
1963 : dyn_cast_or_null<FunctionDecl>(D);
1965 auto CheckDeviceType = [&](QualType Ty) {
1966 if (Ty->isDependentType())
1967 return;
1969 if (Ty->isBitIntType()) {
1970 if (!Context.getTargetInfo().hasBitIntType()) {
1971 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
1972 if (D)
1973 PD << D;
1974 else
1975 PD << "expression";
1976 targetDiag(Loc, PD, FD)
1977 << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
1978 << Ty << Context.getTargetInfo().getTriple().str();
1980 return;
1983 // Check if we are dealing with two 'long double' but with different
1984 // semantics.
1985 bool LongDoubleMismatched = false;
1986 if (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128) {
1987 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(Ty);
1988 if ((&Sem != &llvm::APFloat::PPCDoubleDouble() &&
1989 !Context.getTargetInfo().hasFloat128Type()) ||
1990 (&Sem == &llvm::APFloat::PPCDoubleDouble() &&
1991 !Context.getTargetInfo().hasIbm128Type()))
1992 LongDoubleMismatched = true;
1995 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1996 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1997 (Ty->isIbm128Type() && !Context.getTargetInfo().hasIbm128Type()) ||
1998 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1999 !Context.getTargetInfo().hasInt128Type()) ||
2000 (Ty->isBFloat16Type() && !Context.getTargetInfo().hasBFloat16Type() &&
2001 !LangOpts.CUDAIsDevice) ||
2002 LongDoubleMismatched) {
2003 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2004 if (D)
2005 PD << D;
2006 else
2007 PD << "expression";
2009 if (targetDiag(Loc, PD, FD)
2010 << true /*show bit size*/
2011 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
2012 << false /*return*/ << Context.getTargetInfo().getTriple().str()) {
2013 if (D)
2014 D->setInvalidDecl();
2016 if (D)
2017 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2021 auto CheckType = [&](QualType Ty, bool IsRetTy = false) {
2022 if (LangOpts.SYCLIsDevice ||
2023 (LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice) ||
2024 LangOpts.CUDAIsDevice)
2025 CheckDeviceType(Ty);
2027 QualType UnqualTy = Ty.getCanonicalType().getUnqualifiedType();
2028 const TargetInfo &TI = Context.getTargetInfo();
2029 if (!TI.hasLongDoubleType() && UnqualTy == Context.LongDoubleTy) {
2030 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2031 if (D)
2032 PD << D;
2033 else
2034 PD << "expression";
2036 if (Diag(Loc, PD, FD)
2037 << false /*show bit size*/ << 0 << Ty << false /*return*/
2038 << TI.getTriple().str()) {
2039 if (D)
2040 D->setInvalidDecl();
2042 if (D)
2043 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2046 bool IsDouble = UnqualTy == Context.DoubleTy;
2047 bool IsFloat = UnqualTy == Context.FloatTy;
2048 if (IsRetTy && !TI.hasFPReturn() && (IsDouble || IsFloat)) {
2049 PartialDiagnostic PD = PDiag(diag::err_target_unsupported_type);
2050 if (D)
2051 PD << D;
2052 else
2053 PD << "expression";
2055 if (Diag(Loc, PD, FD)
2056 << false /*show bit size*/ << 0 << Ty << true /*return*/
2057 << TI.getTriple().str()) {
2058 if (D)
2059 D->setInvalidDecl();
2061 if (D)
2062 targetDiag(D->getLocation(), diag::note_defined_here, FD) << D;
2065 if (Ty->isRVVType())
2066 checkRVVTypeSupport(Ty, Loc, D);
2068 // Don't allow SVE types in functions without a SVE target.
2069 if (Ty->isSVESizelessBuiltinType() && FD && FD->hasBody()) {
2070 llvm::StringMap<bool> CallerFeatureMap;
2071 Context.getFunctionFeatureMap(CallerFeatureMap, FD);
2072 if (!Builtin::evaluateRequiredTargetFeatures(
2073 "sve", CallerFeatureMap))
2074 Diag(D->getLocation(), diag::err_sve_vector_in_non_sve_target) << Ty;
2078 CheckType(Ty);
2079 if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
2080 for (const auto &ParamTy : FPTy->param_types())
2081 CheckType(ParamTy);
2082 CheckType(FPTy->getReturnType(), /*IsRetTy=*/true);
2084 if (const auto *FNPTy = dyn_cast<FunctionNoProtoType>(Ty))
2085 CheckType(FNPTy->getReturnType(), /*IsRetTy=*/true);
2088 /// Looks through the macro-expansion chain for the given
2089 /// location, looking for a macro expansion with the given name.
2090 /// If one is found, returns true and sets the location to that
2091 /// expansion loc.
2092 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
2093 SourceLocation loc = locref;
2094 if (!loc.isMacroID()) return false;
2096 // There's no good way right now to look at the intermediate
2097 // expansions, so just jump to the expansion location.
2098 loc = getSourceManager().getExpansionLoc(loc);
2100 // If that's written with the name, stop here.
2101 SmallString<16> buffer;
2102 if (getPreprocessor().getSpelling(loc, buffer) == name) {
2103 locref = loc;
2104 return true;
2106 return false;
2109 /// Determines the active Scope associated with the given declaration
2110 /// context.
2112 /// This routine maps a declaration context to the active Scope object that
2113 /// represents that declaration context in the parser. It is typically used
2114 /// from "scope-less" code (e.g., template instantiation, lazy creation of
2115 /// declarations) that injects a name for name-lookup purposes and, therefore,
2116 /// must update the Scope.
2118 /// \returns The scope corresponding to the given declaraion context, or NULL
2119 /// if no such scope is open.
2120 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
2122 if (!Ctx)
2123 return nullptr;
2125 Ctx = Ctx->getPrimaryContext();
2126 for (Scope *S = getCurScope(); S; S = S->getParent()) {
2127 // Ignore scopes that cannot have declarations. This is important for
2128 // out-of-line definitions of static class members.
2129 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
2130 if (DeclContext *Entity = S->getEntity())
2131 if (Ctx == Entity->getPrimaryContext())
2132 return S;
2135 return nullptr;
2138 /// Enter a new function scope
2139 void Sema::PushFunctionScope() {
2140 if (FunctionScopes.empty() && CachedFunctionScope) {
2141 // Use CachedFunctionScope to avoid allocating memory when possible.
2142 CachedFunctionScope->Clear();
2143 FunctionScopes.push_back(CachedFunctionScope.release());
2144 } else {
2145 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
2147 if (LangOpts.OpenMP)
2148 pushOpenMPFunctionRegion();
2151 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
2152 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
2153 BlockScope, Block));
2154 CapturingFunctionScopes++;
2157 LambdaScopeInfo *Sema::PushLambdaScope() {
2158 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
2159 FunctionScopes.push_back(LSI);
2160 CapturingFunctionScopes++;
2161 return LSI;
2164 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
2165 if (LambdaScopeInfo *const LSI = getCurLambda()) {
2166 LSI->AutoTemplateParameterDepth = Depth;
2167 return;
2169 llvm_unreachable(
2170 "Remove assertion if intentionally called in a non-lambda context.");
2173 // Check that the type of the VarDecl has an accessible copy constructor and
2174 // resolve its destructor's exception specification.
2175 // This also performs initialization of block variables when they are moved
2176 // to the heap. It uses the same rules as applicable for implicit moves
2177 // according to the C++ standard in effect ([class.copy.elision]p3).
2178 static void checkEscapingByref(VarDecl *VD, Sema &S) {
2179 QualType T = VD->getType();
2180 EnterExpressionEvaluationContext scope(
2181 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
2182 SourceLocation Loc = VD->getLocation();
2183 Expr *VarRef =
2184 new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
2185 ExprResult Result;
2186 auto IE = InitializedEntity::InitializeBlock(Loc, T);
2187 if (S.getLangOpts().CPlusPlus23) {
2188 auto *E = ImplicitCastExpr::Create(S.Context, T, CK_NoOp, VarRef, nullptr,
2189 VK_XValue, FPOptionsOverride());
2190 Result = S.PerformCopyInitialization(IE, SourceLocation(), E);
2191 } else {
2192 Result = S.PerformMoveOrCopyInitialization(
2193 IE, Sema::NamedReturnInfo{VD, Sema::NamedReturnInfo::MoveEligible},
2194 VarRef);
2197 if (!Result.isInvalid()) {
2198 Result = S.MaybeCreateExprWithCleanups(Result);
2199 Expr *Init = Result.getAs<Expr>();
2200 S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
2203 // The destructor's exception specification is needed when IRGen generates
2204 // block copy/destroy functions. Resolve it here.
2205 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2206 if (CXXDestructorDecl *DD = RD->getDestructor()) {
2207 auto *FPT = DD->getType()->getAs<FunctionProtoType>();
2208 S.ResolveExceptionSpec(Loc, FPT);
2212 static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
2213 // Set the EscapingByref flag of __block variables captured by
2214 // escaping blocks.
2215 for (const BlockDecl *BD : FSI.Blocks) {
2216 for (const BlockDecl::Capture &BC : BD->captures()) {
2217 VarDecl *VD = BC.getVariable();
2218 if (VD->hasAttr<BlocksAttr>()) {
2219 // Nothing to do if this is a __block variable captured by a
2220 // non-escaping block.
2221 if (BD->doesNotEscape())
2222 continue;
2223 VD->setEscapingByref();
2225 // Check whether the captured variable is or contains an object of
2226 // non-trivial C union type.
2227 QualType CapType = BC.getVariable()->getType();
2228 if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
2229 CapType.hasNonTrivialToPrimitiveCopyCUnion())
2230 S.checkNonTrivialCUnion(BC.getVariable()->getType(),
2231 BD->getCaretLocation(),
2232 Sema::NTCUC_BlockCapture,
2233 Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
2237 for (VarDecl *VD : FSI.ByrefBlockVars) {
2238 // __block variables might require us to capture a copy-initializer.
2239 if (!VD->isEscapingByref())
2240 continue;
2241 // It's currently invalid to ever have a __block variable with an
2242 // array type; should we diagnose that here?
2243 // Regardless, we don't want to ignore array nesting when
2244 // constructing this copy.
2245 if (VD->getType()->isStructureOrClassType())
2246 checkEscapingByref(VD, S);
2250 /// Pop a function (or block or lambda or captured region) scope from the stack.
2252 /// \param WP The warning policy to use for CFG-based warnings, or null if such
2253 /// warnings should not be produced.
2254 /// \param D The declaration corresponding to this function scope, if producing
2255 /// CFG-based warnings.
2256 /// \param BlockType The type of the block expression, if D is a BlockDecl.
2257 Sema::PoppedFunctionScopePtr
2258 Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
2259 const Decl *D, QualType BlockType) {
2260 assert(!FunctionScopes.empty() && "mismatched push/pop!");
2262 markEscapingByrefs(*FunctionScopes.back(), *this);
2264 PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
2265 PoppedFunctionScopeDeleter(this));
2267 if (LangOpts.OpenMP)
2268 popOpenMPFunctionRegion(Scope.get());
2270 // Issue any analysis-based warnings.
2271 if (WP && D)
2272 AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
2273 else
2274 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
2275 Diag(PUD.Loc, PUD.PD);
2277 return Scope;
2280 void Sema::PoppedFunctionScopeDeleter::
2281 operator()(sema::FunctionScopeInfo *Scope) const {
2282 if (!Scope->isPlainFunction())
2283 Self->CapturingFunctionScopes--;
2284 // Stash the function scope for later reuse if it's for a normal function.
2285 if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
2286 Self->CachedFunctionScope.reset(Scope);
2287 else
2288 delete Scope;
2291 void Sema::PushCompoundScope(bool IsStmtExpr) {
2292 getCurFunction()->CompoundScopes.push_back(
2293 CompoundScopeInfo(IsStmtExpr, getCurFPFeatures()));
2296 void Sema::PopCompoundScope() {
2297 FunctionScopeInfo *CurFunction = getCurFunction();
2298 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2300 CurFunction->CompoundScopes.pop_back();
2303 /// Determine whether any errors occurred within this function/method/
2304 /// block.
2305 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2306 return getCurFunction()->hasUnrecoverableErrorOccurred();
2309 void Sema::setFunctionHasBranchIntoScope() {
2310 if (!FunctionScopes.empty())
2311 FunctionScopes.back()->setHasBranchIntoScope();
2314 void Sema::setFunctionHasBranchProtectedScope() {
2315 if (!FunctionScopes.empty())
2316 FunctionScopes.back()->setHasBranchProtectedScope();
2319 void Sema::setFunctionHasIndirectGoto() {
2320 if (!FunctionScopes.empty())
2321 FunctionScopes.back()->setHasIndirectGoto();
2324 void Sema::setFunctionHasMustTail() {
2325 if (!FunctionScopes.empty())
2326 FunctionScopes.back()->setHasMustTail();
2329 BlockScopeInfo *Sema::getCurBlock() {
2330 if (FunctionScopes.empty())
2331 return nullptr;
2333 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2334 if (CurBSI && CurBSI->TheDecl &&
2335 !CurBSI->TheDecl->Encloses(CurContext)) {
2336 // We have switched contexts due to template instantiation.
2337 assert(!CodeSynthesisContexts.empty());
2338 return nullptr;
2341 return CurBSI;
2344 FunctionScopeInfo *Sema::getEnclosingFunction() const {
2345 if (FunctionScopes.empty())
2346 return nullptr;
2348 for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2349 if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
2350 continue;
2351 return FunctionScopes[e];
2353 return nullptr;
2356 LambdaScopeInfo *Sema::getEnclosingLambda() const {
2357 for (auto *Scope : llvm::reverse(FunctionScopes)) {
2358 if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
2359 if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) &&
2360 LSI->AfterParameterList) {
2361 // We have switched contexts due to template instantiation.
2362 // FIXME: We should swap out the FunctionScopes during code synthesis
2363 // so that we don't need to check for this.
2364 assert(!CodeSynthesisContexts.empty());
2365 return nullptr;
2367 return LSI;
2370 return nullptr;
2373 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2374 if (FunctionScopes.empty())
2375 return nullptr;
2377 auto I = FunctionScopes.rbegin();
2378 if (IgnoreNonLambdaCapturingScope) {
2379 auto E = FunctionScopes.rend();
2380 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
2381 ++I;
2382 if (I == E)
2383 return nullptr;
2385 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2386 if (CurLSI && CurLSI->Lambda && CurLSI->CallOperator &&
2387 !CurLSI->Lambda->Encloses(CurContext) && CurLSI->AfterParameterList) {
2388 // We have switched contexts due to template instantiation.
2389 assert(!CodeSynthesisContexts.empty());
2390 return nullptr;
2393 return CurLSI;
2396 // We have a generic lambda if we parsed auto parameters, or we have
2397 // an associated template parameter list.
2398 LambdaScopeInfo *Sema::getCurGenericLambda() {
2399 if (LambdaScopeInfo *LSI = getCurLambda()) {
2400 return (LSI->TemplateParams.size() ||
2401 LSI->GLTemplateParameterList) ? LSI : nullptr;
2403 return nullptr;
2407 void Sema::ActOnComment(SourceRange Comment) {
2408 if (!LangOpts.RetainCommentsFromSystemHeaders &&
2409 SourceMgr.isInSystemHeader(Comment.getBegin()))
2410 return;
2411 RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2412 if (RC.isAlmostTrailingComment() || RC.hasUnsupportedSplice(SourceMgr)) {
2413 SourceRange MagicMarkerRange(Comment.getBegin(),
2414 Comment.getBegin().getLocWithOffset(3));
2415 StringRef MagicMarkerText;
2416 switch (RC.getKind()) {
2417 case RawComment::RCK_OrdinaryBCPL:
2418 MagicMarkerText = "///<";
2419 break;
2420 case RawComment::RCK_OrdinaryC:
2421 MagicMarkerText = "/**<";
2422 break;
2423 case RawComment::RCK_Invalid:
2424 // FIXME: are there other scenarios that could produce an invalid
2425 // raw comment here?
2426 Diag(Comment.getBegin(), diag::warn_splice_in_doxygen_comment);
2427 return;
2428 default:
2429 llvm_unreachable("if this is an almost Doxygen comment, "
2430 "it should be ordinary");
2432 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2433 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2435 Context.addComment(RC);
2438 // Pin this vtable to this file.
2439 ExternalSemaSource::~ExternalSemaSource() {}
2440 char ExternalSemaSource::ID;
2442 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
2443 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
2445 void ExternalSemaSource::ReadKnownNamespaces(
2446 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
2449 void ExternalSemaSource::ReadUndefinedButUsed(
2450 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2452 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
2453 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2455 /// Figure out if an expression could be turned into a call.
2457 /// Use this when trying to recover from an error where the programmer may have
2458 /// written just the name of a function instead of actually calling it.
2460 /// \param E - The expression to examine.
2461 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
2462 /// with no arguments, this parameter is set to the type returned by such a
2463 /// call; otherwise, it is set to an empty QualType.
2464 /// \param OverloadSet - If the expression is an overloaded function
2465 /// name, this parameter is populated with the decls of the various overloads.
2466 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2467 UnresolvedSetImpl &OverloadSet) {
2468 ZeroArgCallReturnTy = QualType();
2469 OverloadSet.clear();
2471 const OverloadExpr *Overloads = nullptr;
2472 bool IsMemExpr = false;
2473 if (E.getType() == Context.OverloadTy) {
2474 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
2476 // Ignore overloads that are pointer-to-member constants.
2477 if (FR.HasFormOfMemberPointer)
2478 return false;
2480 Overloads = FR.Expression;
2481 } else if (E.getType() == Context.BoundMemberTy) {
2482 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2483 IsMemExpr = true;
2486 bool Ambiguous = false;
2487 bool IsMV = false;
2489 if (Overloads) {
2490 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2491 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
2492 OverloadSet.addDecl(*it);
2494 // Check whether the function is a non-template, non-member which takes no
2495 // arguments.
2496 if (IsMemExpr)
2497 continue;
2498 if (const FunctionDecl *OverloadDecl
2499 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2500 if (OverloadDecl->getMinRequiredArguments() == 0) {
2501 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
2502 (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2503 OverloadDecl->isCPUSpecificMultiVersion()))) {
2504 ZeroArgCallReturnTy = QualType();
2505 Ambiguous = true;
2506 } else {
2507 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2508 IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2509 OverloadDecl->isCPUSpecificMultiVersion();
2515 // If it's not a member, use better machinery to try to resolve the call
2516 if (!IsMemExpr)
2517 return !ZeroArgCallReturnTy.isNull();
2520 // Attempt to call the member with no arguments - this will correctly handle
2521 // member templates with defaults/deduction of template arguments, overloads
2522 // with default arguments, etc.
2523 if (IsMemExpr && !E.isTypeDependent()) {
2524 Sema::TentativeAnalysisScope Trap(*this);
2525 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
2526 std::nullopt, SourceLocation());
2527 if (R.isUsable()) {
2528 ZeroArgCallReturnTy = R.get()->getType();
2529 return true;
2531 return false;
2534 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2535 if (const auto *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2536 if (Fun->getMinRequiredArguments() == 0)
2537 ZeroArgCallReturnTy = Fun->getReturnType();
2538 return true;
2542 // We don't have an expression that's convenient to get a FunctionDecl from,
2543 // but we can at least check if the type is "function of 0 arguments".
2544 QualType ExprTy = E.getType();
2545 const FunctionType *FunTy = nullptr;
2546 QualType PointeeTy = ExprTy->getPointeeType();
2547 if (!PointeeTy.isNull())
2548 FunTy = PointeeTy->getAs<FunctionType>();
2549 if (!FunTy)
2550 FunTy = ExprTy->getAs<FunctionType>();
2552 if (const auto *FPT = dyn_cast_if_present<FunctionProtoType>(FunTy)) {
2553 if (FPT->getNumParams() == 0)
2554 ZeroArgCallReturnTy = FunTy->getReturnType();
2555 return true;
2557 return false;
2560 /// Give notes for a set of overloads.
2562 /// A companion to tryExprAsCall. In cases when the name that the programmer
2563 /// wrote was an overloaded function, we may be able to make some guesses about
2564 /// plausible overloads based on their return types; such guesses can be handed
2565 /// off to this method to be emitted as notes.
2567 /// \param Overloads - The overloads to note.
2568 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2569 /// -fshow-overloads=best, this is the location to attach to the note about too
2570 /// many candidates. Typically this will be the location of the original
2571 /// ill-formed expression.
2572 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2573 const SourceLocation FinalNoteLoc) {
2574 unsigned ShownOverloads = 0;
2575 unsigned SuppressedOverloads = 0;
2576 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2577 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2578 if (ShownOverloads >= S.Diags.getNumOverloadCandidatesToShow()) {
2579 ++SuppressedOverloads;
2580 continue;
2583 const NamedDecl *Fn = (*It)->getUnderlyingDecl();
2584 // Don't print overloads for non-default multiversioned functions.
2585 if (const auto *FD = Fn->getAsFunction()) {
2586 if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
2587 !FD->getAttr<TargetAttr>()->isDefaultVersion())
2588 continue;
2589 if (FD->isMultiVersion() && FD->hasAttr<TargetVersionAttr>() &&
2590 !FD->getAttr<TargetVersionAttr>()->isDefaultVersion())
2591 continue;
2593 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2594 ++ShownOverloads;
2597 S.Diags.overloadCandidatesShown(ShownOverloads);
2599 if (SuppressedOverloads)
2600 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2601 << SuppressedOverloads;
2604 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
2605 const UnresolvedSetImpl &Overloads,
2606 bool (*IsPlausibleResult)(QualType)) {
2607 if (!IsPlausibleResult)
2608 return noteOverloads(S, Overloads, Loc);
2610 UnresolvedSet<2> PlausibleOverloads;
2611 for (OverloadExpr::decls_iterator It = Overloads.begin(),
2612 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2613 const auto *OverloadDecl = cast<FunctionDecl>(*It);
2614 QualType OverloadResultTy = OverloadDecl->getReturnType();
2615 if (IsPlausibleResult(OverloadResultTy))
2616 PlausibleOverloads.addDecl(It.getDecl());
2618 noteOverloads(S, PlausibleOverloads, Loc);
2621 /// Determine whether the given expression can be called by just
2622 /// putting parentheses after it. Notably, expressions with unary
2623 /// operators can't be because the unary operator will start parsing
2624 /// outside the call.
2625 static bool IsCallableWithAppend(const Expr *E) {
2626 E = E->IgnoreImplicit();
2627 return (!isa<CStyleCastExpr>(E) &&
2628 !isa<UnaryOperator>(E) &&
2629 !isa<BinaryOperator>(E) &&
2630 !isa<CXXOperatorCallExpr>(E));
2633 static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
2634 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2635 E = UO->getSubExpr();
2637 if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2638 if (ULE->getNumDecls() == 0)
2639 return false;
2641 const NamedDecl *ND = *ULE->decls_begin();
2642 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2643 return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
2645 return false;
2648 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2649 bool ForceComplain,
2650 bool (*IsPlausibleResult)(QualType)) {
2651 SourceLocation Loc = E.get()->getExprLoc();
2652 SourceRange Range = E.get()->getSourceRange();
2653 UnresolvedSet<4> Overloads;
2655 // If this is a SFINAE context, don't try anything that might trigger ADL
2656 // prematurely.
2657 if (!isSFINAEContext()) {
2658 QualType ZeroArgCallTy;
2659 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2660 !ZeroArgCallTy.isNull() &&
2661 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
2662 // At this point, we know E is potentially callable with 0
2663 // arguments and that it returns something of a reasonable type,
2664 // so we can emit a fixit and carry on pretending that E was
2665 // actually a CallExpr.
2666 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2667 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2668 Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2669 << (IsCallableWithAppend(E.get())
2670 ? FixItHint::CreateInsertion(ParenInsertionLoc,
2671 "()")
2672 : FixItHint());
2673 if (!IsMV)
2674 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2676 // FIXME: Try this before emitting the fixit, and suppress diagnostics
2677 // while doing so.
2678 E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), std::nullopt,
2679 Range.getEnd().getLocWithOffset(1));
2680 return true;
2683 if (!ForceComplain) return false;
2685 bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2686 Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2687 if (!IsMV)
2688 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2689 E = ExprError();
2690 return true;
2693 IdentifierInfo *Sema::getSuperIdentifier() const {
2694 if (!Ident_super)
2695 Ident_super = &Context.Idents.get("super");
2696 return Ident_super;
2699 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
2700 CapturedRegionKind K,
2701 unsigned OpenMPCaptureLevel) {
2702 auto *CSI = new CapturedRegionScopeInfo(
2703 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2704 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
2705 OpenMPCaptureLevel);
2706 CSI->ReturnType = Context.VoidTy;
2707 FunctionScopes.push_back(CSI);
2708 CapturingFunctionScopes++;
2711 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
2712 if (FunctionScopes.empty())
2713 return nullptr;
2715 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2718 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
2719 Sema::getMismatchingDeleteExpressions() const {
2720 return DeleteExprs;
2723 Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema &S)
2724 : S(S), OldFPFeaturesState(S.CurFPFeatures),
2725 OldOverrides(S.FpPragmaStack.CurrentValue),
2726 OldEvalMethod(S.PP.getCurrentFPEvalMethod()),
2727 OldFPPragmaLocation(S.PP.getLastFPEvalPragmaLocation()) {}
2729 Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {
2730 S.CurFPFeatures = OldFPFeaturesState;
2731 S.FpPragmaStack.CurrentValue = OldOverrides;
2732 S.PP.setCurrentFPEvalMethod(OldFPPragmaLocation, OldEvalMethod);
2735 bool Sema::isDeclaratorFunctionLike(Declarator &D) {
2736 assert(D.getCXXScopeSpec().isSet() &&
2737 "can only be called for qualified names");
2739 auto LR = LookupResult(*this, D.getIdentifier(), D.getBeginLoc(),
2740 LookupOrdinaryName, forRedeclarationInCurContext());
2741 DeclContext *DC = computeDeclContext(D.getCXXScopeSpec(),
2742 !D.getDeclSpec().isFriendSpecified());
2743 if (!DC)
2744 return false;
2746 LookupQualifiedName(LR, DC);
2747 bool Result = std::all_of(LR.begin(), LR.end(), [](Decl *Dcl) {
2748 if (NamedDecl *ND = dyn_cast<NamedDecl>(Dcl)) {
2749 ND = ND->getUnderlyingDecl();
2750 return isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) ||
2751 isa<UsingDecl>(ND);
2753 return false;
2755 return Result;