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