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