1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the actions class which performs semantic analysis and
11 // builds an AST out of a parse stream.
13 //===----------------------------------------------------------------------===//
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclFriend.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/HeaderSearch.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/CXXFieldCollector.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/ExternalSemaSource.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/MultiplexExternalSemaSource.h"
33 #include "clang/Sema/ObjCMethodList.h"
34 #include "clang/Sema/PrettyDeclStackTrace.h"
35 #include "clang/Sema/Scope.h"
36 #include "clang/Sema/ScopeInfo.h"
37 #include "clang/Sema/SemaConsumer.h"
38 #include "clang/Sema/SemaInternal.h"
39 #include "clang/Sema/TemplateDeduction.h"
40 #include "llvm/ADT/DenseMap.h"
41 #include "llvm/ADT/SmallSet.h"
42 using namespace clang;
45 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
46 return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
49 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
51 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
52 const Preprocessor &PP) {
53 PrintingPolicy Policy = Context.getPrintingPolicy();
54 // Our printing policy is copied over the ASTContext printing policy whenever
55 // a diagnostic is emitted, so recompute it.
56 Policy.Bool = Context.getLangOpts().Bool;
58 if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
59 Policy.Bool = BoolMacro->isObjectLike() &&
60 BoolMacro->getNumTokens() == 1 &&
61 BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
68 void Sema::ActOnTranslationUnitScope(Scope *S) {
70 PushDeclContext(S, Context.getTranslationUnitDecl());
73 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
74 TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
75 : ExternalSource(nullptr), isMultiplexExternalSource(false),
76 FPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
77 Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
78 SourceMgr(PP.getSourceManager()), CollectStats(false),
79 CodeCompleter(CodeCompleter), CurContext(nullptr),
80 OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
81 MSPointerToMemberRepresentationMethod(
82 LangOpts.getMSPointerToMemberRepresentationMethod()),
83 VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)), PackStack(0),
84 DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
85 CodeSegStack(nullptr), CurInitSeg(nullptr), VisContext(nullptr),
86 PragmaAttributeCurrentTargetDecl(nullptr),
87 IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
88 LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
89 StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
90 CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr), NSNumberDecl(nullptr),
91 NSValueDecl(nullptr), NSStringDecl(nullptr),
92 StringWithUTF8StringMethod(nullptr),
93 ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
94 ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
95 DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
96 TUKind(TUKind), NumSFINAEErrors(0), AccessCheckingSFINAE(false),
97 InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
98 ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
99 DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
100 ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
101 CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
104 LoadedExternalKnownNamespaces = false;
105 for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
106 NSNumberLiteralMethods[I] = nullptr;
108 if (getLangOpts().ObjC1)
109 NSAPIObj.reset(new NSAPI(Context));
111 if (getLangOpts().CPlusPlus)
112 FieldCollector.reset(new CXXFieldCollector());
114 // Tell diagnostics how to render things from the AST library.
115 Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
117 ExprEvalContexts.emplace_back(
118 ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
121 FunctionScopes.push_back(new FunctionScopeInfo(Diags));
123 // Initilization of data sharing attributes stack for OpenMP
124 InitDataSharingAttributesStack();
127 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
128 DeclarationName DN = &Context.Idents.get(Name);
129 if (IdResolver.begin(DN) == IdResolver.end())
130 PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
133 void Sema::Initialize() {
134 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
135 SC->InitializeSema(*this);
137 // Tell the external Sema source about this Sema object.
138 if (ExternalSemaSource *ExternalSema
139 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
140 ExternalSema->InitializeSema(*this);
142 // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
143 // will not be able to merge any duplicate __va_list_tag decls correctly.
144 VAListTagName = PP.getIdentifierInfo("__va_list_tag");
149 // Initialize predefined 128-bit integer types, if needed.
150 if (Context.getTargetInfo().hasInt128Type()) {
151 // If either of the 128-bit integer types are unavailable to name lookup,
153 DeclarationName Int128 = &Context.Idents.get("__int128_t");
154 if (IdResolver.begin(Int128) == IdResolver.end())
155 PushOnScopeChains(Context.getInt128Decl(), TUScope);
157 DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
158 if (IdResolver.begin(UInt128) == IdResolver.end())
159 PushOnScopeChains(Context.getUInt128Decl(), TUScope);
163 // Initialize predefined Objective-C types:
164 if (getLangOpts().ObjC1) {
165 // If 'SEL' does not yet refer to any declarations, make it refer to the
167 DeclarationName SEL = &Context.Idents.get("SEL");
168 if (IdResolver.begin(SEL) == IdResolver.end())
169 PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
171 // If 'id' does not yet refer to any declarations, make it refer to the
173 DeclarationName Id = &Context.Idents.get("id");
174 if (IdResolver.begin(Id) == IdResolver.end())
175 PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
177 // Create the built-in typedef for 'Class'.
178 DeclarationName Class = &Context.Idents.get("Class");
179 if (IdResolver.begin(Class) == IdResolver.end())
180 PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
182 // Create the built-in forward declaratino for 'Protocol'.
183 DeclarationName Protocol = &Context.Idents.get("Protocol");
184 if (IdResolver.begin(Protocol) == IdResolver.end())
185 PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
188 // Create the internal type for the *StringMakeConstantString builtins.
189 DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
190 if (IdResolver.begin(ConstantString) == IdResolver.end())
191 PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
193 // Initialize Microsoft "predefined C++ types".
194 if (getLangOpts().MSVCCompat) {
195 if (getLangOpts().CPlusPlus &&
196 IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
197 PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
200 addImplicitTypedef("size_t", Context.getSizeType());
203 // Initialize predefined OpenCL types and supported extensions and (optional)
205 if (getLangOpts().OpenCL) {
206 getOpenCLOptions().addSupport(Context.getTargetInfo().getSupportedOpenCLOpts());
207 getOpenCLOptions().enableSupportedCore(getLangOpts().OpenCLVersion);
208 addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
209 addImplicitTypedef("event_t", Context.OCLEventTy);
210 if (getLangOpts().OpenCLVersion >= 200) {
211 addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
212 addImplicitTypedef("queue_t", Context.OCLQueueTy);
213 addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
214 addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
215 addImplicitTypedef("atomic_uint",
216 Context.getAtomicType(Context.UnsignedIntTy));
217 auto AtomicLongT = Context.getAtomicType(Context.LongTy);
218 addImplicitTypedef("atomic_long", AtomicLongT);
219 auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
220 addImplicitTypedef("atomic_ulong", AtomicULongT);
221 addImplicitTypedef("atomic_float",
222 Context.getAtomicType(Context.FloatTy));
223 auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
224 addImplicitTypedef("atomic_double", AtomicDoubleT);
225 // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
226 // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
227 addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
228 auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
229 addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
230 auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
231 addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
232 auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
233 addImplicitTypedef("atomic_size_t", AtomicSizeT);
234 auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
235 addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
237 // OpenCL v2.0 s6.13.11.6:
238 // - The atomic_long and atomic_ulong types are supported if the
239 // cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
240 // extensions are supported.
241 // - The atomic_double type is only supported if double precision
242 // is supported and the cl_khr_int64_base_atomics and
243 // cl_khr_int64_extended_atomics extensions are supported.
244 // - If the device address space is 64-bits, the data types
245 // atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
246 // atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
247 // cl_khr_int64_extended_atomics extensions are supported.
248 std::vector<QualType> Atomic64BitTypes;
249 Atomic64BitTypes.push_back(AtomicLongT);
250 Atomic64BitTypes.push_back(AtomicULongT);
251 Atomic64BitTypes.push_back(AtomicDoubleT);
252 if (Context.getTypeSize(AtomicSizeT) == 64) {
253 Atomic64BitTypes.push_back(AtomicSizeT);
254 Atomic64BitTypes.push_back(AtomicIntPtrT);
255 Atomic64BitTypes.push_back(AtomicUIntPtrT);
256 Atomic64BitTypes.push_back(AtomicPtrDiffT);
258 for (auto &I : Atomic64BitTypes)
259 setOpenCLExtensionForType(I,
260 "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
262 setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
265 setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
267 #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
268 setOpenCLExtensionForType(Context.Id, Ext);
269 #include "clang/Basic/OpenCLImageTypes.def"
272 if (Context.getTargetInfo().hasBuiltinMSVaList()) {
273 DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
274 if (IdResolver.begin(MSVaList) == IdResolver.end())
275 PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
278 DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
279 if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
280 PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
284 if (VisContext) FreeVisContext();
285 // Kill all the active scopes.
286 for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
287 delete FunctionScopes[I];
288 if (FunctionScopes.size() == 1)
289 delete FunctionScopes[0];
291 // Tell the SemaConsumer to forget about us; we're going out of scope.
292 if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
295 // Detach from the external Sema source.
296 if (ExternalSemaSource *ExternalSema
297 = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
298 ExternalSema->ForgetSema();
300 // If Sema's ExternalSource is the multiplexer - we own it.
301 if (isMultiplexExternalSource)
302 delete ExternalSource;
304 threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
306 // Destroys data sharing attributes stack for OpenMP
307 DestroyDataSharingAttributesStack();
309 assert(DelayedTypos.empty() && "Uncorrected typos!");
312 /// makeUnavailableInSystemHeader - There is an error in the current
313 /// context. If we're still in a system header, and we can plausibly
314 /// make the relevant declaration unavailable instead of erroring, do
315 /// so and return true.
316 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
317 UnavailableAttr::ImplicitReason reason) {
318 // If we're not in a function, it's an error.
319 FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
320 if (!fn) return false;
322 // If we're in template instantiation, it's an error.
323 if (inTemplateInstantiation())
326 // If that function's not in a system header, it's an error.
327 if (!Context.getSourceManager().isInSystemHeader(loc))
330 // If the function is already unavailable, it's not an error.
331 if (fn->hasAttr<UnavailableAttr>()) return true;
333 fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
337 ASTMutationListener *Sema::getASTMutationListener() const {
338 return getASTConsumer().GetASTMutationListener();
341 ///\brief Registers an external source. If an external source already exists,
342 /// creates a multiplex external source and appends to it.
344 ///\param[in] E - A non-null external sema source.
346 void Sema::addExternalSource(ExternalSemaSource *E) {
347 assert(E && "Cannot use with NULL ptr");
349 if (!ExternalSource) {
354 if (isMultiplexExternalSource)
355 static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
357 ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
358 isMultiplexExternalSource = true;
362 /// \brief Print out statistics about the semantic analysis.
363 void Sema::PrintStats() const {
364 llvm::errs() << "\n*** Semantic Analysis Stats:\n";
365 llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
367 BumpAlloc.PrintStats();
368 AnalysisWarnings.PrintStats();
371 void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
373 SourceLocation Loc) {
374 Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
375 if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
378 Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
379 if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
382 Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
385 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
386 if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
388 if (E->getType()->isNullPtrType())
390 // nullptr only exists from C++11 on, so don't warn on its absence earlier.
391 if (!getLangOpts().CPlusPlus11)
394 Diag(E->getLocStart(), diag::warn_zero_as_null_pointer_constant)
395 << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
398 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
399 /// If there is already an implicit cast, merge into the existing one.
400 /// The result is of the given category.
401 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
402 CastKind Kind, ExprValueKind VK,
403 const CXXCastPath *BasePath,
404 CheckedConversionKind CCK) {
406 if (VK == VK_RValue && !E->isRValue()) {
409 llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
411 case CK_LValueToRValue:
412 case CK_ArrayToPointerDecay:
413 case CK_FunctionToPointerDecay:
418 assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
421 diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getLocStart());
422 diagnoseZeroToNullptrConversion(Kind, E);
424 QualType ExprTy = Context.getCanonicalType(E->getType());
425 QualType TypeTy = Context.getCanonicalType(Ty);
427 if (ExprTy == TypeTy)
430 // C++1z [conv.array]: The temporary materialization conversion is applied.
431 // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
432 if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
433 E->getValueKind() == VK_RValue) {
434 // The temporary is an lvalue in C++98 and an xvalue otherwise.
435 ExprResult Materialized = CreateMaterializeTemporaryExpr(
436 E->getType(), E, !getLangOpts().CPlusPlus11);
437 if (Materialized.isInvalid())
439 E = Materialized.get();
442 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
443 if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
444 ImpCast->setType(Ty);
445 ImpCast->setValueKind(VK);
450 return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
453 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
454 /// to the conversion from scalar type ScalarTy to the Boolean type.
455 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
456 switch (ScalarTy->getScalarTypeKind()) {
457 case Type::STK_Bool: return CK_NoOp;
458 case Type::STK_CPointer: return CK_PointerToBoolean;
459 case Type::STK_BlockPointer: return CK_PointerToBoolean;
460 case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
461 case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
462 case Type::STK_Integral: return CK_IntegralToBoolean;
463 case Type::STK_Floating: return CK_FloatingToBoolean;
464 case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
465 case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
470 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
471 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
472 if (D->getMostRecentDecl()->isUsed())
475 if (D->isExternallyVisible())
478 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
479 // If this is a function template and none of its specializations is used,
481 if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
482 for (const auto *Spec : Template->specializations())
483 if (ShouldRemoveFromUnused(SemaRef, Spec))
486 // UnusedFileScopedDecls stores the first declaration.
487 // The declaration may have become definition so check again.
488 const FunctionDecl *DeclToCheck;
489 if (FD->hasBody(DeclToCheck))
490 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
492 // Later redecls may add new information resulting in not having to warn,
494 DeclToCheck = FD->getMostRecentDecl();
495 if (DeclToCheck != FD)
496 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
499 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
500 // If a variable usable in constant expressions is referenced,
501 // don't warn if it isn't used: if the value of a variable is required
502 // for the computation of a constant expression, it doesn't make sense to
503 // warn even if the variable isn't odr-used. (isReferenced doesn't
504 // precisely reflect that, but it's a decent approximation.)
505 if (VD->isReferenced() &&
506 VD->isUsableInConstantExpressions(SemaRef->Context))
509 if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
510 // If this is a variable template and none of its specializations is used,
512 for (const auto *Spec : Template->specializations())
513 if (ShouldRemoveFromUnused(SemaRef, Spec))
516 // UnusedFileScopedDecls stores the first declaration.
517 // The declaration may have become definition so check again.
518 const VarDecl *DeclToCheck = VD->getDefinition();
520 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
522 // Later redecls may add new information resulting in not having to warn,
524 DeclToCheck = VD->getMostRecentDecl();
525 if (DeclToCheck != VD)
526 return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
532 /// Obtains a sorted list of functions and variables that are undefined but
534 void Sema::getUndefinedButUsed(
535 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
536 for (const auto &UndefinedUse : UndefinedButUsed) {
537 NamedDecl *ND = UndefinedUse.first;
539 // Ignore attributes that have become invalid.
540 if (ND->isInvalidDecl()) continue;
542 // __attribute__((weakref)) is basically a definition.
543 if (ND->hasAttr<WeakRefAttr>()) continue;
545 if (isa<CXXDeductionGuideDecl>(ND))
548 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
551 if (FD->isExternallyVisible() &&
552 !FD->getMostRecentDecl()->isInlined())
555 auto *VD = cast<VarDecl>(ND);
556 if (VD->hasDefinition() != VarDecl::DeclarationOnly)
558 if (VD->isExternallyVisible() && !VD->getMostRecentDecl()->isInline())
562 Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
566 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
567 /// or that are inline.
568 static void checkUndefinedButUsed(Sema &S) {
569 if (S.UndefinedButUsed.empty()) return;
571 // Collect all the still-undefined entities with internal linkage.
572 SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
573 S.getUndefinedButUsed(Undefined);
574 if (Undefined.empty()) return;
576 for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
577 I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
578 NamedDecl *ND = I->first;
580 if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
581 // An exported function will always be emitted when defined, so even if
582 // the function is inline, it doesn't have to be emitted in this TU. An
583 // imported function implies that it has been exported somewhere else.
587 if (!ND->isExternallyVisible()) {
588 S.Diag(ND->getLocation(), diag::warn_undefined_internal)
589 << isa<VarDecl>(ND) << ND;
590 } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
592 assert(FD->getMostRecentDecl()->isInlined() &&
593 "used object requires definition but isn't inline or internal?");
594 // FIXME: This is ill-formed; we should reject.
595 S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
597 assert(cast<VarDecl>(ND)->getMostRecentDecl()->isInline() &&
598 "used var requires definition but isn't inline or internal?");
599 S.Diag(ND->getLocation(), diag::err_undefined_inline_var) << ND;
601 if (I->second.isValid())
602 S.Diag(I->second, diag::note_used_here);
605 S.UndefinedButUsed.clear();
608 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
612 SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
613 ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
614 for (auto &WeakID : WeakIDs)
615 WeakUndeclaredIdentifiers.insert(WeakID);
619 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
621 /// \brief Returns true, if all methods and nested classes of the given
622 /// CXXRecordDecl are defined in this translation unit.
624 /// Should only be called from ActOnEndOfTranslationUnit so that all
625 /// definitions are actually read.
626 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
627 RecordCompleteMap &MNCComplete) {
628 RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
629 if (Cache != MNCComplete.end())
630 return Cache->second;
631 if (!RD->isCompleteDefinition())
633 bool Complete = true;
634 for (DeclContext::decl_iterator I = RD->decls_begin(),
636 I != E && Complete; ++I) {
637 if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
638 Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
639 else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
640 // If the template function is marked as late template parsed at this
641 // point, it has not been instantiated and therefore we have not
642 // performed semantic analysis on it yet, so we cannot know if the type
643 // can be considered complete.
644 Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
645 F->getTemplatedDecl()->isDefined();
646 else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
647 if (R->isInjectedClassName())
649 if (R->hasDefinition())
650 Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
656 MNCComplete[RD] = Complete;
660 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
661 /// translation unit, i.e. all methods are defined or pure virtual and all
662 /// friends, friend functions and nested classes are fully defined in this
663 /// translation unit.
665 /// Should only be called from ActOnEndOfTranslationUnit so that all
666 /// definitions are actually read.
667 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
668 RecordCompleteMap &RecordsComplete,
669 RecordCompleteMap &MNCComplete) {
670 RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
671 if (Cache != RecordsComplete.end())
672 return Cache->second;
673 bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
674 for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
675 E = RD->friend_end();
676 I != E && Complete; ++I) {
677 // Check if friend classes and methods are complete.
678 if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
679 // Friend classes are available as the TypeSourceInfo of the FriendDecl.
680 if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
681 Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
685 // Friend functions are available through the NamedDecl of FriendDecl.
686 if (const FunctionDecl *FD =
687 dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
688 Complete = FD->isDefined();
690 // This is a template friend, give up.
694 RecordsComplete[RD] = Complete;
698 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
700 ExternalSource->ReadUnusedLocalTypedefNameCandidates(
701 UnusedLocalTypedefNameCandidates);
702 for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
703 if (TD->isReferenced())
705 Diag(TD->getLocation(), diag::warn_unused_local_typedef)
706 << isa<TypeAliasDecl>(TD) << TD->getDeclName();
708 UnusedLocalTypedefNameCandidates.clear();
711 /// This is called before the very first declaration in the translation unit
712 /// is parsed. Note that the ASTContext may have already injected some
714 void Sema::ActOnStartOfTranslationUnit() {
715 if (getLangOpts().ModulesTS) {
716 // We start in the global module; all those declarations are implicitly
717 // module-private (though they do not have module linkage).
718 Context.getTranslationUnitDecl()->setModuleOwnershipKind(
719 Decl::ModuleOwnershipKind::ModulePrivate);
723 /// ActOnEndOfTranslationUnit - This is called at the very end of the
724 /// translation unit when EOF is reached and all but the top-level scope is
726 void Sema::ActOnEndOfTranslationUnit() {
727 assert(DelayedDiagnostics.getCurrentPool() == nullptr
728 && "reached end of translation unit with a pool attached?");
730 // If code completion is enabled, don't perform any end-of-translation-unit
732 if (PP.isCodeCompletionEnabled())
735 // Complete translation units and modules define vtables and perform implicit
736 // instantiations. PCH files do not.
737 if (TUKind != TU_Prefix) {
738 DiagnoseUseOfUnimplementedSelectors();
740 // If DefinedUsedVTables ends up marking any virtual member functions it
741 // might lead to more pending template instantiations, which we then need
745 // C++: Perform implicit template instantiations.
747 // FIXME: When we perform these implicit instantiations, we do not
748 // carefully keep track of the point of instantiation (C++ [temp.point]).
749 // This means that name lookup that occurs within the template
750 // instantiation will always happen at the end of the translation unit,
751 // so it will find some names that are not required to be found. This is
752 // valid, but we could do better by diagnosing if an instantiation uses a
753 // name that was not visible at its first point of instantiation.
754 if (ExternalSource) {
755 // Load pending instantiations from the external source.
756 SmallVector<PendingImplicitInstantiation, 4> Pending;
757 ExternalSource->ReadPendingInstantiations(Pending);
758 for (auto PII : Pending)
759 if (auto Func = dyn_cast<FunctionDecl>(PII.first))
760 Func->setInstantiationIsPending(true);
761 PendingInstantiations.insert(PendingInstantiations.begin(),
762 Pending.begin(), Pending.end());
764 PerformPendingInstantiations();
766 if (LateTemplateParserCleanup)
767 LateTemplateParserCleanup(OpaqueParser);
769 CheckDelayedMemberExceptionSpecs();
772 DiagnoseUnterminatedPragmaAttribute();
774 // All delayed member exception specs should be checked or we end up accepting
775 // incompatible declarations.
776 // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
777 // write out the lists to the AST file (if any).
778 assert(DelayedDefaultedMemberExceptionSpecs.empty());
779 assert(DelayedExceptionSpecChecks.empty());
781 // All dllexport classes should have been processed already.
782 assert(DelayedDllExportClasses.empty());
784 // Remove file scoped decls that turned out to be used.
785 UnusedFileScopedDecls.erase(
786 std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
787 UnusedFileScopedDecls.end(),
788 [this](const DeclaratorDecl *DD) {
789 return ShouldRemoveFromUnused(this, DD);
791 UnusedFileScopedDecls.end());
793 if (TUKind == TU_Prefix) {
794 // Translation unit prefixes don't need any of the checking below.
795 if (!PP.isIncrementalProcessingEnabled())
800 // Check for #pragma weak identifiers that were never declared
801 LoadExternalWeakUndeclaredIdentifiers();
802 for (auto WeakID : WeakUndeclaredIdentifiers) {
803 if (WeakID.second.getUsed())
806 Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
808 if (PrevDecl != nullptr &&
809 !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
810 Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
811 << "'weak'" << ExpectedVariableOrFunction;
813 Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
817 if (LangOpts.CPlusPlus11 &&
818 !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
819 CheckDelegatingCtorCycles();
821 if (!Diags.hasErrorOccurred()) {
823 ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
824 checkUndefinedButUsed(*this);
827 if (TUKind == TU_Module) {
828 // If we are building a module, resolve all of the exported declarations
830 if (Module *CurrentModule = PP.getCurrentModule()) {
831 ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
833 SmallVector<Module *, 2> Stack;
834 Stack.push_back(CurrentModule);
835 while (!Stack.empty()) {
836 Module *Mod = Stack.pop_back_val();
838 // Resolve the exported declarations and conflicts.
839 // FIXME: Actually complain, once we figure out how to teach the
840 // diagnostic client to deal with complaints in the module map at this
842 ModMap.resolveExports(Mod, /*Complain=*/false);
843 ModMap.resolveUses(Mod, /*Complain=*/false);
844 ModMap.resolveConflicts(Mod, /*Complain=*/false);
846 // Queue the submodules, so their exports will also be resolved.
847 Stack.append(Mod->submodule_begin(), Mod->submodule_end());
851 // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
852 // modules when they are built, not every time they are used.
853 emitAndClearUnusedLocalTypedefWarnings();
855 // Modules don't need any of the checking below.
856 if (!PP.isIncrementalProcessingEnabled())
862 // A declaration of an identifier for an object that has file
863 // scope without an initializer, and without a storage-class
864 // specifier or with the storage-class specifier static,
865 // constitutes a tentative definition. If a translation unit
866 // contains one or more tentative definitions for an identifier,
867 // and the translation unit contains no external definition for
868 // that identifier, then the behavior is exactly as if the
869 // translation unit contains a file scope declaration of that
870 // identifier, with the composite type as of the end of the
871 // translation unit, with an initializer equal to 0.
872 llvm::SmallSet<VarDecl *, 32> Seen;
873 for (TentativeDefinitionsType::iterator
874 T = TentativeDefinitions.begin(ExternalSource),
875 TEnd = TentativeDefinitions.end();
878 VarDecl *VD = (*T)->getActingDefinition();
880 // If the tentative definition was completed, getActingDefinition() returns
881 // null. If we've already seen this variable before, insert()'s second
882 // return value is false.
883 if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
886 if (const IncompleteArrayType *ArrayT
887 = Context.getAsIncompleteArrayType(VD->getType())) {
888 // Set the length of the array to 1 (C99 6.9.2p5).
889 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
890 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
891 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
892 One, ArrayType::Normal, 0);
894 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
895 diag::err_tentative_def_incomplete_type))
896 VD->setInvalidDecl();
898 // No initialization is performed for a tentative definition.
899 CheckCompleteVariableDeclaration(VD);
901 // Notify the consumer that we've completed a tentative definition.
902 if (!VD->isInvalidDecl())
903 Consumer.CompleteTentativeDefinition(VD);
907 // If there were errors, disable 'unused' warnings since they will mostly be
909 if (!Diags.hasErrorOccurred()) {
910 // Output warning for unused file scoped decls.
911 for (UnusedFileScopedDeclsType::iterator
912 I = UnusedFileScopedDecls.begin(ExternalSource),
913 E = UnusedFileScopedDecls.end(); I != E; ++I) {
914 if (ShouldRemoveFromUnused(this, *I))
917 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
918 const FunctionDecl *DiagD;
919 if (!FD->hasBody(DiagD))
921 if (DiagD->isDeleted())
922 continue; // Deleted functions are supposed to be unused.
923 if (DiagD->isReferenced()) {
924 if (isa<CXXMethodDecl>(DiagD))
925 Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
926 << DiagD->getDeclName();
928 if (FD->getStorageClass() == SC_Static &&
929 !FD->isInlineSpecified() &&
930 !SourceMgr.isInMainFile(
931 SourceMgr.getExpansionLoc(FD->getLocation())))
932 Diag(DiagD->getLocation(),
933 diag::warn_unneeded_static_internal_decl)
934 << DiagD->getDeclName();
936 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
937 << /*function*/0 << DiagD->getDeclName();
940 if (FD->getDescribedFunctionTemplate())
941 Diag(DiagD->getLocation(), diag::warn_unused_template)
942 << /*function*/0 << DiagD->getDeclName();
944 Diag(DiagD->getLocation(),
945 isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
946 : diag::warn_unused_function)
947 << DiagD->getDeclName();
950 const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
952 DiagD = cast<VarDecl>(*I);
953 if (DiagD->isReferenced()) {
954 Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
955 << /*variable*/1 << DiagD->getDeclName();
956 } else if (DiagD->getType().isConstQualified()) {
957 const SourceManager &SM = SourceMgr;
958 if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
959 !PP.getLangOpts().IsHeaderFile)
960 Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
961 << DiagD->getDeclName();
963 if (DiagD->getDescribedVarTemplate())
964 Diag(DiagD->getLocation(), diag::warn_unused_template)
965 << /*variable*/1 << DiagD->getDeclName();
967 Diag(DiagD->getLocation(), diag::warn_unused_variable)
968 << DiagD->getDeclName();
973 emitAndClearUnusedLocalTypedefWarnings();
976 if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
977 RecordCompleteMap RecordsComplete;
978 RecordCompleteMap MNCComplete;
979 for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
980 E = UnusedPrivateFields.end(); I != E; ++I) {
981 const NamedDecl *D = *I;
982 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
983 if (RD && !RD->isUnion() &&
984 IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
985 Diag(D->getLocation(), diag::warn_unused_private_field)
991 if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
993 ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
994 for (const auto &DeletedFieldInfo : DeleteExprs) {
995 for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
996 AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
997 DeleteExprLoc.second);
1002 // Check we've noticed that we're no longer parsing the initializer for every
1003 // variable. If we miss cases, then at best we have a performance issue and
1004 // at worst a rejects-valid bug.
1005 assert(ParsingInitForAutoVars.empty() &&
1006 "Didn't unmark var as having its initializer parsed");
1008 if (!PP.isIncrementalProcessingEnabled())
1013 //===----------------------------------------------------------------------===//
1014 // Helper functions.
1015 //===----------------------------------------------------------------------===//
1017 DeclContext *Sema::getFunctionLevelDeclContext() {
1018 DeclContext *DC = CurContext;
1021 if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
1022 DC = DC->getParent();
1023 } else if (isa<CXXMethodDecl>(DC) &&
1024 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1025 cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1026 DC = DC->getParent()->getParent();
1034 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1035 /// to the function decl for the function being parsed. If we're currently
1036 /// in a 'block', this returns the containing context.
1037 FunctionDecl *Sema::getCurFunctionDecl() {
1038 DeclContext *DC = getFunctionLevelDeclContext();
1039 return dyn_cast<FunctionDecl>(DC);
1042 ObjCMethodDecl *Sema::getCurMethodDecl() {
1043 DeclContext *DC = getFunctionLevelDeclContext();
1044 while (isa<RecordDecl>(DC))
1045 DC = DC->getParent();
1046 return dyn_cast<ObjCMethodDecl>(DC);
1049 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
1050 DeclContext *DC = getFunctionLevelDeclContext();
1051 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1052 return cast<NamedDecl>(DC);
1056 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1057 // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1058 // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1059 // been made more painfully obvious by the refactor that introduced this
1060 // function, but it is possible that the incoming argument can be
1061 // eliminated. If it truly cannot be (for example, there is some reentrancy
1062 // issue I am not seeing yet), then there should at least be a clarifying
1063 // comment somewhere.
1064 if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
1065 switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1066 Diags.getCurrentDiagID())) {
1067 case DiagnosticIDs::SFINAE_Report:
1068 // We'll report the diagnostic below.
1071 case DiagnosticIDs::SFINAE_SubstitutionFailure:
1072 // Count this failure so that we know that template argument deduction
1076 // Make a copy of this suppressed diagnostic and store it with the
1077 // template-deduction information.
1078 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1079 Diagnostic DiagInfo(&Diags);
1080 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1081 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1084 Diags.setLastDiagnosticIgnored();
1088 case DiagnosticIDs::SFINAE_AccessControl: {
1089 // Per C++ Core Issue 1170, access control is part of SFINAE.
1090 // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1091 // make access control a part of SFINAE for the purposes of checking
1093 if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
1096 SourceLocation Loc = Diags.getCurrentDiagLoc();
1098 // Suppress this diagnostic.
1101 // Make a copy of this suppressed diagnostic and store it with the
1102 // template-deduction information.
1103 if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1104 Diagnostic DiagInfo(&Diags);
1105 (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1106 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1109 Diags.setLastDiagnosticIgnored();
1112 // Now the diagnostic state is clear, produce a C++98 compatibility
1114 Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1116 // The last diagnostic which Sema produced was ignored. Suppress any
1117 // notes attached to it.
1118 Diags.setLastDiagnosticIgnored();
1122 case DiagnosticIDs::SFINAE_Suppress:
1123 // Make a copy of this suppressed diagnostic and store it with the
1124 // template-deduction information;
1126 Diagnostic DiagInfo(&Diags);
1127 (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1128 PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1131 // Suppress this diagnostic.
1132 Diags.setLastDiagnosticIgnored();
1138 // Set up the context's printing policy based on our current state.
1139 Context.setPrintingPolicy(getPrintingPolicy());
1141 // Emit the diagnostic.
1142 if (!Diags.EmitCurrentDiagnostic())
1145 // If this is not a note, and we're in a template instantiation
1146 // that is different from the last template instantiation where
1147 // we emitted an error, print a template instantiation
1149 if (!DiagnosticIDs::isBuiltinNote(DiagID))
1150 PrintContextStack();
1153 Sema::SemaDiagnosticBuilder
1154 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
1155 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
1161 /// \brief Looks through the macro-expansion chain for the given
1162 /// location, looking for a macro expansion with the given name.
1163 /// If one is found, returns true and sets the location to that
1165 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1166 SourceLocation loc = locref;
1167 if (!loc.isMacroID()) return false;
1169 // There's no good way right now to look at the intermediate
1170 // expansions, so just jump to the expansion location.
1171 loc = getSourceManager().getExpansionLoc(loc);
1173 // If that's written with the name, stop here.
1174 SmallVector<char, 16> buffer;
1175 if (getPreprocessor().getSpelling(loc, buffer) == name) {
1182 /// \brief Determines the active Scope associated with the given declaration
1185 /// This routine maps a declaration context to the active Scope object that
1186 /// represents that declaration context in the parser. It is typically used
1187 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1188 /// declarations) that injects a name for name-lookup purposes and, therefore,
1189 /// must update the Scope.
1191 /// \returns The scope corresponding to the given declaraion context, or NULL
1192 /// if no such scope is open.
1193 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
1198 Ctx = Ctx->getPrimaryContext();
1199 for (Scope *S = getCurScope(); S; S = S->getParent()) {
1200 // Ignore scopes that cannot have declarations. This is important for
1201 // out-of-line definitions of static class members.
1202 if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1203 if (DeclContext *Entity = S->getEntity())
1204 if (Ctx == Entity->getPrimaryContext())
1211 /// \brief Enter a new function scope
1212 void Sema::PushFunctionScope() {
1213 if (FunctionScopes.size() == 1) {
1214 // Use the "top" function scope rather than having to allocate
1215 // memory for a new scope.
1216 FunctionScopes.back()->Clear();
1217 FunctionScopes.push_back(FunctionScopes.back());
1218 if (LangOpts.OpenMP)
1219 pushOpenMPFunctionRegion();
1223 FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1224 if (LangOpts.OpenMP)
1225 pushOpenMPFunctionRegion();
1228 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1229 FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
1230 BlockScope, Block));
1233 LambdaScopeInfo *Sema::PushLambdaScope() {
1234 LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1235 FunctionScopes.push_back(LSI);
1239 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1240 if (LambdaScopeInfo *const LSI = getCurLambda()) {
1241 LSI->AutoTemplateParameterDepth = Depth;
1245 "Remove assertion if intentionally called in a non-lambda context.");
1248 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1249 const Decl *D, const BlockExpr *blkExpr) {
1250 FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1251 assert(!FunctionScopes.empty() && "mismatched push/pop!");
1253 if (LangOpts.OpenMP)
1254 popOpenMPFunctionRegion(Scope);
1256 // Issue any analysis-based warnings.
1258 AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1260 for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1261 Diag(PUD.Loc, PUD.PD);
1263 if (FunctionScopes.back() != Scope)
1267 void Sema::PushCompoundScope() {
1268 getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
1271 void Sema::PopCompoundScope() {
1272 FunctionScopeInfo *CurFunction = getCurFunction();
1273 assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1275 CurFunction->CompoundScopes.pop_back();
1278 /// \brief Determine whether any errors occurred within this function/method/
1280 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
1281 return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
1284 BlockScopeInfo *Sema::getCurBlock() {
1285 if (FunctionScopes.empty())
1288 auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1289 if (CurBSI && CurBSI->TheDecl &&
1290 !CurBSI->TheDecl->Encloses(CurContext)) {
1291 // We have switched contexts due to template instantiation.
1292 assert(!CodeSynthesisContexts.empty());
1299 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
1300 if (FunctionScopes.empty())
1303 auto I = FunctionScopes.rbegin();
1304 if (IgnoreNonLambdaCapturingScope) {
1305 auto E = FunctionScopes.rend();
1306 while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
1311 auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
1312 if (CurLSI && CurLSI->Lambda &&
1313 !CurLSI->Lambda->Encloses(CurContext)) {
1314 // We have switched contexts due to template instantiation.
1315 assert(!CodeSynthesisContexts.empty());
1321 // We have a generic lambda if we parsed auto parameters, or we have
1322 // an associated template parameter list.
1323 LambdaScopeInfo *Sema::getCurGenericLambda() {
1324 if (LambdaScopeInfo *LSI = getCurLambda()) {
1325 return (LSI->AutoTemplateParams.size() ||
1326 LSI->GLTemplateParameterList) ? LSI : nullptr;
1332 void Sema::ActOnComment(SourceRange Comment) {
1333 if (!LangOpts.RetainCommentsFromSystemHeaders &&
1334 SourceMgr.isInSystemHeader(Comment.getBegin()))
1336 RawComment RC(SourceMgr, Comment, false,
1337 LangOpts.CommentOpts.ParseAllComments);
1338 if (RC.isAlmostTrailingComment()) {
1339 SourceRange MagicMarkerRange(Comment.getBegin(),
1340 Comment.getBegin().getLocWithOffset(3));
1341 StringRef MagicMarkerText;
1342 switch (RC.getKind()) {
1343 case RawComment::RCK_OrdinaryBCPL:
1344 MagicMarkerText = "///<";
1346 case RawComment::RCK_OrdinaryC:
1347 MagicMarkerText = "/**<";
1350 llvm_unreachable("if this is an almost Doxygen comment, "
1351 "it should be ordinary");
1353 Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1354 FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1356 Context.addComment(RC);
1359 // Pin this vtable to this file.
1360 ExternalSemaSource::~ExternalSemaSource() {}
1362 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
1363 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
1365 void ExternalSemaSource::ReadKnownNamespaces(
1366 SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1369 void ExternalSemaSource::ReadUndefinedButUsed(
1370 llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
1372 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
1373 FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
1375 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1376 SourceLocation Loc = this->Loc;
1377 if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1378 if (Loc.isValid()) {
1379 Loc.print(OS, S.getSourceManager());
1384 if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
1386 ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true);
1393 /// \brief Figure out if an expression could be turned into a call.
1395 /// Use this when trying to recover from an error where the programmer may have
1396 /// written just the name of a function instead of actually calling it.
1398 /// \param E - The expression to examine.
1399 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1400 /// with no arguments, this parameter is set to the type returned by such a
1401 /// call; otherwise, it is set to an empty QualType.
1402 /// \param OverloadSet - If the expression is an overloaded function
1403 /// name, this parameter is populated with the decls of the various overloads.
1404 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1405 UnresolvedSetImpl &OverloadSet) {
1406 ZeroArgCallReturnTy = QualType();
1407 OverloadSet.clear();
1409 const OverloadExpr *Overloads = nullptr;
1410 bool IsMemExpr = false;
1411 if (E.getType() == Context.OverloadTy) {
1412 OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1414 // Ignore overloads that are pointer-to-member constants.
1415 if (FR.HasFormOfMemberPointer)
1418 Overloads = FR.Expression;
1419 } else if (E.getType() == Context.BoundMemberTy) {
1420 Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1424 bool Ambiguous = false;
1427 for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1428 DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1429 OverloadSet.addDecl(*it);
1431 // Check whether the function is a non-template, non-member which takes no
1435 if (const FunctionDecl *OverloadDecl
1436 = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1437 if (OverloadDecl->getMinRequiredArguments() == 0) {
1438 if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1439 ZeroArgCallReturnTy = QualType();
1442 ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1447 // If it's not a member, use better machinery to try to resolve the call
1449 return !ZeroArgCallReturnTy.isNull();
1452 // Attempt to call the member with no arguments - this will correctly handle
1453 // member templates with defaults/deduction of template arguments, overloads
1454 // with default arguments, etc.
1455 if (IsMemExpr && !E.isTypeDependent()) {
1456 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1457 getDiagnostics().setSuppressAllDiagnostics(true);
1458 ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
1459 None, SourceLocation());
1460 getDiagnostics().setSuppressAllDiagnostics(Suppress);
1462 ZeroArgCallReturnTy = R.get()->getType();
1468 if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1469 if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1470 if (Fun->getMinRequiredArguments() == 0)
1471 ZeroArgCallReturnTy = Fun->getReturnType();
1476 // We don't have an expression that's convenient to get a FunctionDecl from,
1477 // but we can at least check if the type is "function of 0 arguments".
1478 QualType ExprTy = E.getType();
1479 const FunctionType *FunTy = nullptr;
1480 QualType PointeeTy = ExprTy->getPointeeType();
1481 if (!PointeeTy.isNull())
1482 FunTy = PointeeTy->getAs<FunctionType>();
1484 FunTy = ExprTy->getAs<FunctionType>();
1486 if (const FunctionProtoType *FPT =
1487 dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1488 if (FPT->getNumParams() == 0)
1489 ZeroArgCallReturnTy = FunTy->getReturnType();
1495 /// \brief Give notes for a set of overloads.
1497 /// A companion to tryExprAsCall. In cases when the name that the programmer
1498 /// wrote was an overloaded function, we may be able to make some guesses about
1499 /// plausible overloads based on their return types; such guesses can be handed
1500 /// off to this method to be emitted as notes.
1502 /// \param Overloads - The overloads to note.
1503 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1504 /// -fshow-overloads=best, this is the location to attach to the note about too
1505 /// many candidates. Typically this will be the location of the original
1506 /// ill-formed expression.
1507 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1508 const SourceLocation FinalNoteLoc) {
1509 int ShownOverloads = 0;
1510 int SuppressedOverloads = 0;
1511 for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1512 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1513 // FIXME: Magic number for max shown overloads stolen from
1514 // OverloadCandidateSet::NoteCandidates.
1515 if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1516 ++SuppressedOverloads;
1520 NamedDecl *Fn = (*It)->getUnderlyingDecl();
1521 S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1525 if (SuppressedOverloads)
1526 S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1527 << SuppressedOverloads;
1530 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
1531 const UnresolvedSetImpl &Overloads,
1532 bool (*IsPlausibleResult)(QualType)) {
1533 if (!IsPlausibleResult)
1534 return noteOverloads(S, Overloads, Loc);
1536 UnresolvedSet<2> PlausibleOverloads;
1537 for (OverloadExpr::decls_iterator It = Overloads.begin(),
1538 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1539 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1540 QualType OverloadResultTy = OverloadDecl->getReturnType();
1541 if (IsPlausibleResult(OverloadResultTy))
1542 PlausibleOverloads.addDecl(It.getDecl());
1544 noteOverloads(S, PlausibleOverloads, Loc);
1547 /// Determine whether the given expression can be called by just
1548 /// putting parentheses after it. Notably, expressions with unary
1549 /// operators can't be because the unary operator will start parsing
1550 /// outside the call.
1551 static bool IsCallableWithAppend(Expr *E) {
1552 E = E->IgnoreImplicit();
1553 return (!isa<CStyleCastExpr>(E) &&
1554 !isa<UnaryOperator>(E) &&
1555 !isa<BinaryOperator>(E) &&
1556 !isa<CXXOperatorCallExpr>(E));
1559 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1561 bool (*IsPlausibleResult)(QualType)) {
1562 SourceLocation Loc = E.get()->getExprLoc();
1563 SourceRange Range = E.get()->getSourceRange();
1565 QualType ZeroArgCallTy;
1566 UnresolvedSet<4> Overloads;
1567 if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1568 !ZeroArgCallTy.isNull() &&
1569 (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1570 // At this point, we know E is potentially callable with 0
1571 // arguments and that it returns something of a reasonable type,
1572 // so we can emit a fixit and carry on pretending that E was
1573 // actually a CallExpr.
1574 SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
1576 << /*zero-arg*/ 1 << Range
1577 << (IsCallableWithAppend(E.get())
1578 ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1580 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1582 // FIXME: Try this before emitting the fixit, and suppress diagnostics
1584 E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
1585 Range.getEnd().getLocWithOffset(1));
1589 if (!ForceComplain) return false;
1591 Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1592 notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1597 IdentifierInfo *Sema::getSuperIdentifier() const {
1599 Ident_super = &Context.Idents.get("super");
1603 IdentifierInfo *Sema::getFloat128Identifier() const {
1604 if (!Ident___float128)
1605 Ident___float128 = &Context.Idents.get("__float128");
1606 return Ident___float128;
1609 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
1610 CapturedRegionKind K) {
1611 CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
1612 getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
1613 (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0);
1614 CSI->ReturnType = Context.VoidTy;
1615 FunctionScopes.push_back(CSI);
1618 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
1619 if (FunctionScopes.empty())
1622 return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1625 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
1626 Sema::getMismatchingDeleteExpressions() const {
1630 void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
1633 llvm::SmallVector<StringRef, 1> Exts;
1634 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
1635 auto CanT = T.getCanonicalType().getTypePtr();
1636 for (auto &I : Exts)
1637 OpenCLTypeExtMap[CanT].insert(I.str());
1640 void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
1641 llvm::SmallVector<StringRef, 1> Exts;
1642 ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
1645 for (auto &I : Exts)
1646 OpenCLDeclExtMap[FD].insert(I.str());
1649 void Sema::setCurrentOpenCLExtensionForType(QualType T) {
1650 if (CurrOpenCLExtension.empty())
1652 setOpenCLExtensionForType(T, CurrOpenCLExtension);
1655 void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
1656 if (CurrOpenCLExtension.empty())
1658 setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
1661 bool Sema::isOpenCLDisabledDecl(Decl *FD) {
1662 auto Loc = OpenCLDeclExtMap.find(FD);
1663 if (Loc == OpenCLDeclExtMap.end())
1665 for (auto &I : Loc->second) {
1666 if (!getOpenCLOptions().isEnabled(I))
1672 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
1673 bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
1674 DiagInfoT DiagInfo, MapT &Map,
1676 SourceRange SrcRange) {
1677 auto Loc = Map.find(D);
1678 if (Loc == Map.end())
1680 bool Disabled = false;
1681 for (auto &I : Loc->second) {
1682 if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
1683 Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
1691 bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
1692 // Check extensions for declared types.
1693 Decl *Decl = nullptr;
1694 if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
1695 Decl = TypedefT->getDecl();
1696 if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
1697 Decl = TagT->getDecl();
1698 auto Loc = DS.getTypeSpecTypeLoc();
1699 if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
1702 // Check extensions for builtin types.
1703 return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
1704 QT, OpenCLTypeExtMap);
1707 bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) {
1708 IdentifierInfo *FnName = D.getIdentifier();
1709 return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), FnName,
1710 OpenCLDeclExtMap, 1, D.getSourceRange());