xref: /llvm-project-15.0.7/clang/lib/Sema/Sema.cpp (revision 143f2f6e)
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/Sema/DelayedDiagnostic.h"
17 #include "TargetAttributesSema.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/APFloat.h"
21 #include "clang/Sema/CXXFieldCollector.h"
22 #include "clang/Sema/TemplateDeduction.h"
23 #include "clang/Sema/ExternalSemaSource.h"
24 #include "clang/Sema/ObjCMethodList.h"
25 #include "clang/Sema/PrettyDeclStackTrace.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "clang/Sema/SemaConsumer.h"
29 #include "clang/AST/ASTContext.h"
30 #include "clang/AST/ASTDiagnostic.h"
31 #include "clang/AST/DeclCXX.h"
32 #include "clang/AST/DeclObjC.h"
33 #include "clang/AST/Expr.h"
34 #include "clang/AST/ExprCXX.h"
35 #include "clang/AST/StmtCXX.h"
36 #include "clang/Lex/HeaderSearch.h"
37 #include "clang/Lex/Preprocessor.h"
38 #include "clang/Basic/FileManager.h"
39 #include "clang/Basic/PartialDiagnostic.h"
40 #include "clang/Basic/TargetInfo.h"
41 using namespace clang;
42 using namespace sema;
43 
44 FunctionScopeInfo::~FunctionScopeInfo() { }
45 
46 void FunctionScopeInfo::Clear() {
47   HasBranchProtectedScope = false;
48   HasBranchIntoScope = false;
49   HasIndirectGoto = false;
50 
51   SwitchStack.clear();
52   Returns.clear();
53   ErrorTrap.reset();
54   PossiblyUnreachableDiags.clear();
55 }
56 
57 BlockScopeInfo::~BlockScopeInfo() { }
58 LambdaScopeInfo::~LambdaScopeInfo() { }
59 
60 PrintingPolicy Sema::getPrintingPolicy(const ASTContext &Context,
61                                        const Preprocessor &PP) {
62   PrintingPolicy Policy = Context.getPrintingPolicy();
63   Policy.Bool = Context.getLangOptions().Bool;
64   if (!Policy.Bool) {
65     if (MacroInfo *BoolMacro = PP.getMacroInfo(&Context.Idents.get("bool"))) {
66       Policy.Bool = BoolMacro->isObjectLike() &&
67         BoolMacro->getNumTokens() == 1 &&
68         BoolMacro->getReplacementToken(0).is(tok::kw__Bool);
69     }
70   }
71 
72   return Policy;
73 }
74 
75 void Sema::ActOnTranslationUnitScope(Scope *S) {
76   TUScope = S;
77   PushDeclContext(S, Context.getTranslationUnitDecl());
78 
79   VAListTagName = PP.getIdentifierInfo("__va_list_tag");
80 }
81 
82 Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
83            TranslationUnitKind TUKind,
84            CodeCompleteConsumer *CodeCompleter)
85   : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()),
86     LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
87     Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
88     CollectStats(false), ExternalSource(0), CodeCompleter(CodeCompleter),
89     CurContext(0), OriginalLexicalContext(0),
90     PackContext(0), MSStructPragmaOn(false), VisContext(0),
91     ExprNeedsCleanups(false), LateTemplateParser(0), OpaqueParser(0),
92     IdResolver(pp), StdInitializerList(0), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
93     GlobalNewDeleteDeclared(false),
94     ObjCShouldCallSuperDealloc(false),
95     ObjCShouldCallSuperFinalize(false),
96     TUKind(TUKind),
97     NumSFINAEErrors(0), SuppressAccessChecking(false),
98     AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
99     NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
100     CurrentInstantiationScope(0), TyposCorrected(0),
101     AnalysisWarnings(*this)
102 {
103   TUScope = 0;
104   LoadedExternalKnownNamespaces = false;
105 
106   if (getLangOptions().CPlusPlus)
107     FieldCollector.reset(new CXXFieldCollector());
108 
109   // Tell diagnostics how to render things from the AST library.
110   PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
111                                        &Context);
112 
113   ExprEvalContexts.push_back(
114         ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0, false));
115 
116   FunctionScopes.push_back(new FunctionScopeInfo(Diags));
117 }
118 
119 void Sema::Initialize() {
120   // Tell the AST consumer about this Sema object.
121   Consumer.Initialize(Context);
122 
123   // FIXME: Isn't this redundant with the initialization above?
124   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
125     SC->InitializeSema(*this);
126 
127   // Tell the external Sema source about this Sema object.
128   if (ExternalSemaSource *ExternalSema
129       = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
130     ExternalSema->InitializeSema(*this);
131 
132   // Initialize predefined 128-bit integer types, if needed.
133   if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
134     // If either of the 128-bit integer types are unavailable to name lookup,
135     // define them now.
136     DeclarationName Int128 = &Context.Idents.get("__int128_t");
137     if (IdResolver.begin(Int128) == IdResolver.end())
138       PushOnScopeChains(Context.getInt128Decl(), TUScope);
139 
140     DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
141     if (IdResolver.begin(UInt128) == IdResolver.end())
142       PushOnScopeChains(Context.getUInt128Decl(), TUScope);
143   }
144 
145 
146   // Initialize predefined Objective-C types:
147   if (PP.getLangOptions().ObjC1) {
148     // If 'SEL' does not yet refer to any declarations, make it refer to the
149     // predefined 'SEL'.
150     DeclarationName SEL = &Context.Idents.get("SEL");
151     if (IdResolver.begin(SEL) == IdResolver.end())
152       PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
153 
154     // If 'id' does not yet refer to any declarations, make it refer to the
155     // predefined 'id'.
156     DeclarationName Id = &Context.Idents.get("id");
157     if (IdResolver.begin(Id) == IdResolver.end())
158       PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
159 
160     // Create the built-in typedef for 'Class'.
161     DeclarationName Class = &Context.Idents.get("Class");
162     if (IdResolver.begin(Class) == IdResolver.end())
163       PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
164 
165     // Create the built-in forward declaratino for 'Protocol'.
166     DeclarationName Protocol = &Context.Idents.get("Protocol");
167     if (IdResolver.begin(Protocol) == IdResolver.end())
168       PushOnScopeChains(Context.getObjCProtocolDecl(), TUScope);
169   }
170 }
171 
172 Sema::~Sema() {
173   if (PackContext) FreePackedContext();
174   if (VisContext) FreeVisContext();
175   delete TheTargetAttributesSema;
176   MSStructPragmaOn = false;
177   // Kill all the active scopes.
178   for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
179     delete FunctionScopes[I];
180   if (FunctionScopes.size() == 1)
181     delete FunctionScopes[0];
182 
183   // Tell the SemaConsumer to forget about us; we're going out of scope.
184   if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
185     SC->ForgetSema();
186 
187   // Detach from the external Sema source.
188   if (ExternalSemaSource *ExternalSema
189         = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
190     ExternalSema->ForgetSema();
191 }
192 
193 
194 /// makeUnavailableInSystemHeader - There is an error in the current
195 /// context.  If we're still in a system header, and we can plausibly
196 /// make the relevant declaration unavailable instead of erroring, do
197 /// so and return true.
198 bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
199                                          StringRef msg) {
200   // If we're not in a function, it's an error.
201   FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
202   if (!fn) return false;
203 
204   // If we're in template instantiation, it's an error.
205   if (!ActiveTemplateInstantiations.empty())
206     return false;
207 
208   // If that function's not in a system header, it's an error.
209   if (!Context.getSourceManager().isInSystemHeader(loc))
210     return false;
211 
212   // If the function is already unavailable, it's not an error.
213   if (fn->hasAttr<UnavailableAttr>()) return true;
214 
215   fn->addAttr(new (Context) UnavailableAttr(loc, Context, msg));
216   return true;
217 }
218 
219 ASTMutationListener *Sema::getASTMutationListener() const {
220   return getASTConsumer().GetASTMutationListener();
221 }
222 
223 /// \brief Print out statistics about the semantic analysis.
224 void Sema::PrintStats() const {
225   llvm::errs() << "\n*** Semantic Analysis Stats:\n";
226   llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
227 
228   BumpAlloc.PrintStats();
229   AnalysisWarnings.PrintStats();
230 }
231 
232 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
233 /// If there is already an implicit cast, merge into the existing one.
234 /// The result is of the given category.
235 ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
236                                    CastKind Kind, ExprValueKind VK,
237                                    const CXXCastPath *BasePath,
238                                    CheckedConversionKind CCK) {
239 #ifndef NDEBUG
240   if (VK == VK_RValue && !E->isRValue()) {
241     switch (Kind) {
242     default:
243       assert(0 && "can't implicitly cast lvalue to rvalue with this cast kind");
244     case CK_LValueToRValue:
245     case CK_ArrayToPointerDecay:
246     case CK_FunctionToPointerDecay:
247     case CK_ToVoid:
248       break;
249     }
250   }
251   assert((VK == VK_RValue || !E->isRValue()) && "can't cast rvalue to lvalue");
252 #endif
253 
254   QualType ExprTy = Context.getCanonicalType(E->getType());
255   QualType TypeTy = Context.getCanonicalType(Ty);
256 
257   if (ExprTy == TypeTy)
258     return Owned(E);
259 
260   if (getLangOptions().ObjCAutoRefCount)
261     CheckObjCARCConversion(SourceRange(), Ty, E, CCK);
262 
263   // If this is a derived-to-base cast to a through a virtual base, we
264   // need a vtable.
265   if (Kind == CK_DerivedToBase &&
266       BasePathInvolvesVirtualBase(*BasePath)) {
267     QualType T = E->getType();
268     if (const PointerType *Pointer = T->getAs<PointerType>())
269       T = Pointer->getPointeeType();
270     if (const RecordType *RecordTy = T->getAs<RecordType>())
271       MarkVTableUsed(E->getLocStart(),
272                      cast<CXXRecordDecl>(RecordTy->getDecl()));
273   }
274 
275   if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
276     if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
277       ImpCast->setType(Ty);
278       ImpCast->setValueKind(VK);
279       return Owned(E);
280     }
281   }
282 
283   return Owned(ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK));
284 }
285 
286 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
287 /// to the conversion from scalar type ScalarTy to the Boolean type.
288 CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
289   switch (ScalarTy->getScalarTypeKind()) {
290   case Type::STK_Bool: return CK_NoOp;
291   case Type::STK_CPointer: return CK_PointerToBoolean;
292   case Type::STK_BlockPointer: return CK_PointerToBoolean;
293   case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
294   case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
295   case Type::STK_Integral: return CK_IntegralToBoolean;
296   case Type::STK_Floating: return CK_FloatingToBoolean;
297   case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
298   case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
299   }
300   return CK_Invalid;
301 }
302 
303 /// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
304 static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
305   if (D->isUsed())
306     return true;
307 
308   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
309     // UnusedFileScopedDecls stores the first declaration.
310     // The declaration may have become definition so check again.
311     const FunctionDecl *DeclToCheck;
312     if (FD->hasBody(DeclToCheck))
313       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
314 
315     // Later redecls may add new information resulting in not having to warn,
316     // so check again.
317     DeclToCheck = FD->getMostRecentDecl();
318     if (DeclToCheck != FD)
319       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
320   }
321 
322   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
323     // UnusedFileScopedDecls stores the first declaration.
324     // The declaration may have become definition so check again.
325     const VarDecl *DeclToCheck = VD->getDefinition();
326     if (DeclToCheck)
327       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
328 
329     // Later redecls may add new information resulting in not having to warn,
330     // so check again.
331     DeclToCheck = VD->getMostRecentDecl();
332     if (DeclToCheck != VD)
333       return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
334   }
335 
336   return false;
337 }
338 
339 namespace {
340   struct UndefinedInternal {
341     NamedDecl *decl;
342     FullSourceLoc useLoc;
343 
344     UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc)
345       : decl(decl), useLoc(useLoc) {}
346   };
347 
348   bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) {
349     return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc);
350   }
351 }
352 
353 /// checkUndefinedInternals - Check for undefined objects with internal linkage.
354 static void checkUndefinedInternals(Sema &S) {
355   if (S.UndefinedInternals.empty()) return;
356 
357   // Collect all the still-undefined entities with internal linkage.
358   SmallVector<UndefinedInternal, 16> undefined;
359   for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator
360          i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end();
361        i != e; ++i) {
362     NamedDecl *decl = i->first;
363 
364     // Ignore attributes that have become invalid.
365     if (decl->isInvalidDecl()) continue;
366 
367     // __attribute__((weakref)) is basically a definition.
368     if (decl->hasAttr<WeakRefAttr>()) continue;
369 
370     if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
371       if (fn->isPure() || fn->hasBody())
372         continue;
373     } else {
374       if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly)
375         continue;
376     }
377 
378     // We build a FullSourceLoc so that we can sort with array_pod_sort.
379     FullSourceLoc loc(i->second, S.Context.getSourceManager());
380     undefined.push_back(UndefinedInternal(decl, loc));
381   }
382 
383   if (undefined.empty()) return;
384 
385   // Sort (in order of use site) so that we're not (as) dependent on
386   // the iteration order through an llvm::DenseMap.
387   llvm::array_pod_sort(undefined.begin(), undefined.end());
388 
389   for (SmallVectorImpl<UndefinedInternal>::iterator
390          i = undefined.begin(), e = undefined.end(); i != e; ++i) {
391     NamedDecl *decl = i->decl;
392     S.Diag(decl->getLocation(), diag::warn_undefined_internal)
393       << isa<VarDecl>(decl) << decl;
394     S.Diag(i->useLoc, diag::note_used_here);
395   }
396 }
397 
398 void Sema::LoadExternalWeakUndeclaredIdentifiers() {
399   if (!ExternalSource)
400     return;
401 
402   SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
403   ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
404   for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) {
405     llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos
406       = WeakUndeclaredIdentifiers.find(WeakIDs[I].first);
407     if (Pos != WeakUndeclaredIdentifiers.end())
408       continue;
409 
410     WeakUndeclaredIdentifiers.insert(WeakIDs[I]);
411   }
412 }
413 
414 /// ActOnEndOfTranslationUnit - This is called at the very end of the
415 /// translation unit when EOF is reached and all but the top-level scope is
416 /// popped.
417 void Sema::ActOnEndOfTranslationUnit() {
418   // Only complete translation units define vtables and perform implicit
419   // instantiations.
420   if (TUKind == TU_Complete) {
421     // If any dynamic classes have their key function defined within
422     // this translation unit, then those vtables are considered "used" and must
423     // be emitted.
424     for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource),
425                                       E = DynamicClasses.end();
426          I != E; ++I) {
427       assert(!(*I)->isDependentType() &&
428              "Should not see dependent types here!");
429       if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(*I)) {
430         const FunctionDecl *Definition = 0;
431         if (KeyFunction->hasBody(Definition))
432           MarkVTableUsed(Definition->getLocation(), *I, true);
433       }
434     }
435 
436     // If DefinedUsedVTables ends up marking any virtual member functions it
437     // might lead to more pending template instantiations, which we then need
438     // to instantiate.
439     DefineUsedVTables();
440 
441     // C++: Perform implicit template instantiations.
442     //
443     // FIXME: When we perform these implicit instantiations, we do not
444     // carefully keep track of the point of instantiation (C++ [temp.point]).
445     // This means that name lookup that occurs within the template
446     // instantiation will always happen at the end of the translation unit,
447     // so it will find some names that should not be found. Although this is
448     // common behavior for C++ compilers, it is technically wrong. In the
449     // future, we either need to be able to filter the results of name lookup
450     // or we need to perform template instantiations earlier.
451     PerformPendingInstantiations();
452   }
453 
454   // Remove file scoped decls that turned out to be used.
455   UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(0,
456                                                                          true),
457                                              UnusedFileScopedDecls.end(),
458                               std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
459                                            this)),
460                               UnusedFileScopedDecls.end());
461 
462   if (TUKind == TU_Prefix) {
463     // Translation unit prefixes don't need any of the checking below.
464     TUScope = 0;
465     return;
466   }
467 
468   // Check for #pragma weak identifiers that were never declared
469   // FIXME: This will cause diagnostics to be emitted in a non-determinstic
470   // order!  Iterating over a densemap like this is bad.
471   LoadExternalWeakUndeclaredIdentifiers();
472   for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
473        I = WeakUndeclaredIdentifiers.begin(),
474        E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
475     if (I->second.getUsed()) continue;
476 
477     Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
478       << I->first;
479   }
480 
481   if (TUKind == TU_Module) {
482     // If we are building a module, resolve all of the exported declarations
483     // now.
484     if (Module *CurrentModule = PP.getCurrentModule()) {
485       ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
486 
487       llvm::SmallVector<Module *, 2> Stack;
488       Stack.push_back(CurrentModule);
489       while (!Stack.empty()) {
490         Module *Mod = Stack.back();
491         Stack.pop_back();
492 
493         // Resolve the exported declarations.
494         // FIXME: Actually complain, once we figure out how to teach the
495         // diagnostic client to deal with complains in the module map at this
496         // point.
497         ModMap.resolveExports(Mod, /*Complain=*/false);
498 
499         // Queue the submodules, so their exports will also be resolved.
500         for (Module::submodule_iterator Sub = Mod->submodule_begin(),
501                                      SubEnd = Mod->submodule_end();
502              Sub != SubEnd; ++Sub) {
503           Stack.push_back(*Sub);
504         }
505       }
506     }
507 
508     // Modules don't need any of the checking below.
509     TUScope = 0;
510     return;
511   }
512 
513   // C99 6.9.2p2:
514   //   A declaration of an identifier for an object that has file
515   //   scope without an initializer, and without a storage-class
516   //   specifier or with the storage-class specifier static,
517   //   constitutes a tentative definition. If a translation unit
518   //   contains one or more tentative definitions for an identifier,
519   //   and the translation unit contains no external definition for
520   //   that identifier, then the behavior is exactly as if the
521   //   translation unit contains a file scope declaration of that
522   //   identifier, with the composite type as of the end of the
523   //   translation unit, with an initializer equal to 0.
524   llvm::SmallSet<VarDecl *, 32> Seen;
525   for (TentativeDefinitionsType::iterator
526             T = TentativeDefinitions.begin(ExternalSource),
527          TEnd = TentativeDefinitions.end();
528        T != TEnd; ++T)
529   {
530     VarDecl *VD = (*T)->getActingDefinition();
531 
532     // If the tentative definition was completed, getActingDefinition() returns
533     // null. If we've already seen this variable before, insert()'s second
534     // return value is false.
535     if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
536       continue;
537 
538     if (const IncompleteArrayType *ArrayT
539         = Context.getAsIncompleteArrayType(VD->getType())) {
540       if (RequireCompleteType(VD->getLocation(),
541                               ArrayT->getElementType(),
542                               diag::err_tentative_def_incomplete_type_arr)) {
543         VD->setInvalidDecl();
544         continue;
545       }
546 
547       // Set the length of the array to 1 (C99 6.9.2p5).
548       Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
549       llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
550       QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
551                                                 One, ArrayType::Normal, 0);
552       VD->setType(T);
553     } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
554                                    diag::err_tentative_def_incomplete_type))
555       VD->setInvalidDecl();
556 
557     // Notify the consumer that we've completed a tentative definition.
558     if (!VD->isInvalidDecl())
559       Consumer.CompleteTentativeDefinition(VD);
560 
561   }
562 
563   if (LangOpts.CPlusPlus0x &&
564       Diags.getDiagnosticLevel(diag::warn_delegating_ctor_cycle,
565                                SourceLocation())
566         != DiagnosticsEngine::Ignored)
567     CheckDelegatingCtorCycles();
568 
569   // If there were errors, disable 'unused' warnings since they will mostly be
570   // noise.
571   if (!Diags.hasErrorOccurred()) {
572     // Output warning for unused file scoped decls.
573     for (UnusedFileScopedDeclsType::iterator
574            I = UnusedFileScopedDecls.begin(ExternalSource),
575            E = UnusedFileScopedDecls.end(); I != E; ++I) {
576       if (ShouldRemoveFromUnused(this, *I))
577         continue;
578 
579       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
580         const FunctionDecl *DiagD;
581         if (!FD->hasBody(DiagD))
582           DiagD = FD;
583         if (DiagD->isDeleted())
584           continue; // Deleted functions are supposed to be unused.
585         if (DiagD->isReferenced()) {
586           if (isa<CXXMethodDecl>(DiagD))
587             Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
588                   << DiagD->getDeclName();
589           else
590             Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
591                   << /*function*/0 << DiagD->getDeclName();
592         } else {
593           Diag(DiagD->getLocation(),
594                isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
595                                          : diag::warn_unused_function)
596                 << DiagD->getDeclName();
597         }
598       } else {
599         const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
600         if (!DiagD)
601           DiagD = cast<VarDecl>(*I);
602         if (DiagD->isReferenced()) {
603           Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
604                 << /*variable*/1 << DiagD->getDeclName();
605         } else {
606           Diag(DiagD->getLocation(), diag::warn_unused_variable)
607                 << DiagD->getDeclName();
608         }
609       }
610     }
611 
612     checkUndefinedInternals(*this);
613   }
614 
615   // Check we've noticed that we're no longer parsing the initializer for every
616   // variable. If we miss cases, then at best we have a performance issue and
617   // at worst a rejects-valid bug.
618   assert(ParsingInitForAutoVars.empty() &&
619          "Didn't unmark var as having its initializer parsed");
620 
621   TUScope = 0;
622 }
623 
624 
625 //===----------------------------------------------------------------------===//
626 // Helper functions.
627 //===----------------------------------------------------------------------===//
628 
629 DeclContext *Sema::getFunctionLevelDeclContext() {
630   DeclContext *DC = CurContext;
631 
632   while (true) {
633     if (isa<BlockDecl>(DC) || isa<EnumDecl>(DC)) {
634       DC = DC->getParent();
635     } else if (isa<CXXMethodDecl>(DC) &&
636                cast<CXXRecordDecl>(DC->getParent())->isLambda()) {
637       DC = DC->getParent()->getParent();
638     }
639     else break;
640   }
641 
642   return DC;
643 }
644 
645 /// getCurFunctionDecl - If inside of a function body, this returns a pointer
646 /// to the function decl for the function being parsed.  If we're currently
647 /// in a 'block', this returns the containing context.
648 FunctionDecl *Sema::getCurFunctionDecl() {
649   DeclContext *DC = getFunctionLevelDeclContext();
650   return dyn_cast<FunctionDecl>(DC);
651 }
652 
653 ObjCMethodDecl *Sema::getCurMethodDecl() {
654   DeclContext *DC = getFunctionLevelDeclContext();
655   return dyn_cast<ObjCMethodDecl>(DC);
656 }
657 
658 NamedDecl *Sema::getCurFunctionOrMethodDecl() {
659   DeclContext *DC = getFunctionLevelDeclContext();
660   if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
661     return cast<NamedDecl>(DC);
662   return 0;
663 }
664 
665 Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
666   if (!isActive())
667     return;
668 
669   if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) {
670     switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) {
671     case DiagnosticIDs::SFINAE_Report:
672       // We'll report the diagnostic below.
673       break;
674 
675     case DiagnosticIDs::SFINAE_SubstitutionFailure:
676       // Count this failure so that we know that template argument deduction
677       // has failed.
678       ++SemaRef.NumSFINAEErrors;
679       SemaRef.Diags.setLastDiagnosticIgnored();
680       SemaRef.Diags.Clear();
681       Clear();
682       return;
683 
684     case DiagnosticIDs::SFINAE_AccessControl: {
685       // Per C++ Core Issue 1170, access control is part of SFINAE.
686       // Additionally, the AccessCheckingSFINAE flag can be used to temporary
687       // make access control a part of SFINAE for the purposes of checking
688       // type traits.
689       if (!SemaRef.AccessCheckingSFINAE &&
690           !SemaRef.getLangOptions().CPlusPlus0x)
691         break;
692 
693       SourceLocation Loc = getLocation();
694 
695       // Suppress this diagnostic.
696       ++SemaRef.NumSFINAEErrors;
697       SemaRef.Diags.setLastDiagnosticIgnored();
698       SemaRef.Diags.Clear();
699       Clear();
700 
701       // Now the diagnostic state is clear, produce a C++98 compatibility
702       // warning.
703       SemaRef.Diag(Loc, diag::warn_cxx98_compat_sfinae_access_control);
704 
705       // The last diagnostic which Sema produced was ignored. Suppress any
706       // notes attached to it.
707       SemaRef.Diags.setLastDiagnosticIgnored();
708       return;
709     }
710 
711     case DiagnosticIDs::SFINAE_Suppress:
712       // Make a copy of this suppressed diagnostic and store it with the
713       // template-deduction information;
714       FlushCounts();
715       Diagnostic DiagInfo(&SemaRef.Diags);
716 
717       if (*Info)
718         (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
719                         PartialDiagnostic(DiagInfo,
720                                           SemaRef.Context.getDiagAllocator()));
721 
722       // Suppress this diagnostic.
723       SemaRef.Diags.setLastDiagnosticIgnored();
724       SemaRef.Diags.Clear();
725       Clear();
726       return;
727     }
728   }
729 
730   // Set up the context's printing policy based on our current state.
731   SemaRef.Context.setPrintingPolicy(SemaRef.getPrintingPolicy());
732 
733   // Emit the diagnostic.
734   if (!this->Emit())
735     return;
736 
737   // If this is not a note, and we're in a template instantiation
738   // that is different from the last template instantiation where
739   // we emitted an error, print a template instantiation
740   // backtrace.
741   if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
742       !SemaRef.ActiveTemplateInstantiations.empty() &&
743       SemaRef.ActiveTemplateInstantiations.back()
744         != SemaRef.LastTemplateInstantiationErrorContext) {
745     SemaRef.PrintInstantiationStack();
746     SemaRef.LastTemplateInstantiationErrorContext
747       = SemaRef.ActiveTemplateInstantiations.back();
748   }
749 }
750 
751 Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
752   DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
753   return SemaDiagnosticBuilder(DB, *this, DiagID);
754 }
755 
756 Sema::SemaDiagnosticBuilder
757 Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
758   SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
759   PD.Emit(Builder);
760 
761   return Builder;
762 }
763 
764 /// \brief Looks through the macro-expansion chain for the given
765 /// location, looking for a macro expansion with the given name.
766 /// If one is found, returns true and sets the location to that
767 /// expansion loc.
768 bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
769   SourceLocation loc = locref;
770   if (!loc.isMacroID()) return false;
771 
772   // There's no good way right now to look at the intermediate
773   // expansions, so just jump to the expansion location.
774   loc = getSourceManager().getExpansionLoc(loc);
775 
776   // If that's written with the name, stop here.
777   SmallVector<char, 16> buffer;
778   if (getPreprocessor().getSpelling(loc, buffer) == name) {
779     locref = loc;
780     return true;
781   }
782   return false;
783 }
784 
785 /// \brief Determines the active Scope associated with the given declaration
786 /// context.
787 ///
788 /// This routine maps a declaration context to the active Scope object that
789 /// represents that declaration context in the parser. It is typically used
790 /// from "scope-less" code (e.g., template instantiation, lazy creation of
791 /// declarations) that injects a name for name-lookup purposes and, therefore,
792 /// must update the Scope.
793 ///
794 /// \returns The scope corresponding to the given declaraion context, or NULL
795 /// if no such scope is open.
796 Scope *Sema::getScopeForContext(DeclContext *Ctx) {
797 
798   if (!Ctx)
799     return 0;
800 
801   Ctx = Ctx->getPrimaryContext();
802   for (Scope *S = getCurScope(); S; S = S->getParent()) {
803     // Ignore scopes that cannot have declarations. This is important for
804     // out-of-line definitions of static class members.
805     if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
806       if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
807         if (Ctx == Entity->getPrimaryContext())
808           return S;
809   }
810 
811   return 0;
812 }
813 
814 /// \brief Enter a new function scope
815 void Sema::PushFunctionScope() {
816   if (FunctionScopes.size() == 1) {
817     // Use the "top" function scope rather than having to allocate
818     // memory for a new scope.
819     FunctionScopes.back()->Clear();
820     FunctionScopes.push_back(FunctionScopes.back());
821     return;
822   }
823 
824   FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
825 }
826 
827 void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
828   FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
829                                               BlockScope, Block));
830 }
831 
832 void Sema::PushLambdaScope(CXXRecordDecl *Lambda) {
833   FunctionScopes.push_back(new LambdaScopeInfo(getDiagnostics(), Lambda));
834 }
835 
836 void Sema::PopFunctionScopeInfo(const AnalysisBasedWarnings::Policy *WP,
837                                 const Decl *D, const BlockExpr *blkExpr) {
838   FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
839   assert(!FunctionScopes.empty() && "mismatched push/pop!");
840 
841   // Issue any analysis-based warnings.
842   if (WP && D)
843     AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
844   else {
845     for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
846          i = Scope->PossiblyUnreachableDiags.begin(),
847          e = Scope->PossiblyUnreachableDiags.end();
848          i != e; ++i) {
849       const sema::PossiblyUnreachableDiag &D = *i;
850       Diag(D.Loc, D.PD);
851     }
852   }
853 
854   if (FunctionScopes.back() != Scope) {
855     delete Scope;
856   }
857 }
858 
859 /// \brief Determine whether any errors occurred within this function/method/
860 /// block.
861 bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
862   return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
863 }
864 
865 BlockScopeInfo *Sema::getCurBlock() {
866   if (FunctionScopes.empty())
867     return 0;
868 
869   return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
870 }
871 
872 LambdaScopeInfo *Sema::getCurLambda() {
873   if (FunctionScopes.empty())
874     return 0;
875 
876   return dyn_cast<LambdaScopeInfo>(FunctionScopes.back());
877 }
878 
879 // Pin this vtable to this file.
880 ExternalSemaSource::~ExternalSemaSource() {}
881 
882 void ExternalSemaSource::ReadMethodPool(Selector Sel) { }
883 
884 void ExternalSemaSource::ReadKnownNamespaces(
885                            SmallVectorImpl<NamespaceDecl *> &Namespaces) {
886 }
887 
888 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
889   SourceLocation Loc = this->Loc;
890   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
891   if (Loc.isValid()) {
892     Loc.print(OS, S.getSourceManager());
893     OS << ": ";
894   }
895   OS << Message;
896 
897   if (TheDecl && isa<NamedDecl>(TheDecl)) {
898     std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
899     if (!Name.empty())
900       OS << " '" << Name << '\'';
901   }
902 
903   OS << '\n';
904 }
905 
906 /// \brief Figure out if an expression could be turned into a call.
907 ///
908 /// Use this when trying to recover from an error where the programmer may have
909 /// written just the name of a function instead of actually calling it.
910 ///
911 /// \param E - The expression to examine.
912 /// \param ZeroArgCallReturnTy - If the expression can be turned into a call
913 ///  with no arguments, this parameter is set to the type returned by such a
914 ///  call; otherwise, it is set to an empty QualType.
915 /// \param OverloadSet - If the expression is an overloaded function
916 ///  name, this parameter is populated with the decls of the various overloads.
917 bool Sema::isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
918                           UnresolvedSetImpl &OverloadSet) {
919   ZeroArgCallReturnTy = QualType();
920   OverloadSet.clear();
921 
922   if (E.getType() == Context.OverloadTy) {
923     OverloadExpr::FindResult FR = OverloadExpr::find(const_cast<Expr*>(&E));
924     const OverloadExpr *Overloads = FR.Expression;
925 
926     for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
927          DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
928       OverloadSet.addDecl(*it);
929 
930       // Check whether the function is a non-template which takes no
931       // arguments.
932       if (const FunctionDecl *OverloadDecl
933             = dyn_cast<FunctionDecl>((*it)->getUnderlyingDecl())) {
934         if (OverloadDecl->getMinRequiredArguments() == 0)
935           ZeroArgCallReturnTy = OverloadDecl->getResultType();
936       }
937     }
938 
939     // Ignore overloads that are pointer-to-member constants.
940     if (FR.HasFormOfMemberPointer)
941       return false;
942 
943     return true;
944   }
945 
946   if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E.IgnoreParens())) {
947     if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
948       if (Fun->getMinRequiredArguments() == 0)
949         ZeroArgCallReturnTy = Fun->getResultType();
950       return true;
951     }
952   }
953 
954   // We don't have an expression that's convenient to get a FunctionDecl from,
955   // but we can at least check if the type is "function of 0 arguments".
956   QualType ExprTy = E.getType();
957   const FunctionType *FunTy = NULL;
958   QualType PointeeTy = ExprTy->getPointeeType();
959   if (!PointeeTy.isNull())
960     FunTy = PointeeTy->getAs<FunctionType>();
961   if (!FunTy)
962     FunTy = ExprTy->getAs<FunctionType>();
963   if (!FunTy && ExprTy == Context.BoundMemberTy) {
964     // Look for the bound-member type.  If it's still overloaded, give up,
965     // although we probably should have fallen into the OverloadExpr case above
966     // if we actually have an overloaded bound member.
967     QualType BoundMemberTy = Expr::findBoundMemberType(&E);
968     if (!BoundMemberTy.isNull())
969       FunTy = BoundMemberTy->castAs<FunctionType>();
970   }
971 
972   if (const FunctionProtoType *FPT =
973       dyn_cast_or_null<FunctionProtoType>(FunTy)) {
974     if (FPT->getNumArgs() == 0)
975       ZeroArgCallReturnTy = FunTy->getResultType();
976     return true;
977   }
978   return false;
979 }
980 
981 /// \brief Give notes for a set of overloads.
982 ///
983 /// A companion to isExprCallable. In cases when the name that the programmer
984 /// wrote was an overloaded function, we may be able to make some guesses about
985 /// plausible overloads based on their return types; such guesses can be handed
986 /// off to this method to be emitted as notes.
987 ///
988 /// \param Overloads - The overloads to note.
989 /// \param FinalNoteLoc - If we've suppressed printing some overloads due to
990 ///  -fshow-overloads=best, this is the location to attach to the note about too
991 ///  many candidates. Typically this will be the location of the original
992 ///  ill-formed expression.
993 static void noteOverloads(Sema &S, const UnresolvedSetImpl &Overloads,
994                           const SourceLocation FinalNoteLoc) {
995   int ShownOverloads = 0;
996   int SuppressedOverloads = 0;
997   for (UnresolvedSetImpl::iterator It = Overloads.begin(),
998        DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
999     // FIXME: Magic number for max shown overloads stolen from
1000     // OverloadCandidateSet::NoteCandidates.
1001     if (ShownOverloads >= 4 &&
1002         S.Diags.getShowOverloads() == DiagnosticsEngine::Ovl_Best) {
1003       ++SuppressedOverloads;
1004       continue;
1005     }
1006 
1007     NamedDecl *Fn = (*It)->getUnderlyingDecl();
1008     S.Diag(Fn->getLocation(), diag::note_possible_target_of_call);
1009     ++ShownOverloads;
1010   }
1011 
1012   if (SuppressedOverloads)
1013     S.Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
1014       << SuppressedOverloads;
1015 }
1016 
1017 static void notePlausibleOverloads(Sema &S, SourceLocation Loc,
1018                                    const UnresolvedSetImpl &Overloads,
1019                                    bool (*IsPlausibleResult)(QualType)) {
1020   if (!IsPlausibleResult)
1021     return noteOverloads(S, Overloads, Loc);
1022 
1023   UnresolvedSet<2> PlausibleOverloads;
1024   for (OverloadExpr::decls_iterator It = Overloads.begin(),
1025          DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1026     const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1027     QualType OverloadResultTy = OverloadDecl->getResultType();
1028     if (IsPlausibleResult(OverloadResultTy))
1029       PlausibleOverloads.addDecl(It.getDecl());
1030   }
1031   noteOverloads(S, PlausibleOverloads, Loc);
1032 }
1033 
1034 /// Determine whether the given expression can be called by just
1035 /// putting parentheses after it.  Notably, expressions with unary
1036 /// operators can't be because the unary operator will start parsing
1037 /// outside the call.
1038 static bool IsCallableWithAppend(Expr *E) {
1039   E = E->IgnoreImplicit();
1040   return (!isa<CStyleCastExpr>(E) &&
1041           !isa<UnaryOperator>(E) &&
1042           !isa<BinaryOperator>(E) &&
1043           !isa<CXXOperatorCallExpr>(E));
1044 }
1045 
1046 bool Sema::tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
1047                                 bool ForceComplain,
1048                                 bool (*IsPlausibleResult)(QualType)) {
1049   SourceLocation Loc = E.get()->getExprLoc();
1050   SourceRange Range = E.get()->getSourceRange();
1051 
1052   QualType ZeroArgCallTy;
1053   UnresolvedSet<4> Overloads;
1054   if (isExprCallable(*E.get(), ZeroArgCallTy, Overloads) &&
1055       !ZeroArgCallTy.isNull() &&
1056       (!IsPlausibleResult || IsPlausibleResult(ZeroArgCallTy))) {
1057     // At this point, we know E is potentially callable with 0
1058     // arguments and that it returns something of a reasonable type,
1059     // so we can emit a fixit and carry on pretending that E was
1060     // actually a CallExpr.
1061     SourceLocation ParenInsertionLoc =
1062       PP.getLocForEndOfToken(Range.getEnd());
1063     Diag(Loc, PD)
1064       << /*zero-arg*/ 1 << Range
1065       << (IsCallableWithAppend(E.get())
1066           ? FixItHint::CreateInsertion(ParenInsertionLoc, "()")
1067           : FixItHint());
1068     notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1069 
1070     // FIXME: Try this before emitting the fixit, and suppress diagnostics
1071     // while doing so.
1072     E = ActOnCallExpr(0, E.take(), ParenInsertionLoc,
1073                       MultiExprArg(*this, 0, 0),
1074                       ParenInsertionLoc.getLocWithOffset(1));
1075     return true;
1076   }
1077 
1078   if (!ForceComplain) return false;
1079 
1080   Diag(Loc, PD) << /*not zero-arg*/ 0 << Range;
1081   notePlausibleOverloads(*this, Loc, Overloads, IsPlausibleResult);
1082   E = ExprError();
1083   return true;
1084 }
1085