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