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