1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
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
7 //===----------------------------------------------------------------------===//
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"
55 using namespace clang
;
58 SourceLocation
Sema::getLocForEndOfToken(SourceLocation Loc
, unsigned Offset
) {
59 return Lexer::getLocForEndOfToken(Loc
, Offset
, SourceMgr
, LangOpts
);
62 ModuleLoader
&Sema::getModuleLoader() const { return PP
.getModuleLoader(); }
65 Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc
,
67 auto *SDKInfo
= getDarwinSDKInfoForAvailabilityChecking();
68 if (!SDKInfo
&& !WarnedDarwinSDKInfoMissing
) {
69 Diag(Loc
, diag::warn_missing_sdksettings_for_availability_checking
)
71 WarnedDarwinSDKInfoMissing
= true;
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();
87 llvm::consumeError(SDKInfo
.takeError());
88 CachedDarwinSDKInfo
= std::unique_ptr
<DarwinSDKInfo
>();
93 Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo
*ParamName
,
95 std::string InventedName
;
96 llvm::raw_string_ostream
OS(InventedName
);
99 OS
<< "auto:" << Index
+ 1;
101 OS
<< ParamName
->getName() << ":auto";
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
112 Policy
.Bool
= Context
.getLangOpts().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;
127 void Sema::ActOnTranslationUnitScope(Scope
*S
) {
129 PushDeclContext(S
, Context
.getTranslationUnitDecl());
135 class SemaPPCallbacks
: public PPCallbacks
{
137 llvm::SmallVector
<SourceLocation
, 8> IncludeStack
;
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
{
151 SourceManager
&SM
= S
->getSourceManager();
152 SourceLocation IncludeLoc
= SM
.getIncludeLoc(SM
.getFileID(Loc
));
153 if (IncludeLoc
.isValid()) {
154 if (llvm::timeTraceProfilerEnabled()) {
155 OptionalFileEntryRef FE
= SM
.getFileEntryRefForID(SM
.getFileID(Loc
));
156 llvm::timeTraceProfilerBegin("Source", FE
? FE
->getName()
157 : StringRef("<unknown>"));
160 IncludeStack
.push_back(IncludeLoc
);
161 S
->DiagnoseNonDefaultPragmaAlignPack(
162 Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude
,
168 if (!IncludeStack
.empty()) {
169 if (llvm::timeTraceProfilerEnabled())
170 llvm::timeTraceProfilerEnd();
172 S
->DiagnoseNonDefaultPragmaAlignPack(
173 Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit
,
174 IncludeStack
.pop_back_val());
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
);
225 LoadedExternalKnownNamespaces
= false;
226 for (unsigned I
= 0; I
!= NSAPI::NumNSNumberLiteralMethods
; ++I
)
227 NSNumberLiteralMethods
[I
] = nullptr;
229 if (getLangOpts().ObjC
)
230 NSAPIObj
.reset(new NSAPI(Context
));
232 if (getLangOpts().CPlusPlus
)
233 FieldCollector
.reset(new CXXFieldCollector());
235 // Tell diagnostics how to render things from the AST library.
236 Diags
.SetArgToStringFn(&FormatASTNodeDiagnosticArgument
, &Context
);
238 // This evaluation context exists to ensure that there's always at least one
239 // valid evaluation context available. It is never removed from the
241 ExprEvalContexts
.emplace_back(
242 ExpressionEvaluationContext::PotentiallyEvaluated
, 0, CleanupInfo
{},
243 nullptr, ExpressionEvaluationContextRecord::EK_Other
);
245 // Initialization of data sharing attributes stack for OpenMP
246 InitDataSharingAttributesStack();
248 std::unique_ptr
<sema::SemaPPCallbacks
> Callbacks
=
249 std::make_unique
<sema::SemaPPCallbacks
>();
250 SemaPPCallbackHandler
= Callbacks
.get();
251 PP
.addPPCallbacks(std::move(Callbacks
));
252 SemaPPCallbackHandler
->set(*this);
254 CurFPFeatures
.setFPEvalMethod(PP
.getCurrentFPEvalMethod());
257 // Anchor Sema's type info to this TU.
258 void Sema::anchor() {}
260 void Sema::addImplicitTypedef(StringRef Name
, QualType T
) {
261 DeclarationName DN
= &Context
.Idents
.get(Name
);
262 if (IdResolver
.begin(DN
) == IdResolver
.end())
263 PushOnScopeChains(Context
.buildImplicitTypedef(T
, Name
), TUScope
);
266 void Sema::Initialize() {
267 if (SemaConsumer
*SC
= dyn_cast
<SemaConsumer
>(&Consumer
))
268 SC
->InitializeSema(*this);
270 // Tell the external Sema source about this Sema object.
271 if (ExternalSemaSource
*ExternalSema
272 = dyn_cast_or_null
<ExternalSemaSource
>(Context
.getExternalSource()))
273 ExternalSema
->InitializeSema(*this);
275 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
276 // will not be able to merge any duplicate __va_list_tag decls correctly.
277 VAListTagName
= PP
.getIdentifierInfo("__va_list_tag");
282 // Initialize predefined 128-bit integer types, if needed.
283 if (Context
.getTargetInfo().hasInt128Type() ||
284 (Context
.getAuxTargetInfo() &&
285 Context
.getAuxTargetInfo()->hasInt128Type())) {
286 // If either of the 128-bit integer types are unavailable to name lookup,
288 DeclarationName Int128
= &Context
.Idents
.get("__int128_t");
289 if (IdResolver
.begin(Int128
) == IdResolver
.end())
290 PushOnScopeChains(Context
.getInt128Decl(), TUScope
);
292 DeclarationName UInt128
= &Context
.Idents
.get("__uint128_t");
293 if (IdResolver
.begin(UInt128
) == IdResolver
.end())
294 PushOnScopeChains(Context
.getUInt128Decl(), TUScope
);
298 // Initialize predefined Objective-C types:
299 if (getLangOpts().ObjC
) {
300 // If 'SEL' does not yet refer to any declarations, make it refer to the
302 DeclarationName SEL
= &Context
.Idents
.get("SEL");
303 if (IdResolver
.begin(SEL
) == IdResolver
.end())
304 PushOnScopeChains(Context
.getObjCSelDecl(), TUScope
);
306 // If 'id' does not yet refer to any declarations, make it refer to the
308 DeclarationName Id
= &Context
.Idents
.get("id");
309 if (IdResolver
.begin(Id
) == IdResolver
.end())
310 PushOnScopeChains(Context
.getObjCIdDecl(), TUScope
);
312 // Create the built-in typedef for 'Class'.
313 DeclarationName Class
= &Context
.Idents
.get("Class");
314 if (IdResolver
.begin(Class
) == IdResolver
.end())
315 PushOnScopeChains(Context
.getObjCClassDecl(), TUScope
);
317 // Create the built-in forward declaratino for 'Protocol'.
318 DeclarationName Protocol
= &Context
.Idents
.get("Protocol");
319 if (IdResolver
.begin(Protocol
) == IdResolver
.end())
320 PushOnScopeChains(Context
.getObjCProtocolDecl(), TUScope
);
323 // Create the internal type for the *StringMakeConstantString builtins.
324 DeclarationName ConstantString
= &Context
.Idents
.get("__NSConstantString");
325 if (IdResolver
.begin(ConstantString
) == IdResolver
.end())
326 PushOnScopeChains(Context
.getCFConstantStringDecl(), TUScope
);
328 // Initialize Microsoft "predefined C++ types".
329 if (getLangOpts().MSVCCompat
) {
330 if (getLangOpts().CPlusPlus
&&
331 IdResolver
.begin(&Context
.Idents
.get("type_info")) == IdResolver
.end())
332 PushOnScopeChains(Context
.buildImplicitRecord("type_info", TTK_Class
),
335 addImplicitTypedef("size_t", Context
.getSizeType());
338 // Initialize predefined OpenCL types and supported extensions and (optional)
340 if (getLangOpts().OpenCL
) {
341 getOpenCLOptions().addSupport(
342 Context
.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
343 addImplicitTypedef("sampler_t", Context
.OCLSamplerTy
);
344 addImplicitTypedef("event_t", Context
.OCLEventTy
);
345 auto OCLCompatibleVersion
= getLangOpts().getOpenCLCompatibleVersion();
346 if (OCLCompatibleVersion
>= 200) {
347 if (getLangOpts().OpenCLCPlusPlus
|| getLangOpts().Blocks
) {
348 addImplicitTypedef("clk_event_t", Context
.OCLClkEventTy
);
349 addImplicitTypedef("queue_t", Context
.OCLQueueTy
);
351 if (getLangOpts().OpenCLPipes
)
352 addImplicitTypedef("reserve_id_t", Context
.OCLReserveIDTy
);
353 addImplicitTypedef("atomic_int", Context
.getAtomicType(Context
.IntTy
));
354 addImplicitTypedef("atomic_uint",
355 Context
.getAtomicType(Context
.UnsignedIntTy
));
356 addImplicitTypedef("atomic_float",
357 Context
.getAtomicType(Context
.FloatTy
));
358 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
359 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
360 addImplicitTypedef("atomic_flag", Context
.getAtomicType(Context
.IntTy
));
363 // OpenCL v2.0 s6.13.11.6:
364 // - The atomic_long and atomic_ulong types are supported if the
365 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
366 // extensions are supported.
367 // - The atomic_double type is only supported if double precision
368 // is supported and the cl_khr_int64_base_atomics and
369 // cl_khr_int64_extended_atomics extensions are supported.
370 // - If the device address space is 64-bits, the data types
371 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
372 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
373 // cl_khr_int64_extended_atomics extensions are supported.
375 auto AddPointerSizeDependentTypes
= [&]() {
376 auto AtomicSizeT
= Context
.getAtomicType(Context
.getSizeType());
377 auto AtomicIntPtrT
= Context
.getAtomicType(Context
.getIntPtrType());
378 auto AtomicUIntPtrT
= Context
.getAtomicType(Context
.getUIntPtrType());
379 auto AtomicPtrDiffT
=
380 Context
.getAtomicType(Context
.getPointerDiffType());
381 addImplicitTypedef("atomic_size_t", AtomicSizeT
);
382 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT
);
383 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT
);
384 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT
);
387 if (Context
.getTypeSize(Context
.getSizeType()) == 32) {
388 AddPointerSizeDependentTypes();
391 if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
392 auto AtomicHalfT
= Context
.getAtomicType(Context
.HalfTy
);
393 addImplicitTypedef("atomic_half", AtomicHalfT
);
396 std::vector
<QualType
> Atomic64BitTypes
;
397 if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
399 getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
401 if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
402 auto AtomicDoubleT
= Context
.getAtomicType(Context
.DoubleTy
);
403 addImplicitTypedef("atomic_double", AtomicDoubleT
);
404 Atomic64BitTypes
.push_back(AtomicDoubleT
);
406 auto AtomicLongT
= Context
.getAtomicType(Context
.LongTy
);
407 auto AtomicULongT
= Context
.getAtomicType(Context
.UnsignedLongTy
);
408 addImplicitTypedef("atomic_long", AtomicLongT
);
409 addImplicitTypedef("atomic_ulong", AtomicULongT
);
412 if (Context
.getTypeSize(Context
.getSizeType()) == 64) {
413 AddPointerSizeDependentTypes();
418 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
419 if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \
420 addImplicitTypedef(#ExtType, Context.Id##Ty); \
422 #include "clang/Basic/OpenCLExtensionTypes.def"
425 if (Context
.getTargetInfo().hasAArch64SVETypes()) {
426 #define SVE_TYPE(Name, Id, SingletonId) \
427 addImplicitTypedef(Name, Context.SingletonId);
428 #include "clang/Basic/AArch64SVEACLETypes.def"
431 if (Context
.getTargetInfo().getTriple().isPPC64()) {
432 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
433 addImplicitTypedef(#Name, Context.Id##Ty);
434 #include "clang/Basic/PPCTypes.def"
435 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
436 addImplicitTypedef(#Name, Context.Id##Ty);
437 #include "clang/Basic/PPCTypes.def"
440 if (Context
.getTargetInfo().hasRISCVVTypes()) {
441 #define RVV_TYPE(Name, Id, SingletonId) \
442 addImplicitTypedef(Name, Context.SingletonId);
443 #include "clang/Basic/RISCVVTypes.def"
446 if (Context
.getTargetInfo().getTriple().isWasm() &&
447 Context
.getTargetInfo().hasFeature("reference-types")) {
448 #define WASM_TYPE(Name, Id, SingletonId) \
449 addImplicitTypedef(Name, Context.SingletonId);
450 #include "clang/Basic/WebAssemblyReferenceTypes.def"
453 if (Context
.getTargetInfo().hasBuiltinMSVaList()) {
454 DeclarationName MSVaList
= &Context
.Idents
.get("__builtin_ms_va_list");
455 if (IdResolver
.begin(MSVaList
) == IdResolver
.end())
456 PushOnScopeChains(Context
.getBuiltinMSVaListDecl(), TUScope
);
459 DeclarationName BuiltinVaList
= &Context
.Idents
.get("__builtin_va_list");
460 if (IdResolver
.begin(BuiltinVaList
) == IdResolver
.end())
461 PushOnScopeChains(Context
.getBuiltinVaListDecl(), TUScope
);
465 assert(InstantiatingSpecializations
.empty() &&
466 "failed to clean up an InstantiatingTemplate?");
468 if (VisContext
) FreeVisContext();
470 // Kill all the active scopes.
471 for (sema::FunctionScopeInfo
*FSI
: FunctionScopes
)
474 // Tell the SemaConsumer to forget about us; we're going out of scope.
475 if (SemaConsumer
*SC
= dyn_cast
<SemaConsumer
>(&Consumer
))
478 // Detach from the external Sema source.
479 if (ExternalSemaSource
*ExternalSema
480 = dyn_cast_or_null
<ExternalSemaSource
>(Context
.getExternalSource()))
481 ExternalSema
->ForgetSema();
483 // Delete cached satisfactions.
484 std::vector
<ConstraintSatisfaction
*> Satisfactions
;
485 Satisfactions
.reserve(SatisfactionCache
.size());
486 for (auto &Node
: SatisfactionCache
)
487 Satisfactions
.push_back(&Node
);
488 for (auto *Node
: Satisfactions
)
491 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache
);
493 // Destroys data sharing attributes stack for OpenMP
494 DestroyDataSharingAttributesStack();
496 // Detach from the PP callback handler which outlives Sema since it's owned
497 // by the preprocessor.
498 SemaPPCallbackHandler
->reset();
501 void Sema::warnStackExhausted(SourceLocation Loc
) {
502 // Only warn about this once.
503 if (!WarnedStackExhausted
) {
504 Diag(Loc
, diag::warn_stack_exhausted
);
505 WarnedStackExhausted
= true;
509 void Sema::runWithSufficientStackSpace(SourceLocation Loc
,
510 llvm::function_ref
<void()> Fn
) {
511 clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc
); }, Fn
);
514 /// makeUnavailableInSystemHeader - There is an error in the current
515 /// context. If we're still in a system header, and we can plausibly
516 /// make the relevant declaration unavailable instead of erroring, do
517 /// so and return true.
518 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc
,
519 UnavailableAttr::ImplicitReason reason
) {
520 // If we're not in a function, it's an error.
521 FunctionDecl
*fn
= dyn_cast
<FunctionDecl
>(CurContext
);
522 if (!fn
) return false;
524 // If we're in template instantiation, it's an error.
525 if (inTemplateInstantiation())
528 // If that function's not in a system header, it's an error.
529 if (!Context
.getSourceManager().isInSystemHeader(loc
))
532 // If the function is already unavailable, it's not an error.
533 if (fn
->hasAttr
<UnavailableAttr
>()) return true;
535 fn
->addAttr(UnavailableAttr::CreateImplicit(Context
, "", reason
, loc
));
539 ASTMutationListener
*Sema::getASTMutationListener() const {
540 return getASTConsumer().GetASTMutationListener();
543 ///Registers an external source. If an external source already exists,
544 /// creates a multiplex external source and appends to it.
546 ///\param[in] E - A non-null external sema source.
548 void Sema::addExternalSource(ExternalSemaSource
*E
) {
549 assert(E
&& "Cannot use with NULL ptr");
551 if (!ExternalSource
) {
556 if (auto *Ex
= dyn_cast
<MultiplexExternalSemaSource
>(ExternalSource
))
559 ExternalSource
= new MultiplexExternalSemaSource(ExternalSource
.get(), E
);
562 /// Print out statistics about the semantic analysis.
563 void Sema::PrintStats() const {
564 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
565 llvm::errs() << NumSFINAEErrors
<< " SFINAE diagnostics trapped.\n";
567 BumpAlloc
.PrintStats();
568 AnalysisWarnings
.PrintStats();
571 void Sema::diagnoseNullableToNonnullConversion(QualType DstType
,
573 SourceLocation Loc
) {
574 std::optional
<NullabilityKind
> ExprNullability
= SrcType
->getNullability();
575 if (!ExprNullability
|| (*ExprNullability
!= NullabilityKind::Nullable
&&
576 *ExprNullability
!= NullabilityKind::NullableResult
))
579 std::optional
<NullabilityKind
> TypeNullability
= DstType
->getNullability();
580 if (!TypeNullability
|| *TypeNullability
!= NullabilityKind::NonNull
)
583 Diag(Loc
, diag::warn_nullability_lost
) << SrcType
<< DstType
;
586 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind
, const Expr
*E
) {
587 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
588 if (!getLangOpts().CPlusPlus11
)
591 if (Kind
!= CK_NullToPointer
&& Kind
!= CK_NullToMemberPointer
)
594 const Expr
*EStripped
= E
->IgnoreParenImpCasts();
595 if (EStripped
->getType()->isNullPtrType())
597 if (isa
<GNUNullExpr
>(EStripped
))
600 if (Diags
.isIgnored(diag::warn_zero_as_null_pointer_constant
,
604 // Don't diagnose the conversion from a 0 literal to a null pointer argument
605 // in a synthesized call to operator<=>.
606 if (!CodeSynthesisContexts
.empty() &&
607 CodeSynthesisContexts
.back().Kind
==
608 CodeSynthesisContext::RewritingOperatorAsSpaceship
)
611 // Ignore null pointers in defaulted comparison operators.
612 FunctionDecl
*FD
= getCurFunctionDecl();
613 if (FD
&& FD
->isDefaulted()) {
617 // If it is a macro from system header, and if the macro name is not "NULL",
619 // Note that uses of "NULL" will be ignored above on systems that define it
621 SourceLocation MaybeMacroLoc
= E
->getBeginLoc();
622 if (Diags
.getSuppressSystemWarnings() &&
623 SourceMgr
.isInSystemMacro(MaybeMacroLoc
) &&
624 !findMacroSpelling(MaybeMacroLoc
, "NULL"))
627 Diag(E
->getBeginLoc(), diag::warn_zero_as_null_pointer_constant
)
628 << FixItHint::CreateReplacement(E
->getSourceRange(), "nullptr");
631 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
632 /// If there is already an implicit cast, merge into the existing one.
633 /// The result is of the given category.
634 ExprResult
Sema::ImpCastExprToType(Expr
*E
, QualType Ty
,
635 CastKind Kind
, ExprValueKind VK
,
636 const CXXCastPath
*BasePath
,
637 CheckedConversionKind CCK
) {
639 if (VK
== VK_PRValue
&& !E
->isPRValue()) {
643 ("can't implicitly cast glvalue to prvalue with this cast "
645 std::string(CastExpr::getCastKindName(Kind
)))
648 case CK_LValueToRValue
:
649 case CK_ArrayToPointerDecay
:
650 case CK_FunctionToPointerDecay
:
652 case CK_NonAtomicToAtomic
:
656 assert((VK
== VK_PRValue
|| Kind
== CK_Dependent
|| !E
->isPRValue()) &&
657 "can't cast prvalue to glvalue");
660 diagnoseNullableToNonnullConversion(Ty
, E
->getType(), E
->getBeginLoc());
661 diagnoseZeroToNullptrConversion(Kind
, E
);
663 QualType ExprTy
= Context
.getCanonicalType(E
->getType());
664 QualType TypeTy
= Context
.getCanonicalType(Ty
);
666 if (ExprTy
== TypeTy
)
669 if (Kind
== CK_ArrayToPointerDecay
) {
670 // C++1z [conv.array]: The temporary materialization conversion is applied.
671 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
672 if (getLangOpts().CPlusPlus
&& E
->isPRValue()) {
673 // The temporary is an lvalue in C++98 and an xvalue otherwise.
674 ExprResult Materialized
= CreateMaterializeTemporaryExpr(
675 E
->getType(), E
, !getLangOpts().CPlusPlus11
);
676 if (Materialized
.isInvalid())
678 E
= Materialized
.get();
680 // C17 6.7.1p6 footnote 124: The implementation can treat any register
681 // declaration simply as an auto declaration. However, whether or not
682 // addressable storage is actually used, the address of any part of an
683 // object declared with storage-class specifier register cannot be
684 // computed, either explicitly(by use of the unary & operator as discussed
685 // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
686 // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
687 // array declared with storage-class specifier register is sizeof.
688 if (VK
== VK_PRValue
&& !getLangOpts().CPlusPlus
&& !E
->isPRValue()) {
689 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
690 if (const auto *VD
= dyn_cast
<VarDecl
>(DRE
->getDecl())) {
691 if (VD
->getStorageClass() == SC_Register
) {
692 Diag(E
->getExprLoc(), diag::err_typecheck_address_of
)
693 << /*register variable*/ 3 << E
->getSourceRange();
701 if (ImplicitCastExpr
*ImpCast
= dyn_cast
<ImplicitCastExpr
>(E
)) {
702 if (ImpCast
->getCastKind() == Kind
&& (!BasePath
|| BasePath
->empty())) {
703 ImpCast
->setType(Ty
);
704 ImpCast
->setValueKind(VK
);
709 return ImplicitCastExpr::Create(Context
, Ty
, Kind
, E
, BasePath
, VK
,
710 CurFPFeatureOverrides());
713 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
714 /// to the conversion from scalar type ScalarTy to the Boolean type.
715 CastKind
Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy
) {
716 switch (ScalarTy
->getScalarTypeKind()) {
717 case Type::STK_Bool
: return CK_NoOp
;
718 case Type::STK_CPointer
: return CK_PointerToBoolean
;
719 case Type::STK_BlockPointer
: return CK_PointerToBoolean
;
720 case Type::STK_ObjCObjectPointer
: return CK_PointerToBoolean
;
721 case Type::STK_MemberPointer
: return CK_MemberPointerToBoolean
;
722 case Type::STK_Integral
: return CK_IntegralToBoolean
;
723 case Type::STK_Floating
: return CK_FloatingToBoolean
;
724 case Type::STK_IntegralComplex
: return CK_IntegralComplexToBoolean
;
725 case Type::STK_FloatingComplex
: return CK_FloatingComplexToBoolean
;
726 case Type::STK_FixedPoint
: return CK_FixedPointToBoolean
;
728 llvm_unreachable("unknown scalar type kind");
731 /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
732 static bool ShouldRemoveFromUnused(Sema
*SemaRef
, const DeclaratorDecl
*D
) {
733 if (D
->getMostRecentDecl()->isUsed())
736 if (D
->isExternallyVisible())
739 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
740 // If this is a function template and none of its specializations is used,
742 if (FunctionTemplateDecl
*Template
= FD
->getDescribedFunctionTemplate())
743 for (const auto *Spec
: Template
->specializations())
744 if (ShouldRemoveFromUnused(SemaRef
, Spec
))
747 // UnusedFileScopedDecls stores the first declaration.
748 // The declaration may have become definition so check again.
749 const FunctionDecl
*DeclToCheck
;
750 if (FD
->hasBody(DeclToCheck
))
751 return !SemaRef
->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck
);
753 // Later redecls may add new information resulting in not having to warn,
755 DeclToCheck
= FD
->getMostRecentDecl();
756 if (DeclToCheck
!= FD
)
757 return !SemaRef
->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck
);
760 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
761 // If a variable usable in constant expressions is referenced,
762 // don't warn if it isn't used: if the value of a variable is required
763 // for the computation of a constant expression, it doesn't make sense to
764 // warn even if the variable isn't odr-used. (isReferenced doesn't
765 // precisely reflect that, but it's a decent approximation.)
766 if (VD
->isReferenced() &&
767 VD
->mightBeUsableInConstantExpressions(SemaRef
->Context
))
770 if (VarTemplateDecl
*Template
= VD
->getDescribedVarTemplate())
771 // If this is a variable template and none of its specializations is used,
773 for (const auto *Spec
: Template
->specializations())
774 if (ShouldRemoveFromUnused(SemaRef
, Spec
))
777 // UnusedFileScopedDecls stores the first declaration.
778 // The declaration may have become definition so check again.
779 const VarDecl
*DeclToCheck
= VD
->getDefinition();
781 return !SemaRef
->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck
);
783 // Later redecls may add new information resulting in not having to warn,
785 DeclToCheck
= VD
->getMostRecentDecl();
786 if (DeclToCheck
!= VD
)
787 return !SemaRef
->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck
);
793 static bool isFunctionOrVarDeclExternC(const NamedDecl
*ND
) {
794 if (const auto *FD
= dyn_cast
<FunctionDecl
>(ND
))
795 return FD
->isExternC();
796 return cast
<VarDecl
>(ND
)->isExternC();
799 /// Determine whether ND is an external-linkage function or variable whose
800 /// type has no linkage.
801 bool Sema::isExternalWithNoLinkageType(const ValueDecl
*VD
) const {
802 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
803 // because we also want to catch the case where its type has VisibleNoLinkage,
804 // which does not affect the linkage of VD.
805 return getLangOpts().CPlusPlus
&& VD
->hasExternalFormalLinkage() &&
806 !isExternalFormalLinkage(VD
->getType()->getLinkage()) &&
807 !isFunctionOrVarDeclExternC(VD
);
810 /// Obtains a sorted list of functions and variables that are undefined but
812 void Sema::getUndefinedButUsed(
813 SmallVectorImpl
<std::pair
<NamedDecl
*, SourceLocation
> > &Undefined
) {
814 for (const auto &UndefinedUse
: UndefinedButUsed
) {
815 NamedDecl
*ND
= UndefinedUse
.first
;
817 // Ignore attributes that have become invalid.
818 if (ND
->isInvalidDecl()) continue;
820 // __attribute__((weakref)) is basically a definition.
821 if (ND
->hasAttr
<WeakRefAttr
>()) continue;
823 if (isa
<CXXDeductionGuideDecl
>(ND
))
826 if (ND
->hasAttr
<DLLImportAttr
>() || ND
->hasAttr
<DLLExportAttr
>()) {
827 // An exported function will always be emitted when defined, so even if
828 // the function is inline, it doesn't have to be emitted in this TU. An
829 // imported function implies that it has been exported somewhere else.
833 if (const auto *FD
= dyn_cast
<FunctionDecl
>(ND
)) {
836 if (FD
->isExternallyVisible() &&
837 !isExternalWithNoLinkageType(FD
) &&
838 !FD
->getMostRecentDecl()->isInlined() &&
839 !FD
->hasAttr
<ExcludeFromExplicitInstantiationAttr
>())
841 if (FD
->getBuiltinID())
844 const auto *VD
= cast
<VarDecl
>(ND
);
845 if (VD
->hasDefinition() != VarDecl::DeclarationOnly
)
847 if (VD
->isExternallyVisible() &&
848 !isExternalWithNoLinkageType(VD
) &&
849 !VD
->getMostRecentDecl()->isInline() &&
850 !VD
->hasAttr
<ExcludeFromExplicitInstantiationAttr
>())
853 // Skip VarDecls that lack formal definitions but which we know are in
854 // fact defined somewhere.
855 if (VD
->isKnownToBeDefined())
859 Undefined
.push_back(std::make_pair(ND
, UndefinedUse
.second
));
863 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
864 /// or that are inline.
865 static void checkUndefinedButUsed(Sema
&S
) {
866 if (S
.UndefinedButUsed
.empty()) return;
868 // Collect all the still-undefined entities with internal linkage.
869 SmallVector
<std::pair
<NamedDecl
*, SourceLocation
>, 16> Undefined
;
870 S
.getUndefinedButUsed(Undefined
);
871 if (Undefined
.empty()) return;
873 for (const auto &Undef
: Undefined
) {
874 ValueDecl
*VD
= cast
<ValueDecl
>(Undef
.first
);
875 SourceLocation UseLoc
= Undef
.second
;
877 if (S
.isExternalWithNoLinkageType(VD
)) {
878 // C++ [basic.link]p8:
879 // A type without linkage shall not be used as the type of a variable
880 // or function with external linkage unless
881 // -- the entity has C language linkage
882 // -- the entity is not odr-used or is defined in the same TU
884 // As an extension, accept this in cases where the type is externally
885 // visible, since the function or variable actually can be defined in
886 // another translation unit in that case.
887 S
.Diag(VD
->getLocation(), isExternallyVisible(VD
->getType()->getLinkage())
888 ? diag::ext_undefined_internal_type
889 : diag::err_undefined_internal_type
)
890 << isa
<VarDecl
>(VD
) << VD
;
891 } else if (!VD
->isExternallyVisible()) {
892 // FIXME: We can promote this to an error. The function or variable can't
893 // be defined anywhere else, so the program must necessarily violate the
894 // one definition rule.
895 bool IsImplicitBase
= false;
896 if (const auto *BaseD
= dyn_cast
<FunctionDecl
>(VD
)) {
897 auto *DVAttr
= BaseD
->getAttr
<OMPDeclareVariantAttr
>();
898 if (DVAttr
&& !DVAttr
->getTraitInfo().isExtensionActive(
899 llvm::omp::TraitProperty::
900 implementation_extension_disable_implicit_base
)) {
901 const auto *Func
= cast
<FunctionDecl
>(
902 cast
<DeclRefExpr
>(DVAttr
->getVariantFuncRef())->getDecl());
903 IsImplicitBase
= BaseD
->isImplicit() &&
904 Func
->getIdentifier()->isMangledOpenMPVariantName();
907 if (!S
.getLangOpts().OpenMP
|| !IsImplicitBase
)
908 S
.Diag(VD
->getLocation(), diag::warn_undefined_internal
)
909 << isa
<VarDecl
>(VD
) << VD
;
910 } else if (auto *FD
= dyn_cast
<FunctionDecl
>(VD
)) {
912 assert(FD
->getMostRecentDecl()->isInlined() &&
913 "used object requires definition but isn't inline or internal?");
914 // FIXME: This is ill-formed; we should reject.
915 S
.Diag(VD
->getLocation(), diag::warn_undefined_inline
) << VD
;
917 assert(cast
<VarDecl
>(VD
)->getMostRecentDecl()->isInline() &&
918 "used var requires definition but isn't inline or internal?");
919 S
.Diag(VD
->getLocation(), diag::err_undefined_inline_var
) << VD
;
921 if (UseLoc
.isValid())
922 S
.Diag(UseLoc
, diag::note_used_here
);
925 S
.UndefinedButUsed
.clear();
928 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
932 SmallVector
<std::pair
<IdentifierInfo
*, WeakInfo
>, 4> WeakIDs
;
933 ExternalSource
->ReadWeakUndeclaredIdentifiers(WeakIDs
);
934 for (auto &WeakID
: WeakIDs
)
935 (void)WeakUndeclaredIdentifiers
[WeakID
.first
].insert(WeakID
.second
);
939 typedef llvm::DenseMap
<const CXXRecordDecl
*, bool> RecordCompleteMap
;
941 /// Returns true, if all methods and nested classes of the given
942 /// CXXRecordDecl are defined in this translation unit.
944 /// Should only be called from ActOnEndOfTranslationUnit so that all
945 /// definitions are actually read.
946 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl
*RD
,
947 RecordCompleteMap
&MNCComplete
) {
948 RecordCompleteMap::iterator Cache
= MNCComplete
.find(RD
);
949 if (Cache
!= MNCComplete
.end())
950 return Cache
->second
;
951 if (!RD
->isCompleteDefinition())
953 bool Complete
= true;
954 for (DeclContext::decl_iterator I
= RD
->decls_begin(),
956 I
!= E
&& Complete
; ++I
) {
957 if (const CXXMethodDecl
*M
= dyn_cast
<CXXMethodDecl
>(*I
))
958 Complete
= M
->isDefined() || M
->isDefaulted() ||
959 (M
->isPure() && !isa
<CXXDestructorDecl
>(M
));
960 else if (const FunctionTemplateDecl
*F
= dyn_cast
<FunctionTemplateDecl
>(*I
))
961 // If the template function is marked as late template parsed at this
962 // point, it has not been instantiated and therefore we have not
963 // performed semantic analysis on it yet, so we cannot know if the type
964 // can be considered complete.
965 Complete
= !F
->getTemplatedDecl()->isLateTemplateParsed() &&
966 F
->getTemplatedDecl()->isDefined();
967 else if (const CXXRecordDecl
*R
= dyn_cast
<CXXRecordDecl
>(*I
)) {
968 if (R
->isInjectedClassName())
970 if (R
->hasDefinition())
971 Complete
= MethodsAndNestedClassesComplete(R
->getDefinition(),
977 MNCComplete
[RD
] = Complete
;
981 /// Returns true, if the given CXXRecordDecl is fully defined in this
982 /// translation unit, i.e. all methods are defined or pure virtual and all
983 /// friends, friend functions and nested classes are fully defined in this
984 /// translation unit.
986 /// Should only be called from ActOnEndOfTranslationUnit so that all
987 /// definitions are actually read.
988 static bool IsRecordFullyDefined(const CXXRecordDecl
*RD
,
989 RecordCompleteMap
&RecordsComplete
,
990 RecordCompleteMap
&MNCComplete
) {
991 RecordCompleteMap::iterator Cache
= RecordsComplete
.find(RD
);
992 if (Cache
!= RecordsComplete
.end())
993 return Cache
->second
;
994 bool Complete
= MethodsAndNestedClassesComplete(RD
, MNCComplete
);
995 for (CXXRecordDecl::friend_iterator I
= RD
->friend_begin(),
996 E
= RD
->friend_end();
997 I
!= E
&& Complete
; ++I
) {
998 // Check if friend classes and methods are complete.
999 if (TypeSourceInfo
*TSI
= (*I
)->getFriendType()) {
1000 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
1001 if (CXXRecordDecl
*FriendD
= TSI
->getType()->getAsCXXRecordDecl())
1002 Complete
= MethodsAndNestedClassesComplete(FriendD
, MNCComplete
);
1006 // Friend functions are available through the NamedDecl of FriendDecl.
1007 if (const FunctionDecl
*FD
=
1008 dyn_cast
<FunctionDecl
>((*I
)->getFriendDecl()))
1009 Complete
= FD
->isDefined();
1011 // This is a template friend, give up.
1015 RecordsComplete
[RD
] = Complete
;
1019 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
1021 ExternalSource
->ReadUnusedLocalTypedefNameCandidates(
1022 UnusedLocalTypedefNameCandidates
);
1023 for (const TypedefNameDecl
*TD
: UnusedLocalTypedefNameCandidates
) {
1024 if (TD
->isReferenced())
1026 Diag(TD
->getLocation(), diag::warn_unused_local_typedef
)
1027 << isa
<TypeAliasDecl
>(TD
) << TD
->getDeclName();
1029 UnusedLocalTypedefNameCandidates
.clear();
1032 /// This is called before the very first declaration in the translation unit
1033 /// is parsed. Note that the ASTContext may have already injected some
1035 void Sema::ActOnStartOfTranslationUnit() {
1036 if (getLangOpts().CPlusPlusModules
&&
1037 getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit
)
1038 HandleStartOfHeaderUnit();
1041 void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind
) {
1042 // No explicit actions are required at the end of the global module fragment.
1043 if (Kind
== TUFragmentKind::Global
)
1046 // Transfer late parsed template instantiations over to the pending template
1047 // instantiation list. During normal compilation, the late template parser
1048 // will be installed and instantiating these templates will succeed.
1050 // If we are building a TU prefix for serialization, it is also safe to
1051 // transfer these over, even though they are not parsed. The end of the TU
1052 // should be outside of any eager template instantiation scope, so when this
1053 // AST is deserialized, these templates will not be parsed until the end of
1055 PendingInstantiations
.insert(PendingInstantiations
.end(),
1056 LateParsedInstantiations
.begin(),
1057 LateParsedInstantiations
.end());
1058 LateParsedInstantiations
.clear();
1060 // If DefinedUsedVTables ends up marking any virtual member functions it
1061 // might lead to more pending template instantiations, which we then need
1063 DefineUsedVTables();
1065 // C++: Perform implicit template instantiations.
1067 // FIXME: When we perform these implicit instantiations, we do not
1068 // carefully keep track of the point of instantiation (C++ [temp.point]).
1069 // This means that name lookup that occurs within the template
1070 // instantiation will always happen at the end of the translation unit,
1071 // so it will find some names that are not required to be found. This is
1072 // valid, but we could do better by diagnosing if an instantiation uses a
1073 // name that was not visible at its first point of instantiation.
1074 if (ExternalSource
) {
1075 // Load pending instantiations from the external source.
1076 SmallVector
<PendingImplicitInstantiation
, 4> Pending
;
1077 ExternalSource
->ReadPendingInstantiations(Pending
);
1078 for (auto PII
: Pending
)
1079 if (auto Func
= dyn_cast
<FunctionDecl
>(PII
.first
))
1080 Func
->setInstantiationIsPending(true);
1081 PendingInstantiations
.insert(PendingInstantiations
.begin(),
1082 Pending
.begin(), Pending
.end());
1086 llvm::TimeTraceScope
TimeScope("PerformPendingInstantiations");
1087 PerformPendingInstantiations();
1090 emitDeferredDiags();
1092 assert(LateParsedInstantiations
.empty() &&
1093 "end of TU template instantiation should not create more "
1094 "late-parsed templates");
1096 // Report diagnostics for uncorrected delayed typos. Ideally all of them
1097 // should have been corrected by that time, but it is very hard to cover all
1098 // cases in practice.
1099 for (const auto &Typo
: DelayedTypos
) {
1100 // We pass an empty TypoCorrection to indicate no correction was performed.
1101 Typo
.second
.DiagHandler(TypoCorrection());
1103 DelayedTypos
.clear();
1106 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1107 /// translation unit when EOF is reached and all but the top-level scope is
1109 void Sema::ActOnEndOfTranslationUnit() {
1110 assert(DelayedDiagnostics
.getCurrentPool() == nullptr
1111 && "reached end of translation unit with a pool attached?");
1113 // If code completion is enabled, don't perform any end-of-translation-unit
1115 if (PP
.isCodeCompletionEnabled())
1118 // Complete translation units and modules define vtables and perform implicit
1119 // instantiations. PCH files do not.
1120 if (TUKind
!= TU_Prefix
) {
1121 DiagnoseUseOfUnimplementedSelectors();
1123 ActOnEndOfTranslationUnitFragment(
1124 !ModuleScopes
.empty() && ModuleScopes
.back().Module
->Kind
==
1125 Module::PrivateModuleFragment
1126 ? TUFragmentKind::Private
1127 : TUFragmentKind::Normal
);
1129 if (LateTemplateParserCleanup
)
1130 LateTemplateParserCleanup(OpaqueParser
);
1132 CheckDelayedMemberExceptionSpecs();
1134 // If we are building a TU prefix for serialization, it is safe to transfer
1135 // these over, even though they are not parsed. The end of the TU should be
1136 // outside of any eager template instantiation scope, so when this AST is
1137 // deserialized, these templates will not be parsed until the end of the
1139 PendingInstantiations
.insert(PendingInstantiations
.end(),
1140 LateParsedInstantiations
.begin(),
1141 LateParsedInstantiations
.end());
1142 LateParsedInstantiations
.clear();
1144 if (LangOpts
.PCHInstantiateTemplates
) {
1145 llvm::TimeTraceScope
TimeScope("PerformPendingInstantiations");
1146 PerformPendingInstantiations();
1150 DiagnoseUnterminatedPragmaAlignPack();
1151 DiagnoseUnterminatedPragmaAttribute();
1152 DiagnoseUnterminatedOpenMPDeclareTarget();
1154 // All delayed member exception specs should be checked or we end up accepting
1155 // incompatible declarations.
1156 assert(DelayedOverridingExceptionSpecChecks
.empty());
1157 assert(DelayedEquivalentExceptionSpecChecks
.empty());
1159 // All dllexport classes should have been processed already.
1160 assert(DelayedDllExportClasses
.empty());
1161 assert(DelayedDllExportMemberFunctions
.empty());
1163 // Remove file scoped decls that turned out to be used.
1164 UnusedFileScopedDecls
.erase(
1165 std::remove_if(UnusedFileScopedDecls
.begin(nullptr, true),
1166 UnusedFileScopedDecls
.end(),
1167 [this](const DeclaratorDecl
*DD
) {
1168 return ShouldRemoveFromUnused(this, DD
);
1170 UnusedFileScopedDecls
.end());
1172 if (TUKind
== TU_Prefix
) {
1173 // Translation unit prefixes don't need any of the checking below.
1174 if (!PP
.isIncrementalProcessingEnabled())
1179 // Check for #pragma weak identifiers that were never declared
1180 LoadExternalWeakUndeclaredIdentifiers();
1181 for (const auto &WeakIDs
: WeakUndeclaredIdentifiers
) {
1182 if (WeakIDs
.second
.empty())
1185 Decl
*PrevDecl
= LookupSingleName(TUScope
, WeakIDs
.first
, SourceLocation(),
1186 LookupOrdinaryName
);
1187 if (PrevDecl
!= nullptr &&
1188 !(isa
<FunctionDecl
>(PrevDecl
) || isa
<VarDecl
>(PrevDecl
)))
1189 for (const auto &WI
: WeakIDs
.second
)
1190 Diag(WI
.getLocation(), diag::warn_attribute_wrong_decl_type
)
1191 << "'weak'" << /*isRegularKeyword=*/0 << ExpectedVariableOrFunction
;
1193 for (const auto &WI
: WeakIDs
.second
)
1194 Diag(WI
.getLocation(), diag::warn_weak_identifier_undeclared
)
1198 if (LangOpts
.CPlusPlus11
&&
1199 !Diags
.isIgnored(diag::warn_delegating_ctor_cycle
, SourceLocation()))
1200 CheckDelegatingCtorCycles();
1202 if (!Diags
.hasErrorOccurred()) {
1204 ExternalSource
->ReadUndefinedButUsed(UndefinedButUsed
);
1205 checkUndefinedButUsed(*this);
1208 // A global-module-fragment is only permitted within a module unit.
1209 bool DiagnosedMissingModuleDeclaration
= false;
1210 if (!ModuleScopes
.empty() && ModuleScopes
.back().Module
->Kind
==
1211 Module::ExplicitGlobalModuleFragment
) {
1212 Diag(ModuleScopes
.back().BeginLoc
,
1213 diag::err_module_declaration_missing_after_global_module_introducer
);
1214 DiagnosedMissingModuleDeclaration
= true;
1217 if (TUKind
== TU_Module
) {
1218 // If we are building a module interface unit, we need to have seen the
1219 // module declaration by now.
1220 if (getLangOpts().getCompilingModule() ==
1221 LangOptions::CMK_ModuleInterface
&&
1222 !isCurrentModulePurview() && !DiagnosedMissingModuleDeclaration
) {
1223 // FIXME: Make a better guess as to where to put the module declaration.
1224 Diag(getSourceManager().getLocForStartOfFile(
1225 getSourceManager().getMainFileID()),
1226 diag::err_module_declaration_missing
);
1229 // If we are building a module, resolve all of the exported declarations
1231 if (Module
*CurrentModule
= PP
.getCurrentModule()) {
1232 ModuleMap
&ModMap
= PP
.getHeaderSearchInfo().getModuleMap();
1234 SmallVector
<Module
*, 2> Stack
;
1235 Stack
.push_back(CurrentModule
);
1236 while (!Stack
.empty()) {
1237 Module
*Mod
= Stack
.pop_back_val();
1239 // Resolve the exported declarations and conflicts.
1240 // FIXME: Actually complain, once we figure out how to teach the
1241 // diagnostic client to deal with complaints in the module map at this
1243 ModMap
.resolveExports(Mod
, /*Complain=*/false);
1244 ModMap
.resolveUses(Mod
, /*Complain=*/false);
1245 ModMap
.resolveConflicts(Mod
, /*Complain=*/false);
1247 // Queue the submodules, so their exports will also be resolved.
1248 auto SubmodulesRange
= Mod
->submodules();
1249 Stack
.append(SubmodulesRange
.begin(), SubmodulesRange
.end());
1253 // Now we can decide whether the modules we're building need an initializer.
1254 if (Module
*CurrentModule
= getCurrentModule();
1255 CurrentModule
&& CurrentModule
->isInterfaceOrPartition()) {
1256 auto DoesModNeedInit
= [this](Module
*M
) {
1257 if (!getASTContext().getModuleInitializers(M
).empty())
1259 for (auto [Exported
, _
] : M
->Exports
)
1260 if (Exported
->isNamedModuleInterfaceHasInit())
1262 for (Module
*I
: M
->Imports
)
1263 if (I
->isNamedModuleInterfaceHasInit())
1269 CurrentModule
->NamedModuleHasInit
=
1270 DoesModNeedInit(CurrentModule
) ||
1271 llvm::any_of(CurrentModule
->submodules(),
1272 [&](auto *SubM
) { return DoesModNeedInit(SubM
); });
1275 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1276 // modules when they are built, not every time they are used.
1277 emitAndClearUnusedLocalTypedefWarnings();
1280 // C++ standard modules. Diagnose cases where a function is declared inline
1281 // in the module purview but has no definition before the end of the TU or
1282 // the start of a Private Module Fragment (if one is present).
1283 if (!PendingInlineFuncDecls
.empty()) {
1284 for (auto *D
: PendingInlineFuncDecls
) {
1285 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
1286 bool DefInPMF
= false;
1287 if (auto *FDD
= FD
->getDefinition()) {
1288 assert(FDD
->getOwningModule() &&
1289 FDD
->getOwningModule()->isModulePurview());
1290 DefInPMF
= FDD
->getOwningModule()->isPrivateModule();
1294 Diag(FD
->getLocation(), diag::err_export_inline_not_defined
)
1296 // If we have a PMF it should be at the end of the ModuleScopes.
1298 ModuleScopes
.back().Module
->Kind
== Module::PrivateModuleFragment
) {
1299 Diag(ModuleScopes
.back().BeginLoc
,
1300 diag::note_private_module_fragment
);
1304 PendingInlineFuncDecls
.clear();
1308 // A declaration of an identifier for an object that has file
1309 // scope without an initializer, and without a storage-class
1310 // specifier or with the storage-class specifier static,
1311 // constitutes a tentative definition. If a translation unit
1312 // contains one or more tentative definitions for an identifier,
1313 // and the translation unit contains no external definition for
1314 // that identifier, then the behavior is exactly as if the
1315 // translation unit contains a file scope declaration of that
1316 // identifier, with the composite type as of the end of the
1317 // translation unit, with an initializer equal to 0.
1318 llvm::SmallSet
<VarDecl
*, 32> Seen
;
1319 for (TentativeDefinitionsType::iterator
1320 T
= TentativeDefinitions
.begin(ExternalSource
.get()),
1321 TEnd
= TentativeDefinitions
.end();
1323 VarDecl
*VD
= (*T
)->getActingDefinition();
1325 // If the tentative definition was completed, getActingDefinition() returns
1326 // null. If we've already seen this variable before, insert()'s second
1327 // return value is false.
1328 if (!VD
|| VD
->isInvalidDecl() || !Seen
.insert(VD
).second
)
1331 if (const IncompleteArrayType
*ArrayT
1332 = Context
.getAsIncompleteArrayType(VD
->getType())) {
1333 // Set the length of the array to 1 (C99 6.9.2p5).
1334 Diag(VD
->getLocation(), diag::warn_tentative_incomplete_array
);
1335 llvm::APInt
One(Context
.getTypeSize(Context
.getSizeType()), true);
1336 QualType T
= Context
.getConstantArrayType(
1337 ArrayT
->getElementType(), One
, nullptr, ArraySizeModifier::Normal
, 0);
1339 } else if (RequireCompleteType(VD
->getLocation(), VD
->getType(),
1340 diag::err_tentative_def_incomplete_type
))
1341 VD
->setInvalidDecl();
1343 // No initialization is performed for a tentative definition.
1344 CheckCompleteVariableDeclaration(VD
);
1346 // Notify the consumer that we've completed a tentative definition.
1347 if (!VD
->isInvalidDecl())
1348 Consumer
.CompleteTentativeDefinition(VD
);
1351 for (auto *D
: ExternalDeclarations
) {
1352 if (!D
|| D
->isInvalidDecl() || D
->getPreviousDecl() || !D
->isUsed())
1355 Consumer
.CompleteExternalDeclaration(D
);
1358 // If there were errors, disable 'unused' warnings since they will mostly be
1359 // noise. Don't warn for a use from a module: either we should warn on all
1360 // file-scope declarations in modules or not at all, but whether the
1361 // declaration is used is immaterial.
1362 if (!Diags
.hasErrorOccurred() && TUKind
!= TU_Module
) {
1363 // Output warning for unused file scoped decls.
1364 for (UnusedFileScopedDeclsType::iterator
1365 I
= UnusedFileScopedDecls
.begin(ExternalSource
.get()),
1366 E
= UnusedFileScopedDecls
.end();
1368 if (ShouldRemoveFromUnused(this, *I
))
1371 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*I
)) {
1372 const FunctionDecl
*DiagD
;
1373 if (!FD
->hasBody(DiagD
))
1375 if (DiagD
->isDeleted())
1376 continue; // Deleted functions are supposed to be unused.
1377 SourceRange DiagRange
= DiagD
->getLocation();
1378 if (const ASTTemplateArgumentListInfo
*ASTTAL
=
1379 DiagD
->getTemplateSpecializationArgsAsWritten())
1380 DiagRange
.setEnd(ASTTAL
->RAngleLoc
);
1381 if (DiagD
->isReferenced()) {
1382 if (isa
<CXXMethodDecl
>(DiagD
))
1383 Diag(DiagD
->getLocation(), diag::warn_unneeded_member_function
)
1384 << DiagD
<< DiagRange
;
1386 if (FD
->getStorageClass() == SC_Static
&&
1387 !FD
->isInlineSpecified() &&
1388 !SourceMgr
.isInMainFile(
1389 SourceMgr
.getExpansionLoc(FD
->getLocation())))
1390 Diag(DiagD
->getLocation(),
1391 diag::warn_unneeded_static_internal_decl
)
1392 << DiagD
<< DiagRange
;
1394 Diag(DiagD
->getLocation(), diag::warn_unneeded_internal_decl
)
1395 << /*function=*/0 << DiagD
<< DiagRange
;
1398 if (FD
->getDescribedFunctionTemplate())
1399 Diag(DiagD
->getLocation(), diag::warn_unused_template
)
1400 << /*function=*/0 << DiagD
<< DiagRange
;
1402 Diag(DiagD
->getLocation(), isa
<CXXMethodDecl
>(DiagD
)
1403 ? diag::warn_unused_member_function
1404 : diag::warn_unused_function
)
1405 << DiagD
<< DiagRange
;
1408 const VarDecl
*DiagD
= cast
<VarDecl
>(*I
)->getDefinition();
1410 DiagD
= cast
<VarDecl
>(*I
);
1411 SourceRange DiagRange
= DiagD
->getLocation();
1412 if (const auto *VTSD
= dyn_cast
<VarTemplateSpecializationDecl
>(DiagD
)) {
1413 if (const ASTTemplateArgumentListInfo
*ASTTAL
=
1414 VTSD
->getTemplateArgsInfo())
1415 DiagRange
.setEnd(ASTTAL
->RAngleLoc
);
1417 if (DiagD
->isReferenced()) {
1418 Diag(DiagD
->getLocation(), diag::warn_unneeded_internal_decl
)
1419 << /*variable=*/1 << DiagD
<< DiagRange
;
1420 } else if (DiagD
->getDescribedVarTemplate()) {
1421 Diag(DiagD
->getLocation(), diag::warn_unused_template
)
1422 << /*variable=*/1 << DiagD
<< DiagRange
;
1423 } else if (DiagD
->getType().isConstQualified()) {
1424 const SourceManager
&SM
= SourceMgr
;
1425 if (SM
.getMainFileID() != SM
.getFileID(DiagD
->getLocation()) ||
1426 !PP
.getLangOpts().IsHeaderFile
)
1427 Diag(DiagD
->getLocation(), diag::warn_unused_const_variable
)
1428 << DiagD
<< DiagRange
;
1430 Diag(DiagD
->getLocation(), diag::warn_unused_variable
)
1431 << DiagD
<< DiagRange
;
1436 emitAndClearUnusedLocalTypedefWarnings();
1439 if (!Diags
.isIgnored(diag::warn_unused_private_field
, SourceLocation())) {
1440 // FIXME: Load additional unused private field candidates from the external
1442 RecordCompleteMap RecordsComplete
;
1443 RecordCompleteMap MNCComplete
;
1444 for (const NamedDecl
*D
: UnusedPrivateFields
) {
1445 const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
->getDeclContext());
1446 if (RD
&& !RD
->isUnion() &&
1447 IsRecordFullyDefined(RD
, RecordsComplete
, MNCComplete
)) {
1448 Diag(D
->getLocation(), diag::warn_unused_private_field
)
1449 << D
->getDeclName();
1454 if (!Diags
.isIgnored(diag::warn_mismatched_delete_new
, SourceLocation())) {
1456 ExternalSource
->ReadMismatchingDeleteExpressions(DeleteExprs
);
1457 for (const auto &DeletedFieldInfo
: DeleteExprs
) {
1458 for (const auto &DeleteExprLoc
: DeletedFieldInfo
.second
) {
1459 AnalyzeDeleteExprMismatch(DeletedFieldInfo
.first
, DeleteExprLoc
.first
,
1460 DeleteExprLoc
.second
);
1465 AnalysisWarnings
.IssueWarnings(Context
.getTranslationUnitDecl());
1467 // Check we've noticed that we're no longer parsing the initializer for every
1468 // variable. If we miss cases, then at best we have a performance issue and
1469 // at worst a rejects-valid bug.
1470 assert(ParsingInitForAutoVars
.empty() &&
1471 "Didn't unmark var as having its initializer parsed");
1473 if (!PP
.isIncrementalProcessingEnabled())
1478 //===----------------------------------------------------------------------===//
1479 // Helper functions.
1480 //===----------------------------------------------------------------------===//
1482 DeclContext
*Sema::getFunctionLevelDeclContext(bool AllowLambda
) const {
1483 DeclContext
*DC
= CurContext
;
1486 if (isa
<BlockDecl
>(DC
) || isa
<EnumDecl
>(DC
) || isa
<CapturedDecl
>(DC
) ||
1487 isa
<RequiresExprBodyDecl
>(DC
)) {
1488 DC
= DC
->getParent();
1489 } else if (!AllowLambda
&& isa
<CXXMethodDecl
>(DC
) &&
1490 cast
<CXXMethodDecl
>(DC
)->getOverloadedOperator() == OO_Call
&&
1491 cast
<CXXRecordDecl
>(DC
->getParent())->isLambda()) {
1492 DC
= DC
->getParent()->getParent();
1499 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1500 /// to the function decl for the function being parsed. If we're currently
1501 /// in a 'block', this returns the containing context.
1502 FunctionDecl
*Sema::getCurFunctionDecl(bool AllowLambda
) const {
1503 DeclContext
*DC
= getFunctionLevelDeclContext(AllowLambda
);
1504 return dyn_cast
<FunctionDecl
>(DC
);
1507 ObjCMethodDecl
*Sema::getCurMethodDecl() {
1508 DeclContext
*DC
= getFunctionLevelDeclContext();
1509 while (isa
<RecordDecl
>(DC
))
1510 DC
= DC
->getParent();
1511 return dyn_cast
<ObjCMethodDecl
>(DC
);
1514 NamedDecl
*Sema::getCurFunctionOrMethodDecl() const {
1515 DeclContext
*DC
= getFunctionLevelDeclContext();
1516 if (isa
<ObjCMethodDecl
>(DC
) || isa
<FunctionDecl
>(DC
))
1517 return cast
<NamedDecl
>(DC
);
1521 LangAS
Sema::getDefaultCXXMethodAddrSpace() const {
1522 if (getLangOpts().OpenCL
)
1523 return getASTContext().getDefaultOpenCLPointeeAddrSpace();
1524 return LangAS::Default
;
1527 void Sema::EmitCurrentDiagnostic(unsigned DiagID
) {
1528 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1529 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1530 // been made more painfully obvious by the refactor that introduced this
1531 // function, but it is possible that the incoming argument can be
1532 // eliminated. If it truly cannot be (for example, there is some reentrancy
1533 // issue I am not seeing yet), then there should at least be a clarifying
1534 // comment somewhere.
1535 if (std::optional
<TemplateDeductionInfo
*> Info
= isSFINAEContext()) {
1536 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1537 Diags
.getCurrentDiagID())) {
1538 case DiagnosticIDs::SFINAE_Report
:
1539 // We'll report the diagnostic below.
1542 case DiagnosticIDs::SFINAE_SubstitutionFailure
:
1543 // Count this failure so that we know that template argument deduction
1547 // Make a copy of this suppressed diagnostic and store it with the
1548 // template-deduction information.
1549 if (*Info
&& !(*Info
)->hasSFINAEDiagnostic()) {
1550 Diagnostic
DiagInfo(&Diags
);
1551 (*Info
)->addSFINAEDiagnostic(DiagInfo
.getLocation(),
1552 PartialDiagnostic(DiagInfo
, Context
.getDiagAllocator()));
1555 Diags
.setLastDiagnosticIgnored(true);
1559 case DiagnosticIDs::SFINAE_AccessControl
: {
1560 // Per C++ Core Issue 1170, access control is part of SFINAE.
1561 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1562 // make access control a part of SFINAE for the purposes of checking
1564 if (!AccessCheckingSFINAE
&& !getLangOpts().CPlusPlus11
)
1567 SourceLocation Loc
= Diags
.getCurrentDiagLoc();
1569 // Suppress this diagnostic.
1572 // Make a copy of this suppressed diagnostic and store it with the
1573 // template-deduction information.
1574 if (*Info
&& !(*Info
)->hasSFINAEDiagnostic()) {
1575 Diagnostic
DiagInfo(&Diags
);
1576 (*Info
)->addSFINAEDiagnostic(DiagInfo
.getLocation(),
1577 PartialDiagnostic(DiagInfo
, Context
.getDiagAllocator()));
1580 Diags
.setLastDiagnosticIgnored(true);
1583 // Now the diagnostic state is clear, produce a C++98 compatibility
1585 Diag(Loc
, diag::warn_cxx98_compat_sfinae_access_control
);
1587 // The last diagnostic which Sema produced was ignored. Suppress any
1588 // notes attached to it.
1589 Diags
.setLastDiagnosticIgnored(true);
1593 case DiagnosticIDs::SFINAE_Suppress
:
1594 // Make a copy of this suppressed diagnostic and store it with the
1595 // template-deduction information;
1597 Diagnostic
DiagInfo(&Diags
);
1598 (*Info
)->addSuppressedDiagnostic(DiagInfo
.getLocation(),
1599 PartialDiagnostic(DiagInfo
, Context
.getDiagAllocator()));
1602 // Suppress this diagnostic.
1603 Diags
.setLastDiagnosticIgnored(true);
1609 // Copy the diagnostic printing policy over the ASTContext printing policy.
1610 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
1611 Context
.setPrintingPolicy(getPrintingPolicy());
1613 // Emit the diagnostic.
1614 if (!Diags
.EmitCurrentDiagnostic())
1617 // If this is not a note, and we're in a template instantiation
1618 // that is different from the last template instantiation where
1619 // we emitted an error, print a template instantiation
1621 if (!DiagnosticIDs::isBuiltinNote(DiagID
))
1622 PrintContextStack();
1625 Sema::SemaDiagnosticBuilder
1626 Sema::Diag(SourceLocation Loc
, const PartialDiagnostic
&PD
, bool DeferHint
) {
1627 return Diag(Loc
, PD
.getDiagID(), DeferHint
) << PD
;
1630 bool Sema::hasUncompilableErrorOccurred() const {
1631 if (getDiagnostics().hasUncompilableErrorOccurred())
1633 auto *FD
= dyn_cast
<FunctionDecl
>(CurContext
);
1636 auto Loc
= DeviceDeferredDiags
.find(FD
);
1637 if (Loc
== DeviceDeferredDiags
.end())
1639 for (auto PDAt
: Loc
->second
) {
1640 if (DiagnosticIDs::isDefaultMappingAsError(PDAt
.second
.getDiagID()))
1646 // Print notes showing how we can reach FD starting from an a priori
1647 // known-callable function.
1648 static void emitCallStackNotes(Sema
&S
, const FunctionDecl
*FD
) {
1649 auto FnIt
= S
.DeviceKnownEmittedFns
.find(FD
);
1650 while (FnIt
!= S
.DeviceKnownEmittedFns
.end()) {
1651 // Respect error limit.
1652 if (S
.Diags
.hasFatalErrorOccurred())
1654 DiagnosticBuilder
Builder(
1655 S
.Diags
.Report(FnIt
->second
.Loc
, diag::note_called_by
));
1656 Builder
<< FnIt
->second
.FD
;
1657 FnIt
= S
.DeviceKnownEmittedFns
.find(FnIt
->second
.FD
);
1663 /// Helper class that emits deferred diagnostic messages if an entity directly
1664 /// or indirectly using the function that causes the deferred diagnostic
1665 /// messages is known to be emitted.
1667 /// During parsing of AST, certain diagnostic messages are recorded as deferred
1668 /// diagnostics since it is unknown whether the functions containing such
1669 /// diagnostics will be emitted. A list of potentially emitted functions and
1670 /// variables that may potentially trigger emission of functions are also
1671 /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1672 /// by each function to emit deferred diagnostics.
1674 /// During the visit, certain OpenMP directives or initializer of variables
1675 /// with certain OpenMP attributes will cause subsequent visiting of any
1676 /// functions enter a state which is called OpenMP device context in this
1677 /// implementation. The state is exited when the directive or initializer is
1678 /// exited. This state can change the emission states of subsequent uses
1681 /// Conceptually the functions or variables to be visited form a use graph
1682 /// where the parent node uses the child node. At any point of the visit,
1683 /// the tree nodes traversed from the tree root to the current node form a use
1684 /// stack. The emission state of the current node depends on two factors:
1685 /// 1. the emission state of the root node
1686 /// 2. whether the current node is in OpenMP device context
1687 /// If the function is decided to be emitted, its contained deferred diagnostics
1688 /// are emitted, together with the information about the use stack.
1690 class DeferredDiagnosticsEmitter
1691 : public UsedDeclVisitor
<DeferredDiagnosticsEmitter
> {
1693 typedef UsedDeclVisitor
<DeferredDiagnosticsEmitter
> Inherited
;
1695 // Whether the function is already in the current use-path.
1696 llvm::SmallPtrSet
<CanonicalDeclPtr
<Decl
>, 4> InUsePath
;
1698 // The current use-path.
1699 llvm::SmallVector
<CanonicalDeclPtr
<FunctionDecl
>, 4> UsePath
;
1701 // Whether the visiting of the function has been done. Done[0] is for the
1702 // case not in OpenMP device context. Done[1] is for the case in OpenMP
1703 // device context. We need two sets because diagnostics emission may be
1704 // different depending on whether it is in OpenMP device context.
1705 llvm::SmallPtrSet
<CanonicalDeclPtr
<Decl
>, 4> DoneMap
[2];
1707 // Emission state of the root node of the current use graph.
1708 bool ShouldEmitRootNode
;
1710 // Current OpenMP device context level. It is initialized to 0 and each
1711 // entering of device context increases it by 1 and each exit decreases
1712 // it by 1. Non-zero value indicates it is currently in device context.
1713 unsigned InOMPDeviceContext
;
1715 DeferredDiagnosticsEmitter(Sema
&S
)
1716 : Inherited(S
), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1718 bool shouldVisitDiscardedStmt() const { return false; }
1720 void VisitOMPTargetDirective(OMPTargetDirective
*Node
) {
1721 ++InOMPDeviceContext
;
1722 Inherited::VisitOMPTargetDirective(Node
);
1723 --InOMPDeviceContext
;
1726 void visitUsedDecl(SourceLocation Loc
, Decl
*D
) {
1727 if (isa
<VarDecl
>(D
))
1729 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
))
1732 Inherited::visitUsedDecl(Loc
, D
);
1735 void checkVar(VarDecl
*VD
) {
1736 assert(VD
->isFileVarDecl() &&
1737 "Should only check file-scope variables");
1738 if (auto *Init
= VD
->getInit()) {
1739 auto DevTy
= OMPDeclareTargetDeclAttr::getDeviceType(VD
);
1740 bool IsDev
= DevTy
&& (*DevTy
== OMPDeclareTargetDeclAttr::DT_NoHost
||
1741 *DevTy
== OMPDeclareTargetDeclAttr::DT_Any
);
1743 ++InOMPDeviceContext
;
1746 --InOMPDeviceContext
;
1750 void checkFunc(SourceLocation Loc
, FunctionDecl
*FD
) {
1751 auto &Done
= DoneMap
[InOMPDeviceContext
> 0 ? 1 : 0];
1752 FunctionDecl
*Caller
= UsePath
.empty() ? nullptr : UsePath
.back();
1753 if ((!ShouldEmitRootNode
&& !S
.getLangOpts().OpenMP
&& !Caller
) ||
1754 S
.shouldIgnoreInHostDeviceCheck(FD
) || InUsePath
.count(FD
))
1756 // Finalize analysis of OpenMP-specific constructs.
1757 if (Caller
&& S
.LangOpts
.OpenMP
&& UsePath
.size() == 1 &&
1758 (ShouldEmitRootNode
|| InOMPDeviceContext
))
1759 S
.finalizeOpenMPDelayedAnalysis(Caller
, FD
, Loc
);
1761 S
.DeviceKnownEmittedFns
[FD
] = {Caller
, Loc
};
1762 // Always emit deferred diagnostics for the direct users. This does not
1763 // lead to explosion of diagnostics since each user is visited at most
1765 if (ShouldEmitRootNode
|| InOMPDeviceContext
)
1766 emitDeferredDiags(FD
, Caller
);
1767 // Do not revisit a function if the function body has been completely
1769 if (!Done
.insert(FD
).second
)
1771 InUsePath
.insert(FD
);
1772 UsePath
.push_back(FD
);
1773 if (auto *S
= FD
->getBody()) {
1777 InUsePath
.erase(FD
);
1780 void checkRecordedDecl(Decl
*D
) {
1781 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
1782 ShouldEmitRootNode
= S
.getEmissionStatus(FD
, /*Final=*/true) ==
1783 Sema::FunctionEmissionStatus::Emitted
;
1784 checkFunc(SourceLocation(), FD
);
1786 checkVar(cast
<VarDecl
>(D
));
1789 // Emit any deferred diagnostics for FD
1790 void emitDeferredDiags(FunctionDecl
*FD
, bool ShowCallStack
) {
1791 auto It
= S
.DeviceDeferredDiags
.find(FD
);
1792 if (It
== S
.DeviceDeferredDiags
.end())
1794 bool HasWarningOrError
= false;
1795 bool FirstDiag
= true;
1796 for (PartialDiagnosticAt
&PDAt
: It
->second
) {
1797 // Respect error limit.
1798 if (S
.Diags
.hasFatalErrorOccurred())
1800 const SourceLocation
&Loc
= PDAt
.first
;
1801 const PartialDiagnostic
&PD
= PDAt
.second
;
1802 HasWarningOrError
|=
1803 S
.getDiagnostics().getDiagnosticLevel(PD
.getDiagID(), Loc
) >=
1804 DiagnosticsEngine::Warning
;
1806 DiagnosticBuilder
Builder(S
.Diags
.Report(Loc
, PD
.getDiagID()));
1809 // Emit the note on the first diagnostic in case too many diagnostics
1810 // cause the note not emitted.
1811 if (FirstDiag
&& HasWarningOrError
&& ShowCallStack
) {
1812 emitCallStackNotes(S
, FD
);
1820 void Sema::emitDeferredDiags() {
1822 ExternalSource
->ReadDeclsToCheckForDeferredDiags(
1823 DeclsToCheckForDeferredDiags
);
1825 if ((DeviceDeferredDiags
.empty() && !LangOpts
.OpenMP
) ||
1826 DeclsToCheckForDeferredDiags
.empty())
1829 DeferredDiagnosticsEmitter
DDE(*this);
1830 for (auto *D
: DeclsToCheckForDeferredDiags
)
1831 DDE
.checkRecordedDecl(D
);
1834 // In CUDA, there are some constructs which may appear in semantically-valid
1835 // code, but trigger errors if we ever generate code for the function in which
1836 // they appear. Essentially every construct you're not allowed to use on the
1837 // device falls into this category, because you are allowed to use these
1838 // constructs in a __host__ __device__ function, but only if that function is
1839 // never codegen'ed on the device.
1841 // To handle semantic checking for these constructs, we keep track of the set of
1842 // functions we know will be emitted, either because we could tell a priori that
1843 // they would be emitted, or because they were transitively called by a
1844 // known-emitted function.
1846 // We also keep a partial call graph of which not-known-emitted functions call
1847 // which other not-known-emitted functions.
1849 // When we see something which is illegal if the current function is emitted
1850 // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1851 // CheckCUDACall), we first check if the current function is known-emitted. If
1852 // so, we immediately output the diagnostic.
1854 // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
1855 // until we discover that the function is known-emitted, at which point we take
1856 // it out of this map and emit the diagnostic.
1858 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K
, SourceLocation Loc
,
1860 const FunctionDecl
*Fn
,
1862 : S(S
), Loc(Loc
), DiagID(DiagID
), Fn(Fn
),
1863 ShowCallStack(K
== K_ImmediateWithCallStack
|| K
== K_Deferred
) {
1868 case K_ImmediateWithCallStack
:
1869 ImmediateDiag
.emplace(
1870 ImmediateDiagBuilder(S
.Diags
.Report(Loc
, DiagID
), S
, DiagID
));
1873 assert(Fn
&& "Must have a function to attach the deferred diag to.");
1874 auto &Diags
= S
.DeviceDeferredDiags
[Fn
];
1875 PartialDiagId
.emplace(Diags
.size());
1876 Diags
.emplace_back(Loc
, S
.PDiag(DiagID
));
1881 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder
&&D
)
1882 : S(D
.S
), Loc(D
.Loc
), DiagID(D
.DiagID
), Fn(D
.Fn
),
1883 ShowCallStack(D
.ShowCallStack
), ImmediateDiag(D
.ImmediateDiag
),
1884 PartialDiagId(D
.PartialDiagId
) {
1885 // Clean the previous diagnostics.
1886 D
.ShowCallStack
= false;
1887 D
.ImmediateDiag
.reset();
1888 D
.PartialDiagId
.reset();
1891 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
1892 if (ImmediateDiag
) {
1893 // Emit our diagnostic and, if it was a warning or error, output a callstack
1894 // if Fn isn't a priori known-emitted.
1895 bool IsWarningOrError
= S
.getDiagnostics().getDiagnosticLevel(
1896 DiagID
, Loc
) >= DiagnosticsEngine::Warning
;
1897 ImmediateDiag
.reset(); // Emit the immediate diag.
1898 if (IsWarningOrError
&& ShowCallStack
)
1899 emitCallStackNotes(S
, Fn
);
1901 assert((!PartialDiagId
|| ShowCallStack
) &&
1902 "Must always show call stack for deferred diags.");
1906 Sema::SemaDiagnosticBuilder
1907 Sema::targetDiag(SourceLocation Loc
, unsigned DiagID
, const FunctionDecl
*FD
) {
1908 FD
= FD
? FD
: getCurFunctionDecl();
1909 if (LangOpts
.OpenMP
)
1910 return LangOpts
.OpenMPIsTargetDevice
1911 ? diagIfOpenMPDeviceCode(Loc
, DiagID
, FD
)
1912 : diagIfOpenMPHostCode(Loc
, DiagID
, FD
);
1913 if (getLangOpts().CUDA
)
1914 return getLangOpts().CUDAIsDevice
? CUDADiagIfDeviceCode(Loc
, DiagID
)
1915 : CUDADiagIfHostCode(Loc
, DiagID
);
1917 if (getLangOpts().SYCLIsDevice
)
1918 return SYCLDiagIfDeviceCode(Loc
, DiagID
);
1920 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate
, Loc
, DiagID
,
1924 Sema::SemaDiagnosticBuilder
Sema::Diag(SourceLocation Loc
, unsigned DiagID
,
1926 bool IsError
= Diags
.getDiagnosticIDs()->isDefaultMappingAsError(DiagID
);
1927 bool ShouldDefer
= getLangOpts().CUDA
&& LangOpts
.GPUDeferDiag
&&
1928 DiagnosticIDs::isDeferrable(DiagID
) &&
1929 (DeferHint
|| DeferDiags
|| !IsError
);
1930 auto SetIsLastErrorImmediate
= [&](bool Flag
) {
1932 IsLastErrorImmediate
= Flag
;
1935 SetIsLastErrorImmediate(true);
1936 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate
, Loc
,
1937 DiagID
, getCurFunctionDecl(), *this);
1940 SemaDiagnosticBuilder DB
= getLangOpts().CUDAIsDevice
1941 ? CUDADiagIfDeviceCode(Loc
, DiagID
)
1942 : CUDADiagIfHostCode(Loc
, DiagID
);
1943 SetIsLastErrorImmediate(DB
.isImmediate());
1947 void Sema::checkTypeSupport(QualType Ty
, SourceLocation Loc
, ValueDecl
*D
) {
1948 if (isUnevaluatedContext() || Ty
.isNull())
1951 // The original idea behind checkTypeSupport function is that unused
1952 // declarations can be replaced with an array of bytes of the same size during
1953 // codegen, such replacement doesn't seem to be possible for types without
1954 // constant byte size like zero length arrays. So, do a deep check for SYCL.
1955 if (D
&& LangOpts
.SYCLIsDevice
) {
1956 llvm::DenseSet
<QualType
> Visited
;
1957 deepTypeCheckForSYCLDevice(Loc
, Visited
, D
);
1960 Decl
*C
= cast
<Decl
>(getCurLexicalContext());
1962 // Memcpy operations for structs containing a member with unsupported type
1964 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(C
)) {
1965 if ((MD
->isCopyAssignmentOperator() || MD
->isMoveAssignmentOperator()) &&
1969 if (const auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(MD
))
1970 if (Ctor
->isCopyOrMoveConstructor() && Ctor
->isTrivial())
1974 // Try to associate errors with the lexical context, if that is a function, or
1975 // the value declaration otherwise.
1976 const FunctionDecl
*FD
= isa
<FunctionDecl
>(C
)
1977 ? cast
<FunctionDecl
>(C
)
1978 : dyn_cast_or_null
<FunctionDecl
>(D
);
1980 auto CheckDeviceType
= [&](QualType Ty
) {
1981 if (Ty
->isDependentType())
1984 if (Ty
->isBitIntType()) {
1985 if (!Context
.getTargetInfo().hasBitIntType()) {
1986 PartialDiagnostic PD
= PDiag(diag::err_target_unsupported_type
);
1991 targetDiag(Loc
, PD
, FD
)
1992 << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
1993 << Ty
<< Context
.getTargetInfo().getTriple().str();
1998 // Check if we are dealing with two 'long double' but with different
2000 bool LongDoubleMismatched
= false;
2001 if (Ty
->isRealFloatingType() && Context
.getTypeSize(Ty
) == 128) {
2002 const llvm::fltSemantics
&Sem
= Context
.getFloatTypeSemantics(Ty
);
2003 if ((&Sem
!= &llvm::APFloat::PPCDoubleDouble() &&
2004 !Context
.getTargetInfo().hasFloat128Type()) ||
2005 (&Sem
== &llvm::APFloat::PPCDoubleDouble() &&
2006 !Context
.getTargetInfo().hasIbm128Type()))
2007 LongDoubleMismatched
= true;
2010 if ((Ty
->isFloat16Type() && !Context
.getTargetInfo().hasFloat16Type()) ||
2011 (Ty
->isFloat128Type() && !Context
.getTargetInfo().hasFloat128Type()) ||
2012 (Ty
->isIbm128Type() && !Context
.getTargetInfo().hasIbm128Type()) ||
2013 (Ty
->isIntegerType() && Context
.getTypeSize(Ty
) == 128 &&
2014 !Context
.getTargetInfo().hasInt128Type()) ||
2015 (Ty
->isBFloat16Type() && !Context
.getTargetInfo().hasBFloat16Type() &&
2016 !LangOpts
.CUDAIsDevice
) ||
2017 LongDoubleMismatched
) {
2018 PartialDiagnostic PD
= PDiag(diag::err_target_unsupported_type
);
2024 if (targetDiag(Loc
, PD
, FD
)
2025 << true /*show bit size*/
2026 << static_cast<unsigned>(Context
.getTypeSize(Ty
)) << Ty
2027 << false /*return*/ << Context
.getTargetInfo().getTriple().str()) {
2029 D
->setInvalidDecl();
2032 targetDiag(D
->getLocation(), diag::note_defined_here
, FD
) << D
;
2036 auto CheckType
= [&](QualType Ty
, bool IsRetTy
= false) {
2037 if (LangOpts
.SYCLIsDevice
||
2038 (LangOpts
.OpenMP
&& LangOpts
.OpenMPIsTargetDevice
) ||
2039 LangOpts
.CUDAIsDevice
)
2040 CheckDeviceType(Ty
);
2042 QualType UnqualTy
= Ty
.getCanonicalType().getUnqualifiedType();
2043 const TargetInfo
&TI
= Context
.getTargetInfo();
2044 if (!TI
.hasLongDoubleType() && UnqualTy
== Context
.LongDoubleTy
) {
2045 PartialDiagnostic PD
= PDiag(diag::err_target_unsupported_type
);
2051 if (Diag(Loc
, PD
, FD
)
2052 << false /*show bit size*/ << 0 << Ty
<< false /*return*/
2053 << TI
.getTriple().str()) {
2055 D
->setInvalidDecl();
2058 targetDiag(D
->getLocation(), diag::note_defined_here
, FD
) << D
;
2061 bool IsDouble
= UnqualTy
== Context
.DoubleTy
;
2062 bool IsFloat
= UnqualTy
== Context
.FloatTy
;
2063 if (IsRetTy
&& !TI
.hasFPReturn() && (IsDouble
|| IsFloat
)) {
2064 PartialDiagnostic PD
= PDiag(diag::err_target_unsupported_type
);
2070 if (Diag(Loc
, PD
, FD
)
2071 << false /*show bit size*/ << 0 << Ty
<< true /*return*/
2072 << TI
.getTriple().str()) {
2074 D
->setInvalidDecl();
2077 targetDiag(D
->getLocation(), diag::note_defined_here
, FD
) << D
;
2080 if (TI
.hasRISCVVTypes() && Ty
->isRVVType())
2081 checkRVVTypeSupport(Ty
, Loc
, D
);
2083 // Don't allow SVE types in functions without a SVE target.
2084 if (Ty
->isSVESizelessBuiltinType() && FD
&& FD
->hasBody()) {
2085 llvm::StringMap
<bool> CallerFeatureMap
;
2086 Context
.getFunctionFeatureMap(CallerFeatureMap
, FD
);
2087 if (!Builtin::evaluateRequiredTargetFeatures(
2088 "sve", CallerFeatureMap
))
2089 Diag(D
->getLocation(), diag::err_sve_vector_in_non_sve_target
) << Ty
;
2094 if (const auto *FPTy
= dyn_cast
<FunctionProtoType
>(Ty
)) {
2095 for (const auto &ParamTy
: FPTy
->param_types())
2097 CheckType(FPTy
->getReturnType(), /*IsRetTy=*/true);
2099 if (const auto *FNPTy
= dyn_cast
<FunctionNoProtoType
>(Ty
))
2100 CheckType(FNPTy
->getReturnType(), /*IsRetTy=*/true);
2103 /// Looks through the macro-expansion chain for the given
2104 /// location, looking for a macro expansion with the given name.
2105 /// If one is found, returns true and sets the location to that
2107 bool Sema::findMacroSpelling(SourceLocation
&locref
, StringRef name
) {
2108 SourceLocation loc
= locref
;
2109 if (!loc
.isMacroID()) return false;
2111 // There's no good way right now to look at the intermediate
2112 // expansions, so just jump to the expansion location.
2113 loc
= getSourceManager().getExpansionLoc(loc
);
2115 // If that's written with the name, stop here.
2116 SmallString
<16> buffer
;
2117 if (getPreprocessor().getSpelling(loc
, buffer
) == name
) {
2124 /// Determines the active Scope associated with the given declaration
2127 /// This routine maps a declaration context to the active Scope object that
2128 /// represents that declaration context in the parser. It is typically used
2129 /// from "scope-less" code (e.g., template instantiation, lazy creation of
2130 /// declarations) that injects a name for name-lookup purposes and, therefore,
2131 /// must update the Scope.
2133 /// \returns The scope corresponding to the given declaraion context, or NULL
2134 /// if no such scope is open.
2135 Scope
*Sema::getScopeForContext(DeclContext
*Ctx
) {
2140 Ctx
= Ctx
->getPrimaryContext();
2141 for (Scope
*S
= getCurScope(); S
; S
= S
->getParent()) {
2142 // Ignore scopes that cannot have declarations. This is important for
2143 // out-of-line definitions of static class members.
2144 if (S
->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope
))
2145 if (DeclContext
*Entity
= S
->getEntity())
2146 if (Ctx
== Entity
->getPrimaryContext())
2153 /// Enter a new function scope
2154 void Sema::PushFunctionScope() {
2155 if (FunctionScopes
.empty() && CachedFunctionScope
) {
2156 // Use CachedFunctionScope to avoid allocating memory when possible.
2157 CachedFunctionScope
->Clear();
2158 FunctionScopes
.push_back(CachedFunctionScope
.release());
2160 FunctionScopes
.push_back(new FunctionScopeInfo(getDiagnostics()));
2162 if (LangOpts
.OpenMP
)
2163 pushOpenMPFunctionRegion();
2166 void Sema::PushBlockScope(Scope
*BlockScope
, BlockDecl
*Block
) {
2167 FunctionScopes
.push_back(new BlockScopeInfo(getDiagnostics(),
2168 BlockScope
, Block
));
2169 CapturingFunctionScopes
++;
2172 LambdaScopeInfo
*Sema::PushLambdaScope() {
2173 LambdaScopeInfo
*const LSI
= new LambdaScopeInfo(getDiagnostics());
2174 FunctionScopes
.push_back(LSI
);
2175 CapturingFunctionScopes
++;
2179 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth
) {
2180 if (LambdaScopeInfo
*const LSI
= getCurLambda()) {
2181 LSI
->AutoTemplateParameterDepth
= Depth
;
2185 "Remove assertion if intentionally called in a non-lambda context.");
2188 // Check that the type of the VarDecl has an accessible copy constructor and
2189 // resolve its destructor's exception specification.
2190 // This also performs initialization of block variables when they are moved
2191 // to the heap. It uses the same rules as applicable for implicit moves
2192 // according to the C++ standard in effect ([class.copy.elision]p3).
2193 static void checkEscapingByref(VarDecl
*VD
, Sema
&S
) {
2194 QualType T
= VD
->getType();
2195 EnterExpressionEvaluationContext
scope(
2196 S
, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
2197 SourceLocation Loc
= VD
->getLocation();
2199 new (S
.Context
) DeclRefExpr(S
.Context
, VD
, false, T
, VK_LValue
, Loc
);
2201 auto IE
= InitializedEntity::InitializeBlock(Loc
, T
);
2202 if (S
.getLangOpts().CPlusPlus23
) {
2203 auto *E
= ImplicitCastExpr::Create(S
.Context
, T
, CK_NoOp
, VarRef
, nullptr,
2204 VK_XValue
, FPOptionsOverride());
2205 Result
= S
.PerformCopyInitialization(IE
, SourceLocation(), E
);
2207 Result
= S
.PerformMoveOrCopyInitialization(
2208 IE
, Sema::NamedReturnInfo
{VD
, Sema::NamedReturnInfo::MoveEligible
},
2212 if (!Result
.isInvalid()) {
2213 Result
= S
.MaybeCreateExprWithCleanups(Result
);
2214 Expr
*Init
= Result
.getAs
<Expr
>();
2215 S
.Context
.setBlockVarCopyInit(VD
, Init
, S
.canThrow(Init
));
2218 // The destructor's exception specification is needed when IRGen generates
2219 // block copy/destroy functions. Resolve it here.
2220 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
2221 if (CXXDestructorDecl
*DD
= RD
->getDestructor()) {
2222 auto *FPT
= DD
->getType()->getAs
<FunctionProtoType
>();
2223 S
.ResolveExceptionSpec(Loc
, FPT
);
2227 static void markEscapingByrefs(const FunctionScopeInfo
&FSI
, Sema
&S
) {
2228 // Set the EscapingByref flag of __block variables captured by
2230 for (const BlockDecl
*BD
: FSI
.Blocks
) {
2231 for (const BlockDecl::Capture
&BC
: BD
->captures()) {
2232 VarDecl
*VD
= BC
.getVariable();
2233 if (VD
->hasAttr
<BlocksAttr
>()) {
2234 // Nothing to do if this is a __block variable captured by a
2235 // non-escaping block.
2236 if (BD
->doesNotEscape())
2238 VD
->setEscapingByref();
2240 // Check whether the captured variable is or contains an object of
2241 // non-trivial C union type.
2242 QualType CapType
= BC
.getVariable()->getType();
2243 if (CapType
.hasNonTrivialToPrimitiveDestructCUnion() ||
2244 CapType
.hasNonTrivialToPrimitiveCopyCUnion())
2245 S
.checkNonTrivialCUnion(BC
.getVariable()->getType(),
2246 BD
->getCaretLocation(),
2247 Sema::NTCUC_BlockCapture
,
2248 Sema::NTCUK_Destruct
|Sema::NTCUK_Copy
);
2252 for (VarDecl
*VD
: FSI
.ByrefBlockVars
) {
2253 // __block variables might require us to capture a copy-initializer.
2254 if (!VD
->isEscapingByref())
2256 // It's currently invalid to ever have a __block variable with an
2257 // array type; should we diagnose that here?
2258 // Regardless, we don't want to ignore array nesting when
2259 // constructing this copy.
2260 if (VD
->getType()->isStructureOrClassType())
2261 checkEscapingByref(VD
, S
);
2265 /// Pop a function (or block or lambda or captured region) scope from the stack.
2267 /// \param WP The warning policy to use for CFG-based warnings, or null if such
2268 /// warnings should not be produced.
2269 /// \param D The declaration corresponding to this function scope, if producing
2270 /// CFG-based warnings.
2271 /// \param BlockType The type of the block expression, if D is a BlockDecl.
2272 Sema::PoppedFunctionScopePtr
2273 Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy
*WP
,
2274 const Decl
*D
, QualType BlockType
) {
2275 assert(!FunctionScopes
.empty() && "mismatched push/pop!");
2277 markEscapingByrefs(*FunctionScopes
.back(), *this);
2279 PoppedFunctionScopePtr
Scope(FunctionScopes
.pop_back_val(),
2280 PoppedFunctionScopeDeleter(this));
2282 if (LangOpts
.OpenMP
)
2283 popOpenMPFunctionRegion(Scope
.get());
2285 // Issue any analysis-based warnings.
2287 AnalysisWarnings
.IssueWarnings(*WP
, Scope
.get(), D
, BlockType
);
2289 for (const auto &PUD
: Scope
->PossiblyUnreachableDiags
)
2290 Diag(PUD
.Loc
, PUD
.PD
);
2295 void Sema::PoppedFunctionScopeDeleter::
2296 operator()(sema::FunctionScopeInfo
*Scope
) const {
2297 if (!Scope
->isPlainFunction())
2298 Self
->CapturingFunctionScopes
--;
2299 // Stash the function scope for later reuse if it's for a normal function.
2300 if (Scope
->isPlainFunction() && !Self
->CachedFunctionScope
)
2301 Self
->CachedFunctionScope
.reset(Scope
);
2306 void Sema::PushCompoundScope(bool IsStmtExpr
) {
2307 getCurFunction()->CompoundScopes
.push_back(
2308 CompoundScopeInfo(IsStmtExpr
, getCurFPFeatures()));
2311 void Sema::PopCompoundScope() {
2312 FunctionScopeInfo
*CurFunction
= getCurFunction();
2313 assert(!CurFunction
->CompoundScopes
.empty() && "mismatched push/pop");
2315 CurFunction
->CompoundScopes
.pop_back();
2318 /// Determine whether any errors occurred within this function/method/
2320 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2321 return getCurFunction()->hasUnrecoverableErrorOccurred();
2324 void Sema::setFunctionHasBranchIntoScope() {
2325 if (!FunctionScopes
.empty())
2326 FunctionScopes
.back()->setHasBranchIntoScope();
2329 void Sema::setFunctionHasBranchProtectedScope() {
2330 if (!FunctionScopes
.empty())
2331 FunctionScopes
.back()->setHasBranchProtectedScope();
2334 void Sema::setFunctionHasIndirectGoto() {
2335 if (!FunctionScopes
.empty())
2336 FunctionScopes
.back()->setHasIndirectGoto();
2339 void Sema::setFunctionHasMustTail() {
2340 if (!FunctionScopes
.empty())
2341 FunctionScopes
.back()->setHasMustTail();
2344 BlockScopeInfo
*Sema::getCurBlock() {
2345 if (FunctionScopes
.empty())
2348 auto CurBSI
= dyn_cast
<BlockScopeInfo
>(FunctionScopes
.back());
2349 if (CurBSI
&& CurBSI
->TheDecl
&&
2350 !CurBSI
->TheDecl
->Encloses(CurContext
)) {
2351 // We have switched contexts due to template instantiation.
2352 assert(!CodeSynthesisContexts
.empty());
2359 FunctionScopeInfo
*Sema::getEnclosingFunction() const {
2360 if (FunctionScopes
.empty())
2363 for (int e
= FunctionScopes
.size() - 1; e
>= 0; --e
) {
2364 if (isa
<sema::BlockScopeInfo
>(FunctionScopes
[e
]))
2366 return FunctionScopes
[e
];
2371 LambdaScopeInfo
*Sema::getEnclosingLambda() const {
2372 for (auto *Scope
: llvm::reverse(FunctionScopes
)) {
2373 if (auto *LSI
= dyn_cast
<sema::LambdaScopeInfo
>(Scope
)) {
2374 if (LSI
->Lambda
&& !LSI
->Lambda
->Encloses(CurContext
) &&
2375 LSI
->AfterParameterList
) {
2376 // We have switched contexts due to template instantiation.
2377 // FIXME: We should swap out the FunctionScopes during code synthesis
2378 // so that we don't need to check for this.
2379 assert(!CodeSynthesisContexts
.empty());
2388 LambdaScopeInfo
*Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope
) {
2389 if (FunctionScopes
.empty())
2392 auto I
= FunctionScopes
.rbegin();
2393 if (IgnoreNonLambdaCapturingScope
) {
2394 auto E
= FunctionScopes
.rend();
2395 while (I
!= E
&& isa
<CapturingScopeInfo
>(*I
) && !isa
<LambdaScopeInfo
>(*I
))
2400 auto *CurLSI
= dyn_cast
<LambdaScopeInfo
>(*I
);
2401 if (CurLSI
&& CurLSI
->Lambda
&& CurLSI
->CallOperator
&&
2402 !CurLSI
->Lambda
->Encloses(CurContext
) && CurLSI
->AfterParameterList
) {
2403 // We have switched contexts due to template instantiation.
2404 assert(!CodeSynthesisContexts
.empty());
2411 // We have a generic lambda if we parsed auto parameters, or we have
2412 // an associated template parameter list.
2413 LambdaScopeInfo
*Sema::getCurGenericLambda() {
2414 if (LambdaScopeInfo
*LSI
= getCurLambda()) {
2415 return (LSI
->TemplateParams
.size() ||
2416 LSI
->GLTemplateParameterList
) ? LSI
: nullptr;
2422 void Sema::ActOnComment(SourceRange Comment
) {
2423 if (!LangOpts
.RetainCommentsFromSystemHeaders
&&
2424 SourceMgr
.isInSystemHeader(Comment
.getBegin()))
2426 RawComment
RC(SourceMgr
, Comment
, LangOpts
.CommentOpts
, false);
2427 if (RC
.isAlmostTrailingComment() || RC
.hasUnsupportedSplice(SourceMgr
)) {
2428 SourceRange
MagicMarkerRange(Comment
.getBegin(),
2429 Comment
.getBegin().getLocWithOffset(3));
2430 StringRef MagicMarkerText
;
2431 switch (RC
.getKind()) {
2432 case RawComment::RCK_OrdinaryBCPL
:
2433 MagicMarkerText
= "///<";
2435 case RawComment::RCK_OrdinaryC
:
2436 MagicMarkerText
= "/**<";
2438 case RawComment::RCK_Invalid
:
2439 // FIXME: are there other scenarios that could produce an invalid
2440 // raw comment here?
2441 Diag(Comment
.getBegin(), diag::warn_splice_in_doxygen_comment
);
2444 llvm_unreachable("if this is an almost Doxygen comment, "
2445 "it should be ordinary");
2447 Diag(Comment
.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment
) <<
2448 FixItHint::CreateReplacement(MagicMarkerRange
, MagicMarkerText
);
2450 Context
.addComment(RC
);
2453 // Pin this vtable to this file.
2454 ExternalSemaSource::~ExternalSemaSource() {}
2455 char ExternalSemaSource::ID
;
2457 void ExternalSemaSource::ReadMethodPool(Selector Sel
) { }
2458 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel
) { }
2460 void ExternalSemaSource::ReadKnownNamespaces(
2461 SmallVectorImpl
<NamespaceDecl
*> &Namespaces
) {
2464 void ExternalSemaSource::ReadUndefinedButUsed(
2465 llvm::MapVector
<NamedDecl
*, SourceLocation
> &Undefined
) {}
2467 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector
<
2468 FieldDecl
*, llvm::SmallVector
<std::pair
<SourceLocation
, bool>, 4>> &) {}
2470 /// Figure out if an expression could be turned into a call.
2472 /// Use this when trying to recover from an error where the programmer may have
2473 /// written just the name of a function instead of actually calling it.
2475 /// \param E - The expression to examine.
2476 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
2477 /// with no arguments, this parameter is set to the type returned by such a
2478 /// call; otherwise, it is set to an empty QualType.
2479 /// \param OverloadSet - If the expression is an overloaded function
2480 /// name, this parameter is populated with the decls of the various overloads.
2481 bool Sema::tryExprAsCall(Expr
&E
, QualType
&ZeroArgCallReturnTy
,
2482 UnresolvedSetImpl
&OverloadSet
) {
2483 ZeroArgCallReturnTy
= QualType();
2484 OverloadSet
.clear();
2486 const OverloadExpr
*Overloads
= nullptr;
2487 bool IsMemExpr
= false;
2488 if (E
.getType() == Context
.OverloadTy
) {
2489 OverloadExpr::FindResult FR
= OverloadExpr::find(const_cast<Expr
*>(&E
));
2491 // Ignore overloads that are pointer-to-member constants.
2492 if (FR
.HasFormOfMemberPointer
)
2495 Overloads
= FR
.Expression
;
2496 } else if (E
.getType() == Context
.BoundMemberTy
) {
2497 Overloads
= dyn_cast
<UnresolvedMemberExpr
>(E
.IgnoreParens());
2501 bool Ambiguous
= false;
2505 for (OverloadExpr::decls_iterator it
= Overloads
->decls_begin(),
2506 DeclsEnd
= Overloads
->decls_end(); it
!= DeclsEnd
; ++it
) {
2507 OverloadSet
.addDecl(*it
);
2509 // Check whether the function is a non-template, non-member which takes no
2513 if (const FunctionDecl
*OverloadDecl
2514 = dyn_cast
<FunctionDecl
>((*it
)->getUnderlyingDecl())) {
2515 if (OverloadDecl
->getMinRequiredArguments() == 0) {
2516 if (!ZeroArgCallReturnTy
.isNull() && !Ambiguous
&&
2517 (!IsMV
|| !(OverloadDecl
->isCPUDispatchMultiVersion() ||
2518 OverloadDecl
->isCPUSpecificMultiVersion()))) {
2519 ZeroArgCallReturnTy
= QualType();
2522 ZeroArgCallReturnTy
= OverloadDecl
->getReturnType();
2523 IsMV
= OverloadDecl
->isCPUDispatchMultiVersion() ||
2524 OverloadDecl
->isCPUSpecificMultiVersion();
2530 // If it's not a member, use better machinery to try to resolve the call
2532 return !ZeroArgCallReturnTy
.isNull();
2535 // Attempt to call the member with no arguments - this will correctly handle
2536 // member templates with defaults/deduction of template arguments, overloads
2537 // with default arguments, etc.
2538 if (IsMemExpr
&& !E
.isTypeDependent()) {
2539 Sema::TentativeAnalysisScope
Trap(*this);
2540 ExprResult R
= BuildCallToMemberFunction(nullptr, &E
, SourceLocation(),
2541 std::nullopt
, SourceLocation());
2543 ZeroArgCallReturnTy
= R
.get()->getType();
2549 if (const auto *DeclRef
= dyn_cast
<DeclRefExpr
>(E
.IgnoreParens())) {
2550 if (const auto *Fun
= dyn_cast
<FunctionDecl
>(DeclRef
->getDecl())) {
2551 if (Fun
->getMinRequiredArguments() == 0)
2552 ZeroArgCallReturnTy
= Fun
->getReturnType();
2557 // We don't have an expression that's convenient to get a FunctionDecl from,
2558 // but we can at least check if the type is "function of 0 arguments".
2559 QualType ExprTy
= E
.getType();
2560 const FunctionType
*FunTy
= nullptr;
2561 QualType PointeeTy
= ExprTy
->getPointeeType();
2562 if (!PointeeTy
.isNull())
2563 FunTy
= PointeeTy
->getAs
<FunctionType
>();
2565 FunTy
= ExprTy
->getAs
<FunctionType
>();
2567 if (const auto *FPT
= dyn_cast_if_present
<FunctionProtoType
>(FunTy
)) {
2568 if (FPT
->getNumParams() == 0)
2569 ZeroArgCallReturnTy
= FunTy
->getReturnType();
2575 /// Give notes for a set of overloads.
2577 /// A companion to tryExprAsCall. In cases when the name that the programmer
2578 /// wrote was an overloaded function, we may be able to make some guesses about
2579 /// plausible overloads based on their return types; such guesses can be handed
2580 /// off to this method to be emitted as notes.
2582 /// \param Overloads - The overloads to note.
2583 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2584 /// -fshow-overloads=best, this is the location to attach to the note about too
2585 /// many candidates. Typically this will be the location of the original
2586 /// ill-formed expression.
2587 static void noteOverloads(Sema
&S
, const UnresolvedSetImpl
&Overloads
,
2588 const SourceLocation FinalNoteLoc
) {
2589 unsigned ShownOverloads
= 0;
2590 unsigned SuppressedOverloads
= 0;
2591 for (UnresolvedSetImpl::iterator It
= Overloads
.begin(),
2592 DeclsEnd
= Overloads
.end(); It
!= DeclsEnd
; ++It
) {
2593 if (ShownOverloads
>= S
.Diags
.getNumOverloadCandidatesToShow()) {
2594 ++SuppressedOverloads
;
2598 const NamedDecl
*Fn
= (*It
)->getUnderlyingDecl();
2599 // Don't print overloads for non-default multiversioned functions.
2600 if (const auto *FD
= Fn
->getAsFunction()) {
2601 if (FD
->isMultiVersion() && FD
->hasAttr
<TargetAttr
>() &&
2602 !FD
->getAttr
<TargetAttr
>()->isDefaultVersion())
2604 if (FD
->isMultiVersion() && FD
->hasAttr
<TargetVersionAttr
>() &&
2605 !FD
->getAttr
<TargetVersionAttr
>()->isDefaultVersion())
2608 S
.Diag(Fn
->getLocation(), diag::note_possible_target_of_call
);
2612 S
.Diags
.overloadCandidatesShown(ShownOverloads
);
2614 if (SuppressedOverloads
)
2615 S
.Diag(FinalNoteLoc
, diag::note_ovl_too_many_candidates
)
2616 << SuppressedOverloads
;
2619 static void notePlausibleOverloads(Sema
&S
, SourceLocation Loc
,
2620 const UnresolvedSetImpl
&Overloads
,
2621 bool (*IsPlausibleResult
)(QualType
)) {
2622 if (!IsPlausibleResult
)
2623 return noteOverloads(S
, Overloads
, Loc
);
2625 UnresolvedSet
<2> PlausibleOverloads
;
2626 for (OverloadExpr::decls_iterator It
= Overloads
.begin(),
2627 DeclsEnd
= Overloads
.end(); It
!= DeclsEnd
; ++It
) {
2628 const auto *OverloadDecl
= cast
<FunctionDecl
>(*It
);
2629 QualType OverloadResultTy
= OverloadDecl
->getReturnType();
2630 if (IsPlausibleResult(OverloadResultTy
))
2631 PlausibleOverloads
.addDecl(It
.getDecl());
2633 noteOverloads(S
, PlausibleOverloads
, Loc
);
2636 /// Determine whether the given expression can be called by just
2637 /// putting parentheses after it. Notably, expressions with unary
2638 /// operators can't be because the unary operator will start parsing
2639 /// outside the call.
2640 static bool IsCallableWithAppend(const Expr
*E
) {
2641 E
= E
->IgnoreImplicit();
2642 return (!isa
<CStyleCastExpr
>(E
) &&
2643 !isa
<UnaryOperator
>(E
) &&
2644 !isa
<BinaryOperator
>(E
) &&
2645 !isa
<CXXOperatorCallExpr
>(E
));
2648 static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr
*E
) {
2649 if (const auto *UO
= dyn_cast
<UnaryOperator
>(E
))
2650 E
= UO
->getSubExpr();
2652 if (const auto *ULE
= dyn_cast
<UnresolvedLookupExpr
>(E
)) {
2653 if (ULE
->getNumDecls() == 0)
2656 const NamedDecl
*ND
= *ULE
->decls_begin();
2657 if (const auto *FD
= dyn_cast
<FunctionDecl
>(ND
))
2658 return FD
->isCPUDispatchMultiVersion() || FD
->isCPUSpecificMultiVersion();
2663 bool Sema::tryToRecoverWithCall(ExprResult
&E
, const PartialDiagnostic
&PD
,
2665 bool (*IsPlausibleResult
)(QualType
)) {
2666 SourceLocation Loc
= E
.get()->getExprLoc();
2667 SourceRange Range
= E
.get()->getSourceRange();
2668 UnresolvedSet
<4> Overloads
;
2670 // If this is a SFINAE context, don't try anything that might trigger ADL
2672 if (!isSFINAEContext()) {
2673 QualType ZeroArgCallTy
;
2674 if (tryExprAsCall(*E
.get(), ZeroArgCallTy
, Overloads
) &&
2675 !ZeroArgCallTy
.isNull() &&
2676 (!IsPlausibleResult
|| IsPlausibleResult(ZeroArgCallTy
))) {
2677 // At this point, we know E is potentially callable with 0
2678 // arguments and that it returns something of a reasonable type,
2679 // so we can emit a fixit and carry on pretending that E was
2680 // actually a CallExpr.
2681 SourceLocation ParenInsertionLoc
= getLocForEndOfToken(Range
.getEnd());
2682 bool IsMV
= IsCPUDispatchCPUSpecificMultiVersion(E
.get());
2683 Diag(Loc
, PD
) << /*zero-arg*/ 1 << IsMV
<< Range
2684 << (IsCallableWithAppend(E
.get())
2685 ? FixItHint::CreateInsertion(ParenInsertionLoc
,
2689 notePlausibleOverloads(*this, Loc
, Overloads
, IsPlausibleResult
);
2691 // FIXME: Try this before emitting the fixit, and suppress diagnostics
2693 E
= BuildCallExpr(nullptr, E
.get(), Range
.getEnd(), std::nullopt
,
2694 Range
.getEnd().getLocWithOffset(1));
2698 if (!ForceComplain
) return false;
2700 bool IsMV
= IsCPUDispatchCPUSpecificMultiVersion(E
.get());
2701 Diag(Loc
, PD
) << /*not zero-arg*/ 0 << IsMV
<< Range
;
2703 notePlausibleOverloads(*this, Loc
, Overloads
, IsPlausibleResult
);
2708 IdentifierInfo
*Sema::getSuperIdentifier() const {
2710 Ident_super
= &Context
.Idents
.get("super");
2714 void Sema::PushCapturedRegionScope(Scope
*S
, CapturedDecl
*CD
, RecordDecl
*RD
,
2715 CapturedRegionKind K
,
2716 unsigned OpenMPCaptureLevel
) {
2717 auto *CSI
= new CapturedRegionScopeInfo(
2718 getDiagnostics(), S
, CD
, RD
, CD
->getContextParam(), K
,
2719 (getLangOpts().OpenMP
&& K
== CR_OpenMP
) ? getOpenMPNestingLevel() : 0,
2720 OpenMPCaptureLevel
);
2721 CSI
->ReturnType
= Context
.VoidTy
;
2722 FunctionScopes
.push_back(CSI
);
2723 CapturingFunctionScopes
++;
2726 CapturedRegionScopeInfo
*Sema::getCurCapturedRegion() {
2727 if (FunctionScopes
.empty())
2730 return dyn_cast
<CapturedRegionScopeInfo
>(FunctionScopes
.back());
2733 const llvm::MapVector
<FieldDecl
*, Sema::DeleteLocs
> &
2734 Sema::getMismatchingDeleteExpressions() const {
2738 Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema
&S
)
2739 : S(S
), OldFPFeaturesState(S
.CurFPFeatures
),
2740 OldOverrides(S
.FpPragmaStack
.CurrentValue
),
2741 OldEvalMethod(S
.PP
.getCurrentFPEvalMethod()),
2742 OldFPPragmaLocation(S
.PP
.getLastFPEvalPragmaLocation()) {}
2744 Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {
2745 S
.CurFPFeatures
= OldFPFeaturesState
;
2746 S
.FpPragmaStack
.CurrentValue
= OldOverrides
;
2747 S
.PP
.setCurrentFPEvalMethod(OldFPPragmaLocation
, OldEvalMethod
);
2750 bool Sema::isDeclaratorFunctionLike(Declarator
&D
) {
2751 assert(D
.getCXXScopeSpec().isSet() &&
2752 "can only be called for qualified names");
2754 auto LR
= LookupResult(*this, D
.getIdentifier(), D
.getBeginLoc(),
2755 LookupOrdinaryName
, forRedeclarationInCurContext());
2756 DeclContext
*DC
= computeDeclContext(D
.getCXXScopeSpec(),
2757 !D
.getDeclSpec().isFriendSpecified());
2761 LookupQualifiedName(LR
, DC
);
2762 bool Result
= std::all_of(LR
.begin(), LR
.end(), [](Decl
*Dcl
) {
2763 if (NamedDecl
*ND
= dyn_cast
<NamedDecl
>(Dcl
)) {
2764 ND
= ND
->getUnderlyingDecl();
2765 return isa
<FunctionDecl
>(ND
) || isa
<FunctionTemplateDecl
>(ND
) ||