xref: /llvm-project-15.0.7/clang/lib/Sema/Sema.cpp (revision 1cb0256a)
1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the actions class which performs semantic analysis and
11 // builds an AST out of a parse stream.
12 //
13 //===----------------------------------------------------------------------===//
14 
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;
43 using namespace sema;
44 
45 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
46   return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
47 }
48 
49 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
50 
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;
57   if (!Policy.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);
62     }
63   }
64 
65   return Policy;
66 }
67 
68 void Sema::ActOnTranslationUnitScope(Scope *S) {
69   TUScope = S;
70   PushDeclContext(S, Context.getTranslationUnitDecl());
71 }
72 
73 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
74            TranslationUnitKind TUKind,
75            CodeCompleteConsumer *CodeCompleter)
76   : ExternalSource(nullptr),
77     isMultiplexExternalSource(false), FPFeatures(pp.getLangOpts()),
78     LangOpts(pp.getLangOpts()), PP(pp), Context(ctxt), Consumer(consumer),
79     Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
80     CollectStats(false), CodeCompleter(CodeCompleter),
81     CurContext(nullptr), OriginalLexicalContext(nullptr),
82     MSStructPragmaOn(false),
83     MSPointerToMemberRepresentationMethod(
84         LangOpts.getMSPointerToMemberRepresentationMethod()),
85     VtorDispStack(MSVtorDispAttr::Mode(LangOpts.VtorDispMode)),
86     PackStack(0), DataSegStack(nullptr), BSSSegStack(nullptr),
87     ConstSegStack(nullptr), CodeSegStack(nullptr), CurInitSeg(nullptr),
88     VisContext(nullptr),
89     IsBuildingRecoveryCallExpr(false),
90     Cleanup{}, LateTemplateParser(nullptr),
91     LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
92     StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
93     CXXTypeInfoDecl(nullptr), MSVCGuidDecl(nullptr),
94     NSNumberDecl(nullptr), NSValueDecl(nullptr),
95     NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
96     ValueWithBytesObjCTypeMethod(nullptr),
97     NSArrayDecl(nullptr), ArrayWithObjectsMethod(nullptr),
98     NSDictionaryDecl(nullptr), DictionaryWithObjectsMethod(nullptr),
99     GlobalNewDeleteDeclared(false),
100     TUKind(TUKind),
101     NumSFINAEErrors(0),
102     CachedFakeTopLevelModule(nullptr),
103     AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
104     NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
105     CurrentInstantiationScope(nullptr), DisableTypoCorrection(false),
106     TyposCorrected(0), AnalysisWarnings(*this), ThreadSafetyDeclCache(nullptr),
107     VarDataSharingAttributesStack(nullptr), CurScope(nullptr),
108     Ident_super(nullptr), Ident___float128(nullptr)
109 {
110   TUScope = nullptr;
111 
112   LoadedExternalKnownNamespaces = false;
113   for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
114     NSNumberLiteralMethods[I] = nullptr;
115 
116   if (getLangOpts().ObjC1)
117     NSAPIObj.reset(new NSAPI(Context));
118 
119   if (getLangOpts().CPlusPlus)
120     FieldCollector.reset(new CXXFieldCollector());
121 
122   // Tell diagnostics how to render things from the AST library.
123   Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
124 
125   ExprEvalContexts.emplace_back(PotentiallyEvaluated, 0, CleanupInfo{}, nullptr,
126                                 false);
127 
128   FunctionScopes.push_back(new FunctionScopeInfo(Diags));
129 
130   // Initilization of data sharing attributes stack for OpenMP
131   InitDataSharingAttributesStack();
132 }
133 
134 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
135   DeclarationName DN = &Context.Idents.get(Name);
136   if (IdResolver.begin(DN) == IdResolver.end())
137     PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
138 }
139 
140 void Sema::Initialize() {
141   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
142     SC->InitializeSema(*this);
143 
144   // Tell the external Sema source about this Sema object.
145   if (ExternalSemaSource *ExternalSema
146       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
147     ExternalSema->InitializeSema(*this);
148 
149   // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
150   // will not be able to merge any duplicate __va_list_tag decls correctly.
151   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
152 
153   if (!TUScope)
154     return;
155 
156   // Initialize predefined 128-bit integer types, if needed.
157   if (Context.getTargetInfo().hasInt128Type()) {
158     // If either of the 128-bit integer types are unavailable to name lookup,
159     // define them now.
160     DeclarationName Int128 = &Context.Idents.get("__int128_t");
161     if (IdResolver.begin(Int128) == IdResolver.end())
162       PushOnScopeChains(Context.getInt128Decl(), TUScope);
163 
164     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
165     if (IdResolver.begin(UInt128) == IdResolver.end())
166       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
167   }
168 
169 
170   // Initialize predefined Objective-C types:
171   if (getLangOpts().ObjC1) {
172     // If 'SEL' does not yet refer to any declarations, make it refer to the
173     // predefined 'SEL'.
174     DeclarationName SEL = &Context.Idents.get("SEL");
175     if (IdResolver.begin(SEL) == IdResolver.end())
176       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
177 
178     // If 'id' does not yet refer to any declarations, make it refer to the
179     // predefined 'id'.
180     DeclarationName Id = &Context.Idents.get("id");
181     if (IdResolver.begin(Id) == IdResolver.end())
182       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
183 
184     // Create the built-in typedef for 'Class'.
185     DeclarationName Class = &Context.Idents.get("Class");
186     if (IdResolver.begin(Class) == IdResolver.end())
187       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
188 
189     // Create the built-in forward declaratino for 'Protocol'.
190     DeclarationName Protocol = &Context.Idents.get("Protocol");
191     if (IdResolver.begin(Protocol) == IdResolver.end())
192       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
193   }
194 
195   // Create the internal type for the *StringMakeConstantString builtins.
196   DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
197   if (IdResolver.begin(ConstantString) == IdResolver.end())
198     PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
199 
200   // Initialize Microsoft "predefined C++ types".
201   if (getLangOpts().MSVCCompat) {
202     if (getLangOpts().CPlusPlus &&
203         IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
204       PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
205                         TUScope);
206 
207     addImplicitTypedef("size_t", Context.getSizeType());
208   }
209 
210   // Initialize predefined OpenCL types and supported extensions and (optional)
211   // core features.
212   if (getLangOpts().OpenCL) {
213     getOpenCLOptions().addSupport(Context.getTargetInfo().getSupportedOpenCLOpts());
214     getOpenCLOptions().enableSupportedCore(getLangOpts().OpenCLVersion);
215     addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
216     addImplicitTypedef("event_t", Context.OCLEventTy);
217     if (getLangOpts().OpenCLVersion >= 200) {
218       addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
219       addImplicitTypedef("queue_t", Context.OCLQueueTy);
220       addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
221       addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
222       addImplicitTypedef("atomic_uint",
223                          Context.getAtomicType(Context.UnsignedIntTy));
224       auto AtomicLongT = Context.getAtomicType(Context.LongTy);
225       addImplicitTypedef("atomic_long", AtomicLongT);
226       auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
227       addImplicitTypedef("atomic_ulong", AtomicULongT);
228       addImplicitTypedef("atomic_float",
229                          Context.getAtomicType(Context.FloatTy));
230       auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
231       addImplicitTypedef("atomic_double", AtomicDoubleT);
232       // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
233       // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
234       addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
235       auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
236       addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
237       auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
238       addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
239       auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
240       addImplicitTypedef("atomic_size_t", AtomicSizeT);
241       auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
242       addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
243 
244       // OpenCL v2.0 s6.13.11.6:
245       // - The atomic_long and atomic_ulong types are supported if the
246       //   cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
247       //   extensions are supported.
248       // - The atomic_double type is only supported if double precision
249       //   is supported and the cl_khr_int64_base_atomics and
250       //   cl_khr_int64_extended_atomics extensions are supported.
251       // - If the device address space is 64-bits, the data types
252       //   atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
253       //   atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
254       //   cl_khr_int64_extended_atomics extensions are supported.
255       std::vector<QualType> Atomic64BitTypes;
256       Atomic64BitTypes.push_back(AtomicLongT);
257       Atomic64BitTypes.push_back(AtomicULongT);
258       Atomic64BitTypes.push_back(AtomicDoubleT);
259       if (Context.getTypeSize(AtomicSizeT) == 64) {
260         Atomic64BitTypes.push_back(AtomicSizeT);
261         Atomic64BitTypes.push_back(AtomicIntPtrT);
262         Atomic64BitTypes.push_back(AtomicUIntPtrT);
263         Atomic64BitTypes.push_back(AtomicPtrDiffT);
264       }
265       for (auto &I : Atomic64BitTypes)
266         setOpenCLExtensionForType(I,
267             "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
268 
269       setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
270     }
271 
272     setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
273 
274 #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
275     setOpenCLExtensionForType(Context.Id, Ext);
276 #include "clang/Basic/OpenCLImageTypes.def"
277     };
278 
279   if (Context.getTargetInfo().hasBuiltinMSVaList()) {
280     DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
281     if (IdResolver.begin(MSVaList) == IdResolver.end())
282       PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
283   }
284 
285   DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
286   if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
287     PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
288 }
289 
290 Sema::~Sema() {
291   if (VisContext) FreeVisContext();
292   // Kill all the active scopes.
293   for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
294     delete FunctionScopes[I];
295   if (FunctionScopes.size() == 1)
296     delete FunctionScopes[0];
297 
298   // Tell the SemaConsumer to forget about us; we're going out of scope.
299   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
300     SC->ForgetSema();
301 
302   // Detach from the external Sema source.
303   if (ExternalSemaSource *ExternalSema
304         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
305     ExternalSema->ForgetSema();
306 
307   // If Sema's ExternalSource is the multiplexer - we own it.
308   if (isMultiplexExternalSource)
309     delete ExternalSource;
310 
311   threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
312 
313   // Destroys data sharing attributes stack for OpenMP
314   DestroyDataSharingAttributesStack();
315 
316   assert(DelayedTypos.empty() && "Uncorrected typos!");
317 }
318 
319 /// makeUnavailableInSystemHeader - There is an error in the current
320 /// context.  If we're still in a system header, and we can plausibly
321 /// make the relevant declaration unavailable instead of erroring, do
322 /// so and return true.
323 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
324                                       UnavailableAttr::ImplicitReason reason) {
325   // If we're not in a function, it's an error.
326   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
327   if (!fn) return false;
328 
329   // If we're in template instantiation, it's an error.
330   if (inTemplateInstantiation())
331     return false;
332 
333   // If that function's not in a system header, it's an error.
334   if (!Context.getSourceManager().isInSystemHeader(loc))
335     return false;
336 
337   // If the function is already unavailable, it's not an error.
338   if (fn->hasAttr<UnavailableAttr>()) return true;
339 
340   fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
341   return true;
342 }
343 
344 ASTMutationListener *Sema::getASTMutationListener() const {
345   return getASTConsumer().GetASTMutationListener();
346 }
347 
348 ///\brief Registers an external source. If an external source already exists,
349 /// creates a multiplex external source and appends to it.
350 ///
351 ///\param[in] E - A non-null external sema source.
352 ///
353 void Sema::addExternalSource(ExternalSemaSource *E) {
354   assert(E && "Cannot use with NULL ptr");
355 
356   if (!ExternalSource) {
357     ExternalSource = E;
358     return;
359   }
360 
361   if (isMultiplexExternalSource)
362     static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
363   else {
364     ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
365     isMultiplexExternalSource = true;
366   }
367 }
368 
369 /// \brief Print out statistics about the semantic analysis.
370 void Sema::PrintStats() const {
371   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
372   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
373 
374   BumpAlloc.PrintStats();
375   AnalysisWarnings.PrintStats();
376 }
377 
378 void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
379                                                QualType SrcType,
380                                                SourceLocation Loc) {
381   Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
382   if (!ExprNullability || *ExprNullability != NullabilityKind::Nullable)
383     return;
384 
385   Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
386   if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
387     return;
388 
389   Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
390 }
391 
392 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
393 /// If there is already an implicit cast, merge into the existing one.
394 /// The result is of the given category.
395 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
396                                    CastKind Kind, ExprValueKind VK,
397                                    const CXXCastPath *BasePath,
398                                    CheckedConversionKind CCK) {
399 #ifndef NDEBUG
400   if (VK == VK_RValue && !E->isRValue()) {
401     switch (Kind) {
402     default:
403       llvm_unreachable("can't implicitly cast lvalue to rvalue with this cast "
404                        "kind");
405     case CK_LValueToRValue:
406     case CK_ArrayToPointerDecay:
407     case CK_FunctionToPointerDecay:
408     case CK_ToVoid:
409       break;
410     }
411   }
412   assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
413 #endif
414 
415   diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getLocStart());
416 
417   QualType ExprTy = Context.getCanonicalType(E->getType());
418   QualType TypeTy = Context.getCanonicalType(Ty);
419 
420   if (ExprTy == TypeTy)
421     return E;
422 
423   // C++1z [conv.array]: The temporary materialization conversion is applied.
424   // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
425   if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
426       E->getValueKind() == VK_RValue) {
427     // The temporary is an lvalue in C++98 and an xvalue otherwise.
428     ExprResult Materialized = CreateMaterializeTemporaryExpr(
429         E->getType(), E, !getLangOpts().CPlusPlus11);
430     if (Materialized.isInvalid())
431       return ExprError();
432     E = Materialized.get();
433   }
434 
435   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
436     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
437       ImpCast->setType(Ty);
438       ImpCast->setValueKind(VK);
439       return E;
440     }
441   }
442 
443   return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK);
444 }
445 
446 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
447 /// to the conversion from scalar type ScalarTy to the Boolean type.
448 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
449   switch (ScalarTy->getScalarTypeKind()) {
450   case Type::STK_Bool: return CK_NoOp;
451   case Type::STK_CPointer: return CK_PointerToBoolean;
452   case Type::STK_BlockPointer: return CK_PointerToBoolean;
453   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
454   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
455   case Type::STK_Integral: return CK_IntegralToBoolean;
456   case Type::STK_Floating: return CK_FloatingToBoolean;
457   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
458   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
459   }
460   return CK_Invalid;
461 }
462 
463 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
464 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
465   if (D->getMostRecentDecl()->isUsed())
466     return true;
467 
468   if (D->isExternallyVisible())
469     return true;
470 
471   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
472     // UnusedFileScopedDecls stores the first declaration.
473     // The declaration may have become definition so check again.
474     const FunctionDecl *DeclToCheck;
475     if (FD->hasBody(DeclToCheck))
476       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
477 
478     // Later redecls may add new information resulting in not having to warn,
479     // so check again.
480     DeclToCheck = FD->getMostRecentDecl();
481     if (DeclToCheck != FD)
482       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
483   }
484 
485   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
486     // If a variable usable in constant expressions is referenced,
487     // don't warn if it isn't used: if the value of a variable is required
488     // for the computation of a constant expression, it doesn't make sense to
489     // warn even if the variable isn't odr-used.  (isReferenced doesn't
490     // precisely reflect that, but it's a decent approximation.)
491     if (VD->isReferenced() &&
492         VD->isUsableInConstantExpressions(SemaRef->Context))
493       return true;
494 
495     // UnusedFileScopedDecls stores the first declaration.
496     // The declaration may have become definition so check again.
497     const VarDecl *DeclToCheck = VD->getDefinition();
498     if (DeclToCheck)
499       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
500 
501     // Later redecls may add new information resulting in not having to warn,
502     // so check again.
503     DeclToCheck = VD->getMostRecentDecl();
504     if (DeclToCheck != VD)
505       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
506   }
507 
508   return false;
509 }
510 
511 /// Obtains a sorted list of functions and variables that are undefined but
512 /// ODR-used.
513 void Sema::getUndefinedButUsed(
514     SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
515   for (const auto &UndefinedUse : UndefinedButUsed) {
516     NamedDecl *ND = UndefinedUse.first;
517 
518     // Ignore attributes that have become invalid.
519     if (ND->isInvalidDecl()) continue;
520 
521     // __attribute__((weakref)) is basically a definition.
522     if (ND->hasAttr<WeakRefAttr>()) continue;
523 
524     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
525       if (FD->isDefined())
526         continue;
527       if (FD->isExternallyVisible() &&
528           !FD->getMostRecentDecl()->isInlined())
529         continue;
530     } else {
531       auto *VD = cast<VarDecl>(ND);
532       if (VD->hasDefinition() != VarDecl::DeclarationOnly)
533         continue;
534       if (VD->isExternallyVisible() && !VD->getMostRecentDecl()->isInline())
535         continue;
536     }
537 
538     Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
539   }
540 }
541 
542 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
543 /// or that are inline.
544 static void checkUndefinedButUsed(Sema &S) {
545   if (S.UndefinedButUsed.empty()) return;
546 
547   // Collect all the still-undefined entities with internal linkage.
548   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
549   S.getUndefinedButUsed(Undefined);
550   if (Undefined.empty()) return;
551 
552   for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
553          I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
554     NamedDecl *ND = I->first;
555 
556     if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
557       // An exported function will always be emitted when defined, so even if
558       // the function is inline, it doesn't have to be emitted in this TU. An
559       // imported function implies that it has been exported somewhere else.
560       continue;
561     }
562 
563     if (!ND->isExternallyVisible()) {
564       S.Diag(ND->getLocation(), diag::warn_undefined_internal)
565         << isa<VarDecl>(ND) << ND;
566     } else if (auto *FD = dyn_cast<FunctionDecl>(ND)) {
567       (void)FD;
568       assert(FD->getMostRecentDecl()->isInlined() &&
569              "used object requires definition but isn't inline or internal?");
570       // FIXME: This is ill-formed; we should reject.
571       S.Diag(ND->getLocation(), diag::warn_undefined_inline) << ND;
572     } else {
573       assert(cast<VarDecl>(ND)->getMostRecentDecl()->isInline() &&
574              "used var requires definition but isn't inline or internal?");
575       S.Diag(ND->getLocation(), diag::err_undefined_inline_var) << ND;
576     }
577     if (I->second.isValid())
578       S.Diag(I->second, diag::note_used_here);
579   }
580 
581   S.UndefinedButUsed.clear();
582 }
583 
584 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
585   if (!ExternalSource)
586     return;
587 
588   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
589   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
590   for (auto &WeakID : WeakIDs)
591     WeakUndeclaredIdentifiers.insert(WeakID);
592 }
593 
594 
595 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
596 
597 /// \brief Returns true, if all methods and nested classes of the given
598 /// CXXRecordDecl are defined in this translation unit.
599 ///
600 /// Should only be called from ActOnEndOfTranslationUnit so that all
601 /// definitions are actually read.
602 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
603                                             RecordCompleteMap &MNCComplete) {
604   RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
605   if (Cache != MNCComplete.end())
606     return Cache->second;
607   if (!RD->isCompleteDefinition())
608     return false;
609   bool Complete = true;
610   for (DeclContext::decl_iterator I = RD->decls_begin(),
611                                   E = RD->decls_end();
612        I != E && Complete; ++I) {
613     if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
614       Complete = M->isDefined() || (M->isPure() && !isa<CXXDestructorDecl>(M));
615     else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
616       // If the template function is marked as late template parsed at this
617       // point, it has not been instantiated and therefore we have not
618       // performed semantic analysis on it yet, so we cannot know if the type
619       // can be considered complete.
620       Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
621                   F->getTemplatedDecl()->isDefined();
622     else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
623       if (R->isInjectedClassName())
624         continue;
625       if (R->hasDefinition())
626         Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
627                                                    MNCComplete);
628       else
629         Complete = false;
630     }
631   }
632   MNCComplete[RD] = Complete;
633   return Complete;
634 }
635 
636 /// \brief Returns true, if the given CXXRecordDecl is fully defined in this
637 /// translation unit, i.e. all methods are defined or pure virtual and all
638 /// friends, friend functions and nested classes are fully defined in this
639 /// translation unit.
640 ///
641 /// Should only be called from ActOnEndOfTranslationUnit so that all
642 /// definitions are actually read.
643 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
644                                  RecordCompleteMap &RecordsComplete,
645                                  RecordCompleteMap &MNCComplete) {
646   RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
647   if (Cache != RecordsComplete.end())
648     return Cache->second;
649   bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
650   for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
651                                       E = RD->friend_end();
652        I != E && Complete; ++I) {
653     // Check if friend classes and methods are complete.
654     if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
655       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
656       if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
657         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
658       else
659         Complete = false;
660     } else {
661       // Friend functions are available through the NamedDecl of FriendDecl.
662       if (const FunctionDecl *FD =
663           dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
664         Complete = FD->isDefined();
665       else
666         // This is a template friend, give up.
667         Complete = false;
668     }
669   }
670   RecordsComplete[RD] = Complete;
671   return Complete;
672 }
673 
674 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
675   if (ExternalSource)
676     ExternalSource->ReadUnusedLocalTypedefNameCandidates(
677         UnusedLocalTypedefNameCandidates);
678   for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
679     if (TD->isReferenced())
680       continue;
681     Diag(TD->getLocation(), diag::warn_unused_local_typedef)
682         << isa<TypeAliasDecl>(TD) << TD->getDeclName();
683   }
684   UnusedLocalTypedefNameCandidates.clear();
685 }
686 
687 /// ActOnEndOfTranslationUnit - This is called at the very end of the
688 /// translation unit when EOF is reached and all but the top-level scope is
689 /// popped.
690 void Sema::ActOnEndOfTranslationUnit() {
691   assert(DelayedDiagnostics.getCurrentPool() == nullptr
692          && "reached end of translation unit with a pool attached?");
693 
694   // If code completion is enabled, don't perform any end-of-translation-unit
695   // work.
696   if (PP.isCodeCompletionEnabled())
697     return;
698 
699   // Complete translation units and modules define vtables and perform implicit
700   // instantiations. PCH files do not.
701   if (TUKind != TU_Prefix) {
702     DiagnoseUseOfUnimplementedSelectors();
703 
704     // If DefinedUsedVTables ends up marking any virtual member functions it
705     // might lead to more pending template instantiations, which we then need
706     // to instantiate.
707     DefineUsedVTables();
708 
709     // C++: Perform implicit template instantiations.
710     //
711     // FIXME: When we perform these implicit instantiations, we do not
712     // carefully keep track of the point of instantiation (C++ [temp.point]).
713     // This means that name lookup that occurs within the template
714     // instantiation will always happen at the end of the translation unit,
715     // so it will find some names that are not required to be found. This is
716     // valid, but we could do better by diagnosing if an instantiation uses a
717     // name that was not visible at its first point of instantiation.
718     if (ExternalSource) {
719       // Load pending instantiations from the external source.
720       SmallVector<PendingImplicitInstantiation, 4> Pending;
721       ExternalSource->ReadPendingInstantiations(Pending);
722       PendingInstantiations.insert(PendingInstantiations.begin(),
723                                    Pending.begin(), Pending.end());
724     }
725     PerformPendingInstantiations();
726 
727     if (LateTemplateParserCleanup)
728       LateTemplateParserCleanup(OpaqueParser);
729 
730     CheckDelayedMemberExceptionSpecs();
731   }
732 
733   // All delayed member exception specs should be checked or we end up accepting
734   // incompatible declarations.
735   // FIXME: This is wrong for TUKind == TU_Prefix. In that case, we need to
736   // write out the lists to the AST file (if any).
737   assert(DelayedDefaultedMemberExceptionSpecs.empty());
738   assert(DelayedExceptionSpecChecks.empty());
739 
740   // All dllexport classes should have been processed already.
741   assert(DelayedDllExportClasses.empty());
742 
743   // Remove file scoped decls that turned out to be used.
744   UnusedFileScopedDecls.erase(
745       std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
746                      UnusedFileScopedDecls.end(),
747                      std::bind1st(std::ptr_fun(ShouldRemoveFromUnused), this)),
748       UnusedFileScopedDecls.end());
749 
750   if (TUKind == TU_Prefix) {
751     // Translation unit prefixes don't need any of the checking below.
752     if (!PP.isIncrementalProcessingEnabled())
753       TUScope = nullptr;
754     return;
755   }
756 
757   // Check for #pragma weak identifiers that were never declared
758   LoadExternalWeakUndeclaredIdentifiers();
759   for (auto WeakID : WeakUndeclaredIdentifiers) {
760     if (WeakID.second.getUsed())
761       continue;
762 
763     Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
764                                       LookupOrdinaryName);
765     if (PrevDecl != nullptr &&
766         !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
767       Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
768           << "'weak'" << ExpectedVariableOrFunction;
769     else
770       Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
771           << WeakID.first;
772   }
773 
774   if (LangOpts.CPlusPlus11 &&
775       !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
776     CheckDelegatingCtorCycles();
777 
778   if (!Diags.hasErrorOccurred()) {
779     if (ExternalSource)
780       ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
781     checkUndefinedButUsed(*this);
782   }
783 
784   if (TUKind == TU_Module) {
785     // If we are building a module, resolve all of the exported declarations
786     // now.
787     if (Module *CurrentModule = PP.getCurrentModule()) {
788       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
789 
790       SmallVector<Module *, 2> Stack;
791       Stack.push_back(CurrentModule);
792       while (!Stack.empty()) {
793         Module *Mod = Stack.pop_back_val();
794 
795         // Resolve the exported declarations and conflicts.
796         // FIXME: Actually complain, once we figure out how to teach the
797         // diagnostic client to deal with complaints in the module map at this
798         // point.
799         ModMap.resolveExports(Mod, /*Complain=*/false);
800         ModMap.resolveUses(Mod, /*Complain=*/false);
801         ModMap.resolveConflicts(Mod, /*Complain=*/false);
802 
803         // Queue the submodules, so their exports will also be resolved.
804         Stack.append(Mod->submodule_begin(), Mod->submodule_end());
805       }
806     }
807 
808     // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
809     // modules when they are built, not every time they are used.
810     emitAndClearUnusedLocalTypedefWarnings();
811 
812     // Modules don't need any of the checking below.
813     TUScope = nullptr;
814     return;
815   }
816 
817   // C99 6.9.2p2:
818   //   A declaration of an identifier for an object that has file
819   //   scope without an initializer, and without a storage-class
820   //   specifier or with the storage-class specifier static,
821   //   constitutes a tentative definition. If a translation unit
822   //   contains one or more tentative definitions for an identifier,
823   //   and the translation unit contains no external definition for
824   //   that identifier, then the behavior is exactly as if the
825   //   translation unit contains a file scope declaration of that
826   //   identifier, with the composite type as of the end of the
827   //   translation unit, with an initializer equal to 0.
828   llvm::SmallSet<VarDecl *, 32> Seen;
829   for (TentativeDefinitionsType::iterator
830             T = TentativeDefinitions.begin(ExternalSource),
831          TEnd = TentativeDefinitions.end();
832        T != TEnd; ++T)
833   {
834     VarDecl *VD = (*T)->getActingDefinition();
835 
836     // If the tentative definition was completed, getActingDefinition() returns
837     // null. If we've already seen this variable before, insert()'s second
838     // return value is false.
839     if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
840       continue;
841 
842     if (const IncompleteArrayType *ArrayT
843         = Context.getAsIncompleteArrayType(VD->getType())) {
844       // Set the length of the array to 1 (C99 6.9.2p5).
845       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
846       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
847       QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
848                                                 One, ArrayType::Normal, 0);
849       VD->setType(T);
850     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
851                                    diag::err_tentative_def_incomplete_type))
852       VD->setInvalidDecl();
853 
854     // No initialization is performed for a tentative definition.
855     CheckCompleteVariableDeclaration(VD);
856 
857     // Notify the consumer that we've completed a tentative definition.
858     if (!VD->isInvalidDecl())
859       Consumer.CompleteTentativeDefinition(VD);
860 
861   }
862 
863   // If there were errors, disable 'unused' warnings since they will mostly be
864   // noise.
865   if (!Diags.hasErrorOccurred()) {
866     // Output warning for unused file scoped decls.
867     for (UnusedFileScopedDeclsType::iterator
868            I = UnusedFileScopedDecls.begin(ExternalSource),
869            E = UnusedFileScopedDecls.end(); I != E; ++I) {
870       if (ShouldRemoveFromUnused(this, *I))
871         continue;
872 
873       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
874         const FunctionDecl *DiagD;
875         if (!FD->hasBody(DiagD))
876           DiagD = FD;
877         if (DiagD->isDeleted())
878           continue; // Deleted functions are supposed to be unused.
879         if (DiagD->isReferenced()) {
880           if (isa<CXXMethodDecl>(DiagD))
881             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
882                   << DiagD->getDeclName();
883           else {
884             if (FD->getStorageClass() == SC_Static &&
885                 !FD->isInlineSpecified() &&
886                 !SourceMgr.isInMainFile(
887                    SourceMgr.getExpansionLoc(FD->getLocation())))
888               Diag(DiagD->getLocation(),
889                    diag::warn_unneeded_static_internal_decl)
890                   << DiagD->getDeclName();
891             else
892               Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
893                    << /*function*/0 << DiagD->getDeclName();
894           }
895         } else {
896           Diag(DiagD->getLocation(),
897                isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
898                                          : diag::warn_unused_function)
899                 << DiagD->getDeclName();
900         }
901       } else {
902         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
903         if (!DiagD)
904           DiagD = cast<VarDecl>(*I);
905         if (DiagD->isReferenced()) {
906           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
907                 << /*variable*/1 << DiagD->getDeclName();
908         } else if (DiagD->getType().isConstQualified()) {
909           const SourceManager &SM = SourceMgr;
910           if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
911               !PP.getLangOpts().IsHeaderFile)
912             Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
913                 << DiagD->getDeclName();
914         } else {
915           Diag(DiagD->getLocation(), diag::warn_unused_variable)
916               << DiagD->getDeclName();
917         }
918       }
919     }
920 
921     emitAndClearUnusedLocalTypedefWarnings();
922   }
923 
924   if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
925     RecordCompleteMap RecordsComplete;
926     RecordCompleteMap MNCComplete;
927     for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
928          E = UnusedPrivateFields.end(); I != E; ++I) {
929       const NamedDecl *D = *I;
930       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
931       if (RD && !RD->isUnion() &&
932           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
933         Diag(D->getLocation(), diag::warn_unused_private_field)
934               << D->getDeclName();
935       }
936     }
937   }
938 
939   if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
940     if (ExternalSource)
941       ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
942     for (const auto &DeletedFieldInfo : DeleteExprs) {
943       for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
944         AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
945                                   DeleteExprLoc.second);
946       }
947     }
948   }
949 
950   // Check we've noticed that we're no longer parsing the initializer for every
951   // variable. If we miss cases, then at best we have a performance issue and
952   // at worst a rejects-valid bug.
953   assert(ParsingInitForAutoVars.empty() &&
954          "Didn't unmark var as having its initializer parsed");
955 
956   if (!PP.isIncrementalProcessingEnabled())
957     TUScope = nullptr;
958 }
959 
960 
961 //===----------------------------------------------------------------------===//
962 // Helper functions.
963 //===----------------------------------------------------------------------===//
964 
965 DeclContext *Sema::getFunctionLevelDeclContext() {
966   DeclContext *DC = CurContext;
967 
968   while (true) {
969     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC)) {
970       DC = DC->getParent();
971     } else if (isa<CXXMethodDecl>(DC) &&
972                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
973                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
974       DC = DC->getParent()->getParent();
975     }
976     else break;
977   }
978 
979   return DC;
980 }
981 
982 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
983 /// to the function decl for the function being parsed.  If we're currently
984 /// in a 'block', this returns the containing context.
985 FunctionDecl *Sema::getCurFunctionDecl() {
986   DeclContext *DC = getFunctionLevelDeclContext();
987   return dyn_cast<FunctionDecl>(DC);
988 }
989 
990 ObjCMethodDecl *Sema::getCurMethodDecl() {
991   DeclContext *DC = getFunctionLevelDeclContext();
992   while (isa<RecordDecl>(DC))
993     DC = DC->getParent();
994   return dyn_cast<ObjCMethodDecl>(DC);
995 }
996 
997 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
998   DeclContext *DC = getFunctionLevelDeclContext();
999   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1000     return cast<NamedDecl>(DC);
1001   return nullptr;
1002 }
1003 
1004 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1005   // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1006   // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1007   // been made more painfully obvious by the refactor that introduced this
1008   // function, but it is possible that the incoming argument can be
1009   // eliminated. If it truly cannot be (for example, there is some reentrancy
1010   // issue I am not seeing yet), then there should at least be a clarifying
1011   // comment somewhere.
1012   if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
1013     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1014               Diags.getCurrentDiagID())) {
1015     case DiagnosticIDs::SFINAE_Report:
1016       // We'll report the diagnostic below.
1017       break;
1018 
1019     case DiagnosticIDs::SFINAE_SubstitutionFailure:
1020       // Count this failure so that we know that template argument deduction
1021       // has failed.
1022       ++NumSFINAEErrors;
1023 
1024       // Make a copy of this suppressed diagnostic and store it with the
1025       // template-deduction information.
1026       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1027         Diagnostic DiagInfo(&Diags);
1028         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1029                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1030       }
1031 
1032       Diags.setLastDiagnosticIgnored();
1033       Diags.Clear();
1034       return;
1035 
1036     case DiagnosticIDs::SFINAE_AccessControl: {
1037       // Per C++ Core Issue 1170, access control is part of SFINAE.
1038       // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1039       // make access control a part of SFINAE for the purposes of checking
1040       // type traits.
1041       if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
1042         break;
1043 
1044       SourceLocation Loc = Diags.getCurrentDiagLoc();
1045 
1046       // Suppress this diagnostic.
1047       ++NumSFINAEErrors;
1048 
1049       // Make a copy of this suppressed diagnostic and store it with the
1050       // template-deduction information.
1051       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1052         Diagnostic DiagInfo(&Diags);
1053         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1054                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1055       }
1056 
1057       Diags.setLastDiagnosticIgnored();
1058       Diags.Clear();
1059 
1060       // Now the diagnostic state is clear, produce a C++98 compatibility
1061       // warning.
1062       Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1063 
1064       // The last diagnostic which Sema produced was ignored. Suppress any
1065       // notes attached to it.
1066       Diags.setLastDiagnosticIgnored();
1067       return;
1068     }
1069 
1070     case DiagnosticIDs::SFINAE_Suppress:
1071       // Make a copy of this suppressed diagnostic and store it with the
1072       // template-deduction information;
1073       if (*Info) {
1074         Diagnostic DiagInfo(&Diags);
1075         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1076                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1077       }
1078 
1079       // Suppress this diagnostic.
1080       Diags.setLastDiagnosticIgnored();
1081       Diags.Clear();
1082       return;
1083     }
1084   }
1085 
1086   // Set up the context's printing policy based on our current state.
1087   Context.setPrintingPolicy(getPrintingPolicy());
1088 
1089   // Emit the diagnostic.
1090   if (!Diags.EmitCurrentDiagnostic())
1091     return;
1092 
1093   // If this is not a note, and we're in a template instantiation
1094   // that is different from the last template instantiation where
1095   // we emitted an error, print a template instantiation
1096   // backtrace.
1097   if (!DiagnosticIDs::isBuiltinNote(DiagID))
1098     PrintContextStack();
1099 }
1100 
1101 Sema::SemaDiagnosticBuilder
1102 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
1103   SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
1104   PD.Emit(Builder);
1105 
1106   return Builder;
1107 }
1108 
1109 /// \brief Looks through the macro-expansion chain for the given
1110 /// location, looking for a macro expansion with the given name.
1111 /// If one is found, returns true and sets the location to that
1112 /// expansion loc.
1113 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1114   SourceLocation loc = locref;
1115   if (!loc.isMacroID()) return false;
1116 
1117   // There's no good way right now to look at the intermediate
1118   // expansions, so just jump to the expansion location.
1119   loc = getSourceManager().getExpansionLoc(loc);
1120 
1121   // If that's written with the name, stop here.
1122   SmallVector<char, 16> buffer;
1123   if (getPreprocessor().getSpelling(loc, buffer) == name) {
1124     locref = loc;
1125     return true;
1126   }
1127   return false;
1128 }
1129 
1130 /// \brief Determines the active Scope associated with the given declaration
1131 /// context.
1132 ///
1133 /// This routine maps a declaration context to the active Scope object that
1134 /// represents that declaration context in the parser. It is typically used
1135 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1136 /// declarations) that injects a name for name-lookup purposes and, therefore,
1137 /// must update the Scope.
1138 ///
1139 /// \returns The scope corresponding to the given declaraion context, or NULL
1140 /// if no such scope is open.
1141 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
1142 
1143   if (!Ctx)
1144     return nullptr;
1145 
1146   Ctx = Ctx->getPrimaryContext();
1147   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1148     // Ignore scopes that cannot have declarations. This is important for
1149     // out-of-line definitions of static class members.
1150     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1151       if (DeclContext *Entity = S->getEntity())
1152         if (Ctx == Entity->getPrimaryContext())
1153           return S;
1154   }
1155 
1156   return nullptr;
1157 }
1158 
1159 /// \brief Enter a new function scope
1160 void Sema::PushFunctionScope() {
1161   if (FunctionScopes.size() == 1) {
1162     // Use the "top" function scope rather than having to allocate
1163     // memory for a new scope.
1164     FunctionScopes.back()->Clear();
1165     FunctionScopes.push_back(FunctionScopes.back());
1166     return;
1167   }
1168 
1169   FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1170 }
1171 
1172 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1173   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
1174                                               BlockScope, Block));
1175 }
1176 
1177 LambdaScopeInfo *Sema::PushLambdaScope() {
1178   LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1179   FunctionScopes.push_back(LSI);
1180   return LSI;
1181 }
1182 
1183 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1184   if (LambdaScopeInfo *const LSI = getCurLambda()) {
1185     LSI->AutoTemplateParameterDepth = Depth;
1186     return;
1187   }
1188   llvm_unreachable(
1189       "Remove assertion if intentionally called in a non-lambda context.");
1190 }
1191 
1192 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1193                                 const Decl *D, const BlockExpr *blkExpr) {
1194   FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
1195   assert(!FunctionScopes.empty() && "mismatched push/pop!");
1196 
1197   // Issue any analysis-based warnings.
1198   if (WP && D)
1199     AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
1200   else
1201     for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1202       Diag(PUD.Loc, PUD.PD);
1203 
1204   if (FunctionScopes.back() != Scope)
1205     delete Scope;
1206 }
1207 
1208 void Sema::PushCompoundScope() {
1209   getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo());
1210 }
1211 
1212 void Sema::PopCompoundScope() {
1213   FunctionScopeInfo *CurFunction = getCurFunction();
1214   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
1215 
1216   CurFunction->CompoundScopes.pop_back();
1217 }
1218 
1219 /// \brief Determine whether any errors occurred within this function/method/
1220 /// block.
1221 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
1222   return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
1223 }
1224 
1225 BlockScopeInfo *Sema::getCurBlock() {
1226   if (FunctionScopes.empty())
1227     return nullptr;
1228 
1229   auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
1230   if (CurBSI && CurBSI->TheDecl &&
1231       !CurBSI->TheDecl->Encloses(CurContext)) {
1232     // We have switched contexts due to template instantiation.
1233     assert(!CodeSynthesisContexts.empty());
1234     return nullptr;
1235   }
1236 
1237   return CurBSI;
1238 }
1239 
1240 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
1241   if (FunctionScopes.empty())
1242     return nullptr;
1243 
1244   auto I = FunctionScopes.rbegin();
1245   if (IgnoreNonLambdaCapturingScope) {
1246     auto E = FunctionScopes.rend();
1247     while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
1248       ++I;
1249     if (I == E)
1250       return nullptr;
1251   }
1252   auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
1253   if (CurLSI && CurLSI->Lambda &&
1254       !CurLSI->Lambda->Encloses(CurContext)) {
1255     // We have switched contexts due to template instantiation.
1256     assert(!CodeSynthesisContexts.empty());
1257     return nullptr;
1258   }
1259 
1260   return CurLSI;
1261 }
1262 // We have a generic lambda if we parsed auto parameters, or we have
1263 // an associated template parameter list.
1264 LambdaScopeInfo *Sema::getCurGenericLambda() {
1265   if (LambdaScopeInfo *LSI =  getCurLambda()) {
1266     return (LSI->AutoTemplateParams.size() ||
1267                     LSI->GLTemplateParameterList) ? LSI : nullptr;
1268   }
1269   return nullptr;
1270 }
1271 
1272 
1273 void Sema::ActOnComment(SourceRange Comment) {
1274   if (!LangOpts.RetainCommentsFromSystemHeaders &&
1275       SourceMgr.isInSystemHeader(Comment.getBegin()))
1276     return;
1277   RawComment RC(SourceMgr, Comment, false,
1278                 LangOpts.CommentOpts.ParseAllComments);
1279   if (RC.isAlmostTrailingComment()) {
1280     SourceRange MagicMarkerRange(Comment.getBegin(),
1281                                  Comment.getBegin().getLocWithOffset(3));
1282     StringRef MagicMarkerText;
1283     switch (RC.getKind()) {
1284     case RawComment::RCK_OrdinaryBCPL:
1285       MagicMarkerText = "///<";
1286       break;
1287     case RawComment::RCK_OrdinaryC:
1288       MagicMarkerText = "/**<";
1289       break;
1290     default:
1291       llvm_unreachable("if this is an almost Doxygen comment, "
1292                        "it should be ordinary");
1293     }
1294     Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
1295       FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
1296   }
1297   Context.addComment(RC);
1298 }
1299 
1300 // Pin this vtable to this file.
1301 ExternalSemaSource::~ExternalSemaSource() {}
1302 
1303 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
1304 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
1305 
1306 void ExternalSemaSource::ReadKnownNamespaces(
1307                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
1308 }
1309 
1310 void ExternalSemaSource::ReadUndefinedButUsed(
1311     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
1312 
1313 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
1314     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
1315 
1316 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
1317   SourceLocation Loc = this->Loc;
1318   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
1319   if (Loc.isValid()) {
1320     Loc.print(OS, S.getSourceManager());
1321     OS << ": ";
1322   }
1323   OS << Message;
1324 
1325   if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
1326     OS << " '";
1327     ND->getNameForDiagnostic(OS, ND->getASTContext().getPrintingPolicy(), true);
1328     OS << "'";
1329   }
1330 
1331   OS << '\n';
1332 }
1333 
1334 /// \brief Figure out if an expression could be turned into a call.
1335 ///
1336 /// Use this when trying to recover from an error where the programmer may have
1337 /// written just the name of a function instead of actually calling it.
1338 ///
1339 /// \param E - The expression to examine.
1340 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
1341 ///  with no arguments, this parameter is set to the type returned by such a
1342 ///  call; otherwise, it is set to an empty QualType.
1343 /// \param OverloadSet - If the expression is an overloaded function
1344 ///  name, this parameter is populated with the decls of the various overloads.
1345 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
1346                          UnresolvedSetImpl &OverloadSet) {
1347   ZeroArgCallReturnTy = QualType();
1348   OverloadSet.clear();
1349 
1350   const OverloadExpr *Overloads = nullptr;
1351   bool IsMemExpr = false;
1352   if (E.getType() == Context.OverloadTy) {
1353     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
1354 
1355     // Ignore overloads that are pointer-to-member constants.
1356     if (FR.HasFormOfMemberPointer)
1357       return false;
1358 
1359     Overloads = FR.Expression;
1360   } else if (E.getType() == Context.BoundMemberTy) {
1361     Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
1362     IsMemExpr = true;
1363   }
1364 
1365   bool Ambiguous = false;
1366 
1367   if (Overloads) {
1368     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
1369          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
1370       OverloadSet.addDecl(*it);
1371 
1372       // Check whether the function is a non-template, non-member which takes no
1373       // arguments.
1374       if (IsMemExpr)
1375         continue;
1376       if (const FunctionDecl *OverloadDecl
1377             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
1378         if (OverloadDecl->getMinRequiredArguments() == 0) {
1379           if (!ZeroArgCallReturnTy.isNull() && !Ambiguous) {
1380             ZeroArgCallReturnTy = QualType();
1381             Ambiguous = true;
1382           } else
1383             ZeroArgCallReturnTy = OverloadDecl->getReturnType();
1384         }
1385       }
1386     }
1387 
1388     // If it's not a member, use better machinery to try to resolve the call
1389     if (!IsMemExpr)
1390       return !ZeroArgCallReturnTy.isNull();
1391   }
1392 
1393   // Attempt to call the member with no arguments - this will correctly handle
1394   // member templates with defaults/deduction of template arguments, overloads
1395   // with default arguments, etc.
1396   if (IsMemExpr && !E.isTypeDependent()) {
1397     bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
1398     getDiagnostics().setSuppressAllDiagnostics(true);
1399     ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
1400                                              None, SourceLocation());
1401     getDiagnostics().setSuppressAllDiagnostics(Suppress);
1402     if (R.isUsable()) {
1403       ZeroArgCallReturnTy = R.get()->getType();
1404       return true;
1405     }
1406     return false;
1407   }
1408 
1409   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
1410     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
1411       if (Fun->getMinRequiredArguments() == 0)
1412         ZeroArgCallReturnTy = Fun->getReturnType();
1413       return true;
1414     }
1415   }
1416 
1417   // We don't have an expression that's convenient to get a FunctionDecl from,
1418   // but we can at least check if the type is "function of 0 arguments".
1419   QualType ExprTy = E.getType();
1420   const FunctionType *FunTy = nullptr;
1421   QualType PointeeTy = ExprTy->getPointeeType();
1422   if (!PointeeTy.isNull())
1423     FunTy = PointeeTy->getAs<FunctionType>();
1424   if (!FunTy)
1425     FunTy = ExprTy->getAs<FunctionType>();
1426 
1427   if (const FunctionProtoType *FPT =
1428       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
1429     if (FPT->getNumParams() == 0)
1430       ZeroArgCallReturnTy = FunTy->getReturnType();
1431     return true;
1432   }
1433   return false;
1434 }
1435 
1436 /// \brief Give notes for a set of overloads.
1437 ///
1438 /// A companion to tryExprAsCall. In cases when the name that the programmer
1439 /// wrote was an overloaded function, we may be able to make some guesses about
1440 /// plausible overloads based on their return types; such guesses can be handed
1441 /// off to this method to be emitted as notes.
1442 ///
1443 /// \param Overloads - The overloads to note.
1444 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
1445 ///  -fshow-overloads=best, this is the location to attach to the note about too
1446 ///  many candidates. Typically this will be the location of the original
1447 ///  ill-formed expression.
1448 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
1449                           const SourceLocation FinalNoteLoc) {
1450   int ShownOverloads = 0;
1451   int SuppressedOverloads = 0;
1452   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
1453        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1454     // FIXME: Magic number for max shown overloads stolen from
1455     // OverloadCandidateSet::NoteCandidates.
1456     if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
1457       ++SuppressedOverloads;
1458       continue;
1459     }
1460 
1461     NamedDecl *Fn = (*It)->getUnderlyingDecl();
1462     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1463     ++ShownOverloads;
1464   }
1465 
1466   if (SuppressedOverloads)
1467     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1468       << SuppressedOverloads;
1469 }
1470 
1471 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
1472                                    const UnresolvedSetImpl &Overloads,
1473                                    bool (*IsPlausibleResult)(QualType)) {
1474   if (!IsPlausibleResult)
1475     return noteOverloads(S, Overloads, Loc);
1476 
1477   UnresolvedSet<2> PlausibleOverloads;
1478   for (OverloadExpr::decls_iterator It = Overloads.begin(),
1479          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1480     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1481     QualType OverloadResultTy = OverloadDecl->getReturnType();
1482     if (IsPlausibleResult(OverloadResultTy))
1483       PlausibleOverloads.addDecl(It.getDecl());
1484   }
1485   noteOverloads(S, PlausibleOverloads, Loc);
1486 }
1487 
1488 /// Determine whether the given expression can be called by just
1489 /// putting parentheses after it.  Notably, expressions with unary
1490 /// operators can't be because the unary operator will start parsing
1491 /// outside the call.
1492 static bool IsCallableWithAppend(Expr *E) {
1493   E = E->IgnoreImplicit();
1494   return (!isa<CStyleCastExpr>(E) &&
1495           !isa<UnaryOperator>(E) &&
1496           !isa<BinaryOperator>(E) &&
1497           !isa<CXXOperatorCallExpr>(E));
1498 }
1499 
1500 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1501                                 bool ForceComplain,
1502                                 bool (*IsPlausibleResult)(QualType)) {
1503   SourceLocation Loc = E.get()->getExprLoc();
1504   SourceRange Range = E.get()->getSourceRange();
1505 
1506   QualType ZeroArgCallTy;
1507   UnresolvedSet<4> Overloads;
1508   if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
1509       !ZeroArgCallTy.isNull() &&
1510       (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1511     // At this point, we know E is potentially callable with 0
1512     // arguments and that it returns something of a reasonable type,
1513     // so we can emit a fixit and carry on pretending that E was
1514     // actually a CallExpr.
1515     SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
1516     Diag(Loc, PD)
1517       << /*zero-arg*/ 1 << Range
1518       << (IsCallableWithAppend(E.get())
1519           ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1520           : FixItHint());
1521     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1522 
1523     // FIXME: Try this before emitting the fixit, and suppress diagnostics
1524     // while doing so.
1525     E = ActOnCallExpr(nullptr, E.get(), Range.getEnd(), None,
1526                       Range.getEnd().getLocWithOffset(1));
1527     return true;
1528   }
1529 
1530   if (!ForceComplain) return false;
1531 
1532   Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1533   notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1534   E = ExprError();
1535   return true;
1536 }
1537 
1538 IdentifierInfo *Sema::getSuperIdentifier() const {
1539   if (!Ident_super)
1540     Ident_super = &Context.Idents.get("super");
1541   return Ident_super;
1542 }
1543 
1544 IdentifierInfo *Sema::getFloat128Identifier() const {
1545   if (!Ident___float128)
1546     Ident___float128 = &Context.Idents.get("__float128");
1547   return Ident___float128;
1548 }
1549 
1550 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
1551                                    CapturedRegionKind K) {
1552   CapturingScopeInfo *CSI = new CapturedRegionScopeInfo(
1553       getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
1554       (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0);
1555   CSI->ReturnType = Context.VoidTy;
1556   FunctionScopes.push_back(CSI);
1557 }
1558 
1559 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
1560   if (FunctionScopes.empty())
1561     return nullptr;
1562 
1563   return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
1564 }
1565 
1566 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
1567 Sema::getMismatchingDeleteExpressions() const {
1568   return DeleteExprs;
1569 }
1570 
1571 void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
1572   if (ExtStr.empty())
1573     return;
1574   llvm::SmallVector<StringRef, 1> Exts;
1575   ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
1576   auto CanT = T.getCanonicalType().getTypePtr();
1577   for (auto &I : Exts)
1578     OpenCLTypeExtMap[CanT].insert(I.str());
1579 }
1580 
1581 void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
1582   llvm::SmallVector<StringRef, 1> Exts;
1583   ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
1584   if (Exts.empty())
1585     return;
1586   for (auto &I : Exts)
1587     OpenCLDeclExtMap[FD].insert(I.str());
1588 }
1589 
1590 void Sema::setCurrentOpenCLExtensionForType(QualType T) {
1591   if (CurrOpenCLExtension.empty())
1592     return;
1593   setOpenCLExtensionForType(T, CurrOpenCLExtension);
1594 }
1595 
1596 void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
1597   if (CurrOpenCLExtension.empty())
1598     return;
1599   setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
1600 }
1601 
1602 bool Sema::isOpenCLDisabledDecl(Decl *FD) {
1603   auto Loc = OpenCLDeclExtMap.find(FD);
1604   if (Loc == OpenCLDeclExtMap.end())
1605     return false;
1606   for (auto &I : Loc->second) {
1607     if (!getOpenCLOptions().isEnabled(I))
1608       return true;
1609   }
1610   return false;
1611 }
1612 
1613 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
1614 bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
1615                                          DiagInfoT DiagInfo, MapT &Map,
1616                                          unsigned Selector,
1617                                          SourceRange SrcRange) {
1618   auto Loc = Map.find(D);
1619   if (Loc == Map.end())
1620     return false;
1621   bool Disabled = false;
1622   for (auto &I : Loc->second) {
1623     if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
1624       Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
1625                                                          << I << SrcRange;
1626       Disabled = true;
1627     }
1628   }
1629   return Disabled;
1630 }
1631 
1632 bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
1633   // Check extensions for declared types.
1634   Decl *Decl = nullptr;
1635   if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
1636     Decl = TypedefT->getDecl();
1637   if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
1638     Decl = TagT->getDecl();
1639   auto Loc = DS.getTypeSpecTypeLoc();
1640   if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
1641     return true;
1642 
1643   // Check extensions for builtin types.
1644   return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
1645                                        QT, OpenCLTypeExtMap);
1646 }
1647 
1648 bool Sema::checkOpenCLDisabledDecl(const Decl &D, const Expr &E) {
1649   return checkOpenCLDisabledTypeOrDecl(&D, E.getLocStart(), "",
1650                                        OpenCLDeclExtMap, 1, D.getSourceRange());
1651 }
1652