• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the actions class which performs semantic analysis and
10 // builds an AST out of a parse stream.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "UsedDeclVisitor.h"
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/PrettyDeclStackTrace.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/Basic/DiagnosticOptions.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/Stack.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/HeaderSearch.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/CXXFieldCollector.h"
32 #include "clang/Sema/DelayedDiagnostic.h"
33 #include "clang/Sema/ExternalSemaSource.h"
34 #include "clang/Sema/Initialization.h"
35 #include "clang/Sema/MultiplexExternalSemaSource.h"
36 #include "clang/Sema/ObjCMethodList.h"
37 #include "clang/Sema/Scope.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "clang/Sema/SemaConsumer.h"
40 #include "clang/Sema/SemaInternal.h"
41 #include "clang/Sema/TemplateDeduction.h"
42 #include "clang/Sema/TemplateInstCallback.h"
43 #include "clang/Sema/TypoCorrection.h"
44 #include "llvm/ADT/DenseMap.h"
45 #include "llvm/ADT/SmallPtrSet.h"
46 #include "llvm/Support/TimeProfiler.h"
47 
48 using namespace clang;
49 using namespace sema;
50 
getLocForEndOfToken(SourceLocation Loc,unsigned Offset)51 SourceLocation Sema::getLocForEndOfToken(SourceLocation Loc, unsigned Offset) {
52   return Lexer::getLocForEndOfToken(Loc, Offset, SourceMgr, LangOpts);
53 }
54 
getModuleLoader() const55 ModuleLoader &Sema::getModuleLoader() const { return PP.getModuleLoader(); }
56 
57 IdentifierInfo *
InventAbbreviatedTemplateParameterTypeName(IdentifierInfo * ParamName,unsigned int Index)58 Sema::InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
59                                                  unsigned int Index) {
60   std::string InventedName;
61   llvm::raw_string_ostream OS(InventedName);
62 
63   if (!ParamName)
64     OS << "auto:" << Index + 1;
65   else
66     OS << ParamName->getName() << ":auto";
67 
68   OS.flush();
69   return &Context.Idents.get(OS.str());
70 }
71 
getPrintingPolicy(const ASTContext & Context,const Preprocessor & PP)72 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
73                                        const Preprocessor &PP) {
74   PrintingPolicy Policy = Context.getPrintingPolicy();
75   // In diagnostics, we print _Bool as bool if the latter is defined as the
76   // former.
77   Policy.Bool = Context.getLangOpts().Bool;
78   if (!Policy.Bool) {
79     if (const MacroInfo *BoolMacro = PP.getMacroInfo(Context.getBoolName())) {
80       Policy.Bool = BoolMacro->isObjectLike() &&
81                     BoolMacro->getNumTokens() == 1 &&
82                     BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
83     }
84   }
85 
86   return Policy;
87 }
88 
ActOnTranslationUnitScope(Scope * S)89 void Sema::ActOnTranslationUnitScope(Scope *S) {
90   TUScope = S;
91   PushDeclContext(S, Context.getTranslationUnitDecl());
92 }
93 
94 namespace clang {
95 namespace sema {
96 
97 class SemaPPCallbacks : public PPCallbacks {
98   Sema *S = nullptr;
99   llvm::SmallVector<SourceLocation, 8> IncludeStack;
100 
101 public:
set(Sema & S)102   void set(Sema &S) { this->S = &S; }
103 
reset()104   void reset() { S = nullptr; }
105 
FileChanged(SourceLocation Loc,FileChangeReason Reason,SrcMgr::CharacteristicKind FileType,FileID PrevFID)106   virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason,
107                            SrcMgr::CharacteristicKind FileType,
108                            FileID PrevFID) override {
109     if (!S)
110       return;
111     switch (Reason) {
112     case EnterFile: {
113       SourceManager &SM = S->getSourceManager();
114       SourceLocation IncludeLoc = SM.getIncludeLoc(SM.getFileID(Loc));
115       if (IncludeLoc.isValid()) {
116         if (llvm::timeTraceProfilerEnabled()) {
117           const FileEntry *FE = SM.getFileEntryForID(SM.getFileID(Loc));
118           llvm::timeTraceProfilerBegin(
119               "Source", FE != nullptr ? FE->getName() : StringRef("<unknown>"));
120         }
121 
122         IncludeStack.push_back(IncludeLoc);
123         S->DiagnoseNonDefaultPragmaPack(
124             Sema::PragmaPackDiagnoseKind::NonDefaultStateAtInclude, IncludeLoc);
125       }
126       break;
127     }
128     case ExitFile:
129       if (!IncludeStack.empty()) {
130         if (llvm::timeTraceProfilerEnabled())
131           llvm::timeTraceProfilerEnd();
132 
133         S->DiagnoseNonDefaultPragmaPack(
134             Sema::PragmaPackDiagnoseKind::ChangedStateAtExit,
135             IncludeStack.pop_back_val());
136       }
137       break;
138     default:
139       break;
140     }
141   }
142 };
143 
144 } // end namespace sema
145 } // end namespace clang
146 
147 const unsigned Sema::MaxAlignmentExponent;
148 const unsigned Sema::MaximumAlignment;
149 
Sema(Preprocessor & pp,ASTContext & ctxt,ASTConsumer & consumer,TranslationUnitKind TUKind,CodeCompleteConsumer * CodeCompleter)150 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
151            TranslationUnitKind TUKind, CodeCompleteConsumer *CodeCompleter)
152     : ExternalSource(nullptr), isMultiplexExternalSource(false),
153       CurFPFeatures(pp.getLangOpts()), LangOpts(pp.getLangOpts()), PP(pp),
154       Context(ctxt), Consumer(consumer), Diags(PP.getDiagnostics()),
155       SourceMgr(PP.getSourceManager()), CollectStats(false),
156       CodeCompleter(CodeCompleter), CurContext(nullptr),
157       OriginalLexicalContext(nullptr), MSStructPragmaOn(false),
158       MSPointerToMemberRepresentationMethod(
159           LangOpts.getMSPointerToMemberRepresentationMethod()),
160       VtorDispStack(LangOpts.getVtorDispMode()), PackStack(0),
161       DataSegStack(nullptr), BSSSegStack(nullptr), ConstSegStack(nullptr),
162       CodeSegStack(nullptr), FpPragmaStack(FPOptionsOverride()),
163       CurInitSeg(nullptr), VisContext(nullptr),
164       PragmaAttributeCurrentTargetDecl(nullptr),
165       IsBuildingRecoveryCallExpr(false), Cleanup{}, LateTemplateParser(nullptr),
166       LateTemplateParserCleanup(nullptr), OpaqueParser(nullptr), IdResolver(pp),
167       StdExperimentalNamespaceCache(nullptr), StdInitializerList(nullptr),
168       StdCoroutineTraitsCache(nullptr), CXXTypeInfoDecl(nullptr),
169       MSVCGuidDecl(nullptr), NSNumberDecl(nullptr), NSValueDecl(nullptr),
170       NSStringDecl(nullptr), StringWithUTF8StringMethod(nullptr),
171       ValueWithBytesObjCTypeMethod(nullptr), NSArrayDecl(nullptr),
172       ArrayWithObjectsMethod(nullptr), NSDictionaryDecl(nullptr),
173       DictionaryWithObjectsMethod(nullptr), GlobalNewDeleteDeclared(false),
174       TUKind(TUKind), NumSFINAEErrors(0),
175       FullyCheckedComparisonCategories(
176           static_cast<unsigned>(ComparisonCategoryType::Last) + 1),
177       SatisfactionCache(Context), AccessCheckingSFINAE(false),
178       InNonInstantiationSFINAEContext(false), NonInstantiationEntries(0),
179       ArgumentPackSubstitutionIndex(-1), CurrentInstantiationScope(nullptr),
180       DisableTypoCorrection(false), TyposCorrected(0), AnalysisWarnings(*this),
181       ThreadSafetyDeclCache(nullptr), VarDataSharingAttributesStack(nullptr),
182       CurScope(nullptr), Ident_super(nullptr), Ident___float128(nullptr) {
183   TUScope = nullptr;
184   isConstantEvaluatedOverride = false;
185 
186   LoadedExternalKnownNamespaces = false;
187   for (unsigned I = 0; I != NSAPI::NumNSNumberLiteralMethods; ++I)
188     NSNumberLiteralMethods[I] = nullptr;
189 
190   if (getLangOpts().ObjC)
191     NSAPIObj.reset(new NSAPI(Context));
192 
193   if (getLangOpts().CPlusPlus)
194     FieldCollector.reset(new CXXFieldCollector());
195 
196   // Tell diagnostics how to render things from the AST library.
197   Diags.SetArgToStringFn(&FormatASTNodeDiagnosticArgument, &Context);
198 
199   ExprEvalContexts.emplace_back(
200       ExpressionEvaluationContext::PotentiallyEvaluated, 0, CleanupInfo{},
201       nullptr, ExpressionEvaluationContextRecord::EK_Other);
202 
203   // Initialization of data sharing attributes stack for OpenMP
204   InitDataSharingAttributesStack();
205 
206   std::unique_ptr<sema::SemaPPCallbacks> Callbacks =
207       std::make_unique<sema::SemaPPCallbacks>();
208   SemaPPCallbackHandler = Callbacks.get();
209   PP.addPPCallbacks(std::move(Callbacks));
210   SemaPPCallbackHandler->set(*this);
211 }
212 
213 // Anchor Sema's type info to this TU.
anchor()214 void Sema::anchor() {}
215 
addImplicitTypedef(StringRef Name,QualType T)216 void Sema::addImplicitTypedef(StringRef Name, QualType T) {
217   DeclarationName DN = &Context.Idents.get(Name);
218   if (IdResolver.begin(DN) == IdResolver.end())
219     PushOnScopeChains(Context.buildImplicitTypedef(T, Name), TUScope);
220 }
221 
Initialize()222 void Sema::Initialize() {
223   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
224     SC->InitializeSema(*this);
225 
226   // Tell the external Sema source about this Sema object.
227   if (ExternalSemaSource *ExternalSema
228       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
229     ExternalSema->InitializeSema(*this);
230 
231   // This needs to happen after ExternalSemaSource::InitializeSema(this) or we
232   // will not be able to merge any duplicate __va_list_tag decls correctly.
233   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
234 
235   if (!TUScope)
236     return;
237 
238   // Initialize predefined 128-bit integer types, if needed.
239   if (Context.getTargetInfo().hasInt128Type() ||
240       (Context.getAuxTargetInfo() &&
241        Context.getAuxTargetInfo()->hasInt128Type())) {
242     // If either of the 128-bit integer types are unavailable to name lookup,
243     // define them now.
244     DeclarationName Int128 = &Context.Idents.get("__int128_t");
245     if (IdResolver.begin(Int128) == IdResolver.end())
246       PushOnScopeChains(Context.getInt128Decl(), TUScope);
247 
248     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
249     if (IdResolver.begin(UInt128) == IdResolver.end())
250       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
251   }
252 
253 
254   // Initialize predefined Objective-C types:
255   if (getLangOpts().ObjC) {
256     // If 'SEL' does not yet refer to any declarations, make it refer to the
257     // predefined 'SEL'.
258     DeclarationName SEL = &Context.Idents.get("SEL");
259     if (IdResolver.begin(SEL) == IdResolver.end())
260       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
261 
262     // If 'id' does not yet refer to any declarations, make it refer to the
263     // predefined 'id'.
264     DeclarationName Id = &Context.Idents.get("id");
265     if (IdResolver.begin(Id) == IdResolver.end())
266       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
267 
268     // Create the built-in typedef for 'Class'.
269     DeclarationName Class = &Context.Idents.get("Class");
270     if (IdResolver.begin(Class) == IdResolver.end())
271       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
272 
273     // Create the built-in forward declaratino for 'Protocol'.
274     DeclarationName Protocol = &Context.Idents.get("Protocol");
275     if (IdResolver.begin(Protocol) == IdResolver.end())
276       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
277   }
278 
279   // Create the internal type for the *StringMakeConstantString builtins.
280   DeclarationName ConstantString = &Context.Idents.get("__NSConstantString");
281   if (IdResolver.begin(ConstantString) == IdResolver.end())
282     PushOnScopeChains(Context.getCFConstantStringDecl(), TUScope);
283 
284   // Initialize Microsoft "predefined C++ types".
285   if (getLangOpts().MSVCCompat) {
286     if (getLangOpts().CPlusPlus &&
287         IdResolver.begin(&Context.Idents.get("type_info")) == IdResolver.end())
288       PushOnScopeChains(Context.buildImplicitRecord("type_info", TTK_Class),
289                         TUScope);
290 
291     addImplicitTypedef("size_t", Context.getSizeType());
292   }
293 
294   // Initialize predefined OpenCL types and supported extensions and (optional)
295   // core features.
296   if (getLangOpts().OpenCL) {
297     getOpenCLOptions().addSupport(
298         Context.getTargetInfo().getSupportedOpenCLOpts());
299     getOpenCLOptions().enableSupportedCore(getLangOpts());
300     addImplicitTypedef("sampler_t", Context.OCLSamplerTy);
301     addImplicitTypedef("event_t", Context.OCLEventTy);
302     if (getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) {
303       addImplicitTypedef("clk_event_t", Context.OCLClkEventTy);
304       addImplicitTypedef("queue_t", Context.OCLQueueTy);
305       addImplicitTypedef("reserve_id_t", Context.OCLReserveIDTy);
306       addImplicitTypedef("atomic_int", Context.getAtomicType(Context.IntTy));
307       addImplicitTypedef("atomic_uint",
308                          Context.getAtomicType(Context.UnsignedIntTy));
309       auto AtomicLongT = Context.getAtomicType(Context.LongTy);
310       addImplicitTypedef("atomic_long", AtomicLongT);
311       auto AtomicULongT = Context.getAtomicType(Context.UnsignedLongTy);
312       addImplicitTypedef("atomic_ulong", AtomicULongT);
313       addImplicitTypedef("atomic_float",
314                          Context.getAtomicType(Context.FloatTy));
315       auto AtomicDoubleT = Context.getAtomicType(Context.DoubleTy);
316       addImplicitTypedef("atomic_double", AtomicDoubleT);
317       // OpenCLC v2.0, s6.13.11.6 requires that atomic_flag is implemented as
318       // 32-bit integer and OpenCLC v2.0, s6.1.1 int is always 32-bit wide.
319       addImplicitTypedef("atomic_flag", Context.getAtomicType(Context.IntTy));
320       auto AtomicIntPtrT = Context.getAtomicType(Context.getIntPtrType());
321       addImplicitTypedef("atomic_intptr_t", AtomicIntPtrT);
322       auto AtomicUIntPtrT = Context.getAtomicType(Context.getUIntPtrType());
323       addImplicitTypedef("atomic_uintptr_t", AtomicUIntPtrT);
324       auto AtomicSizeT = Context.getAtomicType(Context.getSizeType());
325       addImplicitTypedef("atomic_size_t", AtomicSizeT);
326       auto AtomicPtrDiffT = Context.getAtomicType(Context.getPointerDiffType());
327       addImplicitTypedef("atomic_ptrdiff_t", AtomicPtrDiffT);
328 
329       // OpenCL v2.0 s6.13.11.6:
330       // - The atomic_long and atomic_ulong types are supported if the
331       //   cl_khr_int64_base_atomics and cl_khr_int64_extended_atomics
332       //   extensions are supported.
333       // - The atomic_double type is only supported if double precision
334       //   is supported and the cl_khr_int64_base_atomics and
335       //   cl_khr_int64_extended_atomics extensions are supported.
336       // - If the device address space is 64-bits, the data types
337       //   atomic_intptr_t, atomic_uintptr_t, atomic_size_t and
338       //   atomic_ptrdiff_t are supported if the cl_khr_int64_base_atomics and
339       //   cl_khr_int64_extended_atomics extensions are supported.
340       std::vector<QualType> Atomic64BitTypes;
341       Atomic64BitTypes.push_back(AtomicLongT);
342       Atomic64BitTypes.push_back(AtomicULongT);
343       Atomic64BitTypes.push_back(AtomicDoubleT);
344       if (Context.getTypeSize(AtomicSizeT) == 64) {
345         Atomic64BitTypes.push_back(AtomicSizeT);
346         Atomic64BitTypes.push_back(AtomicIntPtrT);
347         Atomic64BitTypes.push_back(AtomicUIntPtrT);
348         Atomic64BitTypes.push_back(AtomicPtrDiffT);
349       }
350       for (auto &I : Atomic64BitTypes)
351         setOpenCLExtensionForType(I,
352             "cl_khr_int64_base_atomics cl_khr_int64_extended_atomics");
353 
354       setOpenCLExtensionForType(AtomicDoubleT, "cl_khr_fp64");
355     }
356 
357     setOpenCLExtensionForType(Context.DoubleTy, "cl_khr_fp64");
358 
359 #define GENERIC_IMAGE_TYPE_EXT(Type, Id, Ext) \
360     setOpenCLExtensionForType(Context.Id, Ext);
361 #include "clang/Basic/OpenCLImageTypes.def"
362 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
363     addImplicitTypedef(#ExtType, Context.Id##Ty); \
364     setOpenCLExtensionForType(Context.Id##Ty, #Ext);
365 #include "clang/Basic/OpenCLExtensionTypes.def"
366   }
367 
368   if (Context.getTargetInfo().hasAArch64SVETypes()) {
369 #define SVE_TYPE(Name, Id, SingletonId) \
370     addImplicitTypedef(Name, Context.SingletonId);
371 #include "clang/Basic/AArch64SVEACLETypes.def"
372   }
373 
374   if (Context.getTargetInfo().getTriple().isPPC64() &&
375       Context.getTargetInfo().hasFeature("mma")) {
376 #define PPC_MMA_VECTOR_TYPE(Name, Id, Size) \
377     addImplicitTypedef(#Name, Context.Id##Ty);
378 #include "clang/Basic/PPCTypes.def"
379   }
380 
381   if (Context.getTargetInfo().hasBuiltinMSVaList()) {
382     DeclarationName MSVaList = &Context.Idents.get("__builtin_ms_va_list");
383     if (IdResolver.begin(MSVaList) == IdResolver.end())
384       PushOnScopeChains(Context.getBuiltinMSVaListDecl(), TUScope);
385   }
386 
387   DeclarationName BuiltinVaList = &Context.Idents.get("__builtin_va_list");
388   if (IdResolver.begin(BuiltinVaList) == IdResolver.end())
389     PushOnScopeChains(Context.getBuiltinVaListDecl(), TUScope);
390 }
391 
~Sema()392 Sema::~Sema() {
393   if (VisContext) FreeVisContext();
394 
395   // Kill all the active scopes.
396   for (sema::FunctionScopeInfo *FSI : FunctionScopes)
397     delete FSI;
398 
399   // Tell the SemaConsumer to forget about us; we're going out of scope.
400   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
401     SC->ForgetSema();
402 
403   // Detach from the external Sema source.
404   if (ExternalSemaSource *ExternalSema
405         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
406     ExternalSema->ForgetSema();
407 
408   // If Sema's ExternalSource is the multiplexer - we own it.
409   if (isMultiplexExternalSource)
410     delete ExternalSource;
411 
412   // Delete cached satisfactions.
413   std::vector<ConstraintSatisfaction *> Satisfactions;
414   Satisfactions.reserve(Satisfactions.size());
415   for (auto &Node : SatisfactionCache)
416     Satisfactions.push_back(&Node);
417   for (auto *Node : Satisfactions)
418     delete Node;
419 
420   threadSafety::threadSafetyCleanup(ThreadSafetyDeclCache);
421 
422   // Destroys data sharing attributes stack for OpenMP
423   DestroyDataSharingAttributesStack();
424 
425   // Detach from the PP callback handler which outlives Sema since it's owned
426   // by the preprocessor.
427   SemaPPCallbackHandler->reset();
428 }
429 
warnStackExhausted(SourceLocation Loc)430 void Sema::warnStackExhausted(SourceLocation Loc) {
431   // Only warn about this once.
432   if (!WarnedStackExhausted) {
433     Diag(Loc, diag::warn_stack_exhausted);
434     WarnedStackExhausted = true;
435   }
436 }
437 
runWithSufficientStackSpace(SourceLocation Loc,llvm::function_ref<void ()> Fn)438 void Sema::runWithSufficientStackSpace(SourceLocation Loc,
439                                        llvm::function_ref<void()> Fn) {
440   clang::runWithSufficientStackSpace([&] { warnStackExhausted(Loc); }, Fn);
441 }
442 
443 /// makeUnavailableInSystemHeader - There is an error in the current
444 /// context.  If we're still in a system header, and we can plausibly
445 /// make the relevant declaration unavailable instead of erroring, do
446 /// so and return true.
makeUnavailableInSystemHeader(SourceLocation loc,UnavailableAttr::ImplicitReason reason)447 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
448                                       UnavailableAttr::ImplicitReason reason) {
449   // If we're not in a function, it's an error.
450   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
451   if (!fn) return false;
452 
453   // If we're in template instantiation, it's an error.
454   if (inTemplateInstantiation())
455     return false;
456 
457   // If that function's not in a system header, it's an error.
458   if (!Context.getSourceManager().isInSystemHeader(loc))
459     return false;
460 
461   // If the function is already unavailable, it's not an error.
462   if (fn->hasAttr<UnavailableAttr>()) return true;
463 
464   fn->addAttr(UnavailableAttr::CreateImplicit(Context, "", reason, loc));
465   return true;
466 }
467 
getASTMutationListener() const468 ASTMutationListener *Sema::getASTMutationListener() const {
469   return getASTConsumer().GetASTMutationListener();
470 }
471 
472 ///Registers an external source. If an external source already exists,
473 /// creates a multiplex external source and appends to it.
474 ///
475 ///\param[in] E - A non-null external sema source.
476 ///
addExternalSource(ExternalSemaSource * E)477 void Sema::addExternalSource(ExternalSemaSource *E) {
478   assert(E && "Cannot use with NULL ptr");
479 
480   if (!ExternalSource) {
481     ExternalSource = E;
482     return;
483   }
484 
485   if (isMultiplexExternalSource)
486     static_cast<MultiplexExternalSemaSource*>(ExternalSource)->addSource(*E);
487   else {
488     ExternalSource = new MultiplexExternalSemaSource(*ExternalSource, *E);
489     isMultiplexExternalSource = true;
490   }
491 }
492 
493 /// Print out statistics about the semantic analysis.
PrintStats() const494 void Sema::PrintStats() const {
495   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
496   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
497 
498   BumpAlloc.PrintStats();
499   AnalysisWarnings.PrintStats();
500 }
501 
diagnoseNullableToNonnullConversion(QualType DstType,QualType SrcType,SourceLocation Loc)502 void Sema::diagnoseNullableToNonnullConversion(QualType DstType,
503                                                QualType SrcType,
504                                                SourceLocation Loc) {
505   Optional<NullabilityKind> ExprNullability = SrcType->getNullability(Context);
506   if (!ExprNullability || (*ExprNullability != NullabilityKind::Nullable &&
507                            *ExprNullability != NullabilityKind::NullableResult))
508     return;
509 
510   Optional<NullabilityKind> TypeNullability = DstType->getNullability(Context);
511   if (!TypeNullability || *TypeNullability != NullabilityKind::NonNull)
512     return;
513 
514   Diag(Loc, diag::warn_nullability_lost) << SrcType << DstType;
515 }
516 
diagnoseZeroToNullptrConversion(CastKind Kind,const Expr * E)517 void Sema::diagnoseZeroToNullptrConversion(CastKind Kind, const Expr* E) {
518   if (Diags.isIgnored(diag::warn_zero_as_null_pointer_constant,
519                       E->getBeginLoc()))
520     return;
521   // nullptr only exists from C++11 on, so don't warn on its absence earlier.
522   if (!getLangOpts().CPlusPlus11)
523     return;
524 
525   if (Kind != CK_NullToPointer && Kind != CK_NullToMemberPointer)
526     return;
527   if (E->IgnoreParenImpCasts()->getType()->isNullPtrType())
528     return;
529 
530   // If it is a macro from system header, and if the macro name is not "NULL",
531   // do not warn.
532   SourceLocation MaybeMacroLoc = E->getBeginLoc();
533   if (Diags.getSuppressSystemWarnings() &&
534       SourceMgr.isInSystemMacro(MaybeMacroLoc) &&
535       !findMacroSpelling(MaybeMacroLoc, "NULL"))
536     return;
537 
538   Diag(E->getBeginLoc(), diag::warn_zero_as_null_pointer_constant)
539       << FixItHint::CreateReplacement(E->getSourceRange(), "nullptr");
540 }
541 
542 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
543 /// If there is already an implicit cast, merge into the existing one.
544 /// The result is of the given category.
ImpCastExprToType(Expr * E,QualType Ty,CastKind Kind,ExprValueKind VK,const CXXCastPath * BasePath,CheckedConversionKind CCK)545 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
546                                    CastKind Kind, ExprValueKind VK,
547                                    const CXXCastPath *BasePath,
548                                    CheckedConversionKind CCK) {
549 #ifndef NDEBUG
550   if (VK == VK_RValue && !E->isRValue()) {
551     switch (Kind) {
552     default:
553       llvm_unreachable(("can't implicitly cast lvalue to rvalue with this cast "
554                         "kind: " +
555                         std::string(CastExpr::getCastKindName(Kind)))
556                            .c_str());
557     case CK_Dependent:
558     case CK_LValueToRValue:
559     case CK_ArrayToPointerDecay:
560     case CK_FunctionToPointerDecay:
561     case CK_ToVoid:
562     case CK_NonAtomicToAtomic:
563       break;
564     }
565   }
566   assert((VK == VK_RValue || Kind == CK_Dependent || !E->isRValue()) &&
567          "can't cast rvalue to lvalue");
568 #endif
569 
570   diagnoseNullableToNonnullConversion(Ty, E->getType(), E->getBeginLoc());
571   diagnoseZeroToNullptrConversion(Kind, E);
572 
573   QualType ExprTy = Context.getCanonicalType(E->getType());
574   QualType TypeTy = Context.getCanonicalType(Ty);
575 
576   if (ExprTy == TypeTy)
577     return E;
578 
579   // C++1z [conv.array]: The temporary materialization conversion is applied.
580   // We also use this to fuel C++ DR1213, which applies to C++11 onwards.
581   if (Kind == CK_ArrayToPointerDecay && getLangOpts().CPlusPlus &&
582       E->getValueKind() == VK_RValue) {
583     // The temporary is an lvalue in C++98 and an xvalue otherwise.
584     ExprResult Materialized = CreateMaterializeTemporaryExpr(
585         E->getType(), E, !getLangOpts().CPlusPlus11);
586     if (Materialized.isInvalid())
587       return ExprError();
588     E = Materialized.get();
589   }
590 
591   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
592     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
593       ImpCast->setType(Ty);
594       ImpCast->setValueKind(VK);
595       return E;
596     }
597   }
598 
599   return ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK,
600                                   CurFPFeatureOverrides());
601 }
602 
603 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
604 /// to the conversion from scalar type ScalarTy to the Boolean type.
ScalarTypeToBooleanCastKind(QualType ScalarTy)605 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
606   switch (ScalarTy->getScalarTypeKind()) {
607   case Type::STK_Bool: return CK_NoOp;
608   case Type::STK_CPointer: return CK_PointerToBoolean;
609   case Type::STK_BlockPointer: return CK_PointerToBoolean;
610   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
611   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
612   case Type::STK_Integral: return CK_IntegralToBoolean;
613   case Type::STK_Floating: return CK_FloatingToBoolean;
614   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
615   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
616   case Type::STK_FixedPoint: return CK_FixedPointToBoolean;
617   }
618   llvm_unreachable("unknown scalar type kind");
619 }
620 
621 /// Used to prune the decls of Sema's UnusedFileScopedDecls vector.
ShouldRemoveFromUnused(Sema * SemaRef,const DeclaratorDecl * D)622 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
623   if (D->getMostRecentDecl()->isUsed())
624     return true;
625 
626   if (D->isExternallyVisible())
627     return true;
628 
629   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
630     // If this is a function template and none of its specializations is used,
631     // we should warn.
632     if (FunctionTemplateDecl *Template = FD->getDescribedFunctionTemplate())
633       for (const auto *Spec : Template->specializations())
634         if (ShouldRemoveFromUnused(SemaRef, Spec))
635           return true;
636 
637     // UnusedFileScopedDecls stores the first declaration.
638     // The declaration may have become definition so check again.
639     const FunctionDecl *DeclToCheck;
640     if (FD->hasBody(DeclToCheck))
641       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
642 
643     // Later redecls may add new information resulting in not having to warn,
644     // so check again.
645     DeclToCheck = FD->getMostRecentDecl();
646     if (DeclToCheck != FD)
647       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
648   }
649 
650   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
651     // If a variable usable in constant expressions is referenced,
652     // don't warn if it isn't used: if the value of a variable is required
653     // for the computation of a constant expression, it doesn't make sense to
654     // warn even if the variable isn't odr-used.  (isReferenced doesn't
655     // precisely reflect that, but it's a decent approximation.)
656     if (VD->isReferenced() &&
657         VD->mightBeUsableInConstantExpressions(SemaRef->Context))
658       return true;
659 
660     if (VarTemplateDecl *Template = VD->getDescribedVarTemplate())
661       // If this is a variable template and none of its specializations is used,
662       // we should warn.
663       for (const auto *Spec : Template->specializations())
664         if (ShouldRemoveFromUnused(SemaRef, Spec))
665           return true;
666 
667     // UnusedFileScopedDecls stores the first declaration.
668     // The declaration may have become definition so check again.
669     const VarDecl *DeclToCheck = VD->getDefinition();
670     if (DeclToCheck)
671       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
672 
673     // Later redecls may add new information resulting in not having to warn,
674     // so check again.
675     DeclToCheck = VD->getMostRecentDecl();
676     if (DeclToCheck != VD)
677       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
678   }
679 
680   return false;
681 }
682 
isFunctionOrVarDeclExternC(NamedDecl * ND)683 static bool isFunctionOrVarDeclExternC(NamedDecl *ND) {
684   if (auto *FD = dyn_cast<FunctionDecl>(ND))
685     return FD->isExternC();
686   return cast<VarDecl>(ND)->isExternC();
687 }
688 
689 /// Determine whether ND is an external-linkage function or variable whose
690 /// type has no linkage.
isExternalWithNoLinkageType(ValueDecl * VD)691 bool Sema::isExternalWithNoLinkageType(ValueDecl *VD) {
692   // Note: it's not quite enough to check whether VD has UniqueExternalLinkage,
693   // because we also want to catch the case where its type has VisibleNoLinkage,
694   // which does not affect the linkage of VD.
695   return getLangOpts().CPlusPlus && VD->hasExternalFormalLinkage() &&
696          !isExternalFormalLinkage(VD->getType()->getLinkage()) &&
697          !isFunctionOrVarDeclExternC(VD);
698 }
699 
700 /// Obtains a sorted list of functions and variables that are undefined but
701 /// ODR-used.
getUndefinedButUsed(SmallVectorImpl<std::pair<NamedDecl *,SourceLocation>> & Undefined)702 void Sema::getUndefinedButUsed(
703     SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined) {
704   for (const auto &UndefinedUse : UndefinedButUsed) {
705     NamedDecl *ND = UndefinedUse.first;
706 
707     // Ignore attributes that have become invalid.
708     if (ND->isInvalidDecl()) continue;
709 
710     // __attribute__((weakref)) is basically a definition.
711     if (ND->hasAttr<WeakRefAttr>()) continue;
712 
713     if (isa<CXXDeductionGuideDecl>(ND))
714       continue;
715 
716     if (ND->hasAttr<DLLImportAttr>() || ND->hasAttr<DLLExportAttr>()) {
717       // An exported function will always be emitted when defined, so even if
718       // the function is inline, it doesn't have to be emitted in this TU. An
719       // imported function implies that it has been exported somewhere else.
720       continue;
721     }
722 
723     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
724       if (FD->isDefined())
725         continue;
726       if (FD->isExternallyVisible() &&
727           !isExternalWithNoLinkageType(FD) &&
728           !FD->getMostRecentDecl()->isInlined() &&
729           !FD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
730         continue;
731       if (FD->getBuiltinID())
732         continue;
733     } else {
734       auto *VD = cast<VarDecl>(ND);
735       if (VD->hasDefinition() != VarDecl::DeclarationOnly)
736         continue;
737       if (VD->isExternallyVisible() &&
738           !isExternalWithNoLinkageType(VD) &&
739           !VD->getMostRecentDecl()->isInline() &&
740           !VD->hasAttr<ExcludeFromExplicitInstantiationAttr>())
741         continue;
742 
743       // Skip VarDecls that lack formal definitions but which we know are in
744       // fact defined somewhere.
745       if (VD->isKnownToBeDefined())
746         continue;
747     }
748 
749     Undefined.push_back(std::make_pair(ND, UndefinedUse.second));
750   }
751 }
752 
753 /// checkUndefinedButUsed - Check for undefined objects with internal linkage
754 /// or that are inline.
checkUndefinedButUsed(Sema & S)755 static void checkUndefinedButUsed(Sema &S) {
756   if (S.UndefinedButUsed.empty()) return;
757 
758   // Collect all the still-undefined entities with internal linkage.
759   SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
760   S.getUndefinedButUsed(Undefined);
761   if (Undefined.empty()) return;
762 
763   for (auto Undef : Undefined) {
764     ValueDecl *VD = cast<ValueDecl>(Undef.first);
765     SourceLocation UseLoc = Undef.second;
766 
767     if (S.isExternalWithNoLinkageType(VD)) {
768       // C++ [basic.link]p8:
769       //   A type without linkage shall not be used as the type of a variable
770       //   or function with external linkage unless
771       //    -- the entity has C language linkage
772       //    -- the entity is not odr-used or is defined in the same TU
773       //
774       // As an extension, accept this in cases where the type is externally
775       // visible, since the function or variable actually can be defined in
776       // another translation unit in that case.
777       S.Diag(VD->getLocation(), isExternallyVisible(VD->getType()->getLinkage())
778                                     ? diag::ext_undefined_internal_type
779                                     : diag::err_undefined_internal_type)
780         << isa<VarDecl>(VD) << VD;
781     } else if (!VD->isExternallyVisible()) {
782       // FIXME: We can promote this to an error. The function or variable can't
783       // be defined anywhere else, so the program must necessarily violate the
784       // one definition rule.
785       S.Diag(VD->getLocation(), diag::warn_undefined_internal)
786         << isa<VarDecl>(VD) << VD;
787     } else if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
788       (void)FD;
789       assert(FD->getMostRecentDecl()->isInlined() &&
790              "used object requires definition but isn't inline or internal?");
791       // FIXME: This is ill-formed; we should reject.
792       S.Diag(VD->getLocation(), diag::warn_undefined_inline) << VD;
793     } else {
794       assert(cast<VarDecl>(VD)->getMostRecentDecl()->isInline() &&
795              "used var requires definition but isn't inline or internal?");
796       S.Diag(VD->getLocation(), diag::err_undefined_inline_var) << VD;
797     }
798     if (UseLoc.isValid())
799       S.Diag(UseLoc, diag::note_used_here);
800   }
801 
802   S.UndefinedButUsed.clear();
803 }
804 
LoadExternalWeakUndeclaredIdentifiers()805 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
806   if (!ExternalSource)
807     return;
808 
809   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
810   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
811   for (auto &WeakID : WeakIDs)
812     WeakUndeclaredIdentifiers.insert(WeakID);
813 }
814 
815 
816 typedef llvm::DenseMap<const CXXRecordDecl*, bool> RecordCompleteMap;
817 
818 /// Returns true, if all methods and nested classes of the given
819 /// CXXRecordDecl are defined in this translation unit.
820 ///
821 /// Should only be called from ActOnEndOfTranslationUnit so that all
822 /// definitions are actually read.
MethodsAndNestedClassesComplete(const CXXRecordDecl * RD,RecordCompleteMap & MNCComplete)823 static bool MethodsAndNestedClassesComplete(const CXXRecordDecl *RD,
824                                             RecordCompleteMap &MNCComplete) {
825   RecordCompleteMap::iterator Cache = MNCComplete.find(RD);
826   if (Cache != MNCComplete.end())
827     return Cache->second;
828   if (!RD->isCompleteDefinition())
829     return false;
830   bool Complete = true;
831   for (DeclContext::decl_iterator I = RD->decls_begin(),
832                                   E = RD->decls_end();
833        I != E && Complete; ++I) {
834     if (const CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(*I))
835       Complete = M->isDefined() || M->isDefaulted() ||
836                  (M->isPure() && !isa<CXXDestructorDecl>(M));
837     else if (const FunctionTemplateDecl *F = dyn_cast<FunctionTemplateDecl>(*I))
838       // If the template function is marked as late template parsed at this
839       // point, it has not been instantiated and therefore we have not
840       // performed semantic analysis on it yet, so we cannot know if the type
841       // can be considered complete.
842       Complete = !F->getTemplatedDecl()->isLateTemplateParsed() &&
843                   F->getTemplatedDecl()->isDefined();
844     else if (const CXXRecordDecl *R = dyn_cast<CXXRecordDecl>(*I)) {
845       if (R->isInjectedClassName())
846         continue;
847       if (R->hasDefinition())
848         Complete = MethodsAndNestedClassesComplete(R->getDefinition(),
849                                                    MNCComplete);
850       else
851         Complete = false;
852     }
853   }
854   MNCComplete[RD] = Complete;
855   return Complete;
856 }
857 
858 /// Returns true, if the given CXXRecordDecl is fully defined in this
859 /// translation unit, i.e. all methods are defined or pure virtual and all
860 /// friends, friend functions and nested classes are fully defined in this
861 /// translation unit.
862 ///
863 /// Should only be called from ActOnEndOfTranslationUnit so that all
864 /// definitions are actually read.
IsRecordFullyDefined(const CXXRecordDecl * RD,RecordCompleteMap & RecordsComplete,RecordCompleteMap & MNCComplete)865 static bool IsRecordFullyDefined(const CXXRecordDecl *RD,
866                                  RecordCompleteMap &RecordsComplete,
867                                  RecordCompleteMap &MNCComplete) {
868   RecordCompleteMap::iterator Cache = RecordsComplete.find(RD);
869   if (Cache != RecordsComplete.end())
870     return Cache->second;
871   bool Complete = MethodsAndNestedClassesComplete(RD, MNCComplete);
872   for (CXXRecordDecl::friend_iterator I = RD->friend_begin(),
873                                       E = RD->friend_end();
874        I != E && Complete; ++I) {
875     // Check if friend classes and methods are complete.
876     if (TypeSourceInfo *TSI = (*I)->getFriendType()) {
877       // Friend classes are available as the TypeSourceInfo of the FriendDecl.
878       if (CXXRecordDecl *FriendD = TSI->getType()->getAsCXXRecordDecl())
879         Complete = MethodsAndNestedClassesComplete(FriendD, MNCComplete);
880       else
881         Complete = false;
882     } else {
883       // Friend functions are available through the NamedDecl of FriendDecl.
884       if (const FunctionDecl *FD =
885           dyn_cast<FunctionDecl>((*I)->getFriendDecl()))
886         Complete = FD->isDefined();
887       else
888         // This is a template friend, give up.
889         Complete = false;
890     }
891   }
892   RecordsComplete[RD] = Complete;
893   return Complete;
894 }
895 
emitAndClearUnusedLocalTypedefWarnings()896 void Sema::emitAndClearUnusedLocalTypedefWarnings() {
897   if (ExternalSource)
898     ExternalSource->ReadUnusedLocalTypedefNameCandidates(
899         UnusedLocalTypedefNameCandidates);
900   for (const TypedefNameDecl *TD : UnusedLocalTypedefNameCandidates) {
901     if (TD->isReferenced())
902       continue;
903     Diag(TD->getLocation(), diag::warn_unused_local_typedef)
904         << isa<TypeAliasDecl>(TD) << TD->getDeclName();
905   }
906   UnusedLocalTypedefNameCandidates.clear();
907 }
908 
909 /// This is called before the very first declaration in the translation unit
910 /// is parsed. Note that the ASTContext may have already injected some
911 /// declarations.
ActOnStartOfTranslationUnit()912 void Sema::ActOnStartOfTranslationUnit() {
913   if (getLangOpts().ModulesTS &&
914       (getLangOpts().getCompilingModule() == LangOptions::CMK_ModuleInterface ||
915        getLangOpts().getCompilingModule() == LangOptions::CMK_None)) {
916     // We start in an implied global module fragment.
917     SourceLocation StartOfTU =
918         SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
919     ActOnGlobalModuleFragmentDecl(StartOfTU);
920     ModuleScopes.back().ImplicitGlobalModuleFragment = true;
921   }
922 }
923 
ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind)924 void Sema::ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind) {
925   // No explicit actions are required at the end of the global module fragment.
926   if (Kind == TUFragmentKind::Global)
927     return;
928 
929   // Transfer late parsed template instantiations over to the pending template
930   // instantiation list. During normal compilation, the late template parser
931   // will be installed and instantiating these templates will succeed.
932   //
933   // If we are building a TU prefix for serialization, it is also safe to
934   // transfer these over, even though they are not parsed. The end of the TU
935   // should be outside of any eager template instantiation scope, so when this
936   // AST is deserialized, these templates will not be parsed until the end of
937   // the combined TU.
938   PendingInstantiations.insert(PendingInstantiations.end(),
939                                LateParsedInstantiations.begin(),
940                                LateParsedInstantiations.end());
941   LateParsedInstantiations.clear();
942 
943   // If DefinedUsedVTables ends up marking any virtual member functions it
944   // might lead to more pending template instantiations, which we then need
945   // to instantiate.
946   DefineUsedVTables();
947 
948   // C++: Perform implicit template instantiations.
949   //
950   // FIXME: When we perform these implicit instantiations, we do not
951   // carefully keep track of the point of instantiation (C++ [temp.point]).
952   // This means that name lookup that occurs within the template
953   // instantiation will always happen at the end of the translation unit,
954   // so it will find some names that are not required to be found. This is
955   // valid, but we could do better by diagnosing if an instantiation uses a
956   // name that was not visible at its first point of instantiation.
957   if (ExternalSource) {
958     // Load pending instantiations from the external source.
959     SmallVector<PendingImplicitInstantiation, 4> Pending;
960     ExternalSource->ReadPendingInstantiations(Pending);
961     for (auto PII : Pending)
962       if (auto Func = dyn_cast<FunctionDecl>(PII.first))
963         Func->setInstantiationIsPending(true);
964     PendingInstantiations.insert(PendingInstantiations.begin(),
965                                  Pending.begin(), Pending.end());
966   }
967 
968   {
969     llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
970     PerformPendingInstantiations();
971   }
972 
973   emitDeferredDiags();
974 
975   assert(LateParsedInstantiations.empty() &&
976          "end of TU template instantiation should not create more "
977          "late-parsed templates");
978 
979   // Report diagnostics for uncorrected delayed typos. Ideally all of them
980   // should have been corrected by that time, but it is very hard to cover all
981   // cases in practice.
982   for (const auto &Typo : DelayedTypos) {
983     // We pass an empty TypoCorrection to indicate no correction was performed.
984     Typo.second.DiagHandler(TypoCorrection());
985   }
986   DelayedTypos.clear();
987 }
988 
989 /// ActOnEndOfTranslationUnit - This is called at the very end of the
990 /// translation unit when EOF is reached and all but the top-level scope is
991 /// popped.
ActOnEndOfTranslationUnit()992 void Sema::ActOnEndOfTranslationUnit() {
993   assert(DelayedDiagnostics.getCurrentPool() == nullptr
994          && "reached end of translation unit with a pool attached?");
995 
996   // If code completion is enabled, don't perform any end-of-translation-unit
997   // work.
998   if (PP.isCodeCompletionEnabled())
999     return;
1000 
1001   // Complete translation units and modules define vtables and perform implicit
1002   // instantiations. PCH files do not.
1003   if (TUKind != TU_Prefix) {
1004     DiagnoseUseOfUnimplementedSelectors();
1005 
1006     ActOnEndOfTranslationUnitFragment(
1007         !ModuleScopes.empty() && ModuleScopes.back().Module->Kind ==
1008                                      Module::PrivateModuleFragment
1009             ? TUFragmentKind::Private
1010             : TUFragmentKind::Normal);
1011 
1012     if (LateTemplateParserCleanup)
1013       LateTemplateParserCleanup(OpaqueParser);
1014 
1015     CheckDelayedMemberExceptionSpecs();
1016   } else {
1017     // If we are building a TU prefix for serialization, it is safe to transfer
1018     // these over, even though they are not parsed. The end of the TU should be
1019     // outside of any eager template instantiation scope, so when this AST is
1020     // deserialized, these templates will not be parsed until the end of the
1021     // combined TU.
1022     PendingInstantiations.insert(PendingInstantiations.end(),
1023                                  LateParsedInstantiations.begin(),
1024                                  LateParsedInstantiations.end());
1025     LateParsedInstantiations.clear();
1026 
1027     if (LangOpts.PCHInstantiateTemplates) {
1028       llvm::TimeTraceScope TimeScope("PerformPendingInstantiations");
1029       PerformPendingInstantiations();
1030     }
1031   }
1032 
1033   DiagnoseUnterminatedPragmaPack();
1034   DiagnoseUnterminatedPragmaAttribute();
1035 
1036   // All delayed member exception specs should be checked or we end up accepting
1037   // incompatible declarations.
1038   assert(DelayedOverridingExceptionSpecChecks.empty());
1039   assert(DelayedEquivalentExceptionSpecChecks.empty());
1040 
1041   // All dllexport classes should have been processed already.
1042   assert(DelayedDllExportClasses.empty());
1043   assert(DelayedDllExportMemberFunctions.empty());
1044 
1045   // Remove file scoped decls that turned out to be used.
1046   UnusedFileScopedDecls.erase(
1047       std::remove_if(UnusedFileScopedDecls.begin(nullptr, true),
1048                      UnusedFileScopedDecls.end(),
1049                      [this](const DeclaratorDecl *DD) {
1050                        return ShouldRemoveFromUnused(this, DD);
1051                      }),
1052       UnusedFileScopedDecls.end());
1053 
1054   if (TUKind == TU_Prefix) {
1055     // Translation unit prefixes don't need any of the checking below.
1056     if (!PP.isIncrementalProcessingEnabled())
1057       TUScope = nullptr;
1058     return;
1059   }
1060 
1061   // Check for #pragma weak identifiers that were never declared
1062   LoadExternalWeakUndeclaredIdentifiers();
1063   for (auto WeakID : WeakUndeclaredIdentifiers) {
1064     if (WeakID.second.getUsed())
1065       continue;
1066 
1067     Decl *PrevDecl = LookupSingleName(TUScope, WeakID.first, SourceLocation(),
1068                                       LookupOrdinaryName);
1069     if (PrevDecl != nullptr &&
1070         !(isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl)))
1071       Diag(WeakID.second.getLocation(), diag::warn_attribute_wrong_decl_type)
1072           << "'weak'" << ExpectedVariableOrFunction;
1073     else
1074       Diag(WeakID.second.getLocation(), diag::warn_weak_identifier_undeclared)
1075           << WeakID.first;
1076   }
1077 
1078   if (LangOpts.CPlusPlus11 &&
1079       !Diags.isIgnored(diag::warn_delegating_ctor_cycle, SourceLocation()))
1080     CheckDelegatingCtorCycles();
1081 
1082   if (!Diags.hasErrorOccurred()) {
1083     if (ExternalSource)
1084       ExternalSource->ReadUndefinedButUsed(UndefinedButUsed);
1085     checkUndefinedButUsed(*this);
1086   }
1087 
1088   // A global-module-fragment is only permitted within a module unit.
1089   bool DiagnosedMissingModuleDeclaration = false;
1090   if (!ModuleScopes.empty() &&
1091       ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment &&
1092       !ModuleScopes.back().ImplicitGlobalModuleFragment) {
1093     Diag(ModuleScopes.back().BeginLoc,
1094          diag::err_module_declaration_missing_after_global_module_introducer);
1095     DiagnosedMissingModuleDeclaration = true;
1096   }
1097 
1098   if (TUKind == TU_Module) {
1099     // If we are building a module interface unit, we need to have seen the
1100     // module declaration by now.
1101     if (getLangOpts().getCompilingModule() ==
1102             LangOptions::CMK_ModuleInterface &&
1103         (ModuleScopes.empty() ||
1104          !ModuleScopes.back().Module->isModulePurview()) &&
1105         !DiagnosedMissingModuleDeclaration) {
1106       // FIXME: Make a better guess as to where to put the module declaration.
1107       Diag(getSourceManager().getLocForStartOfFile(
1108                getSourceManager().getMainFileID()),
1109            diag::err_module_declaration_missing);
1110     }
1111 
1112     // If we are building a module, resolve all of the exported declarations
1113     // now.
1114     if (Module *CurrentModule = PP.getCurrentModule()) {
1115       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
1116 
1117       SmallVector<Module *, 2> Stack;
1118       Stack.push_back(CurrentModule);
1119       while (!Stack.empty()) {
1120         Module *Mod = Stack.pop_back_val();
1121 
1122         // Resolve the exported declarations and conflicts.
1123         // FIXME: Actually complain, once we figure out how to teach the
1124         // diagnostic client to deal with complaints in the module map at this
1125         // point.
1126         ModMap.resolveExports(Mod, /*Complain=*/false);
1127         ModMap.resolveUses(Mod, /*Complain=*/false);
1128         ModMap.resolveConflicts(Mod, /*Complain=*/false);
1129 
1130         // Queue the submodules, so their exports will also be resolved.
1131         Stack.append(Mod->submodule_begin(), Mod->submodule_end());
1132       }
1133     }
1134 
1135     // Warnings emitted in ActOnEndOfTranslationUnit() should be emitted for
1136     // modules when they are built, not every time they are used.
1137     emitAndClearUnusedLocalTypedefWarnings();
1138   }
1139 
1140   // C99 6.9.2p2:
1141   //   A declaration of an identifier for an object that has file
1142   //   scope without an initializer, and without a storage-class
1143   //   specifier or with the storage-class specifier static,
1144   //   constitutes a tentative definition. If a translation unit
1145   //   contains one or more tentative definitions for an identifier,
1146   //   and the translation unit contains no external definition for
1147   //   that identifier, then the behavior is exactly as if the
1148   //   translation unit contains a file scope declaration of that
1149   //   identifier, with the composite type as of the end of the
1150   //   translation unit, with an initializer equal to 0.
1151   llvm::SmallSet<VarDecl *, 32> Seen;
1152   for (TentativeDefinitionsType::iterator
1153             T = TentativeDefinitions.begin(ExternalSource),
1154          TEnd = TentativeDefinitions.end();
1155        T != TEnd; ++T) {
1156     VarDecl *VD = (*T)->getActingDefinition();
1157 
1158     // If the tentative definition was completed, getActingDefinition() returns
1159     // null. If we've already seen this variable before, insert()'s second
1160     // return value is false.
1161     if (!VD || VD->isInvalidDecl() || !Seen.insert(VD).second)
1162       continue;
1163 
1164     if (const IncompleteArrayType *ArrayT
1165         = Context.getAsIncompleteArrayType(VD->getType())) {
1166       // Set the length of the array to 1 (C99 6.9.2p5).
1167       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
1168       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
1169       QualType T = Context.getConstantArrayType(ArrayT->getElementType(), One,
1170                                                 nullptr, ArrayType::Normal, 0);
1171       VD->setType(T);
1172     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
1173                                    diag::err_tentative_def_incomplete_type))
1174       VD->setInvalidDecl();
1175 
1176     // No initialization is performed for a tentative definition.
1177     CheckCompleteVariableDeclaration(VD);
1178 
1179     // Notify the consumer that we've completed a tentative definition.
1180     if (!VD->isInvalidDecl())
1181       Consumer.CompleteTentativeDefinition(VD);
1182   }
1183 
1184   for (auto D : ExternalDeclarations) {
1185     if (!D || D->isInvalidDecl() || D->getPreviousDecl() || !D->isUsed())
1186       continue;
1187 
1188     Consumer.CompleteExternalDeclaration(D);
1189   }
1190 
1191   // If there were errors, disable 'unused' warnings since they will mostly be
1192   // noise. Don't warn for a use from a module: either we should warn on all
1193   // file-scope declarations in modules or not at all, but whether the
1194   // declaration is used is immaterial.
1195   if (!Diags.hasErrorOccurred() && TUKind != TU_Module) {
1196     // Output warning for unused file scoped decls.
1197     for (UnusedFileScopedDeclsType::iterator
1198            I = UnusedFileScopedDecls.begin(ExternalSource),
1199            E = UnusedFileScopedDecls.end(); I != E; ++I) {
1200       if (ShouldRemoveFromUnused(this, *I))
1201         continue;
1202 
1203       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
1204         const FunctionDecl *DiagD;
1205         if (!FD->hasBody(DiagD))
1206           DiagD = FD;
1207         if (DiagD->isDeleted())
1208           continue; // Deleted functions are supposed to be unused.
1209         if (DiagD->isReferenced()) {
1210           if (isa<CXXMethodDecl>(DiagD))
1211             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
1212                 << DiagD;
1213           else {
1214             if (FD->getStorageClass() == SC_Static &&
1215                 !FD->isInlineSpecified() &&
1216                 !SourceMgr.isInMainFile(
1217                    SourceMgr.getExpansionLoc(FD->getLocation())))
1218               Diag(DiagD->getLocation(),
1219                    diag::warn_unneeded_static_internal_decl)
1220                   << DiagD;
1221             else
1222               Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1223                   << /*function*/ 0 << DiagD;
1224           }
1225         } else {
1226           if (FD->getDescribedFunctionTemplate())
1227             Diag(DiagD->getLocation(), diag::warn_unused_template)
1228                 << /*function*/ 0 << DiagD;
1229           else
1230             Diag(DiagD->getLocation(), isa<CXXMethodDecl>(DiagD)
1231                                            ? diag::warn_unused_member_function
1232                                            : diag::warn_unused_function)
1233                 << DiagD;
1234         }
1235       } else {
1236         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
1237         if (!DiagD)
1238           DiagD = cast<VarDecl>(*I);
1239         if (DiagD->isReferenced()) {
1240           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
1241               << /*variable*/ 1 << DiagD;
1242         } else if (DiagD->getType().isConstQualified()) {
1243           const SourceManager &SM = SourceMgr;
1244           if (SM.getMainFileID() != SM.getFileID(DiagD->getLocation()) ||
1245               !PP.getLangOpts().IsHeaderFile)
1246             Diag(DiagD->getLocation(), diag::warn_unused_const_variable)
1247                 << DiagD;
1248         } else {
1249           if (DiagD->getDescribedVarTemplate())
1250             Diag(DiagD->getLocation(), diag::warn_unused_template)
1251                 << /*variable*/ 1 << DiagD;
1252           else
1253             Diag(DiagD->getLocation(), diag::warn_unused_variable) << DiagD;
1254         }
1255       }
1256     }
1257 
1258     emitAndClearUnusedLocalTypedefWarnings();
1259   }
1260 
1261   if (!Diags.isIgnored(diag::warn_unused_private_field, SourceLocation())) {
1262     // FIXME: Load additional unused private field candidates from the external
1263     // source.
1264     RecordCompleteMap RecordsComplete;
1265     RecordCompleteMap MNCComplete;
1266     for (NamedDeclSetType::iterator I = UnusedPrivateFields.begin(),
1267          E = UnusedPrivateFields.end(); I != E; ++I) {
1268       const NamedDecl *D = *I;
1269       const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
1270       if (RD && !RD->isUnion() &&
1271           IsRecordFullyDefined(RD, RecordsComplete, MNCComplete)) {
1272         Diag(D->getLocation(), diag::warn_unused_private_field)
1273               << D->getDeclName();
1274       }
1275     }
1276   }
1277 
1278   if (!Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) {
1279     if (ExternalSource)
1280       ExternalSource->ReadMismatchingDeleteExpressions(DeleteExprs);
1281     for (const auto &DeletedFieldInfo : DeleteExprs) {
1282       for (const auto &DeleteExprLoc : DeletedFieldInfo.second) {
1283         AnalyzeDeleteExprMismatch(DeletedFieldInfo.first, DeleteExprLoc.first,
1284                                   DeleteExprLoc.second);
1285       }
1286     }
1287   }
1288 
1289   // Check we've noticed that we're no longer parsing the initializer for every
1290   // variable. If we miss cases, then at best we have a performance issue and
1291   // at worst a rejects-valid bug.
1292   assert(ParsingInitForAutoVars.empty() &&
1293          "Didn't unmark var as having its initializer parsed");
1294 
1295   if (!PP.isIncrementalProcessingEnabled())
1296     TUScope = nullptr;
1297 }
1298 
1299 
1300 //===----------------------------------------------------------------------===//
1301 // Helper functions.
1302 //===----------------------------------------------------------------------===//
1303 
getFunctionLevelDeclContext()1304 DeclContext *Sema::getFunctionLevelDeclContext() {
1305   DeclContext *DC = CurContext;
1306 
1307   while (true) {
1308     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC) || isa<CapturedDecl>(DC) ||
1309         isa<RequiresExprBodyDecl>(DC)) {
1310       DC = DC->getParent();
1311     } else if (isa<CXXMethodDecl>(DC) &&
1312                cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
1313                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
1314       DC = DC->getParent()->getParent();
1315     }
1316     else break;
1317   }
1318 
1319   return DC;
1320 }
1321 
1322 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
1323 /// to the function decl for the function being parsed.  If we're currently
1324 /// in a 'block', this returns the containing context.
getCurFunctionDecl()1325 FunctionDecl *Sema::getCurFunctionDecl() {
1326   DeclContext *DC = getFunctionLevelDeclContext();
1327   return dyn_cast<FunctionDecl>(DC);
1328 }
1329 
getCurMethodDecl()1330 ObjCMethodDecl *Sema::getCurMethodDecl() {
1331   DeclContext *DC = getFunctionLevelDeclContext();
1332   while (isa<RecordDecl>(DC))
1333     DC = DC->getParent();
1334   return dyn_cast<ObjCMethodDecl>(DC);
1335 }
1336 
getCurFunctionOrMethodDecl()1337 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
1338   DeclContext *DC = getFunctionLevelDeclContext();
1339   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
1340     return cast<NamedDecl>(DC);
1341   return nullptr;
1342 }
1343 
getDefaultCXXMethodAddrSpace() const1344 LangAS Sema::getDefaultCXXMethodAddrSpace() const {
1345   if (getLangOpts().OpenCL)
1346     return LangAS::opencl_generic;
1347   return LangAS::Default;
1348 }
1349 
EmitCurrentDiagnostic(unsigned DiagID)1350 void Sema::EmitCurrentDiagnostic(unsigned DiagID) {
1351   // FIXME: It doesn't make sense to me that DiagID is an incoming argument here
1352   // and yet we also use the current diag ID on the DiagnosticsEngine. This has
1353   // been made more painfully obvious by the refactor that introduced this
1354   // function, but it is possible that the incoming argument can be
1355   // eliminated. If it truly cannot be (for example, there is some reentrancy
1356   // issue I am not seeing yet), then there should at least be a clarifying
1357   // comment somewhere.
1358   if (Optional<TemplateDeductionInfo*> Info = isSFINAEContext()) {
1359     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(
1360               Diags.getCurrentDiagID())) {
1361     case DiagnosticIDs::SFINAE_Report:
1362       // We'll report the diagnostic below.
1363       break;
1364 
1365     case DiagnosticIDs::SFINAE_SubstitutionFailure:
1366       // Count this failure so that we know that template argument deduction
1367       // has failed.
1368       ++NumSFINAEErrors;
1369 
1370       // Make a copy of this suppressed diagnostic and store it with the
1371       // template-deduction information.
1372       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1373         Diagnostic DiagInfo(&Diags);
1374         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1375                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1376       }
1377 
1378       Diags.setLastDiagnosticIgnored(true);
1379       Diags.Clear();
1380       return;
1381 
1382     case DiagnosticIDs::SFINAE_AccessControl: {
1383       // Per C++ Core Issue 1170, access control is part of SFINAE.
1384       // Additionally, the AccessCheckingSFINAE flag can be used to temporarily
1385       // make access control a part of SFINAE for the purposes of checking
1386       // type traits.
1387       if (!AccessCheckingSFINAE && !getLangOpts().CPlusPlus11)
1388         break;
1389 
1390       SourceLocation Loc = Diags.getCurrentDiagLoc();
1391 
1392       // Suppress this diagnostic.
1393       ++NumSFINAEErrors;
1394 
1395       // Make a copy of this suppressed diagnostic and store it with the
1396       // template-deduction information.
1397       if (*Info && !(*Info)->hasSFINAEDiagnostic()) {
1398         Diagnostic DiagInfo(&Diags);
1399         (*Info)->addSFINAEDiagnostic(DiagInfo.getLocation(),
1400                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1401       }
1402 
1403       Diags.setLastDiagnosticIgnored(true);
1404       Diags.Clear();
1405 
1406       // Now the diagnostic state is clear, produce a C++98 compatibility
1407       // warning.
1408       Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
1409 
1410       // The last diagnostic which Sema produced was ignored. Suppress any
1411       // notes attached to it.
1412       Diags.setLastDiagnosticIgnored(true);
1413       return;
1414     }
1415 
1416     case DiagnosticIDs::SFINAE_Suppress:
1417       // Make a copy of this suppressed diagnostic and store it with the
1418       // template-deduction information;
1419       if (*Info) {
1420         Diagnostic DiagInfo(&Diags);
1421         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
1422                        PartialDiagnostic(DiagInfo, Context.getDiagAllocator()));
1423       }
1424 
1425       // Suppress this diagnostic.
1426       Diags.setLastDiagnosticIgnored(true);
1427       Diags.Clear();
1428       return;
1429     }
1430   }
1431 
1432   // Copy the diagnostic printing policy over the ASTContext printing policy.
1433   // TODO: Stop doing that.  See: https://reviews.llvm.org/D45093#1090292
1434   Context.setPrintingPolicy(getPrintingPolicy());
1435 
1436   // Emit the diagnostic.
1437   if (!Diags.EmitCurrentDiagnostic())
1438     return;
1439 
1440   // If this is not a note, and we're in a template instantiation
1441   // that is different from the last template instantiation where
1442   // we emitted an error, print a template instantiation
1443   // backtrace.
1444   if (!DiagnosticIDs::isBuiltinNote(DiagID))
1445     PrintContextStack();
1446 }
1447 
1448 Sema::SemaDiagnosticBuilder
Diag(SourceLocation Loc,const PartialDiagnostic & PD,bool DeferHint)1449 Sema::Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint) {
1450   return Diag(Loc, PD.getDiagID(), DeferHint) << PD;
1451 }
1452 
hasUncompilableErrorOccurred() const1453 bool Sema::hasUncompilableErrorOccurred() const {
1454   if (getDiagnostics().hasUncompilableErrorOccurred())
1455     return true;
1456   auto *FD = dyn_cast<FunctionDecl>(CurContext);
1457   if (!FD)
1458     return false;
1459   auto Loc = DeviceDeferredDiags.find(FD);
1460   if (Loc == DeviceDeferredDiags.end())
1461     return false;
1462   for (auto PDAt : Loc->second) {
1463     if (DiagnosticIDs::isDefaultMappingAsError(PDAt.second.getDiagID()))
1464       return true;
1465   }
1466   return false;
1467 }
1468 
1469 // Print notes showing how we can reach FD starting from an a priori
1470 // known-callable function.
emitCallStackNotes(Sema & S,FunctionDecl * FD)1471 static void emitCallStackNotes(Sema &S, FunctionDecl *FD) {
1472   auto FnIt = S.DeviceKnownEmittedFns.find(FD);
1473   while (FnIt != S.DeviceKnownEmittedFns.end()) {
1474     // Respect error limit.
1475     if (S.Diags.hasFatalErrorOccurred())
1476       return;
1477     DiagnosticBuilder Builder(
1478         S.Diags.Report(FnIt->second.Loc, diag::note_called_by));
1479     Builder << FnIt->second.FD;
1480     FnIt = S.DeviceKnownEmittedFns.find(FnIt->second.FD);
1481   }
1482 }
1483 
1484 namespace {
1485 
1486 /// Helper class that emits deferred diagnostic messages if an entity directly
1487 /// or indirectly using the function that causes the deferred diagnostic
1488 /// messages is known to be emitted.
1489 ///
1490 /// During parsing of AST, certain diagnostic messages are recorded as deferred
1491 /// diagnostics since it is unknown whether the functions containing such
1492 /// diagnostics will be emitted. A list of potentially emitted functions and
1493 /// variables that may potentially trigger emission of functions are also
1494 /// recorded. DeferredDiagnosticsEmitter recursively visits used functions
1495 /// by each function to emit deferred diagnostics.
1496 ///
1497 /// During the visit, certain OpenMP directives or initializer of variables
1498 /// with certain OpenMP attributes will cause subsequent visiting of any
1499 /// functions enter a state which is called OpenMP device context in this
1500 /// implementation. The state is exited when the directive or initializer is
1501 /// exited. This state can change the emission states of subsequent uses
1502 /// of functions.
1503 ///
1504 /// Conceptually the functions or variables to be visited form a use graph
1505 /// where the parent node uses the child node. At any point of the visit,
1506 /// the tree nodes traversed from the tree root to the current node form a use
1507 /// stack. The emission state of the current node depends on two factors:
1508 ///    1. the emission state of the root node
1509 ///    2. whether the current node is in OpenMP device context
1510 /// If the function is decided to be emitted, its contained deferred diagnostics
1511 /// are emitted, together with the information about the use stack.
1512 ///
1513 class DeferredDiagnosticsEmitter
1514     : public UsedDeclVisitor<DeferredDiagnosticsEmitter> {
1515 public:
1516   typedef UsedDeclVisitor<DeferredDiagnosticsEmitter> Inherited;
1517 
1518   // Whether the function is already in the current use-path.
1519   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> InUsePath;
1520 
1521   // The current use-path.
1522   llvm::SmallVector<CanonicalDeclPtr<FunctionDecl>, 4> UsePath;
1523 
1524   // Whether the visiting of the function has been done. Done[0] is for the
1525   // case not in OpenMP device context. Done[1] is for the case in OpenMP
1526   // device context. We need two sets because diagnostics emission may be
1527   // different depending on whether it is in OpenMP device context.
1528   llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> DoneMap[2];
1529 
1530   // Emission state of the root node of the current use graph.
1531   bool ShouldEmitRootNode;
1532 
1533   // Current OpenMP device context level. It is initialized to 0 and each
1534   // entering of device context increases it by 1 and each exit decreases
1535   // it by 1. Non-zero value indicates it is currently in device context.
1536   unsigned InOMPDeviceContext;
1537 
DeferredDiagnosticsEmitter(Sema & S)1538   DeferredDiagnosticsEmitter(Sema &S)
1539       : Inherited(S), ShouldEmitRootNode(false), InOMPDeviceContext(0) {}
1540 
VisitOMPTargetDirective(OMPTargetDirective * Node)1541   void VisitOMPTargetDirective(OMPTargetDirective *Node) {
1542     ++InOMPDeviceContext;
1543     Inherited::VisitOMPTargetDirective(Node);
1544     --InOMPDeviceContext;
1545   }
1546 
visitUsedDecl(SourceLocation Loc,Decl * D)1547   void visitUsedDecl(SourceLocation Loc, Decl *D) {
1548     if (isa<VarDecl>(D))
1549       return;
1550     if (auto *FD = dyn_cast<FunctionDecl>(D))
1551       checkFunc(Loc, FD);
1552     else
1553       Inherited::visitUsedDecl(Loc, D);
1554   }
1555 
checkVar(VarDecl * VD)1556   void checkVar(VarDecl *VD) {
1557     assert(VD->isFileVarDecl() &&
1558            "Should only check file-scope variables");
1559     if (auto *Init = VD->getInit()) {
1560       auto DevTy = OMPDeclareTargetDeclAttr::getDeviceType(VD);
1561       bool IsDev = DevTy && (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
1562                              *DevTy == OMPDeclareTargetDeclAttr::DT_Any);
1563       if (IsDev)
1564         ++InOMPDeviceContext;
1565       this->Visit(Init);
1566       if (IsDev)
1567         --InOMPDeviceContext;
1568     }
1569   }
1570 
checkFunc(SourceLocation Loc,FunctionDecl * FD)1571   void checkFunc(SourceLocation Loc, FunctionDecl *FD) {
1572     auto &Done = DoneMap[InOMPDeviceContext > 0 ? 1 : 0];
1573     FunctionDecl *Caller = UsePath.empty() ? nullptr : UsePath.back();
1574     if ((!ShouldEmitRootNode && !S.getLangOpts().OpenMP && !Caller) ||
1575         S.shouldIgnoreInHostDeviceCheck(FD) || InUsePath.count(FD))
1576       return;
1577     // Finalize analysis of OpenMP-specific constructs.
1578     if (Caller && S.LangOpts.OpenMP && UsePath.size() == 1 &&
1579         (ShouldEmitRootNode || InOMPDeviceContext))
1580       S.finalizeOpenMPDelayedAnalysis(Caller, FD, Loc);
1581     if (Caller)
1582       S.DeviceKnownEmittedFns[FD] = {Caller, Loc};
1583     // Always emit deferred diagnostics for the direct users. This does not
1584     // lead to explosion of diagnostics since each user is visited at most
1585     // twice.
1586     if (ShouldEmitRootNode || InOMPDeviceContext)
1587       emitDeferredDiags(FD, Caller);
1588     // Do not revisit a function if the function body has been completely
1589     // visited before.
1590     if (!Done.insert(FD).second)
1591       return;
1592     InUsePath.insert(FD);
1593     UsePath.push_back(FD);
1594     if (auto *S = FD->getBody()) {
1595       this->Visit(S);
1596     }
1597     UsePath.pop_back();
1598     InUsePath.erase(FD);
1599   }
1600 
checkRecordedDecl(Decl * D)1601   void checkRecordedDecl(Decl *D) {
1602     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1603       ShouldEmitRootNode = S.getEmissionStatus(FD, /*Final=*/true) ==
1604                            Sema::FunctionEmissionStatus::Emitted;
1605       checkFunc(SourceLocation(), FD);
1606     } else
1607       checkVar(cast<VarDecl>(D));
1608   }
1609 
1610   // Emit any deferred diagnostics for FD
emitDeferredDiags(FunctionDecl * FD,bool ShowCallStack)1611   void emitDeferredDiags(FunctionDecl *FD, bool ShowCallStack) {
1612     auto It = S.DeviceDeferredDiags.find(FD);
1613     if (It == S.DeviceDeferredDiags.end())
1614       return;
1615     bool HasWarningOrError = false;
1616     bool FirstDiag = true;
1617     for (PartialDiagnosticAt &PDAt : It->second) {
1618       // Respect error limit.
1619       if (S.Diags.hasFatalErrorOccurred())
1620         return;
1621       const SourceLocation &Loc = PDAt.first;
1622       const PartialDiagnostic &PD = PDAt.second;
1623       HasWarningOrError |=
1624           S.getDiagnostics().getDiagnosticLevel(PD.getDiagID(), Loc) >=
1625           DiagnosticsEngine::Warning;
1626       {
1627         DiagnosticBuilder Builder(S.Diags.Report(Loc, PD.getDiagID()));
1628         PD.Emit(Builder);
1629       }
1630       // Emit the note on the first diagnostic in case too many diagnostics
1631       // cause the note not emitted.
1632       if (FirstDiag && HasWarningOrError && ShowCallStack) {
1633         emitCallStackNotes(S, FD);
1634         FirstDiag = false;
1635       }
1636     }
1637   }
1638 };
1639 } // namespace
1640 
emitDeferredDiags()1641 void Sema::emitDeferredDiags() {
1642   if (ExternalSource)
1643     ExternalSource->ReadDeclsToCheckForDeferredDiags(
1644         DeclsToCheckForDeferredDiags);
1645 
1646   if ((DeviceDeferredDiags.empty() && !LangOpts.OpenMP) ||
1647       DeclsToCheckForDeferredDiags.empty())
1648     return;
1649 
1650   DeferredDiagnosticsEmitter DDE(*this);
1651   for (auto D : DeclsToCheckForDeferredDiags)
1652     DDE.checkRecordedDecl(D);
1653 }
1654 
1655 // In CUDA, there are some constructs which may appear in semantically-valid
1656 // code, but trigger errors if we ever generate code for the function in which
1657 // they appear.  Essentially every construct you're not allowed to use on the
1658 // device falls into this category, because you are allowed to use these
1659 // constructs in a __host__ __device__ function, but only if that function is
1660 // never codegen'ed on the device.
1661 //
1662 // To handle semantic checking for these constructs, we keep track of the set of
1663 // functions we know will be emitted, either because we could tell a priori that
1664 // they would be emitted, or because they were transitively called by a
1665 // known-emitted function.
1666 //
1667 // We also keep a partial call graph of which not-known-emitted functions call
1668 // which other not-known-emitted functions.
1669 //
1670 // When we see something which is illegal if the current function is emitted
1671 // (usually by way of CUDADiagIfDeviceCode, CUDADiagIfHostCode, or
1672 // CheckCUDACall), we first check if the current function is known-emitted.  If
1673 // so, we immediately output the diagnostic.
1674 //
1675 // Otherwise, we "defer" the diagnostic.  It sits in Sema::DeviceDeferredDiags
1676 // until we discover that the function is known-emitted, at which point we take
1677 // it out of this map and emit the diagnostic.
1678 
SemaDiagnosticBuilder(Kind K,SourceLocation Loc,unsigned DiagID,FunctionDecl * Fn,Sema & S)1679 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(Kind K, SourceLocation Loc,
1680                                                    unsigned DiagID,
1681                                                    FunctionDecl *Fn, Sema &S)
1682     : S(S), Loc(Loc), DiagID(DiagID), Fn(Fn),
1683       ShowCallStack(K == K_ImmediateWithCallStack || K == K_Deferred) {
1684   switch (K) {
1685   case K_Nop:
1686     break;
1687   case K_Immediate:
1688   case K_ImmediateWithCallStack:
1689     ImmediateDiag.emplace(
1690         ImmediateDiagBuilder(S.Diags.Report(Loc, DiagID), S, DiagID));
1691     break;
1692   case K_Deferred:
1693     assert(Fn && "Must have a function to attach the deferred diag to.");
1694     auto &Diags = S.DeviceDeferredDiags[Fn];
1695     PartialDiagId.emplace(Diags.size());
1696     Diags.emplace_back(Loc, S.PDiag(DiagID));
1697     break;
1698   }
1699 }
1700 
SemaDiagnosticBuilder(SemaDiagnosticBuilder && D)1701 Sema::SemaDiagnosticBuilder::SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D)
1702     : S(D.S), Loc(D.Loc), DiagID(D.DiagID), Fn(D.Fn),
1703       ShowCallStack(D.ShowCallStack), ImmediateDiag(D.ImmediateDiag),
1704       PartialDiagId(D.PartialDiagId) {
1705   // Clean the previous diagnostics.
1706   D.ShowCallStack = false;
1707   D.ImmediateDiag.reset();
1708   D.PartialDiagId.reset();
1709 }
1710 
~SemaDiagnosticBuilder()1711 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
1712   if (ImmediateDiag) {
1713     // Emit our diagnostic and, if it was a warning or error, output a callstack
1714     // if Fn isn't a priori known-emitted.
1715     bool IsWarningOrError = S.getDiagnostics().getDiagnosticLevel(
1716                                 DiagID, Loc) >= DiagnosticsEngine::Warning;
1717     ImmediateDiag.reset(); // Emit the immediate diag.
1718     if (IsWarningOrError && ShowCallStack)
1719       emitCallStackNotes(S, Fn);
1720   } else {
1721     assert((!PartialDiagId || ShowCallStack) &&
1722            "Must always show call stack for deferred diags.");
1723   }
1724 }
1725 
targetDiag(SourceLocation Loc,unsigned DiagID)1726 Sema::SemaDiagnosticBuilder Sema::targetDiag(SourceLocation Loc,
1727                                              unsigned DiagID) {
1728   if (LangOpts.OpenMP)
1729     return LangOpts.OpenMPIsDevice ? diagIfOpenMPDeviceCode(Loc, DiagID)
1730                                    : diagIfOpenMPHostCode(Loc, DiagID);
1731   if (getLangOpts().CUDA)
1732     return getLangOpts().CUDAIsDevice ? CUDADiagIfDeviceCode(Loc, DiagID)
1733                                       : CUDADiagIfHostCode(Loc, DiagID);
1734 
1735   if (getLangOpts().SYCLIsDevice)
1736     return SYCLDiagIfDeviceCode(Loc, DiagID);
1737 
1738   return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc, DiagID,
1739                                getCurFunctionDecl(), *this);
1740 }
1741 
Diag(SourceLocation Loc,unsigned DiagID,bool DeferHint)1742 Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID,
1743                                        bool DeferHint) {
1744   bool IsError = Diags.getDiagnosticIDs()->isDefaultMappingAsError(DiagID);
1745   bool ShouldDefer = getLangOpts().CUDA && LangOpts.GPUDeferDiag &&
1746                      DiagnosticIDs::isDeferrable(DiagID) &&
1747                      (DeferHint || !IsError);
1748   auto SetIsLastErrorImmediate = [&](bool Flag) {
1749     if (IsError)
1750       IsLastErrorImmediate = Flag;
1751   };
1752   if (!ShouldDefer) {
1753     SetIsLastErrorImmediate(true);
1754     return SemaDiagnosticBuilder(SemaDiagnosticBuilder::K_Immediate, Loc,
1755                                  DiagID, getCurFunctionDecl(), *this);
1756   }
1757 
1758   SemaDiagnosticBuilder DB =
1759       getLangOpts().CUDAIsDevice
1760           ? CUDADiagIfDeviceCode(Loc, DiagID)
1761           : CUDADiagIfHostCode(Loc, DiagID);
1762   SetIsLastErrorImmediate(DB.isImmediate());
1763   return DB;
1764 }
1765 
checkDeviceDecl(const ValueDecl * D,SourceLocation Loc)1766 void Sema::checkDeviceDecl(const ValueDecl *D, SourceLocation Loc) {
1767   if (isUnevaluatedContext())
1768     return;
1769 
1770   Decl *C = cast<Decl>(getCurLexicalContext());
1771 
1772   // Memcpy operations for structs containing a member with unsupported type
1773   // are ok, though.
1774   if (const auto *MD = dyn_cast<CXXMethodDecl>(C)) {
1775     if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) &&
1776         MD->isTrivial())
1777       return;
1778 
1779     if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(MD))
1780       if (Ctor->isCopyOrMoveConstructor() && Ctor->isTrivial())
1781         return;
1782   }
1783 
1784   auto CheckType = [&](QualType Ty) {
1785     if (Ty->isDependentType())
1786       return;
1787 
1788     if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1789         ((Ty->isFloat128Type() ||
1790           (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1791          !Context.getTargetInfo().hasFloat128Type()) ||
1792         (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1793          !Context.getTargetInfo().hasInt128Type())) {
1794       targetDiag(Loc, diag::err_device_unsupported_type)
1795           << D << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1796           << Context.getTargetInfo().getTriple().str();
1797       targetDiag(D->getLocation(), diag::note_defined_here) << D;
1798     }
1799   };
1800 
1801   QualType Ty = D->getType();
1802   CheckType(Ty);
1803 
1804   if (const auto *FPTy = dyn_cast<FunctionProtoType>(Ty)) {
1805     for (const auto &ParamTy : FPTy->param_types())
1806       CheckType(ParamTy);
1807     CheckType(FPTy->getReturnType());
1808   }
1809 }
1810 
1811 /// Looks through the macro-expansion chain for the given
1812 /// location, looking for a macro expansion with the given name.
1813 /// If one is found, returns true and sets the location to that
1814 /// expansion loc.
findMacroSpelling(SourceLocation & locref,StringRef name)1815 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
1816   SourceLocation loc = locref;
1817   if (!loc.isMacroID()) return false;
1818 
1819   // There's no good way right now to look at the intermediate
1820   // expansions, so just jump to the expansion location.
1821   loc = getSourceManager().getExpansionLoc(loc);
1822 
1823   // If that's written with the name, stop here.
1824   SmallString<16> buffer;
1825   if (getPreprocessor().getSpelling(loc, buffer) == name) {
1826     locref = loc;
1827     return true;
1828   }
1829   return false;
1830 }
1831 
1832 /// Determines the active Scope associated with the given declaration
1833 /// context.
1834 ///
1835 /// This routine maps a declaration context to the active Scope object that
1836 /// represents that declaration context in the parser. It is typically used
1837 /// from "scope-less" code (e.g., template instantiation, lazy creation of
1838 /// declarations) that injects a name for name-lookup purposes and, therefore,
1839 /// must update the Scope.
1840 ///
1841 /// \returns The scope corresponding to the given declaraion context, or NULL
1842 /// if no such scope is open.
getScopeForContext(DeclContext * Ctx)1843 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
1844 
1845   if (!Ctx)
1846     return nullptr;
1847 
1848   Ctx = Ctx->getPrimaryContext();
1849   for (Scope *S = getCurScope(); S; S = S->getParent()) {
1850     // Ignore scopes that cannot have declarations. This is important for
1851     // out-of-line definitions of static class members.
1852     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
1853       if (DeclContext *Entity = S->getEntity())
1854         if (Ctx == Entity->getPrimaryContext())
1855           return S;
1856   }
1857 
1858   return nullptr;
1859 }
1860 
1861 /// Enter a new function scope
PushFunctionScope()1862 void Sema::PushFunctionScope() {
1863   if (FunctionScopes.empty() && CachedFunctionScope) {
1864     // Use CachedFunctionScope to avoid allocating memory when possible.
1865     CachedFunctionScope->Clear();
1866     FunctionScopes.push_back(CachedFunctionScope.release());
1867   } else {
1868     FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
1869   }
1870   if (LangOpts.OpenMP)
1871     pushOpenMPFunctionRegion();
1872 }
1873 
PushBlockScope(Scope * BlockScope,BlockDecl * Block)1874 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
1875   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
1876                                               BlockScope, Block));
1877 }
1878 
PushLambdaScope()1879 LambdaScopeInfo *Sema::PushLambdaScope() {
1880   LambdaScopeInfo *const LSI = new LambdaScopeInfo(getDiagnostics());
1881   FunctionScopes.push_back(LSI);
1882   return LSI;
1883 }
1884 
RecordParsingTemplateParameterDepth(unsigned Depth)1885 void Sema::RecordParsingTemplateParameterDepth(unsigned Depth) {
1886   if (LambdaScopeInfo *const LSI = getCurLambda()) {
1887     LSI->AutoTemplateParameterDepth = Depth;
1888     return;
1889   }
1890   llvm_unreachable(
1891       "Remove assertion if intentionally called in a non-lambda context.");
1892 }
1893 
1894 // Check that the type of the VarDecl has an accessible copy constructor and
1895 // resolve its destructor's exception specification.
checkEscapingByref(VarDecl * VD,Sema & S)1896 static void checkEscapingByref(VarDecl *VD, Sema &S) {
1897   QualType T = VD->getType();
1898   EnterExpressionEvaluationContext scope(
1899       S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1900   SourceLocation Loc = VD->getLocation();
1901   Expr *VarRef =
1902       new (S.Context) DeclRefExpr(S.Context, VD, false, T, VK_LValue, Loc);
1903   ExprResult Result = S.PerformMoveOrCopyInitialization(
1904       InitializedEntity::InitializeBlock(Loc, T, false), VD, VD->getType(),
1905       VarRef, /*AllowNRVO=*/true);
1906   if (!Result.isInvalid()) {
1907     Result = S.MaybeCreateExprWithCleanups(Result);
1908     Expr *Init = Result.getAs<Expr>();
1909     S.Context.setBlockVarCopyInit(VD, Init, S.canThrow(Init));
1910   }
1911 
1912   // The destructor's exception specification is needed when IRGen generates
1913   // block copy/destroy functions. Resolve it here.
1914   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1915     if (CXXDestructorDecl *DD = RD->getDestructor()) {
1916       auto *FPT = DD->getType()->getAs<FunctionProtoType>();
1917       S.ResolveExceptionSpec(Loc, FPT);
1918     }
1919 }
1920 
markEscapingByrefs(const FunctionScopeInfo & FSI,Sema & S)1921 static void markEscapingByrefs(const FunctionScopeInfo &FSI, Sema &S) {
1922   // Set the EscapingByref flag of __block variables captured by
1923   // escaping blocks.
1924   for (const BlockDecl *BD : FSI.Blocks) {
1925     for (const BlockDecl::Capture &BC : BD->captures()) {
1926       VarDecl *VD = BC.getVariable();
1927       if (VD->hasAttr<BlocksAttr>()) {
1928         // Nothing to do if this is a __block variable captured by a
1929         // non-escaping block.
1930         if (BD->doesNotEscape())
1931           continue;
1932         VD->setEscapingByref();
1933       }
1934       // Check whether the captured variable is or contains an object of
1935       // non-trivial C union type.
1936       QualType CapType = BC.getVariable()->getType();
1937       if (CapType.hasNonTrivialToPrimitiveDestructCUnion() ||
1938           CapType.hasNonTrivialToPrimitiveCopyCUnion())
1939         S.checkNonTrivialCUnion(BC.getVariable()->getType(),
1940                                 BD->getCaretLocation(),
1941                                 Sema::NTCUC_BlockCapture,
1942                                 Sema::NTCUK_Destruct|Sema::NTCUK_Copy);
1943     }
1944   }
1945 
1946   for (VarDecl *VD : FSI.ByrefBlockVars) {
1947     // __block variables might require us to capture a copy-initializer.
1948     if (!VD->isEscapingByref())
1949       continue;
1950     // It's currently invalid to ever have a __block variable with an
1951     // array type; should we diagnose that here?
1952     // Regardless, we don't want to ignore array nesting when
1953     // constructing this copy.
1954     if (VD->getType()->isStructureOrClassType())
1955       checkEscapingByref(VD, S);
1956   }
1957 }
1958 
1959 /// Pop a function (or block or lambda or captured region) scope from the stack.
1960 ///
1961 /// \param WP The warning policy to use for CFG-based warnings, or null if such
1962 ///        warnings should not be produced.
1963 /// \param D The declaration corresponding to this function scope, if producing
1964 ///        CFG-based warnings.
1965 /// \param BlockType The type of the block expression, if D is a BlockDecl.
1966 Sema::PoppedFunctionScopePtr
PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy * WP,const Decl * D,QualType BlockType)1967 Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
1968                            const Decl *D, QualType BlockType) {
1969   assert(!FunctionScopes.empty() && "mismatched push/pop!");
1970 
1971   markEscapingByrefs(*FunctionScopes.back(), *this);
1972 
1973   PoppedFunctionScopePtr Scope(FunctionScopes.pop_back_val(),
1974                                PoppedFunctionScopeDeleter(this));
1975 
1976   if (LangOpts.OpenMP)
1977     popOpenMPFunctionRegion(Scope.get());
1978 
1979   // Issue any analysis-based warnings.
1980   if (WP && D)
1981     AnalysisWarnings.IssueWarnings(*WP, Scope.get(), D, BlockType);
1982   else
1983     for (const auto &PUD : Scope->PossiblyUnreachableDiags)
1984       Diag(PUD.Loc, PUD.PD);
1985 
1986   return Scope;
1987 }
1988 
1989 void Sema::PoppedFunctionScopeDeleter::
operator ()(sema::FunctionScopeInfo * Scope) const1990 operator()(sema::FunctionScopeInfo *Scope) const {
1991   // Stash the function scope for later reuse if it's for a normal function.
1992   if (Scope->isPlainFunction() && !Self->CachedFunctionScope)
1993     Self->CachedFunctionScope.reset(Scope);
1994   else
1995     delete Scope;
1996 }
1997 
PushCompoundScope(bool IsStmtExpr)1998 void Sema::PushCompoundScope(bool IsStmtExpr) {
1999   getCurFunction()->CompoundScopes.push_back(CompoundScopeInfo(IsStmtExpr));
2000 }
2001 
PopCompoundScope()2002 void Sema::PopCompoundScope() {
2003   FunctionScopeInfo *CurFunction = getCurFunction();
2004   assert(!CurFunction->CompoundScopes.empty() && "mismatched push/pop");
2005 
2006   CurFunction->CompoundScopes.pop_back();
2007 }
2008 
2009 /// Determine whether any errors occurred within this function/method/
2010 /// block.
hasAnyUnrecoverableErrorsInThisFunction() const2011 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
2012   return getCurFunction()->hasUnrecoverableErrorOccurred();
2013 }
2014 
setFunctionHasBranchIntoScope()2015 void Sema::setFunctionHasBranchIntoScope() {
2016   if (!FunctionScopes.empty())
2017     FunctionScopes.back()->setHasBranchIntoScope();
2018 }
2019 
setFunctionHasBranchProtectedScope()2020 void Sema::setFunctionHasBranchProtectedScope() {
2021   if (!FunctionScopes.empty())
2022     FunctionScopes.back()->setHasBranchProtectedScope();
2023 }
2024 
setFunctionHasIndirectGoto()2025 void Sema::setFunctionHasIndirectGoto() {
2026   if (!FunctionScopes.empty())
2027     FunctionScopes.back()->setHasIndirectGoto();
2028 }
2029 
getCurBlock()2030 BlockScopeInfo *Sema::getCurBlock() {
2031   if (FunctionScopes.empty())
2032     return nullptr;
2033 
2034   auto CurBSI = dyn_cast<BlockScopeInfo>(FunctionScopes.back());
2035   if (CurBSI && CurBSI->TheDecl &&
2036       !CurBSI->TheDecl->Encloses(CurContext)) {
2037     // We have switched contexts due to template instantiation.
2038     assert(!CodeSynthesisContexts.empty());
2039     return nullptr;
2040   }
2041 
2042   return CurBSI;
2043 }
2044 
getEnclosingFunction() const2045 FunctionScopeInfo *Sema::getEnclosingFunction() const {
2046   if (FunctionScopes.empty())
2047     return nullptr;
2048 
2049   for (int e = FunctionScopes.size() - 1; e >= 0; --e) {
2050     if (isa<sema::BlockScopeInfo>(FunctionScopes[e]))
2051       continue;
2052     return FunctionScopes[e];
2053   }
2054   return nullptr;
2055 }
2056 
getEnclosingLambda() const2057 LambdaScopeInfo *Sema::getEnclosingLambda() const {
2058   for (auto *Scope : llvm::reverse(FunctionScopes)) {
2059     if (auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope)) {
2060       if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext)) {
2061         // We have switched contexts due to template instantiation.
2062         // FIXME: We should swap out the FunctionScopes during code synthesis
2063         // so that we don't need to check for this.
2064         assert(!CodeSynthesisContexts.empty());
2065         return nullptr;
2066       }
2067       return LSI;
2068     }
2069   }
2070   return nullptr;
2071 }
2072 
getCurLambda(bool IgnoreNonLambdaCapturingScope)2073 LambdaScopeInfo *Sema::getCurLambda(bool IgnoreNonLambdaCapturingScope) {
2074   if (FunctionScopes.empty())
2075     return nullptr;
2076 
2077   auto I = FunctionScopes.rbegin();
2078   if (IgnoreNonLambdaCapturingScope) {
2079     auto E = FunctionScopes.rend();
2080     while (I != E && isa<CapturingScopeInfo>(*I) && !isa<LambdaScopeInfo>(*I))
2081       ++I;
2082     if (I == E)
2083       return nullptr;
2084   }
2085   auto *CurLSI = dyn_cast<LambdaScopeInfo>(*I);
2086   if (CurLSI && CurLSI->Lambda &&
2087       !CurLSI->Lambda->Encloses(CurContext)) {
2088     // We have switched contexts due to template instantiation.
2089     assert(!CodeSynthesisContexts.empty());
2090     return nullptr;
2091   }
2092 
2093   return CurLSI;
2094 }
2095 
2096 // We have a generic lambda if we parsed auto parameters, or we have
2097 // an associated template parameter list.
getCurGenericLambda()2098 LambdaScopeInfo *Sema::getCurGenericLambda() {
2099   if (LambdaScopeInfo *LSI =  getCurLambda()) {
2100     return (LSI->TemplateParams.size() ||
2101                     LSI->GLTemplateParameterList) ? LSI : nullptr;
2102   }
2103   return nullptr;
2104 }
2105 
2106 
ActOnComment(SourceRange Comment)2107 void Sema::ActOnComment(SourceRange Comment) {
2108   if (!LangOpts.RetainCommentsFromSystemHeaders &&
2109       SourceMgr.isInSystemHeader(Comment.getBegin()))
2110     return;
2111   RawComment RC(SourceMgr, Comment, LangOpts.CommentOpts, false);
2112   if (RC.isAlmostTrailingComment()) {
2113     SourceRange MagicMarkerRange(Comment.getBegin(),
2114                                  Comment.getBegin().getLocWithOffset(3));
2115     StringRef MagicMarkerText;
2116     switch (RC.getKind()) {
2117     case RawComment::RCK_OrdinaryBCPL:
2118       MagicMarkerText = "///<";
2119       break;
2120     case RawComment::RCK_OrdinaryC:
2121       MagicMarkerText = "/**<";
2122       break;
2123     default:
2124       llvm_unreachable("if this is an almost Doxygen comment, "
2125                        "it should be ordinary");
2126     }
2127     Diag(Comment.getBegin(), diag::warn_not_a_doxygen_trailing_member_comment) <<
2128       FixItHint::CreateReplacement(MagicMarkerRange, MagicMarkerText);
2129   }
2130   Context.addComment(RC);
2131 }
2132 
2133 // Pin this vtable to this file.
~ExternalSemaSource()2134 ExternalSemaSource::~ExternalSemaSource() {}
2135 char ExternalSemaSource::ID;
2136 
ReadMethodPool(Selector Sel)2137 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
updateOutOfDateSelector(Selector Sel)2138 void ExternalSemaSource::updateOutOfDateSelector(Selector Sel) { }
2139 
ReadKnownNamespaces(SmallVectorImpl<NamespaceDecl * > & Namespaces)2140 void ExternalSemaSource::ReadKnownNamespaces(
2141                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
2142 }
2143 
ReadUndefinedButUsed(llvm::MapVector<NamedDecl *,SourceLocation> & Undefined)2144 void ExternalSemaSource::ReadUndefinedButUsed(
2145     llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {}
2146 
ReadMismatchingDeleteExpressions(llvm::MapVector<FieldDecl *,llvm::SmallVector<std::pair<SourceLocation,bool>,4>> &)2147 void ExternalSemaSource::ReadMismatchingDeleteExpressions(llvm::MapVector<
2148     FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &) {}
2149 
2150 /// Figure out if an expression could be turned into a call.
2151 ///
2152 /// Use this when trying to recover from an error where the programmer may have
2153 /// written just the name of a function instead of actually calling it.
2154 ///
2155 /// \param E - The expression to examine.
2156 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
2157 ///  with no arguments, this parameter is set to the type returned by such a
2158 ///  call; otherwise, it is set to an empty QualType.
2159 /// \param OverloadSet - If the expression is an overloaded function
2160 ///  name, this parameter is populated with the decls of the various overloads.
tryExprAsCall(Expr & E,QualType & ZeroArgCallReturnTy,UnresolvedSetImpl & OverloadSet)2161 bool Sema::tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
2162                          UnresolvedSetImpl &OverloadSet) {
2163   ZeroArgCallReturnTy = QualType();
2164   OverloadSet.clear();
2165 
2166   const OverloadExpr *Overloads = nullptr;
2167   bool IsMemExpr = false;
2168   if (E.getType() == Context.OverloadTy) {
2169     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
2170 
2171     // Ignore overloads that are pointer-to-member constants.
2172     if (FR.HasFormOfMemberPointer)
2173       return false;
2174 
2175     Overloads = FR.Expression;
2176   } else if (E.getType() == Context.BoundMemberTy) {
2177     Overloads = dyn_cast<UnresolvedMemberExpr>(E.IgnoreParens());
2178     IsMemExpr = true;
2179   }
2180 
2181   bool Ambiguous = false;
2182   bool IsMV = false;
2183 
2184   if (Overloads) {
2185     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
2186          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
2187       OverloadSet.addDecl(*it);
2188 
2189       // Check whether the function is a non-template, non-member which takes no
2190       // arguments.
2191       if (IsMemExpr)
2192         continue;
2193       if (const FunctionDecl *OverloadDecl
2194             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
2195         if (OverloadDecl->getMinRequiredArguments() == 0) {
2196           if (!ZeroArgCallReturnTy.isNull() && !Ambiguous &&
2197               (!IsMV || !(OverloadDecl->isCPUDispatchMultiVersion() ||
2198                           OverloadDecl->isCPUSpecificMultiVersion()))) {
2199             ZeroArgCallReturnTy = QualType();
2200             Ambiguous = true;
2201           } else {
2202             ZeroArgCallReturnTy = OverloadDecl->getReturnType();
2203             IsMV = OverloadDecl->isCPUDispatchMultiVersion() ||
2204                    OverloadDecl->isCPUSpecificMultiVersion();
2205           }
2206         }
2207       }
2208     }
2209 
2210     // If it's not a member, use better machinery to try to resolve the call
2211     if (!IsMemExpr)
2212       return !ZeroArgCallReturnTy.isNull();
2213   }
2214 
2215   // Attempt to call the member with no arguments - this will correctly handle
2216   // member templates with defaults/deduction of template arguments, overloads
2217   // with default arguments, etc.
2218   if (IsMemExpr && !E.isTypeDependent()) {
2219     Sema::TentativeAnalysisScope Trap(*this);
2220     ExprResult R = BuildCallToMemberFunction(nullptr, &E, SourceLocation(),
2221                                              None, SourceLocation());
2222     if (R.isUsable()) {
2223       ZeroArgCallReturnTy = R.get()->getType();
2224       return true;
2225     }
2226     return false;
2227   }
2228 
2229   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
2230     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
2231       if (Fun->getMinRequiredArguments() == 0)
2232         ZeroArgCallReturnTy = Fun->getReturnType();
2233       return true;
2234     }
2235   }
2236 
2237   // We don't have an expression that's convenient to get a FunctionDecl from,
2238   // but we can at least check if the type is "function of 0 arguments".
2239   QualType ExprTy = E.getType();
2240   const FunctionType *FunTy = nullptr;
2241   QualType PointeeTy = ExprTy->getPointeeType();
2242   if (!PointeeTy.isNull())
2243     FunTy = PointeeTy->getAs<FunctionType>();
2244   if (!FunTy)
2245     FunTy = ExprTy->getAs<FunctionType>();
2246 
2247   if (const FunctionProtoType *FPT =
2248       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
2249     if (FPT->getNumParams() == 0)
2250       ZeroArgCallReturnTy = FunTy->getReturnType();
2251     return true;
2252   }
2253   return false;
2254 }
2255 
2256 /// Give notes for a set of overloads.
2257 ///
2258 /// A companion to tryExprAsCall. In cases when the name that the programmer
2259 /// wrote was an overloaded function, we may be able to make some guesses about
2260 /// plausible overloads based on their return types; such guesses can be handed
2261 /// off to this method to be emitted as notes.
2262 ///
2263 /// \param Overloads - The overloads to note.
2264 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
2265 ///  -fshow-overloads=best, this is the location to attach to the note about too
2266 ///  many candidates. Typically this will be the location of the original
2267 ///  ill-formed expression.
noteOverloads(Sema & S,const UnresolvedSetImpl & Overloads,const SourceLocation FinalNoteLoc)2268 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
2269                           const SourceLocation FinalNoteLoc) {
2270   int ShownOverloads = 0;
2271   int SuppressedOverloads = 0;
2272   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
2273        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2274     // FIXME: Magic number for max shown overloads stolen from
2275     // OverloadCandidateSet::NoteCandidates.
2276     if (ShownOverloads >= 4 && S.Diags.getShowOverloads() == Ovl_Best) {
2277       ++SuppressedOverloads;
2278       continue;
2279     }
2280 
2281     NamedDecl *Fn = (*It)->getUnderlyingDecl();
2282     // Don't print overloads for non-default multiversioned functions.
2283     if (const auto *FD = Fn->getAsFunction()) {
2284       if (FD->isMultiVersion() && FD->hasAttr<TargetAttr>() &&
2285           !FD->getAttr<TargetAttr>()->isDefaultVersion())
2286         continue;
2287     }
2288     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
2289     ++ShownOverloads;
2290   }
2291 
2292   if (SuppressedOverloads)
2293     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
2294       << SuppressedOverloads;
2295 }
2296 
notePlausibleOverloads(Sema & S,SourceLocation Loc,const UnresolvedSetImpl & Overloads,bool (* IsPlausibleResult)(QualType))2297 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
2298                                    const UnresolvedSetImpl &Overloads,
2299                                    bool (*IsPlausibleResult)(QualType)) {
2300   if (!IsPlausibleResult)
2301     return noteOverloads(S, Overloads, Loc);
2302 
2303   UnresolvedSet<2> PlausibleOverloads;
2304   for (OverloadExpr::decls_iterator It = Overloads.begin(),
2305          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
2306     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
2307     QualType OverloadResultTy = OverloadDecl->getReturnType();
2308     if (IsPlausibleResult(OverloadResultTy))
2309       PlausibleOverloads.addDecl(It.getDecl());
2310   }
2311   noteOverloads(S, PlausibleOverloads, Loc);
2312 }
2313 
2314 /// Determine whether the given expression can be called by just
2315 /// putting parentheses after it.  Notably, expressions with unary
2316 /// operators can't be because the unary operator will start parsing
2317 /// outside the call.
IsCallableWithAppend(Expr * E)2318 static bool IsCallableWithAppend(Expr *E) {
2319   E = E->IgnoreImplicit();
2320   return (!isa<CStyleCastExpr>(E) &&
2321           !isa<UnaryOperator>(E) &&
2322           !isa<BinaryOperator>(E) &&
2323           !isa<CXXOperatorCallExpr>(E));
2324 }
2325 
IsCPUDispatchCPUSpecificMultiVersion(const Expr * E)2326 static bool IsCPUDispatchCPUSpecificMultiVersion(const Expr *E) {
2327   if (const auto *UO = dyn_cast<UnaryOperator>(E))
2328     E = UO->getSubExpr();
2329 
2330   if (const auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
2331     if (ULE->getNumDecls() == 0)
2332       return false;
2333 
2334     const NamedDecl *ND = *ULE->decls_begin();
2335     if (const auto *FD = dyn_cast<FunctionDecl>(ND))
2336       return FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion();
2337   }
2338   return false;
2339 }
2340 
tryToRecoverWithCall(ExprResult & E,const PartialDiagnostic & PD,bool ForceComplain,bool (* IsPlausibleResult)(QualType))2341 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
2342                                 bool ForceComplain,
2343                                 bool (*IsPlausibleResult)(QualType)) {
2344   SourceLocation Loc = E.get()->getExprLoc();
2345   SourceRange Range = E.get()->getSourceRange();
2346 
2347   QualType ZeroArgCallTy;
2348   UnresolvedSet<4> Overloads;
2349   if (tryExprAsCall(*E.get(), ZeroArgCallTy, Overloads) &&
2350       !ZeroArgCallTy.isNull() &&
2351       (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
2352     // At this point, we know E is potentially callable with 0
2353     // arguments and that it returns something of a reasonable type,
2354     // so we can emit a fixit and carry on pretending that E was
2355     // actually a CallExpr.
2356     SourceLocation ParenInsertionLoc = getLocForEndOfToken(Range.getEnd());
2357     bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2358     Diag(Loc, PD) << /*zero-arg*/ 1 << IsMV << Range
2359                   << (IsCallableWithAppend(E.get())
2360                           ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
2361                           : FixItHint());
2362     if (!IsMV)
2363       notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2364 
2365     // FIXME: Try this before emitting the fixit, and suppress diagnostics
2366     // while doing so.
2367     E = BuildCallExpr(nullptr, E.get(), Range.getEnd(), None,
2368                       Range.getEnd().getLocWithOffset(1));
2369     return true;
2370   }
2371 
2372   if (!ForceComplain) return false;
2373 
2374   bool IsMV = IsCPUDispatchCPUSpecificMultiVersion(E.get());
2375   Diag(Loc, PD) << /*not zero-arg*/ 0 << IsMV << Range;
2376   if (!IsMV)
2377     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
2378   E = ExprError();
2379   return true;
2380 }
2381 
getSuperIdentifier() const2382 IdentifierInfo *Sema::getSuperIdentifier() const {
2383   if (!Ident_super)
2384     Ident_super = &Context.Idents.get("super");
2385   return Ident_super;
2386 }
2387 
getFloat128Identifier() const2388 IdentifierInfo *Sema::getFloat128Identifier() const {
2389   if (!Ident___float128)
2390     Ident___float128 = &Context.Idents.get("__float128");
2391   return Ident___float128;
2392 }
2393 
PushCapturedRegionScope(Scope * S,CapturedDecl * CD,RecordDecl * RD,CapturedRegionKind K,unsigned OpenMPCaptureLevel)2394 void Sema::PushCapturedRegionScope(Scope *S, CapturedDecl *CD, RecordDecl *RD,
2395                                    CapturedRegionKind K,
2396                                    unsigned OpenMPCaptureLevel) {
2397   auto *CSI = new CapturedRegionScopeInfo(
2398       getDiagnostics(), S, CD, RD, CD->getContextParam(), K,
2399       (getLangOpts().OpenMP && K == CR_OpenMP) ? getOpenMPNestingLevel() : 0,
2400       OpenMPCaptureLevel);
2401   CSI->ReturnType = Context.VoidTy;
2402   FunctionScopes.push_back(CSI);
2403 }
2404 
getCurCapturedRegion()2405 CapturedRegionScopeInfo *Sema::getCurCapturedRegion() {
2406   if (FunctionScopes.empty())
2407     return nullptr;
2408 
2409   return dyn_cast<CapturedRegionScopeInfo>(FunctionScopes.back());
2410 }
2411 
2412 const llvm::MapVector<FieldDecl *, Sema::DeleteLocs> &
getMismatchingDeleteExpressions() const2413 Sema::getMismatchingDeleteExpressions() const {
2414   return DeleteExprs;
2415 }
2416 
setOpenCLExtensionForType(QualType T,llvm::StringRef ExtStr)2417 void Sema::setOpenCLExtensionForType(QualType T, llvm::StringRef ExtStr) {
2418   if (ExtStr.empty())
2419     return;
2420   llvm::SmallVector<StringRef, 1> Exts;
2421   ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
2422   auto CanT = T.getCanonicalType().getTypePtr();
2423   for (auto &I : Exts)
2424     OpenCLTypeExtMap[CanT].insert(I.str());
2425 }
2426 
setOpenCLExtensionForDecl(Decl * FD,StringRef ExtStr)2427 void Sema::setOpenCLExtensionForDecl(Decl *FD, StringRef ExtStr) {
2428   llvm::SmallVector<StringRef, 1> Exts;
2429   ExtStr.split(Exts, " ", /* limit */ -1, /* keep empty */ false);
2430   if (Exts.empty())
2431     return;
2432   for (auto &I : Exts)
2433     OpenCLDeclExtMap[FD].insert(I.str());
2434 }
2435 
setCurrentOpenCLExtensionForType(QualType T)2436 void Sema::setCurrentOpenCLExtensionForType(QualType T) {
2437   if (CurrOpenCLExtension.empty())
2438     return;
2439   setOpenCLExtensionForType(T, CurrOpenCLExtension);
2440 }
2441 
setCurrentOpenCLExtensionForDecl(Decl * D)2442 void Sema::setCurrentOpenCLExtensionForDecl(Decl *D) {
2443   if (CurrOpenCLExtension.empty())
2444     return;
2445   setOpenCLExtensionForDecl(D, CurrOpenCLExtension);
2446 }
2447 
getOpenCLExtensionsFromDeclExtMap(FunctionDecl * FD)2448 std::string Sema::getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD) {
2449   if (!OpenCLDeclExtMap.empty())
2450     return getOpenCLExtensionsFromExtMap(FD, OpenCLDeclExtMap);
2451 
2452   return "";
2453 }
2454 
getOpenCLExtensionsFromTypeExtMap(FunctionType * FT)2455 std::string Sema::getOpenCLExtensionsFromTypeExtMap(FunctionType *FT) {
2456   if (!OpenCLTypeExtMap.empty())
2457     return getOpenCLExtensionsFromExtMap(FT, OpenCLTypeExtMap);
2458 
2459   return "";
2460 }
2461 
2462 template <typename T, typename MapT>
getOpenCLExtensionsFromExtMap(T * FDT,MapT & Map)2463 std::string Sema::getOpenCLExtensionsFromExtMap(T *FDT, MapT &Map) {
2464   auto Loc = Map.find(FDT);
2465   return llvm::join(Loc->second, " ");
2466 }
2467 
isOpenCLDisabledDecl(Decl * FD)2468 bool Sema::isOpenCLDisabledDecl(Decl *FD) {
2469   auto Loc = OpenCLDeclExtMap.find(FD);
2470   if (Loc == OpenCLDeclExtMap.end())
2471     return false;
2472   for (auto &I : Loc->second) {
2473     if (!getOpenCLOptions().isEnabled(I))
2474       return true;
2475   }
2476   return false;
2477 }
2478 
2479 template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT>
checkOpenCLDisabledTypeOrDecl(T D,DiagLocT DiagLoc,DiagInfoT DiagInfo,MapT & Map,unsigned Selector,SourceRange SrcRange)2480 bool Sema::checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc,
2481                                          DiagInfoT DiagInfo, MapT &Map,
2482                                          unsigned Selector,
2483                                          SourceRange SrcRange) {
2484   auto Loc = Map.find(D);
2485   if (Loc == Map.end())
2486     return false;
2487   bool Disabled = false;
2488   for (auto &I : Loc->second) {
2489     if (I != CurrOpenCLExtension && !getOpenCLOptions().isEnabled(I)) {
2490       Diag(DiagLoc, diag::err_opencl_requires_extension) << Selector << DiagInfo
2491                                                          << I << SrcRange;
2492       Disabled = true;
2493     }
2494   }
2495   return Disabled;
2496 }
2497 
checkOpenCLDisabledTypeDeclSpec(const DeclSpec & DS,QualType QT)2498 bool Sema::checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType QT) {
2499   // Check extensions for declared types.
2500   Decl *Decl = nullptr;
2501   if (auto TypedefT = dyn_cast<TypedefType>(QT.getTypePtr()))
2502     Decl = TypedefT->getDecl();
2503   if (auto TagT = dyn_cast<TagType>(QT.getCanonicalType().getTypePtr()))
2504     Decl = TagT->getDecl();
2505   auto Loc = DS.getTypeSpecTypeLoc();
2506 
2507   // Check extensions for vector types.
2508   // e.g. double4 is not allowed when cl_khr_fp64 is absent.
2509   if (QT->isExtVectorType()) {
2510     auto TypePtr = QT->castAs<ExtVectorType>()->getElementType().getTypePtr();
2511     return checkOpenCLDisabledTypeOrDecl(TypePtr, Loc, QT, OpenCLTypeExtMap);
2512   }
2513 
2514   if (checkOpenCLDisabledTypeOrDecl(Decl, Loc, QT, OpenCLDeclExtMap))
2515     return true;
2516 
2517   // Check extensions for builtin types.
2518   return checkOpenCLDisabledTypeOrDecl(QT.getCanonicalType().getTypePtr(), Loc,
2519                                        QT, OpenCLTypeExtMap);
2520 }
2521 
checkOpenCLDisabledDecl(const NamedDecl & D,const Expr & E)2522 bool Sema::checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E) {
2523   IdentifierInfo *FnName = D.getIdentifier();
2524   return checkOpenCLDisabledTypeOrDecl(&D, E.getBeginLoc(), FnName,
2525                                        OpenCLDeclExtMap, 1, D.getSourceRange());
2526 }
2527