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