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