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/ExternalSemaSource.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/MultiplexExternalSemaSource.h"
39 #include "clang/Sema/ObjCMethodList.h"
40 #include "clang/Sema/RISCVIntrinsicManager.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaConsumer.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/TemplateDeduction.h"
46 #include "clang/Sema/TemplateInstCallback.h"
47 #include "clang/Sema/TypoCorrection.h"
48 #include "llvm/ADT/DenseMap.h"
49 #include "llvm/ADT/SmallPtrSet.h"
50 #include "llvm/Support/TimeProfiler.h"
52 using namespace clang
;
55 SourceLocation
Sema::getLocForEndOfToken(SourceLocation Loc
, unsigned Offset
) {
56 return Lexer::getLocForEndOfToken(Loc
, Offset
, SourceMgr
, LangOpts
);
59 ModuleLoader
&Sema::getModuleLoader() const { return PP
.getModuleLoader(); }
62 Sema::getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc
,
64 auto *SDKInfo
= getDarwinSDKInfoForAvailabilityChecking();
65 if (!SDKInfo
&& !WarnedDarwinSDKInfoMissing
) {
66 Diag(Loc
, diag::warn_missing_sdksettings_for_availability_checking
)
68 WarnedDarwinSDKInfoMissing
= true;
73 DarwinSDKInfo
*Sema::getDarwinSDKInfoForAvailabilityChecking() {
74 if (CachedDarwinSDKInfo
)
75 return CachedDarwinSDKInfo
->get();
76 auto SDKInfo
= parseDarwinSDKInfo(
77 PP
.getFileManager().getVirtualFileSystem(),
78 PP
.getHeaderSearchInfo().getHeaderSearchOpts().Sysroot
);
79 if (SDKInfo
&& *SDKInfo
) {
80 CachedDarwinSDKInfo
= std::make_unique
<DarwinSDKInfo
>(std::move(**SDKInfo
));
81 return CachedDarwinSDKInfo
->get();
84 llvm::consumeError(SDKInfo
.takeError());
85 CachedDarwinSDKInfo
= std::unique_ptr
<DarwinSDKInfo
>();
90 Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo
*ParamName
,
92 std::string InventedName
;
93 llvm::raw_string_ostream
OS(InventedName
);
96 OS
<< "auto:" << Index
+ 1;
98 OS
<< ParamName
->getName() << ":auto";
101 return &Context
.Idents
.get(OS
.str());
104 PrintingPolicy
Sema::getPrintingPolicy(const ASTContext
&Context
,
105 const Preprocessor
&PP
) {
106 PrintingPolicy Policy
= Context
.getPrintingPolicy();
107 // In diagnostics, we print _Bool as bool if the latter is defined as the
109 Policy
.Bool
= Context
.getLangOpts().Bool
;
111 if (const MacroInfo
*BoolMacro
= PP
.getMacroInfo(Context
.getBoolName())) {
112 Policy
.Bool
= BoolMacro
->isObjectLike() &&
113 BoolMacro
->getNumTokens() == 1 &&
114 BoolMacro
->getReplacementToken(0).is(tok::kw__Bool
);
118 // Shorten the data output if needed
119 Policy
.EntireContentsOfLargeArray
= false;
124 void Sema::ActOnTranslationUnitScope(Scope
*S
) {
126 PushDeclContext(S
, Context
.getTranslationUnitDecl());
132 class SemaPPCallbacks
: public PPCallbacks
{
134 llvm::SmallVector
<SourceLocation
, 8> IncludeStack
;
137 void set(Sema
&S
) { this->S
= &S
; }
139 void reset() { S
= nullptr; }
141 void FileChanged(SourceLocation Loc
, FileChangeReason Reason
,
142 SrcMgr::CharacteristicKind FileType
,
143 FileID PrevFID
) override
{
148 SourceManager
&SM
= S
->getSourceManager();
149 SourceLocation IncludeLoc
= SM
.getIncludeLoc(SM
.getFileID(Loc
));
150 if (IncludeLoc
.isValid()) {
151 if (llvm::timeTraceProfilerEnabled()) {
152 const FileEntry
*FE
= SM
.getFileEntryForID(SM
.getFileID(Loc
));
153 llvm::timeTraceProfilerBegin(
154 "Source", FE
!= nullptr ? FE
->getName() : StringRef("<unknown>"));
157 IncludeStack
.push_back(IncludeLoc
);
158 S
->DiagnoseNonDefaultPragmaAlignPack(
159 Sema::PragmaAlignPackDiagnoseKind::NonDefaultStateAtInclude
,
165 if (!IncludeStack
.empty()) {
166 if (llvm::timeTraceProfilerEnabled())
167 llvm::timeTraceProfilerEnd();
169 S
->DiagnoseNonDefaultPragmaAlignPack(
170 Sema::PragmaAlignPackDiagnoseKind::ChangedStateAtExit
,
171 IncludeStack
.pop_back_val());
180 } // end namespace sema
181 } // end namespace clang
183 const unsigned Sema::MaxAlignmentExponent
;
184 const uint64_t Sema::MaximumAlignment
;
186 Sema::Sema(Preprocessor
&pp
, ASTContext
&ctxt
, ASTConsumer
&consumer
,
187 TranslationUnitKind TUKind
, CodeCompleteConsumer
*CodeCompleter
)
188 : ExternalSource(nullptr), CurFPFeatures(pp
.getLangOpts()),
189 LangOpts(pp
.getLangOpts()), PP(pp
), Context(ctxt
), Consumer(consumer
),
190 Diags(PP
.getDiagnostics()), SourceMgr(PP
.getSourceManager()),
191 CollectStats(false), CodeCompleter(CodeCompleter
), CurContext(nullptr),
192 OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
193 MSPointerToMemberRepresentationMethod(
194 LangOpts
.getMSPointerToMemberRepresentationMethod()),
195 VtorDispStack(LangOpts
.getVtorDispMode()),
196 AlignPackStack(AlignPackInfo(getLangOpts().XLPragmaPack
)),
197 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
198 CodeSegStack(nullptr), FpPragmaStack(FPOptionsOverride()),
199 CurInitSeg(nullptr), VisContext(nullptr),
200 PragmaAttributeCurrentTargetDecl(nullptr),
201 IsBuildingRecoveryCallExpr(false), LateTemplateParser(nullptr),
202 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp
),
203 StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
204 StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
205 MSVCGuidDecl(nullptr), StdSourceLocationImplDecl(nullptr),
206 NSNumberDecl(nullptr), NSValueDecl(nullptr), NSStringDecl(nullptr),
207 StringWithUTF8StringMethod(nullptr),
208 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
209 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
210 DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
211 TUKind(TUKind
), NumSFINAEErrors(0),
212 FullyCheckedComparisonCategories(
213 static_cast<unsigned>(ComparisonCategoryType::Last
) + 1),
214 SatisfactionCache(Context
), AccessCheckingSFINAE(false),
215 InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
216 ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
217 DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
218 ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
219 CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
220 assert(pp
.TUKind
== TUKind
);
222 isConstantEvaluatedOverride
= false;
224 LoadedExternalKnownNamespaces
= false;
225 for (unsigned I
= 0; I
!= NSAPI::NumNSNumberLiteralMethods
; ++I
)
226 NSNumberLiteralMethods
[I
] = nullptr;
228 if (getLangOpts().ObjC
)
229 NSAPIObj
.reset(new NSAPI(Context
));
231 if (getLangOpts().CPlusPlus
)
232 FieldCollector
.reset(new CXXFieldCollector());
234 // Tell diagnostics how to render things from the AST library.
235 Diags
.SetArgToStringFn(&FormatASTNodeDiagnosticArgument
, &Context
);
237 // This evaluation context exists to ensure that there's always at least one
238 // valid evaluation context available. It is never removed from the
240 ExprEvalContexts
.emplace_back(
241 ExpressionEvaluationContext::PotentiallyEvaluated
, 0, CleanupInfo
{},
242 nullptr, ExpressionEvaluationContextRecord::EK_Other
);
244 // Initialization of data sharing attributes stack for OpenMP
245 InitDataSharingAttributesStack();
247 std::unique_ptr
<sema::SemaPPCallbacks
> Callbacks
=
248 std::make_unique
<sema::SemaPPCallbacks
>();
249 SemaPPCallbackHandler
= Callbacks
.get();
250 PP
.addPPCallbacks(std::move(Callbacks
));
251 SemaPPCallbackHandler
->set(*this);
253 CurFPFeatures
.setFPEvalMethod(PP
.getCurrentFPEvalMethod());
256 // Anchor Sema's type info to this TU.
257 void Sema::anchor() {}
259 void Sema::addImplicitTypedef(StringRef Name
, QualType T
) {
260 DeclarationName DN
= &Context
.Idents
.get(Name
);
261 if (IdResolver
.begin(DN
) == IdResolver
.end())
262 PushOnScopeChains(Context
.buildImplicitTypedef(T
, Name
), TUScope
);
265 void Sema::Initialize() {
266 if (SemaConsumer
*SC
= dyn_cast
<SemaConsumer
>(&Consumer
))
267 SC
->InitializeSema(*this);
269 // Tell the external Sema source about this Sema object.
270 if (ExternalSemaSource
*ExternalSema
271 = dyn_cast_or_null
<ExternalSemaSource
>(Context
.getExternalSource()))
272 ExternalSema
->InitializeSema(*this);
274 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
275 // will not be able to merge any duplicate __va_list_tag decls correctly.
276 VAListTagName
= PP
.getIdentifierInfo("__va_list_tag");
281 // Initialize predefined 128-bit integer types, if needed.
282 if (Context
.getTargetInfo().hasInt128Type() ||
283 (Context
.getAuxTargetInfo() &&
284 Context
.getAuxTargetInfo()->hasInt128Type())) {
285 // If either of the 128-bit integer types are unavailable to name lookup,
287 DeclarationName Int128
= &Context
.Idents
.get("__int128_t");
288 if (IdResolver
.begin(Int128
) == IdResolver
.end())
289 PushOnScopeChains(Context
.getInt128Decl(), TUScope
);
291 DeclarationName UInt128
= &Context
.Idents
.get("__uint128_t");
292 if (IdResolver
.begin(UInt128
) == IdResolver
.end())
293 PushOnScopeChains(Context
.getUInt128Decl(), TUScope
);
297 // Initialize predefined Objective-C types:
298 if (getLangOpts().ObjC
) {
299 // If 'SEL' does not yet refer to any declarations, make it refer to the
301 DeclarationName SEL
= &Context
.Idents
.get("SEL");
302 if (IdResolver
.begin(SEL
) == IdResolver
.end())
303 PushOnScopeChains(Context
.getObjCSelDecl(), TUScope
);
305 // If 'id' does not yet refer to any declarations, make it refer to the
307 DeclarationName Id
= &Context
.Idents
.get("id");
308 if (IdResolver
.begin(Id
) == IdResolver
.end())
309 PushOnScopeChains(Context
.getObjCIdDecl(), TUScope
);
311 // Create the built-in typedef for 'Class'.
312 DeclarationName Class
= &Context
.Idents
.get("Class");
313 if (IdResolver
.begin(Class
) == IdResolver
.end())
314 PushOnScopeChains(Context
.getObjCClassDecl(), TUScope
);
316 // Create the built-in forward declaratino for 'Protocol'.
317 DeclarationName Protocol
= &Context
.Idents
.get("Protocol");
318 if (IdResolver
.begin(Protocol
) == IdResolver
.end())
319 PushOnScopeChains(Context
.getObjCProtocolDecl(), TUScope
);
322 // Create the internal type for the *StringMakeConstantString builtins.
323 DeclarationName ConstantString
= &Context
.Idents
.get("__NSConstantString");
324 if (IdResolver
.begin(ConstantString
) == IdResolver
.end())
325 PushOnScopeChains(Context
.getCFConstantStringDecl(), TUScope
);
327 // Initialize Microsoft "predefined C++ types".
328 if (getLangOpts().MSVCCompat
) {
329 if (getLangOpts().CPlusPlus
&&
330 IdResolver
.begin(&Context
.Idents
.get("type_info")) == IdResolver
.end())
331 PushOnScopeChains(Context
.buildImplicitRecord("type_info", TTK_Class
),
334 addImplicitTypedef("size_t", Context
.getSizeType());
337 // Initialize predefined OpenCL types and supported extensions and (optional)
339 if (getLangOpts().OpenCL
) {
340 getOpenCLOptions().addSupport(
341 Context
.getTargetInfo().getSupportedOpenCLOpts(), getLangOpts());
342 addImplicitTypedef("sampler_t", Context
.OCLSamplerTy
);
343 addImplicitTypedef("event_t", Context
.OCLEventTy
);
344 auto OCLCompatibleVersion
= getLangOpts().getOpenCLCompatibleVersion();
345 if (OCLCompatibleVersion
>= 200) {
346 if (getLangOpts().OpenCLCPlusPlus
|| getLangOpts().Blocks
) {
347 addImplicitTypedef("clk_event_t", Context
.OCLClkEventTy
);
348 addImplicitTypedef("queue_t", Context
.OCLQueueTy
);
350 if (getLangOpts().OpenCLPipes
)
351 addImplicitTypedef("reserve_id_t", Context
.OCLReserveIDTy
);
352 addImplicitTypedef("atomic_int", Context
.getAtomicType(Context
.IntTy
));
353 addImplicitTypedef("atomic_uint",
354 Context
.getAtomicType(Context
.UnsignedIntTy
));
355 addImplicitTypedef("atomic_float",
356 Context
.getAtomicType(Context
.FloatTy
));
357 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
358 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
359 addImplicitTypedef("atomic_flag", Context
.getAtomicType(Context
.IntTy
));
362 // OpenCL v2.0 s6.13.11.6:
363 // - The atomic_long and atomic_ulong types are supported if the
364 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
365 // extensions are supported.
366 // - The atomic_double type is only supported if double precision
367 // is supported and the cl_khr_int64_base_atomics and
368 // cl_khr_int64_extended_atomics extensions are supported.
369 // - If the device address space is 64-bits, the data types
370 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
371 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
372 // cl_khr_int64_extended_atomics extensions are supported.
374 auto AddPointerSizeDependentTypes
= [&]() {
375 auto AtomicSizeT
= Context
.getAtomicType(Context
.getSizeType());
376 auto AtomicIntPtrT
= Context
.getAtomicType(Context
.getIntPtrType());
377 auto AtomicUIntPtrT
= Context
.getAtomicType(Context
.getUIntPtrType());
378 auto AtomicPtrDiffT
=
379 Context
.getAtomicType(Context
.getPointerDiffType());
380 addImplicitTypedef("atomic_size_t", AtomicSizeT
);
381 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT
);
382 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT
);
383 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT
);
386 if (Context
.getTypeSize(Context
.getSizeType()) == 32) {
387 AddPointerSizeDependentTypes();
390 if (getOpenCLOptions().isSupported("cl_khr_fp16", getLangOpts())) {
391 auto AtomicHalfT
= Context
.getAtomicType(Context
.HalfTy
);
392 addImplicitTypedef("atomic_half", AtomicHalfT
);
395 std::vector
<QualType
> Atomic64BitTypes
;
396 if (getOpenCLOptions().isSupported("cl_khr_int64_base_atomics",
398 getOpenCLOptions().isSupported("cl_khr_int64_extended_atomics",
400 if (getOpenCLOptions().isSupported("cl_khr_fp64", getLangOpts())) {
401 auto AtomicDoubleT
= Context
.getAtomicType(Context
.DoubleTy
);
402 addImplicitTypedef("atomic_double", AtomicDoubleT
);
403 Atomic64BitTypes
.push_back(AtomicDoubleT
);
405 auto AtomicLongT
= Context
.getAtomicType(Context
.LongTy
);
406 auto AtomicULongT
= Context
.getAtomicType(Context
.UnsignedLongTy
);
407 addImplicitTypedef("atomic_long", AtomicLongT
);
408 addImplicitTypedef("atomic_ulong", AtomicULongT
);
411 if (Context
.getTypeSize(Context
.getSizeType()) == 64) {
412 AddPointerSizeDependentTypes();
417 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
418 if (getOpenCLOptions().isSupported(#Ext, getLangOpts())) { \
419 addImplicitTypedef(#ExtType, Context.Id##Ty); \
421 #include "clang/Basic/OpenCLExtensionTypes.def"
424 if (Context
.getTargetInfo().hasAArch64SVETypes()) {
425 #define SVE_TYPE(Name, Id, SingletonId) \
426 addImplicitTypedef(Name, Context.SingletonId);
427 #include "clang/Basic/AArch64SVEACLETypes.def"
430 if (Context
.getTargetInfo().getTriple().isPPC64()) {
431 #define PPC_VECTOR_MMA_TYPE(Name, Id, Size) \
432 addImplicitTypedef(#Name, Context.Id##Ty);
433 #include "clang/Basic/PPCTypes.def"
434 #define PPC_VECTOR_VSX_TYPE(Name, Id, Size) \
435 addImplicitTypedef(#Name, Context.Id##Ty);
436 #include "clang/Basic/PPCTypes.def"
439 if (Context
.getTargetInfo().hasRISCVVTypes()) {
440 #define RVV_TYPE(Name, Id, SingletonId) \
441 addImplicitTypedef(Name, Context.SingletonId);
442 #include "clang/Basic/RISCVVTypes.def"
445 if (Context
.getTargetInfo().hasBuiltinMSVaList()) {
446 DeclarationName MSVaList
= &Context
.Idents
.get("__builtin_ms_va_list");
447 if (IdResolver
.begin(MSVaList
) == IdResolver
.end())
448 PushOnScopeChains(Context
.getBuiltinMSVaListDecl(), TUScope
);
451 DeclarationName BuiltinVaList
= &Context
.Idents
.get("__builtin_va_list");
452 if (IdResolver
.begin(BuiltinVaList
) == IdResolver
.end())
453 PushOnScopeChains(Context
.getBuiltinVaListDecl(), TUScope
);
457 assert(InstantiatingSpecializations
.empty() &&
458 "failed to clean up an InstantiatingTemplate?");
460 if (VisContext
) FreeVisContext();
462 // Kill all the active scopes.
463 for (sema::FunctionScopeInfo
*FSI
: FunctionScopes
)
466 // Tell the SemaConsumer to forget about us; we're going out of scope.
467 if (SemaConsumer
*SC
= dyn_cast
<SemaConsumer
>(&Consumer
))
470 // Detach from the external Sema source.
471 if (ExternalSemaSource
*ExternalSema
472 = dyn_cast_or_null
<ExternalSemaSource
>(Context
.getExternalSource()))
473 ExternalSema
->ForgetSema();
475 // Delete cached satisfactions.
476 std::vector
<ConstraintSatisfaction
*> Satisfactions
;
477 Satisfactions
.reserve(Satisfactions
.size());
478 for (auto &Node
: SatisfactionCache
)
479 Satisfactions
.push_back(&Node
);
480 for (auto *Node
: Satisfactions
)
483 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache
);
485 // Destroys data sharing attributes stack for OpenMP
486 DestroyDataSharingAttributesStack();
488 // Detach from the PP callback handler which outlives Sema since it's owned
489 // by the preprocessor.
490 SemaPPCallbackHandler
->reset();
493 void Sema::warnStackExhausted(SourceLocation Loc
) {
494 // Only warn about this once.
495 if (!WarnedStackExhausted
) {
496 Diag(Loc
, diag::warn_stack_exhausted
);
497 WarnedStackExhausted
= true;
501 void Sema::runWithSufficientStackSpace(SourceLocation Loc
,
502 llvm::function_ref
<void()> Fn
) {
503 clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc
); }, Fn
);
506 /// makeUnavailableInSystemHeader - There is an error in the current
507 /// context. If we're still in a system header, and we can plausibly
508 /// make the relevant declaration unavailable instead of erroring, do
509 /// so and return true.
510 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc
,
511 UnavailableAttr::ImplicitReason reason
) {
512 // If we're not in a function, it's an error.
513 FunctionDecl
*fn
= dyn_cast
<FunctionDecl
>(CurContext
);
514 if (!fn
) return false;
516 // If we're in template instantiation, it's an error.
517 if (inTemplateInstantiation())
520 // If that function's not in a system header, it's an error.
521 if (!Context
.getSourceManager().isInSystemHeader(loc
))
524 // If the function is already unavailable, it's not an error.
525 if (fn
->hasAttr
<UnavailableAttr
>()) return true;
527 fn
->addAttr(UnavailableAttr::CreateImplicit(Context
, "", reason
, loc
));
531 ASTMutationListener
*Sema::getASTMutationListener() const {
532 return getASTConsumer().GetASTMutationListener();
535 ///Registers an external source. If an external source already exists,
536 /// creates a multiplex external source and appends to it.
538 ///\param[in] E - A non-null external sema source.
540 void Sema::addExternalSource(ExternalSemaSource
*E
) {
541 assert(E
&& "Cannot use with NULL ptr");
543 if (!ExternalSource
) {
548 if (auto *Ex
= dyn_cast
<MultiplexExternalSemaSource
>(ExternalSource
))
551 ExternalSource
= new MultiplexExternalSemaSource(ExternalSource
.get(), E
);
554 /// Print out statistics about the semantic analysis.
555 void Sema::PrintStats() const {
556 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
557 llvm::errs() << NumSFINAEErrors
<< " SFINAE diagnostics trapped.\n";
559 BumpAlloc
.PrintStats();
560 AnalysisWarnings
.PrintStats();
563 void Sema::diagnoseNullableToNonnullConversion(QualType DstType
,
565 SourceLocation Loc
) {
566 Optional
<NullabilityKind
> ExprNullability
= SrcType
->getNullability(Context
);
567 if (!ExprNullability
|| (*ExprNullability
!= NullabilityKind::Nullable
&&
568 *ExprNullability
!= NullabilityKind::NullableResult
))
571 Optional
<NullabilityKind
> TypeNullability
= DstType
->getNullability(Context
);
572 if (!TypeNullability
|| *TypeNullability
!= NullabilityKind::NonNull
)
575 Diag(Loc
, diag::warn_nullability_lost
) << SrcType
<< DstType
;
578 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind
, const Expr
*E
) {
579 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
580 if (!getLangOpts().CPlusPlus11
)
583 if (Kind
!= CK_NullToPointer
&& Kind
!= CK_NullToMemberPointer
)
585 if (E
->IgnoreParenImpCasts()->getType()->isNullPtrType())
588 if (Diags
.isIgnored(diag::warn_zero_as_null_pointer_constant
,
592 // Don't diagnose the conversion from a 0 literal to a null pointer argument
593 // in a synthesized call to operator<=>.
594 if (!CodeSynthesisContexts
.empty() &&
595 CodeSynthesisContexts
.back().Kind
==
596 CodeSynthesisContext::RewritingOperatorAsSpaceship
)
599 // If it is a macro from system header, and if the macro name is not "NULL",
601 SourceLocation MaybeMacroLoc
= E
->getBeginLoc();
602 if (Diags
.getSuppressSystemWarnings() &&
603 SourceMgr
.isInSystemMacro(MaybeMacroLoc
) &&
604 !findMacroSpelling(MaybeMacroLoc
, "NULL"))
607 Diag(E
->getBeginLoc(), diag::warn_zero_as_null_pointer_constant
)
608 << FixItHint::CreateReplacement(E
->getSourceRange(), "nullptr");
611 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
612 /// If there is already an implicit cast, merge into the existing one.
613 /// The result is of the given category.
614 ExprResult
Sema::ImpCastExprToType(Expr
*E
, QualType Ty
,
615 CastKind Kind
, ExprValueKind VK
,
616 const CXXCastPath
*BasePath
,
617 CheckedConversionKind CCK
) {
619 if (VK
== VK_PRValue
&& !E
->isPRValue()) {
623 ("can't implicitly cast glvalue to prvalue with this cast "
625 std::string(CastExpr::getCastKindName(Kind
)))
628 case CK_LValueToRValue
:
629 case CK_ArrayToPointerDecay
:
630 case CK_FunctionToPointerDecay
:
632 case CK_NonAtomicToAtomic
:
636 assert((VK
== VK_PRValue
|| Kind
== CK_Dependent
|| !E
->isPRValue()) &&
637 "can't cast prvalue to glvalue");
640 diagnoseNullableToNonnullConversion(Ty
, E
->getType(), E
->getBeginLoc());
641 diagnoseZeroToNullptrConversion(Kind
, E
);
643 QualType ExprTy
= Context
.getCanonicalType(E
->getType());
644 QualType TypeTy
= Context
.getCanonicalType(Ty
);
646 if (ExprTy
== TypeTy
)
649 if (Kind
== CK_ArrayToPointerDecay
) {
650 // C++1z [conv.array]: The temporary materialization conversion is applied.
651 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
652 if (getLangOpts().CPlusPlus
&& E
->isPRValue()) {
653 // The temporary is an lvalue in C++98 and an xvalue otherwise.
654 ExprResult Materialized
= CreateMaterializeTemporaryExpr(
655 E
->getType(), E
, !getLangOpts().CPlusPlus11
);
656 if (Materialized
.isInvalid())
658 E
= Materialized
.get();
660 // C17 6.7.1p6 footnote 124: The implementation can treat any register
661 // declaration simply as an auto declaration. However, whether or not
662 // addressable storage is actually used, the address of any part of an
663 // object declared with storage-class specifier register cannot be
664 // computed, either explicitly(by use of the unary & operator as discussed
665 // in 6.5.3.2) or implicitly(by converting an array name to a pointer as
666 // discussed in 6.3.2.1).Thus, the only operator that can be applied to an
667 // array declared with storage-class specifier register is sizeof.
668 if (VK
== VK_PRValue
&& !getLangOpts().CPlusPlus
&& !E
->isPRValue()) {
669 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
670 if (const auto *VD
= dyn_cast
<VarDecl
>(DRE
->getDecl())) {
671 if (VD
->getStorageClass() == SC_Register
) {
672 Diag(E
->getExprLoc(), diag::err_typecheck_address_of
)
673 << /*register variable*/ 3 << E
->getSourceRange();
681 if (ImplicitCastExpr
*ImpCast
= dyn_cast
<ImplicitCastExpr
>(E
)) {
682 if (ImpCast
->getCastKind() == Kind
&& (!BasePath
|| BasePath
->empty())) {
683 ImpCast
->setType(Ty
);
684 ImpCast
->setValueKind(VK
);
689 return ImplicitCastExpr::Create(Context
, Ty
, Kind
, E
, BasePath
, VK
,
690 CurFPFeatureOverrides());
693 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
694 /// to the conversion from scalar type ScalarTy to the Boolean type.
695 CastKind
Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy
) {
696 switch (ScalarTy
->getScalarTypeKind()) {
697 case Type::STK_Bool
: return CK_NoOp
;
698 case Type::STK_CPointer
: return CK_PointerToBoolean
;
699 case Type::STK_BlockPointer
: return CK_PointerToBoolean
;
700 case Type::STK_ObjCObjectPointer
: return CK_PointerToBoolean
;
701 case Type::STK_MemberPointer
: return CK_MemberPointerToBoolean
;
702 case Type::STK_Integral
: return CK_IntegralToBoolean
;
703 case Type::STK_Floating
: return CK_FloatingToBoolean
;
704 case Type::STK_IntegralComplex
: return CK_IntegralComplexToBoolean
;
705 case Type::STK_FloatingComplex
: return CK_FloatingComplexToBoolean
;
706 case Type::STK_FixedPoint
: return CK_FixedPointToBoolean
;
708 llvm_unreachable("unknown scalar type kind");
711 /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
712 static bool ShouldRemoveFromUnused(Sema
*SemaRef
, const DeclaratorDecl
*D
) {
713 if (D
->getMostRecentDecl()->isUsed())
716 if (D
->isExternallyVisible())
719 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
720 // If this is a function template and none of its specializations is used,
722 if (FunctionTemplateDecl
*Template
= FD
->getDescribedFunctionTemplate())
723 for (const auto *Spec
: Template
->specializations())
724 if (ShouldRemoveFromUnused(SemaRef
, Spec
))
727 // UnusedFileScopedDecls stores the first declaration.
728 // The declaration may have become definition so check again.
729 const FunctionDecl
*DeclToCheck
;
730 if (FD
->hasBody(DeclToCheck
))
731 return !SemaRef
->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck
);
733 // Later redecls may add new information resulting in not having to warn,
735 DeclToCheck
= FD
->getMostRecentDecl();
736 if (DeclToCheck
!= FD
)
737 return !SemaRef
->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck
);
740 if (const VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
741 // If a variable usable in constant expressions is referenced,
742 // don't warn if it isn't used: if the value of a variable is required
743 // for the computation of a constant expression, it doesn't make sense to
744 // warn even if the variable isn't odr-used. (isReferenced doesn't
745 // precisely reflect that, but it's a decent approximation.)
746 if (VD
->isReferenced() &&
747 VD
->mightBeUsableInConstantExpressions(SemaRef
->Context
))
750 if (VarTemplateDecl
*Template
= VD
->getDescribedVarTemplate())
751 // If this is a variable template and none of its specializations is used,
753 for (const auto *Spec
: Template
->specializations())
754 if (ShouldRemoveFromUnused(SemaRef
, Spec
))
757 // UnusedFileScopedDecls stores the first declaration.
758 // The declaration may have become definition so check again.
759 const VarDecl
*DeclToCheck
= VD
->getDefinition();
761 return !SemaRef
->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck
);
763 // Later redecls may add new information resulting in not having to warn,
765 DeclToCheck
= VD
->getMostRecentDecl();
766 if (DeclToCheck
!= VD
)
767 return !SemaRef
->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck
);
773 static bool isFunctionOrVarDeclExternC(NamedDecl
*ND
) {
774 if (auto *FD
= dyn_cast
<FunctionDecl
>(ND
))
775 return FD
->isExternC();
776 return cast
<VarDecl
>(ND
)->isExternC();
779 /// Determine whether ND is an external-linkage function or variable whose
780 /// type has no linkage.
781 bool Sema::isExternalWithNoLinkageType(ValueDecl
*VD
) {
782 // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
783 // because we also want to catch the case where its type has VisibleNoLinkage,
784 // which does not affect the linkage of VD.
785 return getLangOpts().CPlusPlus
&& VD
->hasExternalFormalLinkage() &&
786 !isExternalFormalLinkage(VD
->getType()->getLinkage()) &&
787 !isFunctionOrVarDeclExternC(VD
);
790 /// Obtains a sorted list of functions and variables that are undefined but
792 void Sema::getUndefinedButUsed(
793 SmallVectorImpl
<std::pair
<NamedDecl
*, SourceLocation
> > &Undefined
) {
794 for (const auto &UndefinedUse
: UndefinedButUsed
) {
795 NamedDecl
*ND
= UndefinedUse
.first
;
797 // Ignore attributes that have become invalid.
798 if (ND
->isInvalidDecl()) continue;
800 // __attribute__((weakref)) is basically a definition.
801 if (ND
->hasAttr
<WeakRefAttr
>()) continue;
803 if (isa
<CXXDeductionGuideDecl
>(ND
))
806 if (ND
->hasAttr
<DLLImportAttr
>() || ND
->hasAttr
<DLLExportAttr
>()) {
807 // An exported function will always be emitted when defined, so even if
808 // the function is inline, it doesn't have to be emitted in this TU. An
809 // imported function implies that it has been exported somewhere else.
813 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(ND
)) {
816 if (FD
->isExternallyVisible() &&
817 !isExternalWithNoLinkageType(FD
) &&
818 !FD
->getMostRecentDecl()->isInlined() &&
819 !FD
->hasAttr
<ExcludeFromExplicitInstantiationAttr
>())
821 if (FD
->getBuiltinID())
824 auto *VD
= cast
<VarDecl
>(ND
);
825 if (VD
->hasDefinition() != VarDecl::DeclarationOnly
)
827 if (VD
->isExternallyVisible() &&
828 !isExternalWithNoLinkageType(VD
) &&
829 !VD
->getMostRecentDecl()->isInline() &&
830 !VD
->hasAttr
<ExcludeFromExplicitInstantiationAttr
>())
833 // Skip VarDecls that lack formal definitions but which we know are in
834 // fact defined somewhere.
835 if (VD
->isKnownToBeDefined())
839 Undefined
.push_back(std::make_pair(ND
, UndefinedUse
.second
));
843 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
844 /// or that are inline.
845 static void checkUndefinedButUsed(Sema
&S
) {
846 if (S
.UndefinedButUsed
.empty()) return;
848 // Collect all the still-undefined entities with internal linkage.
849 SmallVector
<std::pair
<NamedDecl
*, SourceLocation
>, 16> Undefined
;
850 S
.getUndefinedButUsed(Undefined
);
851 if (Undefined
.empty()) return;
853 for (auto Undef
: Undefined
) {
854 ValueDecl
*VD
= cast
<ValueDecl
>(Undef
.first
);
855 SourceLocation UseLoc
= Undef
.second
;
857 if (S
.isExternalWithNoLinkageType(VD
)) {
858 // C++ [basic.link]p8:
859 // A type without linkage shall not be used as the type of a variable
860 // or function with external linkage unless
861 // -- the entity has C language linkage
862 // -- the entity is not odr-used or is defined in the same TU
864 // As an extension, accept this in cases where the type is externally
865 // visible, since the function or variable actually can be defined in
866 // another translation unit in that case.
867 S
.Diag(VD
->getLocation(), isExternallyVisible(VD
->getType()->getLinkage())
868 ? diag::ext_undefined_internal_type
869 : diag::err_undefined_internal_type
)
870 << isa
<VarDecl
>(VD
) << VD
;
871 } else if (!VD
->isExternallyVisible()) {
872 // FIXME: We can promote this to an error. The function or variable can't
873 // be defined anywhere else, so the program must necessarily violate the
874 // one definition rule.
875 bool IsImplicitBase
= false;
876 if (const auto *BaseD
= dyn_cast
<FunctionDecl
>(VD
)) {
877 auto *DVAttr
= BaseD
->getAttr
<OMPDeclareVariantAttr
>();
878 if (DVAttr
&& !DVAttr
->getTraitInfo().isExtensionActive(
879 llvm::omp::TraitProperty::
880 implementation_extension_disable_implicit_base
)) {
881 const auto *Func
= cast
<FunctionDecl
>(
882 cast
<DeclRefExpr
>(DVAttr
->getVariantFuncRef())->getDecl());
883 IsImplicitBase
= BaseD
->isImplicit() &&
884 Func
->getIdentifier()->isMangledOpenMPVariantName();
887 if (!S
.getLangOpts().OpenMP
|| !IsImplicitBase
)
888 S
.Diag(VD
->getLocation(), diag::warn_undefined_internal
)
889 << isa
<VarDecl
>(VD
) << VD
;
890 } else if (auto *FD
= dyn_cast
<FunctionDecl
>(VD
)) {
892 assert(FD
->getMostRecentDecl()->isInlined() &&
893 "used object requires definition but isn't inline or internal?");
894 // FIXME: This is ill-formed; we should reject.
895 S
.Diag(VD
->getLocation(), diag::warn_undefined_inline
) << VD
;
897 assert(cast
<VarDecl
>(VD
)->getMostRecentDecl()->isInline() &&
898 "used var requires definition but isn't inline or internal?");
899 S
.Diag(VD
->getLocation(), diag::err_undefined_inline_var
) << VD
;
901 if (UseLoc
.isValid())
902 S
.Diag(UseLoc
, diag::note_used_here
);
905 S
.UndefinedButUsed
.clear();
908 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
912 SmallVector
<std::pair
<IdentifierInfo
*, WeakInfo
>, 4> WeakIDs
;
913 ExternalSource
->ReadWeakUndeclaredIdentifiers(WeakIDs
);
914 for (auto &WeakID
: WeakIDs
)
915 (void)WeakUndeclaredIdentifiers
[WeakID
.first
].insert(WeakID
.second
);
919 typedef llvm::DenseMap
<const CXXRecordDecl
*, bool> RecordCompleteMap
;
921 /// Returns true, if all methods and nested classes of the given
922 /// CXXRecordDecl are defined in this translation unit.
924 /// Should only be called from ActOnEndOfTranslationUnit so that all
925 /// definitions are actually read.
926 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl
*RD
,
927 RecordCompleteMap
&MNCComplete
) {
928 RecordCompleteMap::iterator Cache
= MNCComplete
.find(RD
);
929 if (Cache
!= MNCComplete
.end())
930 return Cache
->second
;
931 if (!RD
->isCompleteDefinition())
933 bool Complete
= true;
934 for (DeclContext::decl_iterator I
= RD
->decls_begin(),
936 I
!= E
&& Complete
; ++I
) {
937 if (const CXXMethodDecl
*M
= dyn_cast
<CXXMethodDecl
>(*I
))
938 Complete
= M
->isDefined() || M
->isDefaulted() ||
939 (M
->isPure() && !isa
<CXXDestructorDecl
>(M
));
940 else if (const FunctionTemplateDecl
*F
= dyn_cast
<FunctionTemplateDecl
>(*I
))
941 // If the template function is marked as late template parsed at this
942 // point, it has not been instantiated and therefore we have not
943 // performed semantic analysis on it yet, so we cannot know if the type
944 // can be considered complete.
945 Complete
= !F
->getTemplatedDecl()->isLateTemplateParsed() &&
946 F
->getTemplatedDecl()->isDefined();
947 else if (const CXXRecordDecl
*R
= dyn_cast
<CXXRecordDecl
>(*I
)) {
948 if (R
->isInjectedClassName())
950 if (R
->hasDefinition())
951 Complete
= MethodsAndNestedClassesComplete(R
->getDefinition(),
957 MNCComplete
[RD
] = Complete
;
961 /// Returns true, if the given CXXRecordDecl is fully defined in this
962 /// translation unit, i.e. all methods are defined or pure virtual and all
963 /// friends, friend functions and nested classes are fully defined in this
964 /// translation unit.
966 /// Should only be called from ActOnEndOfTranslationUnit so that all
967 /// definitions are actually read.
968 static bool IsRecordFullyDefined(const CXXRecordDecl
*RD
,
969 RecordCompleteMap
&RecordsComplete
,
970 RecordCompleteMap
&MNCComplete
) {
971 RecordCompleteMap::iterator Cache
= RecordsComplete
.find(RD
);
972 if (Cache
!= RecordsComplete
.end())
973 return Cache
->second
;
974 bool Complete
= MethodsAndNestedClassesComplete(RD
, MNCComplete
);
975 for (CXXRecordDecl::friend_iterator I
= RD
->friend_begin(),
976 E
= RD
->friend_end();
977 I
!= E
&& Complete
; ++I
) {
978 // Check if friend classes and methods are complete.
979 if (TypeSourceInfo
*TSI
= (*I
)->getFriendType()) {
980 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
981 if (CXXRecordDecl
*FriendD
= TSI
->getType()->getAsCXXRecordDecl())
982 Complete
= MethodsAndNestedClassesComplete(FriendD
, MNCComplete
);
986 // Friend functions are available through the NamedDecl of FriendDecl.
987 if (const FunctionDecl
*FD
=
988 dyn_cast
<FunctionDecl
>((*I
)->getFriendDecl()))
989 Complete
= FD
->isDefined();
991 // This is a template friend, give up.
995 RecordsComplete
[RD
] = Complete
;
999 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
1001 ExternalSource
->ReadUnusedLocalTypedefNameCandidates(
1002 UnusedLocalTypedefNameCandidates
);
1003 for (const TypedefNameDecl
*TD
: UnusedLocalTypedefNameCandidates
) {
1004 if (TD
->isReferenced())
1006 Diag(TD
->getLocation(), diag::warn_unused_local_typedef
)
1007 << isa
<TypeAliasDecl
>(TD
) << TD
->getDeclName();
1009 UnusedLocalTypedefNameCandidates
.clear();
1012 /// This is called before the very first declaration in the translation unit
1013 /// is parsed. Note that the ASTContext may have already injected some
1015 void Sema::ActOnStartOfTranslationUnit() {
1016 if (getLangOpts().CPlusPlusModules
&&
1017 getLangOpts().getCompilingModule() == LangOptions::CMK_HeaderUnit
)
1018 HandleStartOfHeaderUnit();
1019 else if (getLangOpts().ModulesTS
&&
1020 (getLangOpts().getCompilingModule() ==
1021 LangOptions::CMK_ModuleInterface
||
1022 getLangOpts().getCompilingModule() == LangOptions::CMK_None
)) {
1023 // We start in an implied global module fragment.
1024 SourceLocation StartOfTU
=
1025 SourceMgr
.getLocForStartOfFile(SourceMgr
.getMainFileID());
1026 ActOnGlobalModuleFragmentDecl(StartOfTU
);
1027 ModuleScopes
.back().ImplicitGlobalModuleFragment
= true;
1031 void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind
) {
1032 // No explicit actions are required at the end of the global module fragment.
1033 if (Kind
== TUFragmentKind::Global
)
1036 // Transfer late parsed template instantiations over to the pending template
1037 // instantiation list. During normal compilation, the late template parser
1038 // will be installed and instantiating these templates will succeed.
1040 // If we are building a TU prefix for serialization, it is also safe to
1041 // transfer these over, even though they are not parsed. The end of the TU
1042 // should be outside of any eager template instantiation scope, so when this
1043 // AST is deserialized, these templates will not be parsed until the end of
1045 PendingInstantiations
.insert(PendingInstantiations
.end(),
1046 LateParsedInstantiations
.begin(),
1047 LateParsedInstantiations
.end());
1048 LateParsedInstantiations
.clear();
1050 // If DefinedUsedVTables ends up marking any virtual member functions it
1051 // might lead to more pending template instantiations, which we then need
1053 DefineUsedVTables();
1055 // C++: Perform implicit template instantiations.
1057 // FIXME: When we perform these implicit instantiations, we do not
1058 // carefully keep track of the point of instantiation (C++ [temp.point]).
1059 // This means that name lookup that occurs within the template
1060 // instantiation will always happen at the end of the translation unit,
1061 // so it will find some names that are not required to be found. This is
1062 // valid, but we could do better by diagnosing if an instantiation uses a
1063 // name that was not visible at its first point of instantiation.
1064 if (ExternalSource
) {
1065 // Load pending instantiations from the external source.
1066 SmallVector
<PendingImplicitInstantiation
, 4> Pending
;
1067 ExternalSource
->ReadPendingInstantiations(Pending
);
1068 for (auto PII
: Pending
)
1069 if (auto Func
= dyn_cast
<FunctionDecl
>(PII
.first
))
1070 Func
->setInstantiationIsPending(true);
1071 PendingInstantiations
.insert(PendingInstantiations
.begin(),
1072 Pending
.begin(), Pending
.end());
1076 llvm::TimeTraceScope
TimeScope("PerformPendingInstantiations");
1077 PerformPendingInstantiations();
1080 emitDeferredDiags();
1082 assert(LateParsedInstantiations
.empty() &&
1083 "end of TU template instantiation should not create more "
1084 "late-parsed templates");
1086 // Report diagnostics for uncorrected delayed typos. Ideally all of them
1087 // should have been corrected by that time, but it is very hard to cover all
1088 // cases in practice.
1089 for (const auto &Typo
: DelayedTypos
) {
1090 // We pass an empty TypoCorrection to indicate no correction was performed.
1091 Typo
.second
.DiagHandler(TypoCorrection());
1093 DelayedTypos
.clear();
1096 /// ActOnEndOfTranslationUnit - This is called at the very end of the
1097 /// translation unit when EOF is reached and all but the top-level scope is
1099 void Sema::ActOnEndOfTranslationUnit() {
1100 assert(DelayedDiagnostics
.getCurrentPool() == nullptr
1101 && "reached end of translation unit with a pool attached?");
1103 // If code completion is enabled, don't perform any end-of-translation-unit
1105 if (PP
.isCodeCompletionEnabled())
1108 // Complete translation units and modules define vtables and perform implicit
1109 // instantiations. PCH files do not.
1110 if (TUKind
!= TU_Prefix
) {
1111 DiagnoseUseOfUnimplementedSelectors();
1113 ActOnEndOfTranslationUnitFragment(
1114 !ModuleScopes
.empty() && ModuleScopes
.back().Module
->Kind
==
1115 Module::PrivateModuleFragment
1116 ? TUFragmentKind::Private
1117 : TUFragmentKind::Normal
);
1119 if (LateTemplateParserCleanup
)
1120 LateTemplateParserCleanup(OpaqueParser
);
1122 CheckDelayedMemberExceptionSpecs();
1124 // If we are building a TU prefix for serialization, it is safe to transfer
1125 // these over, even though they are not parsed. The end of the TU should be
1126 // outside of any eager template instantiation scope, so when this AST is
1127 // deserialized, these templates will not be parsed until the end of the
1129 PendingInstantiations
.insert(PendingInstantiations
.end(),
1130 LateParsedInstantiations
.begin(),
1131 LateParsedInstantiations
.end());
1132 LateParsedInstantiations
.clear();
1134 if (LangOpts
.PCHInstantiateTemplates
) {
1135 llvm::TimeTraceScope
TimeScope("PerformPendingInstantiations");
1136 PerformPendingInstantiations();
1140 DiagnoseUnterminatedPragmaAlignPack();
1141 DiagnoseUnterminatedPragmaAttribute();
1142 DiagnoseUnterminatedOpenMPDeclareTarget();
1144 // All delayed member exception specs should be checked or we end up accepting
1145 // incompatible declarations.
1146 assert(DelayedOverridingExceptionSpecChecks
.empty());
1147 assert(DelayedEquivalentExceptionSpecChecks
.empty());
1149 // All dllexport classes should have been processed already.
1150 assert(DelayedDllExportClasses
.empty());
1151 assert(DelayedDllExportMemberFunctions
.empty());
1153 // Remove file scoped decls that turned out to be used.
1154 UnusedFileScopedDecls
.erase(
1155 std::remove_if(UnusedFileScopedDecls
.begin(nullptr, true),
1156 UnusedFileScopedDecls
.end(),
1157 [this](const DeclaratorDecl
*DD
) {
1158 return ShouldRemoveFromUnused(this, DD
);
1160 UnusedFileScopedDecls
.end());
1162 if (TUKind
== TU_Prefix
) {
1163 // Translation unit prefixes don't need any of the checking below.
1164 if (!PP
.isIncrementalProcessingEnabled())
1169 // Check for #pragma weak identifiers that were never declared
1170 LoadExternalWeakUndeclaredIdentifiers();
1171 for (const auto &WeakIDs
: WeakUndeclaredIdentifiers
) {
1172 if (WeakIDs
.second
.empty())
1175 Decl
*PrevDecl
= LookupSingleName(TUScope
, WeakIDs
.first
, SourceLocation(),
1176 LookupOrdinaryName
);
1177 if (PrevDecl
!= nullptr &&
1178 !(isa
<FunctionDecl
>(PrevDecl
) || isa
<VarDecl
>(PrevDecl
)))
1179 for (const auto &WI
: WeakIDs
.second
)
1180 Diag(WI
.getLocation(), diag::warn_attribute_wrong_decl_type
)
1181 << "'weak'" << ExpectedVariableOrFunction
;
1183 for (const auto &WI
: WeakIDs
.second
)
1184 Diag(WI
.getLocation(), diag::warn_weak_identifier_undeclared
)
1188 if (LangOpts
.CPlusPlus11
&&
1189 !Diags
.isIgnored(diag::warn_delegating_ctor_cycle
, SourceLocation()))
1190 CheckDelegatingCtorCycles();
1192 if (!Diags
.hasErrorOccurred()) {
1194 ExternalSource
->ReadUndefinedButUsed(UndefinedButUsed
);
1195 checkUndefinedButUsed(*this);
1198 // A global-module-fragment is only permitted within a module unit.
1199 bool DiagnosedMissingModuleDeclaration
= false;
1200 if (!ModuleScopes
.empty() &&
1201 ModuleScopes
.back().Module
->Kind
== Module::GlobalModuleFragment
&&
1202 !ModuleScopes
.back().ImplicitGlobalModuleFragment
) {
1203 Diag(ModuleScopes
.back().BeginLoc
,
1204 diag::err_module_declaration_missing_after_global_module_introducer
);
1205 DiagnosedMissingModuleDeclaration
= true;
1208 if (TUKind
== TU_Module
) {
1209 // If we are building a module interface unit, we need to have seen the
1210 // module declaration by now.
1211 if (getLangOpts().getCompilingModule() ==
1212 LangOptions::CMK_ModuleInterface
&&
1213 !isCurrentModulePurview() && !DiagnosedMissingModuleDeclaration
) {
1214 // FIXME: Make a better guess as to where to put the module declaration.
1215 Diag(getSourceManager().getLocForStartOfFile(
1216 getSourceManager().getMainFileID()),
1217 diag::err_module_declaration_missing
);
1220 // If we are building a module, resolve all of the exported declarations
1222 if (Module
*CurrentModule
= PP
.getCurrentModule()) {
1223 ModuleMap
&ModMap
= PP
.getHeaderSearchInfo().getModuleMap();
1225 SmallVector
<Module
*, 2> Stack
;
1226 Stack
.push_back(CurrentModule
);
1227 while (!Stack
.empty()) {
1228 Module
*Mod
= Stack
.pop_back_val();
1230 // Resolve the exported declarations and conflicts.
1231 // FIXME: Actually complain, once we figure out how to teach the
1232 // diagnostic client to deal with complaints in the module map at this
1234 ModMap
.resolveExports(Mod
, /*Complain=*/false);
1235 ModMap
.resolveUses(Mod
, /*Complain=*/false);
1236 ModMap
.resolveConflicts(Mod
, /*Complain=*/false);
1238 // Queue the submodules, so their exports will also be resolved.
1239 Stack
.append(Mod
->submodule_begin(), Mod
->submodule_end());
1243 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1244 // modules when they are built, not every time they are used.
1245 emitAndClearUnusedLocalTypedefWarnings();
1248 // C++ standard modules. Diagnose cases where a function is declared inline
1249 // in the module purview but has no definition before the end of the TU or
1250 // the start of a Private Module Fragment (if one is present).
1251 if (!PendingInlineFuncDecls
.empty()) {
1252 for (auto *D
: PendingInlineFuncDecls
) {
1253 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
1254 bool DefInPMF
= false;
1255 if (auto *FDD
= FD
->getDefinition()) {
1256 assert(FDD
->getOwningModule() &&
1257 FDD
->getOwningModule()->isModulePurview());
1258 DefInPMF
= FDD
->getOwningModule()->isPrivateModule();
1262 Diag(FD
->getLocation(), diag::err_export_inline_not_defined
)
1264 // If we have a PMF it should be at the end of the ModuleScopes.
1266 ModuleScopes
.back().Module
->Kind
== Module::PrivateModuleFragment
) {
1267 Diag(ModuleScopes
.back().BeginLoc
,
1268 diag::note_private_module_fragment
);
1272 PendingInlineFuncDecls
.clear();
1276 // A declaration of an identifier for an object that has file
1277 // scope without an initializer, and without a storage-class
1278 // specifier or with the storage-class specifier static,
1279 // constitutes a tentative definition. If a translation unit
1280 // contains one or more tentative definitions for an identifier,
1281 // and the translation unit contains no external definition for
1282 // that identifier, then the behavior is exactly as if the
1283 // translation unit contains a file scope declaration of that
1284 // identifier, with the composite type as of the end of the
1285 // translation unit, with an initializer equal to 0.
1286 llvm::SmallSet
<VarDecl
*, 32> Seen
;
1287 for (TentativeDefinitionsType::iterator
1288 T
= TentativeDefinitions
.begin(ExternalSource
.get()),
1289 TEnd
= TentativeDefinitions
.end();
1291 VarDecl
*VD
= (*T
)->getActingDefinition();
1293 // If the tentative definition was completed, getActingDefinition() returns
1294 // null. If we've already seen this variable before, insert()'s second
1295 // return value is false.
1296 if (!VD
|| VD
->isInvalidDecl() || !Seen
.insert(VD
).second
)
1299 if (const IncompleteArrayType
*ArrayT
1300 = Context
.getAsIncompleteArrayType(VD
->getType())) {
1301 // Set the length of the array to 1 (C99 6.9.2p5).
1302 Diag(VD
->getLocation(), diag::warn_tentative_incomplete_array
);
1303 llvm::APInt
One(Context
.getTypeSize(Context
.getSizeType()), true);
1304 QualType T
= Context
.getConstantArrayType(ArrayT
->getElementType(), One
,
1305 nullptr, ArrayType::Normal
, 0);
1307 } else if (RequireCompleteType(VD
->getLocation(), VD
->getType(),
1308 diag::err_tentative_def_incomplete_type
))
1309 VD
->setInvalidDecl();
1311 // No initialization is performed for a tentative definition.
1312 CheckCompleteVariableDeclaration(VD
);
1314 // Notify the consumer that we've completed a tentative definition.
1315 if (!VD
->isInvalidDecl())
1316 Consumer
.CompleteTentativeDefinition(VD
);
1319 for (auto *D
: ExternalDeclarations
) {
1320 if (!D
|| D
->isInvalidDecl() || D
->getPreviousDecl() || !D
->isUsed())
1323 Consumer
.CompleteExternalDeclaration(D
);
1326 // If there were errors, disable 'unused' warnings since they will mostly be
1327 // noise. Don't warn for a use from a module: either we should warn on all
1328 // file-scope declarations in modules or not at all, but whether the
1329 // declaration is used is immaterial.
1330 if (!Diags
.hasErrorOccurred() && TUKind
!= TU_Module
) {
1331 // Output warning for unused file scoped decls.
1332 for (UnusedFileScopedDeclsType::iterator
1333 I
= UnusedFileScopedDecls
.begin(ExternalSource
.get()),
1334 E
= UnusedFileScopedDecls
.end();
1336 if (ShouldRemoveFromUnused(this, *I
))
1339 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(*I
)) {
1340 const FunctionDecl
*DiagD
;
1341 if (!FD
->hasBody(DiagD
))
1343 if (DiagD
->isDeleted())
1344 continue; // Deleted functions are supposed to be unused.
1345 if (DiagD
->isReferenced()) {
1346 if (isa
<CXXMethodDecl
>(DiagD
))
1347 Diag(DiagD
->getLocation(), diag::warn_unneeded_member_function
)
1350 if (FD
->getStorageClass() == SC_Static
&&
1351 !FD
->isInlineSpecified() &&
1352 !SourceMgr
.isInMainFile(
1353 SourceMgr
.getExpansionLoc(FD
->getLocation())))
1354 Diag(DiagD
->getLocation(),
1355 diag::warn_unneeded_static_internal_decl
)
1358 Diag(DiagD
->getLocation(), diag::warn_unneeded_internal_decl
)
1359 << /*function*/ 0 << DiagD
;
1362 if (FD
->getDescribedFunctionTemplate())
1363 Diag(DiagD
->getLocation(), diag::warn_unused_template
)
1364 << /*function*/ 0 << DiagD
;
1366 Diag(DiagD
->getLocation(), isa
<CXXMethodDecl
>(DiagD
)
1367 ? diag::warn_unused_member_function
1368 : diag::warn_unused_function
)
1372 const VarDecl
*DiagD
= cast
<VarDecl
>(*I
)->getDefinition();
1374 DiagD
= cast
<VarDecl
>(*I
);
1375 if (DiagD
->isReferenced()) {
1376 Diag(DiagD
->getLocation(), diag::warn_unneeded_internal_decl
)
1377 << /*variable*/ 1 << DiagD
;
1378 } else if (DiagD
->getType().isConstQualified()) {
1379 const SourceManager
&SM
= SourceMgr
;
1380 if (SM
.getMainFileID() != SM
.getFileID(DiagD
->getLocation()) ||
1381 !PP
.getLangOpts().IsHeaderFile
)
1382 Diag(DiagD
->getLocation(), diag::warn_unused_const_variable
)
1385 if (DiagD
->getDescribedVarTemplate())
1386 Diag(DiagD
->getLocation(), diag::warn_unused_template
)
1387 << /*variable*/ 1 << DiagD
;
1389 Diag(DiagD
->getLocation(), diag::warn_unused_variable
) << DiagD
;
1394 emitAndClearUnusedLocalTypedefWarnings();
1397 if (!Diags
.isIgnored(diag::warn_unused_private_field
, SourceLocation())) {
1398 // FIXME: Load additional unused private field candidates from the external
1400 RecordCompleteMap RecordsComplete
;
1401 RecordCompleteMap MNCComplete
;
1402 for (NamedDeclSetType::iterator I
= UnusedPrivateFields
.begin(),
1403 E
= UnusedPrivateFields
.end(); I
!= E
; ++I
) {
1404 const NamedDecl
*D
= *I
;
1405 const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
->getDeclContext());
1406 if (RD
&& !RD
->isUnion() &&
1407 IsRecordFullyDefined(RD
, RecordsComplete
, MNCComplete
)) {
1408 Diag(D
->getLocation(), diag::warn_unused_private_field
)
1409 << D
->getDeclName();
1414 if (!Diags
.isIgnored(diag::warn_mismatched_delete_new
, SourceLocation())) {
1416 ExternalSource
->ReadMismatchingDeleteExpressions(DeleteExprs
);
1417 for (const auto &DeletedFieldInfo
: DeleteExprs
) {
1418 for (const auto &DeleteExprLoc
: DeletedFieldInfo
.second
) {
1419 AnalyzeDeleteExprMismatch(DeletedFieldInfo
.first
, DeleteExprLoc
.first
,
1420 DeleteExprLoc
.second
);
1425 // Check we've noticed that we're no longer parsing the initializer for every
1426 // variable. If we miss cases, then at best we have a performance issue and
1427 // at worst a rejects-valid bug.
1428 assert(ParsingInitForAutoVars
.empty() &&
1429 "Didn't unmark var as having its initializer parsed");
1431 if (!PP
.isIncrementalProcessingEnabled())
1436 //===----------------------------------------------------------------------===//
1437 // Helper functions.
1438 //===----------------------------------------------------------------------===//
1440 DeclContext
*Sema::getFunctionLevelDeclContext(bool AllowLambda
) {
1441 DeclContext
*DC
= CurContext
;
1444 if (isa
<BlockDecl
>(DC
) || isa
<EnumDecl
>(DC
) || isa
<CapturedDecl
>(DC
) ||
1445 isa
<RequiresExprBodyDecl
>(DC
)) {
1446 DC
= DC
->getParent();
1447 } else if (!AllowLambda
&& isa
<CXXMethodDecl
>(DC
) &&
1448 cast
<CXXMethodDecl
>(DC
)->getOverloadedOperator() == OO_Call
&&
1449 cast
<CXXRecordDecl
>(DC
->getParent())->isLambda()) {
1450 DC
= DC
->getParent()->getParent();
1457 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1458 /// to the function decl for the function being parsed. If we're currently
1459 /// in a 'block', this returns the containing context.
1460 FunctionDecl
*Sema::getCurFunctionDecl(bool AllowLambda
) {
1461 DeclContext
*DC
= getFunctionLevelDeclContext(AllowLambda
);
1462 return dyn_cast
<FunctionDecl
>(DC
);
1465 ObjCMethodDecl
*Sema::getCurMethodDecl() {
1466 DeclContext
*DC
= getFunctionLevelDeclContext();
1467 while (isa
<RecordDecl
>(DC
))
1468 DC
= DC
->getParent();
1469 return dyn_cast
<ObjCMethodDecl
>(DC
);
1472 NamedDecl
*Sema::getCurFunctionOrMethodDecl() {
1473 DeclContext
*DC
= getFunctionLevelDeclContext();
1474 if (isa
<ObjCMethodDecl
>(DC
) || isa
<FunctionDecl
>(DC
))
1475 return cast
<NamedDecl
>(DC
);
1479 LangAS
Sema::getDefaultCXXMethodAddrSpace() const {
1480 if (getLangOpts().OpenCL
)
1481 return getASTContext().getDefaultOpenCLPointeeAddrSpace();
1482 return LangAS::Default
;
1485 void Sema::EmitCurrentDiagnostic(unsigned DiagID
) {
1486 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1487 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1488 // been made more painfully obvious by the refactor that introduced this
1489 // function, but it is possible that the incoming argument can be
1490 // eliminated. If it truly cannot be (for example, there is some reentrancy
1491 // issue I am not seeing yet), then there should at least be a clarifying
1492 // comment somewhere.
1493 if (Optional
<TemplateDeductionInfo
*> Info
= isSFINAEContext()) {
1494 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1495 Diags
.getCurrentDiagID())) {
1496 case DiagnosticIDs::SFINAE_Report
:
1497 // We'll report the diagnostic below.
1500 case DiagnosticIDs::SFINAE_SubstitutionFailure
:
1501 // Count this failure so that we know that template argument deduction
1505 // Make a copy of this suppressed diagnostic and store it with the
1506 // template-deduction information.
1507 if (*Info
&& !(*Info
)->hasSFINAEDiagnostic()) {
1508 Diagnostic
DiagInfo(&Diags
);
1509 (*Info
)->addSFINAEDiagnostic(DiagInfo
.getLocation(),
1510 PartialDiagnostic(DiagInfo
, Context
.getDiagAllocator()));
1513 Diags
.setLastDiagnosticIgnored(true);
1517 case DiagnosticIDs::SFINAE_AccessControl
: {
1518 // Per C++ Core Issue 1170, access control is part of SFINAE.
1519 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1520 // make access control a part of SFINAE for the purposes of checking
1522 if (!AccessCheckingSFINAE
&& !getLangOpts().CPlusPlus11
)
1525 SourceLocation Loc
= Diags
.getCurrentDiagLoc();
1527 // Suppress this diagnostic.
1530 // Make a copy of this suppressed diagnostic and store it with the
1531 // template-deduction information.
1532 if (*Info
&& !(*Info
)->hasSFINAEDiagnostic()) {
1533 Diagnostic
DiagInfo(&Diags
);
1534 (*Info
)->addSFINAEDiagnostic(DiagInfo
.getLocation(),
1535 PartialDiagnostic(DiagInfo
, Context
.getDiagAllocator()));
1538 Diags
.setLastDiagnosticIgnored(true);
1541 // Now the diagnostic state is clear, produce a C++98 compatibility
1543 Diag(Loc
, diag::warn_cxx98_compat_sfinae_access_control
);
1545 // The last diagnostic which Sema produced was ignored. Suppress any
1546 // notes attached to it.
1547 Diags
.setLastDiagnosticIgnored(true);
1551 case DiagnosticIDs::SFINAE_Suppress
:
1552 // Make a copy of this suppressed diagnostic and store it with the
1553 // template-deduction information;
1555 Diagnostic
DiagInfo(&Diags
);
1556 (*Info
)->addSuppressedDiagnostic(DiagInfo
.getLocation(),
1557 PartialDiagnostic(DiagInfo
, Context
.getDiagAllocator()));
1560 // Suppress this diagnostic.
1561 Diags
.setLastDiagnosticIgnored(true);
1567 // Copy the diagnostic printing policy over the ASTContext printing policy.
1568 // TODO: Stop doing that. See: https://reviews.llvm.org/D45093#1090292
1569 Context
.setPrintingPolicy(getPrintingPolicy());
1571 // Emit the diagnostic.
1572 if (!Diags
.EmitCurrentDiagnostic())
1575 // If this is not a note, and we're in a template instantiation
1576 // that is different from the last template instantiation where
1577 // we emitted an error, print a template instantiation
1579 if (!DiagnosticIDs::isBuiltinNote(DiagID
))
1580 PrintContextStack();
1583 Sema::SemaDiagnosticBuilder
1584 Sema::Diag(SourceLocation Loc
, const PartialDiagnostic
&PD
, bool DeferHint
) {
1585 return Diag(Loc
, PD
.getDiagID(), DeferHint
) << PD
;
1588 bool Sema::hasUncompilableErrorOccurred() const {
1589 if (getDiagnostics().hasUncompilableErrorOccurred())
1591 auto *FD
= dyn_cast
<FunctionDecl
>(CurContext
);
1594 auto Loc
= DeviceDeferredDiags
.find(FD
);
1595 if (Loc
== DeviceDeferredDiags
.end())
1597 for (auto PDAt
: Loc
->second
) {
1598 if (DiagnosticIDs::isDefaultMappingAsError(PDAt
.second
.getDiagID()))
1604 // Print notes showing how we can reach FD starting from an a priori
1605 // known-callable function.
1606 static void emitCallStackNotes(Sema
&S
, FunctionDecl
*FD
) {
1607 auto FnIt
= S
.DeviceKnownEmittedFns
.find(FD
);
1608 while (FnIt
!= S
.DeviceKnownEmittedFns
.end()) {
1609 // Respect error limit.
1610 if (S
.Diags
.hasFatalErrorOccurred())
1612 DiagnosticBuilder
Builder(
1613 S
.Diags
.Report(FnIt
->second
.Loc
, diag::note_called_by
));
1614 Builder
<< FnIt
->second
.FD
;
1615 FnIt
= S
.DeviceKnownEmittedFns
.find(FnIt
->second
.FD
);
1621 /// Helper class that emits deferred diagnostic messages if an entity directly
1622 /// or indirectly using the function that causes the deferred diagnostic
1623 /// messages is known to be emitted.
1625 /// During parsing of AST, certain diagnostic messages are recorded as deferred
1626 /// diagnostics since it is unknown whether the functions containing such
1627 /// diagnostics will be emitted. A list of potentially emitted functions and
1628 /// variables that may potentially trigger emission of functions are also
1629 /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1630 /// by each function to emit deferred diagnostics.
1632 /// During the visit, certain OpenMP directives or initializer of variables
1633 /// with certain OpenMP attributes will cause subsequent visiting of any
1634 /// functions enter a state which is called OpenMP device context in this
1635 /// implementation. The state is exited when the directive or initializer is
1636 /// exited. This state can change the emission states of subsequent uses
1639 /// Conceptually the functions or variables to be visited form a use graph
1640 /// where the parent node uses the child node. At any point of the visit,
1641 /// the tree nodes traversed from the tree root to the current node form a use
1642 /// stack. The emission state of the current node depends on two factors:
1643 /// 1. the emission state of the root node
1644 /// 2. whether the current node is in OpenMP device context
1645 /// If the function is decided to be emitted, its contained deferred diagnostics
1646 /// are emitted, together with the information about the use stack.
1648 class DeferredDiagnosticsEmitter
1649 : public UsedDeclVisitor
<DeferredDiagnosticsEmitter
> {
1651 typedef UsedDeclVisitor
<DeferredDiagnosticsEmitter
> Inherited
;
1653 // Whether the function is already in the current use-path.
1654 llvm::SmallPtrSet
<CanonicalDeclPtr
<Decl
>, 4> InUsePath
;
1656 // The current use-path.
1657 llvm::SmallVector
<CanonicalDeclPtr
<FunctionDecl
>, 4> UsePath
;
1659 // Whether the visiting of the function has been done. Done[0] is for the
1660 // case not in OpenMP device context. Done[1] is for the case in OpenMP
1661 // device context. We need two sets because diagnostics emission may be
1662 // different depending on whether it is in OpenMP device context.
1663 llvm::SmallPtrSet
<CanonicalDeclPtr
<Decl
>, 4> DoneMap
[2];
1665 // Emission state of the root node of the current use graph.
1666 bool ShouldEmitRootNode
;
1668 // Current OpenMP device context level. It is initialized to 0 and each
1669 // entering of device context increases it by 1 and each exit decreases
1670 // it by 1. Non-zero value indicates it is currently in device context.
1671 unsigned InOMPDeviceContext
;
1673 DeferredDiagnosticsEmitter(Sema
&S
)
1674 : Inherited(S
), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1676 bool shouldVisitDiscardedStmt() const { return false; }
1678 void VisitOMPTargetDirective(OMPTargetDirective
*Node
) {
1679 ++InOMPDeviceContext
;
1680 Inherited::VisitOMPTargetDirective(Node
);
1681 --InOMPDeviceContext
;
1684 void visitUsedDecl(SourceLocation Loc
, Decl
*D
) {
1685 if (isa
<VarDecl
>(D
))
1687 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
))
1690 Inherited::visitUsedDecl(Loc
, D
);
1693 void checkVar(VarDecl
*VD
) {
1694 assert(VD
->isFileVarDecl() &&
1695 "Should only check file-scope variables");
1696 if (auto *Init
= VD
->getInit()) {
1697 auto DevTy
= OMPDeclareTargetDeclAttr::getDeviceType(VD
);
1698 bool IsDev
= DevTy
&& (*DevTy
== OMPDeclareTargetDeclAttr::DT_NoHost
||
1699 *DevTy
== OMPDeclareTargetDeclAttr::DT_Any
);
1701 ++InOMPDeviceContext
;
1704 --InOMPDeviceContext
;
1708 void checkFunc(SourceLocation Loc
, FunctionDecl
*FD
) {
1709 auto &Done
= DoneMap
[InOMPDeviceContext
> 0 ? 1 : 0];
1710 FunctionDecl
*Caller
= UsePath
.empty() ? nullptr : UsePath
.back();
1711 if ((!ShouldEmitRootNode
&& !S
.getLangOpts().OpenMP
&& !Caller
) ||
1712 S
.shouldIgnoreInHostDeviceCheck(FD
) || InUsePath
.count(FD
))
1714 // Finalize analysis of OpenMP-specific constructs.
1715 if (Caller
&& S
.LangOpts
.OpenMP
&& UsePath
.size() == 1 &&
1716 (ShouldEmitRootNode
|| InOMPDeviceContext
))
1717 S
.finalizeOpenMPDelayedAnalysis(Caller
, FD
, Loc
);
1719 S
.DeviceKnownEmittedFns
[FD
] = {Caller
, Loc
};
1720 // Always emit deferred diagnostics for the direct users. This does not
1721 // lead to explosion of diagnostics since each user is visited at most
1723 if (ShouldEmitRootNode
|| InOMPDeviceContext
)
1724 emitDeferredDiags(FD
, Caller
);
1725 // Do not revisit a function if the function body has been completely
1727 if (!Done
.insert(FD
).second
)
1729 InUsePath
.insert(FD
);
1730 UsePath
.push_back(FD
);
1731 if (auto *S
= FD
->getBody()) {
1735 InUsePath
.erase(FD
);
1738 void checkRecordedDecl(Decl
*D
) {
1739 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
1740 ShouldEmitRootNode
= S
.getEmissionStatus(FD
, /*Final=*/true) ==
1741 Sema::FunctionEmissionStatus::Emitted
;
1742 checkFunc(SourceLocation(), FD
);
1744 checkVar(cast
<VarDecl
>(D
));
1747 // Emit any deferred diagnostics for FD
1748 void emitDeferredDiags(FunctionDecl
*FD
, bool ShowCallStack
) {
1749 auto It
= S
.DeviceDeferredDiags
.find(FD
);
1750 if (It
== S
.DeviceDeferredDiags
.end())
1752 bool HasWarningOrError
= false;
1753 bool FirstDiag
= true;
1754 for (PartialDiagnosticAt
&PDAt
: It
->second
) {
1755 // Respect error limit.
1756 if (S
.Diags
.hasFatalErrorOccurred())
1758 const SourceLocation
&Loc
= PDAt
.first
;
1759 const PartialDiagnostic
&PD
= PDAt
.second
;
1760 HasWarningOrError
|=
1761 S
.getDiagnostics().getDiagnosticLevel(PD
.getDiagID(), Loc
) >=
1762 DiagnosticsEngine::Warning
;
1764 DiagnosticBuilder
Builder(S
.Diags
.Report(Loc
, PD
.getDiagID()));
1767 // Emit the note on the first diagnostic in case too many diagnostics
1768 // cause the note not emitted.
1769 if (FirstDiag
&& HasWarningOrError
&& ShowCallStack
) {
1770 emitCallStackNotes(S
, FD
);
1778 void Sema::emitDeferredDiags() {
1780 ExternalSource
->ReadDeclsToCheckForDeferredDiags(
1781 DeclsToCheckForDeferredDiags
);
1783 if ((DeviceDeferredDiags
.empty() && !LangOpts
.OpenMP
) ||
1784 DeclsToCheckForDeferredDiags
.empty())
1787 DeferredDiagnosticsEmitter
DDE(*this);
1788 for (auto *D
: DeclsToCheckForDeferredDiags
)
1789 DDE
.checkRecordedDecl(D
);
1792 // In CUDA, there are some constructs which may appear in semantically-valid
1793 // code, but trigger errors if we ever generate code for the function in which
1794 // they appear. Essentially every construct you're not allowed to use on the
1795 // device falls into this category, because you are allowed to use these
1796 // constructs in a __host__ __device__ function, but only if that function is
1797 // never codegen'ed on the device.
1799 // To handle semantic checking for these constructs, we keep track of the set of
1800 // functions we know will be emitted, either because we could tell a priori that
1801 // they would be emitted, or because they were transitively called by a
1802 // known-emitted function.
1804 // We also keep a partial call graph of which not-known-emitted functions call
1805 // which other not-known-emitted functions.
1807 // When we see something which is illegal if the current function is emitted
1808 // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1809 // CheckCUDACall), we first check if the current function is known-emitted. If
1810 // so, we immediately output the diagnostic.
1812 // Otherwise, we "defer" the diagnostic. It sits in Sema::DeviceDeferredDiags
1813 // until we discover that the function is known-emitted, at which point we take
1814 // it out of this map and emit the diagnostic.
1816 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K
, SourceLocation Loc
,
1818 FunctionDecl
*Fn
, Sema
&S
)
1819 : S(S
), Loc(Loc
), DiagID(DiagID
), Fn(Fn
),
1820 ShowCallStack(K
== K_ImmediateWithCallStack
|| K
== K_Deferred
) {
1825 case K_ImmediateWithCallStack
:
1826 ImmediateDiag
.emplace(
1827 ImmediateDiagBuilder(S
.Diags
.Report(Loc
, DiagID
), S
, DiagID
));
1830 assert(Fn
&& "Must have a function to attach the deferred diag to.");
1831 auto &Diags
= S
.DeviceDeferredDiags
[Fn
];
1832 PartialDiagId
.emplace(Diags
.size());
1833 Diags
.emplace_back(Loc
, S
.PDiag(DiagID
));
1838 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder
&&D
)
1839 : S(D
.S
), Loc(D
.Loc
), DiagID(D
.DiagID
), Fn(D
.Fn
),
1840 ShowCallStack(D
.ShowCallStack
), ImmediateDiag(D
.ImmediateDiag
),
1841 PartialDiagId(D
.PartialDiagId
) {
1842 // Clean the previous diagnostics.
1843 D
.ShowCallStack
= false;
1844 D
.ImmediateDiag
.reset();
1845 D
.PartialDiagId
.reset();
1848 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
1849 if (ImmediateDiag
) {
1850 // Emit our diagnostic and, if it was a warning or error, output a callstack
1851 // if Fn isn't a priori known-emitted.
1852 bool IsWarningOrError
= S
.getDiagnostics().getDiagnosticLevel(
1853 DiagID
, Loc
) >= DiagnosticsEngine::Warning
;
1854 ImmediateDiag
.reset(); // Emit the immediate diag.
1855 if (IsWarningOrError
&& ShowCallStack
)
1856 emitCallStackNotes(S
, Fn
);
1858 assert((!PartialDiagId
|| ShowCallStack
) &&
1859 "Must always show call stack for deferred diags.");
1863 Sema::SemaDiagnosticBuilder
1864 Sema::targetDiag(SourceLocation Loc
, unsigned DiagID
, FunctionDecl
*FD
) {
1865 FD
= FD
? FD
: getCurFunctionDecl();
1866 if (LangOpts
.OpenMP
)
1867 return LangOpts
.OpenMPIsDevice
? diagIfOpenMPDeviceCode(Loc
, DiagID
, FD
)
1868 : diagIfOpenMPHostCode(Loc
, DiagID
, FD
);
1869 if (getLangOpts().CUDA
)
1870 return getLangOpts().CUDAIsDevice
? CUDADiagIfDeviceCode(Loc
, DiagID
)
1871 : CUDADiagIfHostCode(Loc
, DiagID
);
1873 if (getLangOpts().SYCLIsDevice
)
1874 return SYCLDiagIfDeviceCode(Loc
, DiagID
);
1876 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate
, Loc
, DiagID
,
1880 Sema::SemaDiagnosticBuilder
Sema::Diag(SourceLocation Loc
, unsigned DiagID
,
1882 bool IsError
= Diags
.getDiagnosticIDs()->isDefaultMappingAsError(DiagID
);
1883 bool ShouldDefer
= getLangOpts().CUDA
&& LangOpts
.GPUDeferDiag
&&
1884 DiagnosticIDs::isDeferrable(DiagID
) &&
1885 (DeferHint
|| DeferDiags
|| !IsError
);
1886 auto SetIsLastErrorImmediate
= [&](bool Flag
) {
1888 IsLastErrorImmediate
= Flag
;
1891 SetIsLastErrorImmediate(true);
1892 return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate
, Loc
,
1893 DiagID
, getCurFunctionDecl(), *this);
1896 SemaDiagnosticBuilder DB
= getLangOpts().CUDAIsDevice
1897 ? CUDADiagIfDeviceCode(Loc
, DiagID
)
1898 : CUDADiagIfHostCode(Loc
, DiagID
);
1899 SetIsLastErrorImmediate(DB
.isImmediate());
1903 void Sema::checkTypeSupport(QualType Ty
, SourceLocation Loc
, ValueDecl
*D
) {
1904 if (isUnevaluatedContext() || Ty
.isNull())
1907 // The original idea behind checkTypeSupport function is that unused
1908 // declarations can be replaced with an array of bytes of the same size during
1909 // codegen, such replacement doesn't seem to be possible for types without
1910 // constant byte size like zero length arrays. So, do a deep check for SYCL.
1911 if (D
&& LangOpts
.SYCLIsDevice
) {
1912 llvm::DenseSet
<QualType
> Visited
;
1913 deepTypeCheckForSYCLDevice(Loc
, Visited
, D
);
1916 Decl
*C
= cast
<Decl
>(getCurLexicalContext());
1918 // Memcpy operations for structs containing a member with unsupported type
1920 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(C
)) {
1921 if ((MD
->isCopyAssignmentOperator() || MD
->isMoveAssignmentOperator()) &&
1925 if (const auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(MD
))
1926 if (Ctor
->isCopyOrMoveConstructor() && Ctor
->isTrivial())
1930 // Try to associate errors with the lexical context, if that is a function, or
1931 // the value declaration otherwise.
1932 FunctionDecl
*FD
= isa
<FunctionDecl
>(C
) ? cast
<FunctionDecl
>(C
)
1933 : dyn_cast_or_null
<FunctionDecl
>(D
);
1935 auto CheckDeviceType
= [&](QualType Ty
) {
1936 if (Ty
->isDependentType())
1939 if (Ty
->isBitIntType()) {
1940 if (!Context
.getTargetInfo().hasBitIntType()) {
1941 PartialDiagnostic PD
= PDiag(diag::err_target_unsupported_type
);
1946 targetDiag(Loc
, PD
, FD
)
1947 << false /*show bit size*/ << 0 /*bitsize*/ << false /*return*/
1948 << Ty
<< Context
.getTargetInfo().getTriple().str();
1953 // Check if we are dealing with two 'long double' but with different
1955 bool LongDoubleMismatched
= false;
1956 if (Ty
->isRealFloatingType() && Context
.getTypeSize(Ty
) == 128) {
1957 const llvm::fltSemantics
&Sem
= Context
.getFloatTypeSemantics(Ty
);
1958 if ((&Sem
!= &llvm::APFloat::PPCDoubleDouble() &&
1959 !Context
.getTargetInfo().hasFloat128Type()) ||
1960 (&Sem
== &llvm::APFloat::PPCDoubleDouble() &&
1961 !Context
.getTargetInfo().hasIbm128Type()))
1962 LongDoubleMismatched
= true;
1965 if ((Ty
->isFloat16Type() && !Context
.getTargetInfo().hasFloat16Type()) ||
1966 (Ty
->isFloat128Type() && !Context
.getTargetInfo().hasFloat128Type()) ||
1967 (Ty
->isIbm128Type() && !Context
.getTargetInfo().hasIbm128Type()) ||
1968 (Ty
->isIntegerType() && Context
.getTypeSize(Ty
) == 128 &&
1969 !Context
.getTargetInfo().hasInt128Type()) ||
1970 LongDoubleMismatched
) {
1971 PartialDiagnostic PD
= PDiag(diag::err_target_unsupported_type
);
1977 if (targetDiag(Loc
, PD
, FD
)
1978 << true /*show bit size*/
1979 << static_cast<unsigned>(Context
.getTypeSize(Ty
)) << Ty
1980 << false /*return*/ << Context
.getTargetInfo().getTriple().str()) {
1982 D
->setInvalidDecl();
1985 targetDiag(D
->getLocation(), diag::note_defined_here
, FD
) << D
;
1989 auto CheckType
= [&](QualType Ty
, bool IsRetTy
= false) {
1990 if (LangOpts
.SYCLIsDevice
|| (LangOpts
.OpenMP
&& LangOpts
.OpenMPIsDevice
) ||
1991 LangOpts
.CUDAIsDevice
)
1992 CheckDeviceType(Ty
);
1994 QualType UnqualTy
= Ty
.getCanonicalType().getUnqualifiedType();
1995 const TargetInfo
&TI
= Context
.getTargetInfo();
1996 if (!TI
.hasLongDoubleType() && UnqualTy
== Context
.LongDoubleTy
) {
1997 PartialDiagnostic PD
= PDiag(diag::err_target_unsupported_type
);
2003 if (Diag(Loc
, PD
, FD
)
2004 << false /*show bit size*/ << 0 << Ty
<< false /*return*/
2005 << Context
.getTargetInfo().getTriple().str()) {
2007 D
->setInvalidDecl();
2010 targetDiag(D
->getLocation(), diag::note_defined_here
, FD
) << D
;
2013 bool IsDouble
= UnqualTy
== Context
.DoubleTy
;
2014 bool IsFloat
= UnqualTy
== Context
.FloatTy
;
2015 if (IsRetTy
&& !TI
.hasFPReturn() && (IsDouble
|| IsFloat
)) {
2016 PartialDiagnostic PD
= PDiag(diag::err_target_unsupported_type
);
2022 if (Diag(Loc
, PD
, FD
)
2023 << false /*show bit size*/ << 0 << Ty
<< true /*return*/
2024 << Context
.getTargetInfo().getTriple().str()) {
2026 D
->setInvalidDecl();
2029 targetDiag(D
->getLocation(), diag::note_defined_here
, FD
) << D
;
2034 if (const auto *FPTy
= dyn_cast
<FunctionProtoType
>(Ty
)) {
2035 for (const auto &ParamTy
: FPTy
->param_types())
2037 CheckType(FPTy
->getReturnType(), /*IsRetTy=*/true);
2039 if (const auto *FNPTy
= dyn_cast
<FunctionNoProtoType
>(Ty
))
2040 CheckType(FNPTy
->getReturnType(), /*IsRetTy=*/true);
2043 /// Looks through the macro-expansion chain for the given
2044 /// location, looking for a macro expansion with the given name.
2045 /// If one is found, returns true and sets the location to that
2047 bool Sema::findMacroSpelling(SourceLocation
&locref
, StringRef name
) {
2048 SourceLocation loc
= locref
;
2049 if (!loc
.isMacroID()) return false;
2051 // There's no good way right now to look at the intermediate
2052 // expansions, so just jump to the expansion location.
2053 loc
= getSourceManager().getExpansionLoc(loc
);
2055 // If that's written with the name, stop here.
2056 SmallString
<16> buffer
;
2057 if (getPreprocessor().getSpelling(loc
, buffer
) == name
) {
2064 /// Determines the active Scope associated with the given declaration
2067 /// This routine maps a declaration context to the active Scope object that
2068 /// represents that declaration context in the parser. It is typically used
2069 /// from "scope-less" code (e.g., template instantiation, lazy creation of
2070 /// declarations) that injects a name for name-lookup purposes and, therefore,
2071 /// must update the Scope.
2073 /// \returns The scope corresponding to the given declaraion context, or NULL
2074 /// if no such scope is open.
2075 Scope
*Sema::getScopeForContext(DeclContext
*Ctx
) {
2080 Ctx
= Ctx
->getPrimaryContext();
2081 for (Scope
*S
= getCurScope(); S
; S
= S
->getParent()) {
2082 // Ignore scopes that cannot have declarations. This is important for
2083 // out-of-line definitions of static class members.
2084 if (S
->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope
))
2085 if (DeclContext
*Entity
= S
->getEntity())
2086 if (Ctx
== Entity
->getPrimaryContext())
2093 /// Enter a new function scope
2094 void Sema::PushFunctionScope() {
2095 if (FunctionScopes
.empty() && CachedFunctionScope
) {
2096 // Use CachedFunctionScope to avoid allocating memory when possible.
2097 CachedFunctionScope
->Clear();
2098 FunctionScopes
.push_back(CachedFunctionScope
.release());
2100 FunctionScopes
.push_back(new FunctionScopeInfo(getDiagnostics()));
2102 if (LangOpts
.OpenMP
)
2103 pushOpenMPFunctionRegion();
2106 void Sema::PushBlockScope(Scope
*BlockScope
, BlockDecl
*Block
) {
2107 FunctionScopes
.push_back(new BlockScopeInfo(getDiagnostics(),
2108 BlockScope
, Block
));
2111 LambdaScopeInfo
*Sema::PushLambdaScope() {
2112 LambdaScopeInfo
*const LSI
= new LambdaScopeInfo(getDiagnostics());
2113 FunctionScopes
.push_back(LSI
);
2117 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth
) {
2118 if (LambdaScopeInfo
*const LSI
= getCurLambda()) {
2119 LSI
->AutoTemplateParameterDepth
= Depth
;
2123 "Remove assertion if intentionally called in a non-lambda context.");
2126 // Check that the type of the VarDecl has an accessible copy constructor and
2127 // resolve its destructor's exception specification.
2128 // This also performs initialization of block variables when they are moved
2129 // to the heap. It uses the same rules as applicable for implicit moves
2130 // according to the C++ standard in effect ([class.copy.elision]p3).
2131 static void checkEscapingByref(VarDecl
*VD
, Sema
&S
) {
2132 QualType T
= VD
->getType();
2133 EnterExpressionEvaluationContext
scope(
2134 S
, Sema::ExpressionEvaluationContext::PotentiallyEvaluated
);
2135 SourceLocation Loc
= VD
->getLocation();
2137 new (S
.Context
) DeclRefExpr(S
.Context
, VD
, false, T
, VK_LValue
, Loc
);
2139 auto IE
= InitializedEntity::InitializeBlock(Loc
, T
);
2140 if (S
.getLangOpts().CPlusPlus2b
) {
2141 auto *E
= ImplicitCastExpr::Create(S
.Context
, T
, CK_NoOp
, VarRef
, nullptr,
2142 VK_XValue
, FPOptionsOverride());
2143 Result
= S
.PerformCopyInitialization(IE
, SourceLocation(), E
);
2145 Result
= S
.PerformMoveOrCopyInitialization(
2146 IE
, Sema::NamedReturnInfo
{VD
, Sema::NamedReturnInfo::MoveEligible
},
2150 if (!Result
.isInvalid()) {
2151 Result
= S
.MaybeCreateExprWithCleanups(Result
);
2152 Expr
*Init
= Result
.getAs
<Expr
>();
2153 S
.Context
.setBlockVarCopyInit(VD
, Init
, S
.canThrow(Init
));
2156 // The destructor's exception specification is needed when IRGen generates
2157 // block copy/destroy functions. Resolve it here.
2158 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
2159 if (CXXDestructorDecl
*DD
= RD
->getDestructor()) {
2160 auto *FPT
= DD
->getType()->getAs
<FunctionProtoType
>();
2161 S
.ResolveExceptionSpec(Loc
, FPT
);
2165 static void markEscapingByrefs(const FunctionScopeInfo
&FSI
, Sema
&S
) {
2166 // Set the EscapingByref flag of __block variables captured by
2168 for (const BlockDecl
*BD
: FSI
.Blocks
) {
2169 for (const BlockDecl::Capture
&BC
: BD
->captures()) {
2170 VarDecl
*VD
= BC
.getVariable();
2171 if (VD
->hasAttr
<BlocksAttr
>()) {
2172 // Nothing to do if this is a __block variable captured by a
2173 // non-escaping block.
2174 if (BD
->doesNotEscape())
2176 VD
->setEscapingByref();
2178 // Check whether the captured variable is or contains an object of
2179 // non-trivial C union type.
2180 QualType CapType
= BC
.getVariable()->getType();
2181 if (CapType
.hasNonTrivialToPrimitiveDestructCUnion() ||
2182 CapType
.hasNonTrivialToPrimitiveCopyCUnion())
2183 S
.checkNonTrivialCUnion(BC
.getVariable()->getType(),
2184 BD
->getCaretLocation(),
2185 Sema::NTCUC_BlockCapture
,
2186 Sema::NTCUK_Destruct
|Sema::NTCUK_Copy
);
2190 for (VarDecl
*VD
: FSI
.ByrefBlockVars
) {
2191 // __block variables might require us to capture a copy-initializer.
2192 if (!VD
->isEscapingByref())
2194 // It's currently invalid to ever have a __block variable with an
2195 // array type; should we diagnose that here?
2196 // Regardless, we don't want to ignore array nesting when
2197 // constructing this copy.
2198 if (VD
->getType()->isStructureOrClassType())
2199 checkEscapingByref(VD
, S
);
2203 /// Pop a function (or block or lambda or captured region) scope from the stack.
2205 /// \param WP The warning policy to use for CFG-based warnings, or null if such
2206 /// warnings should not be produced.
2207 /// \param D The declaration corresponding to this function scope, if producing
2208 /// CFG-based warnings.
2209 /// \param BlockType The type of the block expression, if D is a BlockDecl.
2210 Sema::PoppedFunctionScopePtr
2211 Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy
*WP
,
2212 const Decl
*D
, QualType BlockType
) {
2213 assert(!FunctionScopes
.empty() && "mismatched push/pop!");
2215 markEscapingByrefs(*FunctionScopes
.back(), *this);
2217 PoppedFunctionScopePtr
Scope(FunctionScopes
.pop_back_val(),
2218 PoppedFunctionScopeDeleter(this));
2220 if (LangOpts
.OpenMP
)
2221 popOpenMPFunctionRegion(Scope
.get());
2223 // Issue any analysis-based warnings.
2225 AnalysisWarnings
.IssueWarnings(*WP
, Scope
.get(), D
, BlockType
);
2227 for (const auto &PUD
: Scope
->PossiblyUnreachableDiags
)
2228 Diag(PUD
.Loc
, PUD
.PD
);
2233 void Sema::PoppedFunctionScopeDeleter::
2234 operator()(sema::FunctionScopeInfo
*Scope
) const {
2235 // Stash the function scope for later reuse if it's for a normal function.
2236 if (Scope
->isPlainFunction() && !Self
->CachedFunctionScope
)
2237 Self
->CachedFunctionScope
.reset(Scope
);
2242 void Sema::PushCompoundScope(bool IsStmtExpr
) {
2243 getCurFunction()->CompoundScopes
.push_back(
2244 CompoundScopeInfo(IsStmtExpr
, getCurFPFeatures()));
2247 void Sema::PopCompoundScope() {
2248 FunctionScopeInfo
*CurFunction
= getCurFunction();
2249 assert(!CurFunction
->CompoundScopes
.empty() && "mismatched push/pop");
2251 CurFunction
->CompoundScopes
.pop_back();
2254 /// Determine whether any errors occurred within this function/method/
2256 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2257 return getCurFunction()->hasUnrecoverableErrorOccurred();
2260 void Sema::setFunctionHasBranchIntoScope() {
2261 if (!FunctionScopes
.empty())
2262 FunctionScopes
.back()->setHasBranchIntoScope();
2265 void Sema::setFunctionHasBranchProtectedScope() {
2266 if (!FunctionScopes
.empty())
2267 FunctionScopes
.back()->setHasBranchProtectedScope();
2270 void Sema::setFunctionHasIndirectGoto() {
2271 if (!FunctionScopes
.empty())
2272 FunctionScopes
.back()->setHasIndirectGoto();
2275 void Sema::setFunctionHasMustTail() {
2276 if (!FunctionScopes
.empty())
2277 FunctionScopes
.back()->setHasMustTail();
2280 BlockScopeInfo
*Sema::getCurBlock() {
2281 if (FunctionScopes
.empty())
2284 auto CurBSI
= dyn_cast
<BlockScopeInfo
>(FunctionScopes
.back());
2285 if (CurBSI
&& CurBSI
->TheDecl
&&
2286 !CurBSI
->TheDecl
->Encloses(CurContext
)) {
2287 // We have switched contexts due to template instantiation.
2288 assert(!CodeSynthesisContexts
.empty());
2295 FunctionScopeInfo
*Sema::getEnclosingFunction() const {
2296 if (FunctionScopes
.empty())
2299 for (int e
= FunctionScopes
.size() - 1; e
>= 0; --e
) {
2300 if (isa
<sema::BlockScopeInfo
>(FunctionScopes
[e
]))
2302 return FunctionScopes
[e
];
2307 LambdaScopeInfo
*Sema::getEnclosingLambda() const {
2308 for (auto *Scope
: llvm::reverse(FunctionScopes
)) {
2309 if (auto *LSI
= dyn_cast
<sema::LambdaScopeInfo
>(Scope
)) {
2310 if (LSI
->Lambda
&& !LSI
->Lambda
->Encloses(CurContext
)) {
2311 // We have switched contexts due to template instantiation.
2312 // FIXME: We should swap out the FunctionScopes during code synthesis
2313 // so that we don't need to check for this.
2314 assert(!CodeSynthesisContexts
.empty());
2323 LambdaScopeInfo
*Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope
) {
2324 if (FunctionScopes
.empty())
2327 auto I
= FunctionScopes
.rbegin();
2328 if (IgnoreNonLambdaCapturingScope
) {
2329 auto E
= FunctionScopes
.rend();
2330 while (I
!= E
&& isa
<CapturingScopeInfo
>(*I
) && !isa
<LambdaScopeInfo
>(*I
))
2335 auto *CurLSI
= dyn_cast
<LambdaScopeInfo
>(*I
);
2336 if (CurLSI
&& CurLSI
->Lambda
&&
2337 !CurLSI
->Lambda
->Encloses(CurContext
)) {
2338 // We have switched contexts due to template instantiation.
2339 assert(!CodeSynthesisContexts
.empty());
2346 // We have a generic lambda if we parsed auto parameters, or we have
2347 // an associated template parameter list.
2348 LambdaScopeInfo
*Sema::getCurGenericLambda() {
2349 if (LambdaScopeInfo
*LSI
= getCurLambda()) {
2350 return (LSI
->TemplateParams
.size() ||
2351 LSI
->GLTemplateParameterList
) ? LSI
: nullptr;
2357 void Sema::ActOnComment(SourceRange Comment
) {
2358 if (!LangOpts
.RetainCommentsFromSystemHeaders
&&
2359 SourceMgr
.isInSystemHeader(Comment
.getBegin()))
2361 RawComment
RC(SourceMgr
, Comment
, LangOpts
.CommentOpts
, false);
2362 if (RC
.isAlmostTrailingComment()) {
2363 SourceRange
MagicMarkerRange(Comment
.getBegin(),
2364 Comment
.getBegin().getLocWithOffset(3));
2365 StringRef MagicMarkerText
;
2366 switch (RC
.getKind()) {
2367 case RawComment::RCK_OrdinaryBCPL
:
2368 MagicMarkerText
= "///<";
2370 case RawComment::RCK_OrdinaryC
:
2371 MagicMarkerText
= "/**<";
2374 llvm_unreachable("if this is an almost Doxygen comment, "
2375 "it should be ordinary");
2377 Diag(Comment
.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment
) <<
2378 FixItHint::CreateReplacement(MagicMarkerRange
, MagicMarkerText
);
2380 Context
.addComment(RC
);
2383 // Pin this vtable to this file.
2384 ExternalSemaSource::~ExternalSemaSource() {}
2385 char ExternalSemaSource::ID
;
2387 void ExternalSemaSource::ReadMethodPool(Selector Sel
) { }
2388 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel
) { }
2390 void ExternalSemaSource::ReadKnownNamespaces(
2391 SmallVectorImpl
<NamespaceDecl
*> &Namespaces
) {
2394 void ExternalSemaSource::ReadUndefinedButUsed(
2395 llvm::MapVector
<NamedDecl
*, SourceLocation
> &Undefined
) {}
2397 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector
<
2398 FieldDecl
*, llvm::SmallVector
<std::pair
<SourceLocation
, bool>, 4>> &) {}
2400 /// Figure out if an expression could be turned into a call.
2402 /// Use this when trying to recover from an error where the programmer may have
2403 /// written just the name of a function instead of actually calling it.
2405 /// \param E - The expression to examine.
2406 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
2407 /// with no arguments, this parameter is set to the type returned by such a
2408 /// call; otherwise, it is set to an empty QualType.
2409 /// \param OverloadSet - If the expression is an overloaded function
2410 /// name, this parameter is populated with the decls of the various overloads.
2411 bool Sema::tryExprAsCall(Expr
&E
, QualType
&ZeroArgCallReturnTy
,
2412 UnresolvedSetImpl
&OverloadSet
) {
2413 ZeroArgCallReturnTy
= QualType();
2414 OverloadSet
.clear();
2416 const OverloadExpr
*Overloads
= nullptr;
2417 bool IsMemExpr
= false;
2418 if (E
.getType() == Context
.OverloadTy
) {
2419 OverloadExpr::FindResult FR
= OverloadExpr::find(const_cast<Expr
*>(&E
));
2421 // Ignore overloads that are pointer-to-member constants.
2422 if (FR
.HasFormOfMemberPointer
)
2425 Overloads
= FR
.Expression
;
2426 } else if (E
.getType() == Context
.BoundMemberTy
) {
2427 Overloads
= dyn_cast
<UnresolvedMemberExpr
>(E
.IgnoreParens());
2431 bool Ambiguous
= false;
2435 for (OverloadExpr::decls_iterator it
= Overloads
->decls_begin(),
2436 DeclsEnd
= Overloads
->decls_end(); it
!= DeclsEnd
; ++it
) {
2437 OverloadSet
.addDecl(*it
);
2439 // Check whether the function is a non-template, non-member which takes no
2443 if (const FunctionDecl
*OverloadDecl
2444 = dyn_cast
<FunctionDecl
>((*it
)->getUnderlyingDecl())) {
2445 if (OverloadDecl
->getMinRequiredArguments() == 0) {
2446 if (!ZeroArgCallReturnTy
.isNull() && !Ambiguous
&&
2447 (!IsMV
|| !(OverloadDecl
->isCPUDispatchMultiVersion() ||
2448 OverloadDecl
->isCPUSpecificMultiVersion()))) {
2449 ZeroArgCallReturnTy
= QualType();
2452 ZeroArgCallReturnTy
= OverloadDecl
->getReturnType();
2453 IsMV
= OverloadDecl
->isCPUDispatchMultiVersion() ||
2454 OverloadDecl
->isCPUSpecificMultiVersion();
2460 // If it's not a member, use better machinery to try to resolve the call
2462 return !ZeroArgCallReturnTy
.isNull();
2465 // Attempt to call the member with no arguments - this will correctly handle
2466 // member templates with defaults/deduction of template arguments, overloads
2467 // with default arguments, etc.
2468 if (IsMemExpr
&& !E
.isTypeDependent()) {
2469 Sema::TentativeAnalysisScope
Trap(*this);
2470 ExprResult R
= BuildCallToMemberFunction(nullptr, &E
, SourceLocation(),
2471 None
, SourceLocation());
2473 ZeroArgCallReturnTy
= R
.get()->getType();
2479 if (const DeclRefExpr
*DeclRef
= dyn_cast
<DeclRefExpr
>(E
.IgnoreParens())) {
2480 if (const FunctionDecl
*Fun
= dyn_cast
<FunctionDecl
>(DeclRef
->getDecl())) {
2481 if (Fun
->getMinRequiredArguments() == 0)
2482 ZeroArgCallReturnTy
= Fun
->getReturnType();
2487 // We don't have an expression that's convenient to get a FunctionDecl from,
2488 // but we can at least check if the type is "function of 0 arguments".
2489 QualType ExprTy
= E
.getType();
2490 const FunctionType
*FunTy
= nullptr;
2491 QualType PointeeTy
= ExprTy
->getPointeeType();
2492 if (!PointeeTy
.isNull())
2493 FunTy
= PointeeTy
->getAs
<FunctionType
>();
2495 FunTy
= ExprTy
->getAs
<FunctionType
>();
2497 if (const FunctionProtoType
*FPT
=
2498 dyn_cast_or_null
<FunctionProtoType
>(FunTy
)) {
2499 if (FPT
->getNumParams() == 0)
2500 ZeroArgCallReturnTy
= FunTy
->getReturnType();
2506 /// Give notes for a set of overloads.
2508 /// A companion to tryExprAsCall. In cases when the name that the programmer
2509 /// wrote was an overloaded function, we may be able to make some guesses about
2510 /// plausible overloads based on their return types; such guesses can be handed
2511 /// off to this method to be emitted as notes.
2513 /// \param Overloads - The overloads to note.
2514 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2515 /// -fshow-overloads=best, this is the location to attach to the note about too
2516 /// many candidates. Typically this will be the location of the original
2517 /// ill-formed expression.
2518 static void noteOverloads(Sema
&S
, const UnresolvedSetImpl
&Overloads
,
2519 const SourceLocation FinalNoteLoc
) {
2520 unsigned ShownOverloads
= 0;
2521 unsigned SuppressedOverloads
= 0;
2522 for (UnresolvedSetImpl::iterator It
= Overloads
.begin(),
2523 DeclsEnd
= Overloads
.end(); It
!= DeclsEnd
; ++It
) {
2524 if (ShownOverloads
>= S
.Diags
.getNumOverloadCandidatesToShow()) {
2525 ++SuppressedOverloads
;
2529 NamedDecl
*Fn
= (*It
)->getUnderlyingDecl();
2530 // Don't print overloads for non-default multiversioned functions.
2531 if (const auto *FD
= Fn
->getAsFunction()) {
2532 if (FD
->isMultiVersion() && FD
->hasAttr
<TargetAttr
>() &&
2533 !FD
->getAttr
<TargetAttr
>()->isDefaultVersion())
2536 S
.Diag(Fn
->getLocation(), diag::note_possible_target_of_call
);
2540 S
.Diags
.overloadCandidatesShown(ShownOverloads
);
2542 if (SuppressedOverloads
)
2543 S
.Diag(FinalNoteLoc
, diag::note_ovl_too_many_candidates
)
2544 << SuppressedOverloads
;
2547 static void notePlausibleOverloads(Sema
&S
, SourceLocation Loc
,
2548 const UnresolvedSetImpl
&Overloads
,
2549 bool (*IsPlausibleResult
)(QualType
)) {
2550 if (!IsPlausibleResult
)
2551 return noteOverloads(S
, Overloads
, Loc
);
2553 UnresolvedSet
<2> PlausibleOverloads
;
2554 for (OverloadExpr::decls_iterator It
= Overloads
.begin(),
2555 DeclsEnd
= Overloads
.end(); It
!= DeclsEnd
; ++It
) {
2556 const FunctionDecl
*OverloadDecl
= cast
<FunctionDecl
>(*It
);
2557 QualType OverloadResultTy
= OverloadDecl
->getReturnType();
2558 if (IsPlausibleResult(OverloadResultTy
))
2559 PlausibleOverloads
.addDecl(It
.getDecl());
2561 noteOverloads(S
, PlausibleOverloads
, Loc
);
2564 /// Determine whether the given expression can be called by just
2565 /// putting parentheses after it. Notably, expressions with unary
2566 /// operators can't be because the unary operator will start parsing
2567 /// outside the call.
2568 static bool IsCallableWithAppend(Expr
*E
) {
2569 E
= E
->IgnoreImplicit();
2570 return (!isa
<CStyleCastExpr
>(E
) &&
2571 !isa
<UnaryOperator
>(E
) &&
2572 !isa
<BinaryOperator
>(E
) &&
2573 !isa
<CXXOperatorCallExpr
>(E
));
2576 static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr
*E
) {
2577 if (const auto *UO
= dyn_cast
<UnaryOperator
>(E
))
2578 E
= UO
->getSubExpr();
2580 if (const auto *ULE
= dyn_cast
<UnresolvedLookupExpr
>(E
)) {
2581 if (ULE
->getNumDecls() == 0)
2584 const NamedDecl
*ND
= *ULE
->decls_begin();
2585 if (const auto *FD
= dyn_cast
<FunctionDecl
>(ND
))
2586 return FD
->isCPUDispatchMultiVersion() || FD
->isCPUSpecificMultiVersion();
2591 bool Sema::tryToRecoverWithCall(ExprResult
&E
, const PartialDiagnostic
&PD
,
2593 bool (*IsPlausibleResult
)(QualType
)) {
2594 SourceLocation Loc
= E
.get()->getExprLoc();
2595 SourceRange Range
= E
.get()->getSourceRange();
2596 UnresolvedSet
<4> Overloads
;
2598 // If this is a SFINAE context, don't try anything that might trigger ADL
2600 if (!isSFINAEContext()) {
2601 QualType ZeroArgCallTy
;
2602 if (tryExprAsCall(*E
.get(), ZeroArgCallTy
, Overloads
) &&
2603 !ZeroArgCallTy
.isNull() &&
2604 (!IsPlausibleResult
|| IsPlausibleResult(ZeroArgCallTy
))) {
2605 // At this point, we know E is potentially callable with 0
2606 // arguments and that it returns something of a reasonable type,
2607 // so we can emit a fixit and carry on pretending that E was
2608 // actually a CallExpr.
2609 SourceLocation ParenInsertionLoc
= getLocForEndOfToken(Range
.getEnd());
2610 bool IsMV
= IsCPUDispatchCPUSpecificMultiVersion(E
.get());
2611 Diag(Loc
, PD
) << /*zero-arg*/ 1 << IsMV
<< Range
2612 << (IsCallableWithAppend(E
.get())
2613 ? FixItHint::CreateInsertion(ParenInsertionLoc
,
2617 notePlausibleOverloads(*this, Loc
, Overloads
, IsPlausibleResult
);
2619 // FIXME: Try this before emitting the fixit, and suppress diagnostics
2621 E
= BuildCallExpr(nullptr, E
.get(), Range
.getEnd(), None
,
2622 Range
.getEnd().getLocWithOffset(1));
2626 if (!ForceComplain
) return false;
2628 bool IsMV
= IsCPUDispatchCPUSpecificMultiVersion(E
.get());
2629 Diag(Loc
, PD
) << /*not zero-arg*/ 0 << IsMV
<< Range
;
2631 notePlausibleOverloads(*this, Loc
, Overloads
, IsPlausibleResult
);
2636 IdentifierInfo
*Sema::getSuperIdentifier() const {
2638 Ident_super
= &Context
.Idents
.get("super");
2642 IdentifierInfo
*Sema::getFloat128Identifier() const {
2643 if (!Ident___float128
)
2644 Ident___float128
= &Context
.Idents
.get("__float128");
2645 return Ident___float128
;
2648 void Sema::PushCapturedRegionScope(Scope
*S
, CapturedDecl
*CD
, RecordDecl
*RD
,
2649 CapturedRegionKind K
,
2650 unsigned OpenMPCaptureLevel
) {
2651 auto *CSI
= new CapturedRegionScopeInfo(
2652 getDiagnostics(), S
, CD
, RD
, CD
->getContextParam(), K
,
2653 (getLangOpts().OpenMP
&& K
== CR_OpenMP
) ? getOpenMPNestingLevel() : 0,
2654 OpenMPCaptureLevel
);
2655 CSI
->ReturnType
= Context
.VoidTy
;
2656 FunctionScopes
.push_back(CSI
);
2659 CapturedRegionScopeInfo
*Sema::getCurCapturedRegion() {
2660 if (FunctionScopes
.empty())
2663 return dyn_cast
<CapturedRegionScopeInfo
>(FunctionScopes
.back());
2666 const llvm::MapVector
<FieldDecl
*, Sema::DeleteLocs
> &
2667 Sema::getMismatchingDeleteExpressions() const {
2671 Sema::FPFeaturesStateRAII::FPFeaturesStateRAII(Sema
&S
)
2672 : S(S
), OldFPFeaturesState(S
.CurFPFeatures
),
2673 OldOverrides(S
.FpPragmaStack
.CurrentValue
),
2674 OldEvalMethod(S
.PP
.getCurrentFPEvalMethod()),
2675 OldFPPragmaLocation(S
.PP
.getLastFPEvalPragmaLocation()) {}
2677 Sema::FPFeaturesStateRAII::~FPFeaturesStateRAII() {
2678 S
.CurFPFeatures
= OldFPFeaturesState
;
2679 S
.FpPragmaStack
.CurrentValue
= OldOverrides
;
2680 S
.PP
.setCurrentFPEvalMethod(OldFPPragmaLocation
, OldEvalMethod
);