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