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