Sema.cpp revision 40847cfb58acc3cac7d68727df9455ac45f2e118
179f15823c34ae1e423108295e416213200bb280fAndreas Huber//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
279f15823c34ae1e423108295e416213200bb280fAndreas Huber//
379f15823c34ae1e423108295e416213200bb280fAndreas Huber//                     The LLVM Compiler Infrastructure
479f15823c34ae1e423108295e416213200bb280fAndreas Huber//
579f15823c34ae1e423108295e416213200bb280fAndreas Huber// This file is distributed under the University of Illinois Open Source
679f15823c34ae1e423108295e416213200bb280fAndreas Huber// License. See LICENSE.TXT for details.
779f15823c34ae1e423108295e416213200bb280fAndreas Huber//
879f15823c34ae1e423108295e416213200bb280fAndreas Huber//===----------------------------------------------------------------------===//
979f15823c34ae1e423108295e416213200bb280fAndreas Huber//
1079f15823c34ae1e423108295e416213200bb280fAndreas Huber// This file implements the actions class which performs semantic analysis and
1179f15823c34ae1e423108295e416213200bb280fAndreas Huber// builds an AST out of a parse stream.
1279f15823c34ae1e423108295e416213200bb280fAndreas Huber//
1379f15823c34ae1e423108295e416213200bb280fAndreas Huber//===----------------------------------------------------------------------===//
1479f15823c34ae1e423108295e416213200bb280fAndreas Huber
1579f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Sema/SemaInternal.h"
1679f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Sema/DelayedDiagnostic.h"
1779f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "TargetAttributesSema.h"
1879f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "llvm/ADT/DenseMap.h"
1979f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "llvm/ADT/SmallSet.h"
2079f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "llvm/ADT/APFloat.h"
2179f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Sema/CXXFieldCollector.h"
2279f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Sema/TemplateDeduction.h"
2379f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Sema/ExternalSemaSource.h"
2479f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Sema/ObjCMethodList.h"
2579f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Sema/PrettyDeclStackTrace.h"
2679f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Sema/Scope.h"
2779f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Sema/ScopeInfo.h"
2879f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Sema/SemaConsumer.h"
2979f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/AST/ASTContext.h"
3079f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/AST/ASTDiagnostic.h"
3179f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/AST/DeclCXX.h"
3279f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/AST/DeclObjC.h"
3379f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/AST/Expr.h"
3479f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/AST/ExprCXX.h"
3579f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/AST/StmtCXX.h"
3679f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Lex/Preprocessor.h"
3779f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Basic/FileManager.h"
3879f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Basic/PartialDiagnostic.h"
3979f15823c34ae1e423108295e416213200bb280fAndreas Huber#include "clang/Basic/TargetInfo.h"
4079f15823c34ae1e423108295e416213200bb280fAndreas Huberusing namespace clang;
4179f15823c34ae1e423108295e416213200bb280fAndreas Huberusing namespace sema;
4279f15823c34ae1e423108295e416213200bb280fAndreas Huber
4379f15823c34ae1e423108295e416213200bb280fAndreas HuberFunctionScopeInfo::~FunctionScopeInfo() { }
4479f15823c34ae1e423108295e416213200bb280fAndreas Huber
4579f15823c34ae1e423108295e416213200bb280fAndreas Hubervoid FunctionScopeInfo::Clear() {
4679f15823c34ae1e423108295e416213200bb280fAndreas Huber  HasBranchProtectedScope = false;
4779f15823c34ae1e423108295e416213200bb280fAndreas Huber  HasBranchIntoScope = false;
4879f15823c34ae1e423108295e416213200bb280fAndreas Huber  HasIndirectGoto = false;
4979f15823c34ae1e423108295e416213200bb280fAndreas Huber
5079f15823c34ae1e423108295e416213200bb280fAndreas Huber  SwitchStack.clear();
5179f15823c34ae1e423108295e416213200bb280fAndreas Huber  Returns.clear();
5279f15823c34ae1e423108295e416213200bb280fAndreas Huber  ErrorTrap.reset();
5379f15823c34ae1e423108295e416213200bb280fAndreas Huber  PossiblyUnreachableDiags.clear();
5479f15823c34ae1e423108295e416213200bb280fAndreas Huber}
5579f15823c34ae1e423108295e416213200bb280fAndreas Huber
5679f15823c34ae1e423108295e416213200bb280fAndreas HuberBlockScopeInfo::~BlockScopeInfo() { }
5779f15823c34ae1e423108295e416213200bb280fAndreas Huber
5879f15823c34ae1e423108295e416213200bb280fAndreas Hubervoid Sema::ActOnTranslationUnitScope(Scope *S) {
5979f15823c34ae1e423108295e416213200bb280fAndreas Huber  TUScope = S;
6079f15823c34ae1e423108295e416213200bb280fAndreas Huber  PushDeclContext(S, Context.getTranslationUnitDecl());
6179f15823c34ae1e423108295e416213200bb280fAndreas Huber
6279f15823c34ae1e423108295e416213200bb280fAndreas Huber  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
6379f15823c34ae1e423108295e416213200bb280fAndreas Huber
6479f15823c34ae1e423108295e416213200bb280fAndreas Huber  if (PP.getLangOptions().ObjC1) {
6579f15823c34ae1e423108295e416213200bb280fAndreas Huber    // Synthesize "@class Protocol;
6679f15823c34ae1e423108295e416213200bb280fAndreas Huber    if (Context.getObjCProtoType().isNull()) {
6779f15823c34ae1e423108295e416213200bb280fAndreas Huber      ObjCInterfaceDecl *ProtocolDecl =
6879f15823c34ae1e423108295e416213200bb280fAndreas Huber        ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
6979f15823c34ae1e423108295e416213200bb280fAndreas Huber                                  &Context.Idents.get("Protocol"),
7079f15823c34ae1e423108295e416213200bb280fAndreas Huber                                  SourceLocation(), true);
7179f15823c34ae1e423108295e416213200bb280fAndreas Huber      Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
7279f15823c34ae1e423108295e416213200bb280fAndreas Huber      PushOnScopeChains(ProtocolDecl, TUScope, false);
7379f15823c34ae1e423108295e416213200bb280fAndreas Huber    }
7479f15823c34ae1e423108295e416213200bb280fAndreas Huber  }
7579f15823c34ae1e423108295e416213200bb280fAndreas Huber}
7679f15823c34ae1e423108295e416213200bb280fAndreas Huber
7779f15823c34ae1e423108295e416213200bb280fAndreas HuberSema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
7879f15823c34ae1e423108295e416213200bb280fAndreas Huber           TranslationUnitKind TUKind,
7979f15823c34ae1e423108295e416213200bb280fAndreas Huber           CodeCompleteConsumer *CodeCompleter)
8079f15823c34ae1e423108295e416213200bb280fAndreas Huber  : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()),
8179f15823c34ae1e423108295e416213200bb280fAndreas Huber    LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
8279f15823c34ae1e423108295e416213200bb280fAndreas Huber    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
8379f15823c34ae1e423108295e416213200bb280fAndreas Huber    CollectStats(false), ExternalSource(0), CodeCompleter(CodeCompleter),
8479f15823c34ae1e423108295e416213200bb280fAndreas Huber    CurContext(0), PackContext(0), MSStructPragmaOn(false), VisContext(0),
8579f15823c34ae1e423108295e416213200bb280fAndreas Huber    ExprNeedsCleanups(0), LateTemplateParser(0), OpaqueParser(0),
8679f15823c34ae1e423108295e416213200bb280fAndreas Huber    IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
8779f15823c34ae1e423108295e416213200bb280fAndreas Huber    GlobalNewDeleteDeclared(false),
8879f15823c34ae1e423108295e416213200bb280fAndreas Huber    ObjCShouldCallSuperDealloc(false),
8979f15823c34ae1e423108295e416213200bb280fAndreas Huber    ObjCShouldCallSuperFinalize(false),
9079f15823c34ae1e423108295e416213200bb280fAndreas Huber    TUKind(TUKind),
9179f15823c34ae1e423108295e416213200bb280fAndreas Huber    NumSFINAEErrors(0), SuppressAccessChecking(false),
9279f15823c34ae1e423108295e416213200bb280fAndreas Huber    AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
9379f15823c34ae1e423108295e416213200bb280fAndreas Huber    NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
9479f15823c34ae1e423108295e416213200bb280fAndreas Huber    CurrentInstantiationScope(0), TyposCorrected(0),
9579f15823c34ae1e423108295e416213200bb280fAndreas Huber    AnalysisWarnings(*this)
9679f15823c34ae1e423108295e416213200bb280fAndreas Huber{
9779f15823c34ae1e423108295e416213200bb280fAndreas Huber  TUScope = 0;
9879f15823c34ae1e423108295e416213200bb280fAndreas Huber  LoadedExternalKnownNamespaces = false;
9979f15823c34ae1e423108295e416213200bb280fAndreas Huber
10079f15823c34ae1e423108295e416213200bb280fAndreas Huber  if (getLangOptions().CPlusPlus)
10179f15823c34ae1e423108295e416213200bb280fAndreas Huber    FieldCollector.reset(new CXXFieldCollector());
10279f15823c34ae1e423108295e416213200bb280fAndreas Huber
10379f15823c34ae1e423108295e416213200bb280fAndreas Huber  // Tell diagnostics how to render things from the AST library.
10479f15823c34ae1e423108295e416213200bb280fAndreas Huber  PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
10579f15823c34ae1e423108295e416213200bb280fAndreas Huber                                       &Context);
10679f15823c34ae1e423108295e416213200bb280fAndreas Huber
10779f15823c34ae1e423108295e416213200bb280fAndreas Huber  ExprEvalContexts.push_back(
10879f15823c34ae1e423108295e416213200bb280fAndreas Huber        ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0, false));
10979f15823c34ae1e423108295e416213200bb280fAndreas Huber
11079f15823c34ae1e423108295e416213200bb280fAndreas Huber  FunctionScopes.push_back(new FunctionScopeInfo(Diags));
11179f15823c34ae1e423108295e416213200bb280fAndreas Huber}
11279f15823c34ae1e423108295e416213200bb280fAndreas Huber
11379f15823c34ae1e423108295e416213200bb280fAndreas Hubervoid Sema::Initialize() {
11479f15823c34ae1e423108295e416213200bb280fAndreas Huber  // Tell the AST consumer about this Sema object.
11579f15823c34ae1e423108295e416213200bb280fAndreas Huber  Consumer.Initialize(Context);
11679f15823c34ae1e423108295e416213200bb280fAndreas Huber
11779f15823c34ae1e423108295e416213200bb280fAndreas Huber  // FIXME: Isn't this redundant with the initialization above?
11879f15823c34ae1e423108295e416213200bb280fAndreas Huber  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
11979f15823c34ae1e423108295e416213200bb280fAndreas Huber    SC->InitializeSema(*this);
12079f15823c34ae1e423108295e416213200bb280fAndreas Huber
121  // Tell the external Sema source about this Sema object.
122  if (ExternalSemaSource *ExternalSema
123      = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
124    ExternalSema->InitializeSema(*this);
125
126  // Initialize predefined 128-bit integer types, if needed.
127  if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
128    // If either of the 128-bit integer types are unavailable to name lookup,
129    // define them now.
130    DeclarationName Int128 = &Context.Idents.get("__int128_t");
131    if (IdentifierResolver::begin(Int128) == IdentifierResolver::end())
132      PushOnScopeChains(Context.getInt128Decl(), TUScope);
133
134    DeclarationName UInt128 = &Context.Idents.get("__uint128_t");
135    if (IdentifierResolver::begin(UInt128) == IdentifierResolver::end())
136      PushOnScopeChains(Context.getUInt128Decl(), TUScope);
137  }
138
139
140  // Initialize predefined Objective-C types:
141  if (PP.getLangOptions().ObjC1) {
142    // If 'SEL' does not yet refer to any declarations, make it refer to the
143    // predefined 'SEL'.
144    DeclarationName SEL = &Context.Idents.get("SEL");
145    if (IdentifierResolver::begin(SEL) == IdentifierResolver::end())
146      PushOnScopeChains(Context.getObjCSelDecl(), TUScope);
147
148    // If 'id' does not yet refer to any declarations, make it refer to the
149    // predefined 'id'.
150    DeclarationName Id = &Context.Idents.get("id");
151    if (IdentifierResolver::begin(Id) == IdentifierResolver::end())
152      PushOnScopeChains(Context.getObjCIdDecl(), TUScope);
153
154    // Create the built-in typedef for 'Class'.
155    DeclarationName Class = &Context.Idents.get("Class");
156    if (IdentifierResolver::begin(Class) == IdentifierResolver::end())
157      PushOnScopeChains(Context.getObjCClassDecl(), TUScope);
158  }
159}
160
161Sema::~Sema() {
162  if (PackContext) FreePackedContext();
163  if (VisContext) FreeVisContext();
164  delete TheTargetAttributesSema;
165  MSStructPragmaOn = false;
166  // Kill all the active scopes.
167  for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
168    delete FunctionScopes[I];
169  if (FunctionScopes.size() == 1)
170    delete FunctionScopes[0];
171
172  // Tell the SemaConsumer to forget about us; we're going out of scope.
173  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
174    SC->ForgetSema();
175
176  // Detach from the external Sema source.
177  if (ExternalSemaSource *ExternalSema
178        = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
179    ExternalSema->ForgetSema();
180}
181
182
183/// makeUnavailableInSystemHeader - There is an error in the current
184/// context.  If we're still in a system header, and we can plausibly
185/// make the relevant declaration unavailable instead of erroring, do
186/// so and return true.
187bool Sema::makeUnavailableInSystemHeader(SourceLocation loc,
188                                         StringRef msg) {
189  // If we're not in a function, it's an error.
190  FunctionDecl *fn = dyn_cast<FunctionDecl>(CurContext);
191  if (!fn) return false;
192
193  // If we're in template instantiation, it's an error.
194  if (!ActiveTemplateInstantiations.empty())
195    return false;
196
197  // If that function's not in a system header, it's an error.
198  if (!Context.getSourceManager().isInSystemHeader(loc))
199    return false;
200
201  // If the function is already unavailable, it's not an error.
202  if (fn->hasAttr<UnavailableAttr>()) return true;
203
204  fn->addAttr(new (Context) UnavailableAttr(loc, Context, msg));
205  return true;
206}
207
208ASTMutationListener *Sema::getASTMutationListener() const {
209  return getASTConsumer().GetASTMutationListener();
210}
211
212/// \brief Print out statistics about the semantic analysis.
213void Sema::PrintStats() const {
214  llvm::errs() << "\n*** Semantic Analysis Stats:\n";
215  llvm::errs() << NumSFINAEErrors << " SFINAE diagnostics trapped.\n";
216
217  BumpAlloc.PrintStats();
218  AnalysisWarnings.PrintStats();
219}
220
221/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
222/// If there is already an implicit cast, merge into the existing one.
223/// The result is of the given category.
224ExprResult Sema::ImpCastExprToType(Expr *E, QualType Ty,
225                                   CastKind Kind, ExprValueKind VK,
226                                   const CXXCastPath *BasePath,
227                                   CheckedConversionKind CCK) {
228  QualType ExprTy = Context.getCanonicalType(E->getType());
229  QualType TypeTy = Context.getCanonicalType(Ty);
230
231  if (ExprTy == TypeTy)
232    return Owned(E);
233
234  if (getLangOptions().ObjCAutoRefCount)
235    CheckObjCARCConversion(SourceRange(), Ty, E, CCK);
236
237  // If this is a derived-to-base cast to a through a virtual base, we
238  // need a vtable.
239  if (Kind == CK_DerivedToBase &&
240      BasePathInvolvesVirtualBase(*BasePath)) {
241    QualType T = E->getType();
242    if (const PointerType *Pointer = T->getAs<PointerType>())
243      T = Pointer->getPointeeType();
244    if (const RecordType *RecordTy = T->getAs<RecordType>())
245      MarkVTableUsed(E->getLocStart(),
246                     cast<CXXRecordDecl>(RecordTy->getDecl()));
247  }
248
249  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(E)) {
250    if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
251      ImpCast->setType(Ty);
252      ImpCast->setValueKind(VK);
253      return Owned(E);
254    }
255  }
256
257  return Owned(ImplicitCastExpr::Create(Context, Ty, Kind, E, BasePath, VK));
258}
259
260/// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
261/// to the conversion from scalar type ScalarTy to the Boolean type.
262CastKind Sema::ScalarTypeToBooleanCastKind(QualType ScalarTy) {
263  switch (ScalarTy->getScalarTypeKind()) {
264  case Type::STK_Bool: return CK_NoOp;
265  case Type::STK_CPointer: return CK_PointerToBoolean;
266  case Type::STK_BlockPointer: return CK_PointerToBoolean;
267  case Type::STK_ObjCObjectPointer: return CK_PointerToBoolean;
268  case Type::STK_MemberPointer: return CK_MemberPointerToBoolean;
269  case Type::STK_Integral: return CK_IntegralToBoolean;
270  case Type::STK_Floating: return CK_FloatingToBoolean;
271  case Type::STK_IntegralComplex: return CK_IntegralComplexToBoolean;
272  case Type::STK_FloatingComplex: return CK_FloatingComplexToBoolean;
273  }
274  return CK_Invalid;
275}
276
277ExprValueKind Sema::CastCategory(Expr *E) {
278  Expr::Classification Classification = E->Classify(Context);
279  return Classification.isRValue() ? VK_RValue :
280      (Classification.isLValue() ? VK_LValue : VK_XValue);
281}
282
283/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
284static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
285  if (D->isUsed())
286    return true;
287
288  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
289    // UnusedFileScopedDecls stores the first declaration.
290    // The declaration may have become definition so check again.
291    const FunctionDecl *DeclToCheck;
292    if (FD->hasBody(DeclToCheck))
293      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
294
295    // Later redecls may add new information resulting in not having to warn,
296    // so check again.
297    DeclToCheck = FD->getMostRecentDeclaration();
298    if (DeclToCheck != FD)
299      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
300  }
301
302  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
303    // UnusedFileScopedDecls stores the first declaration.
304    // The declaration may have become definition so check again.
305    const VarDecl *DeclToCheck = VD->getDefinition();
306    if (DeclToCheck)
307      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
308
309    // Later redecls may add new information resulting in not having to warn,
310    // so check again.
311    DeclToCheck = VD->getMostRecentDeclaration();
312    if (DeclToCheck != VD)
313      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
314  }
315
316  return false;
317}
318
319namespace {
320  struct UndefinedInternal {
321    NamedDecl *decl;
322    FullSourceLoc useLoc;
323
324    UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc)
325      : decl(decl), useLoc(useLoc) {}
326  };
327
328  bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) {
329    return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc);
330  }
331}
332
333/// checkUndefinedInternals - Check for undefined objects with internal linkage.
334static void checkUndefinedInternals(Sema &S) {
335  if (S.UndefinedInternals.empty()) return;
336
337  // Collect all the still-undefined entities with internal linkage.
338  SmallVector<UndefinedInternal, 16> undefined;
339  for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator
340         i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end();
341       i != e; ++i) {
342    NamedDecl *decl = i->first;
343
344    // Ignore attributes that have become invalid.
345    if (decl->isInvalidDecl()) continue;
346
347    // __attribute__((weakref)) is basically a definition.
348    if (decl->hasAttr<WeakRefAttr>()) continue;
349
350    if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
351      if (fn->isPure() || fn->hasBody())
352        continue;
353    } else {
354      if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly)
355        continue;
356    }
357
358    // We build a FullSourceLoc so that we can sort with array_pod_sort.
359    FullSourceLoc loc(i->second, S.Context.getSourceManager());
360    undefined.push_back(UndefinedInternal(decl, loc));
361  }
362
363  if (undefined.empty()) return;
364
365  // Sort (in order of use site) so that we're not (as) dependent on
366  // the iteration order through an llvm::DenseMap.
367  llvm::array_pod_sort(undefined.begin(), undefined.end());
368
369  for (SmallVectorImpl<UndefinedInternal>::iterator
370         i = undefined.begin(), e = undefined.end(); i != e; ++i) {
371    NamedDecl *decl = i->decl;
372    S.Diag(decl->getLocation(), diag::warn_undefined_internal)
373      << isa<VarDecl>(decl) << decl;
374    S.Diag(i->useLoc, diag::note_used_here);
375  }
376}
377
378void Sema::LoadExternalWeakUndeclaredIdentifiers() {
379  if (!ExternalSource)
380    return;
381
382  SmallVector<std::pair<IdentifierInfo *, WeakInfo>, 4> WeakIDs;
383  ExternalSource->ReadWeakUndeclaredIdentifiers(WeakIDs);
384  for (unsigned I = 0, N = WeakIDs.size(); I != N; ++I) {
385    llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator Pos
386      = WeakUndeclaredIdentifiers.find(WeakIDs[I].first);
387    if (Pos != WeakUndeclaredIdentifiers.end())
388      continue;
389
390    WeakUndeclaredIdentifiers.insert(WeakIDs[I]);
391  }
392}
393
394/// ActOnEndOfTranslationUnit - This is called at the very end of the
395/// translation unit when EOF is reached and all but the top-level scope is
396/// popped.
397void Sema::ActOnEndOfTranslationUnit() {
398  // Only complete translation units define vtables and perform implicit
399  // instantiations.
400  if (TUKind == TU_Complete) {
401    // If any dynamic classes have their key function defined within
402    // this translation unit, then those vtables are considered "used" and must
403    // be emitted.
404    for (DynamicClassesType::iterator I = DynamicClasses.begin(ExternalSource),
405                                      E = DynamicClasses.end();
406         I != E; ++I) {
407      assert(!(*I)->isDependentType() &&
408             "Should not see dependent types here!");
409      if (const CXXMethodDecl *KeyFunction = Context.getKeyFunction(*I)) {
410        const FunctionDecl *Definition = 0;
411        if (KeyFunction->hasBody(Definition))
412          MarkVTableUsed(Definition->getLocation(), *I, true);
413      }
414    }
415
416    // If DefinedUsedVTables ends up marking any virtual member functions it
417    // might lead to more pending template instantiations, which we then need
418    // to instantiate.
419    DefineUsedVTables();
420
421    // C++: Perform implicit template instantiations.
422    //
423    // FIXME: When we perform these implicit instantiations, we do not
424    // carefully keep track of the point of instantiation (C++ [temp.point]).
425    // This means that name lookup that occurs within the template
426    // instantiation will always happen at the end of the translation unit,
427    // so it will find some names that should not be found. Although this is
428    // common behavior for C++ compilers, it is technically wrong. In the
429    // future, we either need to be able to filter the results of name lookup
430    // or we need to perform template instantiations earlier.
431    PerformPendingInstantiations();
432  }
433
434  // Remove file scoped decls that turned out to be used.
435  UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(0,
436                                                                         true),
437                                             UnusedFileScopedDecls.end(),
438                              std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
439                                           this)),
440                              UnusedFileScopedDecls.end());
441
442  if (TUKind == TU_Prefix) {
443    // Translation unit prefixes don't need any of the checking below.
444    TUScope = 0;
445    return;
446  }
447
448  // Check for #pragma weak identifiers that were never declared
449  // FIXME: This will cause diagnostics to be emitted in a non-determinstic
450  // order!  Iterating over a densemap like this is bad.
451  LoadExternalWeakUndeclaredIdentifiers();
452  for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
453       I = WeakUndeclaredIdentifiers.begin(),
454       E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
455    if (I->second.getUsed()) continue;
456
457    Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
458      << I->first;
459  }
460
461  if (TUKind == TU_Module) {
462    // Mark any macros from system headers (in /usr/include) as exported, along
463    // with our own Clang headers.
464    // FIXME: This is a gross hack to deal with the fact that system headers
465    // are #include'd in many places within module headers, but are not
466    // themselves modularized. This doesn't actually work, but it lets us
467    // focus on other issues for the moment.
468    for (Preprocessor::macro_iterator M = PP.macro_begin(false),
469                                   MEnd = PP.macro_end(false);
470         M != MEnd; ++M) {
471      if (M->second &&
472          !M->second->isExported() &&
473          !M->second->isBuiltinMacro()) {
474        SourceLocation Loc = M->second->getDefinitionLoc();
475        if (SourceMgr.isInSystemHeader(Loc)) {
476          const FileEntry *File
477            = SourceMgr.getFileEntryForID(SourceMgr.getFileID(Loc));
478          if (File &&
479              ((StringRef(File->getName()).find("lib/clang")
480                  != StringRef::npos) ||
481               (StringRef(File->getName()).find("usr/include")
482                  != StringRef::npos) ||
483               (StringRef(File->getName()).find("usr/local/include")
484                  != StringRef::npos)))
485            M->second->setExportLocation(Loc);
486        }
487      }
488    }
489
490    // Modules don't need any of the checking below.
491    TUScope = 0;
492    return;
493  }
494
495  // C99 6.9.2p2:
496  //   A declaration of an identifier for an object that has file
497  //   scope without an initializer, and without a storage-class
498  //   specifier or with the storage-class specifier static,
499  //   constitutes a tentative definition. If a translation unit
500  //   contains one or more tentative definitions for an identifier,
501  //   and the translation unit contains no external definition for
502  //   that identifier, then the behavior is exactly as if the
503  //   translation unit contains a file scope declaration of that
504  //   identifier, with the composite type as of the end of the
505  //   translation unit, with an initializer equal to 0.
506  llvm::SmallSet<VarDecl *, 32> Seen;
507  for (TentativeDefinitionsType::iterator
508            T = TentativeDefinitions.begin(ExternalSource),
509         TEnd = TentativeDefinitions.end();
510       T != TEnd; ++T)
511  {
512    VarDecl *VD = (*T)->getActingDefinition();
513
514    // If the tentative definition was completed, getActingDefinition() returns
515    // null. If we've already seen this variable before, insert()'s second
516    // return value is false.
517    if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
518      continue;
519
520    if (const IncompleteArrayType *ArrayT
521        = Context.getAsIncompleteArrayType(VD->getType())) {
522      if (RequireCompleteType(VD->getLocation(),
523                              ArrayT->getElementType(),
524                              diag::err_tentative_def_incomplete_type_arr)) {
525        VD->setInvalidDecl();
526        continue;
527      }
528
529      // Set the length of the array to 1 (C99 6.9.2p5).
530      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
531      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
532      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
533                                                One, ArrayType::Normal, 0);
534      VD->setType(T);
535    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
536                                   diag::err_tentative_def_incomplete_type))
537      VD->setInvalidDecl();
538
539    // Notify the consumer that we've completed a tentative definition.
540    if (!VD->isInvalidDecl())
541      Consumer.CompleteTentativeDefinition(VD);
542
543  }
544
545  if (LangOpts.CPlusPlus0x &&
546      Diags.getDiagnosticLevel(diag::warn_delegating_ctor_cycle,
547                               SourceLocation())
548        != DiagnosticsEngine::Ignored)
549    CheckDelegatingCtorCycles();
550
551  // If there were errors, disable 'unused' warnings since they will mostly be
552  // noise.
553  if (!Diags.hasErrorOccurred()) {
554    // Output warning for unused file scoped decls.
555    for (UnusedFileScopedDeclsType::iterator
556           I = UnusedFileScopedDecls.begin(ExternalSource),
557           E = UnusedFileScopedDecls.end(); I != E; ++I) {
558      if (ShouldRemoveFromUnused(this, *I))
559        continue;
560
561      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
562        const FunctionDecl *DiagD;
563        if (!FD->hasBody(DiagD))
564          DiagD = FD;
565        if (DiagD->isDeleted())
566          continue; // Deleted functions are supposed to be unused.
567        if (DiagD->isReferenced()) {
568          if (isa<CXXMethodDecl>(DiagD))
569            Diag(DiagD->getLocation(), diag::warn_unneeded_member_function)
570                  << DiagD->getDeclName();
571          else
572            Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
573                  << /*function*/0 << DiagD->getDeclName();
574        } else {
575          Diag(DiagD->getLocation(),
576               isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
577                                         : diag::warn_unused_function)
578                << DiagD->getDeclName();
579        }
580      } else {
581        const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
582        if (!DiagD)
583          DiagD = cast<VarDecl>(*I);
584        if (DiagD->isReferenced()) {
585          Diag(DiagD->getLocation(), diag::warn_unneeded_internal_decl)
586                << /*variable*/1 << DiagD->getDeclName();
587        } else {
588          Diag(DiagD->getLocation(), diag::warn_unused_variable)
589                << DiagD->getDeclName();
590        }
591      }
592    }
593
594    checkUndefinedInternals(*this);
595  }
596
597  // Check we've noticed that we're no longer parsing the initializer for every
598  // variable. If we miss cases, then at best we have a performance issue and
599  // at worst a rejects-valid bug.
600  assert(ParsingInitForAutoVars.empty() &&
601         "Didn't unmark var as having its initializer parsed");
602
603  TUScope = 0;
604}
605
606
607//===----------------------------------------------------------------------===//
608// Helper functions.
609//===----------------------------------------------------------------------===//
610
611DeclContext *Sema::getFunctionLevelDeclContext() {
612  DeclContext *DC = CurContext;
613
614  while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
615    DC = DC->getParent();
616
617  return DC;
618}
619
620/// getCurFunctionDecl - If inside of a function body, this returns a pointer
621/// to the function decl for the function being parsed.  If we're currently
622/// in a 'block', this returns the containing context.
623FunctionDecl *Sema::getCurFunctionDecl() {
624  DeclContext *DC = getFunctionLevelDeclContext();
625  return dyn_cast<FunctionDecl>(DC);
626}
627
628ObjCMethodDecl *Sema::getCurMethodDecl() {
629  DeclContext *DC = getFunctionLevelDeclContext();
630  return dyn_cast<ObjCMethodDecl>(DC);
631}
632
633NamedDecl *Sema::getCurFunctionOrMethodDecl() {
634  DeclContext *DC = getFunctionLevelDeclContext();
635  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
636    return cast<NamedDecl>(DC);
637  return 0;
638}
639
640Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
641  if (!isActive())
642    return;
643
644  if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) {
645    switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) {
646    case DiagnosticIDs::SFINAE_Report:
647      // Fall through; we'll report the diagnostic below.
648      break;
649
650    case DiagnosticIDs::SFINAE_AccessControl:
651      // Per C++ Core Issue 1170, access control is part of SFINAE.
652      // Additionally, the AccessCheckingSFINAE flag can be used to temporary
653      // make access control a part of SFINAE for the purposes of checking
654      // type traits.
655      if (!SemaRef.AccessCheckingSFINAE &&
656          !SemaRef.getLangOptions().CPlusPlus0x)
657        break;
658
659    case DiagnosticIDs::SFINAE_SubstitutionFailure:
660      // Count this failure so that we know that template argument deduction
661      // has failed.
662      ++SemaRef.NumSFINAEErrors;
663      SemaRef.Diags.setLastDiagnosticIgnored();
664      SemaRef.Diags.Clear();
665      Clear();
666      return;
667
668    case DiagnosticIDs::SFINAE_Suppress:
669      // Make a copy of this suppressed diagnostic and store it with the
670      // template-deduction information;
671      FlushCounts();
672      Diagnostic DiagInfo(&SemaRef.Diags);
673
674      if (*Info)
675        (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
676                        PartialDiagnostic(DiagInfo,
677                                          SemaRef.Context.getDiagAllocator()));
678
679      // Suppress this diagnostic.
680      SemaRef.Diags.setLastDiagnosticIgnored();
681      SemaRef.Diags.Clear();
682      Clear();
683      return;
684    }
685  }
686
687  // Emit the diagnostic.
688  if (!this->Emit())
689    return;
690
691  // If this is not a note, and we're in a template instantiation
692  // that is different from the last template instantiation where
693  // we emitted an error, print a template instantiation
694  // backtrace.
695  if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
696      !SemaRef.ActiveTemplateInstantiations.empty() &&
697      SemaRef.ActiveTemplateInstantiations.back()
698        != SemaRef.LastTemplateInstantiationErrorContext) {
699    SemaRef.PrintInstantiationStack();
700    SemaRef.LastTemplateInstantiationErrorContext
701      = SemaRef.ActiveTemplateInstantiations.back();
702  }
703}
704
705Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
706  DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
707  return SemaDiagnosticBuilder(DB, *this, DiagID);
708}
709
710Sema::SemaDiagnosticBuilder
711Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
712  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
713  PD.Emit(Builder);
714
715  return Builder;
716}
717
718/// \brief Looks through the macro-expansion chain for the given
719/// location, looking for a macro expansion with the given name.
720/// If one is found, returns true and sets the location to that
721/// expansion loc.
722bool Sema::findMacroSpelling(SourceLocation &locref, StringRef name) {
723  SourceLocation loc = locref;
724  if (!loc.isMacroID()) return false;
725
726  // There's no good way right now to look at the intermediate
727  // expansions, so just jump to the expansion location.
728  loc = getSourceManager().getExpansionLoc(loc);
729
730  // If that's written with the name, stop here.
731  SmallVector<char, 16> buffer;
732  if (getPreprocessor().getSpelling(loc, buffer) == name) {
733    locref = loc;
734    return true;
735  }
736  return false;
737}
738
739/// \brief Determines the active Scope associated with the given declaration
740/// context.
741///
742/// This routine maps a declaration context to the active Scope object that
743/// represents that declaration context in the parser. It is typically used
744/// from "scope-less" code (e.g., template instantiation, lazy creation of
745/// declarations) that injects a name for name-lookup purposes and, therefore,
746/// must update the Scope.
747///
748/// \returns The scope corresponding to the given declaraion context, or NULL
749/// if no such scope is open.
750Scope *Sema::getScopeForContext(DeclContext *Ctx) {
751
752  if (!Ctx)
753    return 0;
754
755  Ctx = Ctx->getPrimaryContext();
756  for (Scope *S = getCurScope(); S; S = S->getParent()) {
757    // Ignore scopes that cannot have declarations. This is important for
758    // out-of-line definitions of static class members.
759    if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
760      if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
761        if (Ctx == Entity->getPrimaryContext())
762          return S;
763  }
764
765  return 0;
766}
767
768/// \brief Enter a new function scope
769void Sema::PushFunctionScope() {
770  if (FunctionScopes.size() == 1) {
771    // Use the "top" function scope rather than having to allocate
772    // memory for a new scope.
773    FunctionScopes.back()->Clear();
774    FunctionScopes.push_back(FunctionScopes.back());
775    return;
776  }
777
778  FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
779}
780
781void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
782  FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
783                                              BlockScope, Block));
784}
785
786void Sema::PopFunctionOrBlockScope(const AnalysisBasedWarnings::Policy *WP,
787                                   const Decl *D, const BlockExpr *blkExpr) {
788  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
789  assert(!FunctionScopes.empty() && "mismatched push/pop!");
790
791  // Issue any analysis-based warnings.
792  if (WP && D)
793    AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
794  else {
795    for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
796         i = Scope->PossiblyUnreachableDiags.begin(),
797         e = Scope->PossiblyUnreachableDiags.end();
798         i != e; ++i) {
799      const sema::PossiblyUnreachableDiag &D = *i;
800      Diag(D.Loc, D.PD);
801    }
802  }
803
804  if (FunctionScopes.back() != Scope) {
805    delete Scope;
806  }
807}
808
809/// \brief Determine whether any errors occurred within this function/method/
810/// block.
811bool Sema::hasAnyUnrecoverableErrorsInThisFunction() const {
812  return getCurFunction()->ErrorTrap.hasUnrecoverableErrorOccurred();
813}
814
815BlockScopeInfo *Sema::getCurBlock() {
816  if (FunctionScopes.empty())
817    return 0;
818
819  return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
820}
821
822// Pin this vtable to this file.
823ExternalSemaSource::~ExternalSemaSource() {}
824
825std::pair<ObjCMethodList, ObjCMethodList>
826ExternalSemaSource::ReadMethodPool(Selector Sel) {
827  return std::pair<ObjCMethodList, ObjCMethodList>();
828}
829
830void ExternalSemaSource::ReadKnownNamespaces(
831                           SmallVectorImpl<NamespaceDecl *> &Namespaces) {
832}
833
834void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
835  SourceLocation Loc = this->Loc;
836  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
837  if (Loc.isValid()) {
838    Loc.print(OS, S.getSourceManager());
839    OS << ": ";
840  }
841  OS << Message;
842
843  if (TheDecl && isa<NamedDecl>(TheDecl)) {
844    std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
845    if (!Name.empty())
846      OS << " '" << Name << '\'';
847  }
848
849  OS << '\n';
850}
851
852/// \brief Figure out if an expression could be turned into a call.
853///
854/// Use this when trying to recover from an error where the programmer may have
855/// written just the name of a function instead of actually calling it.
856///
857/// \param E - The expression to examine.
858/// \param ZeroArgCallReturnTy - If the expression can be turned into a call
859///  with no arguments, this parameter is set to the type returned by such a
860///  call; otherwise, it is set to an empty QualType.
861/// \param NonTemplateOverloads - If the expression is an overloaded function
862///  name, this parameter is populated with the decls of the various overloads.
863bool Sema::isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy,
864                          UnresolvedSetImpl &NonTemplateOverloads) {
865  ZeroArgCallReturnTy = QualType();
866  NonTemplateOverloads.clear();
867  if (const OverloadExpr *Overloads = dyn_cast<OverloadExpr>(&E)) {
868    for (OverloadExpr::decls_iterator it = Overloads->decls_begin(),
869         DeclsEnd = Overloads->decls_end(); it != DeclsEnd; ++it) {
870      // Our overload set may include TemplateDecls, which we'll ignore for our
871      // present purpose.
872      if (const FunctionDecl *OverloadDecl = dyn_cast<FunctionDecl>(*it)) {
873        NonTemplateOverloads.addDecl(*it);
874        if (OverloadDecl->getMinRequiredArguments() == 0)
875          ZeroArgCallReturnTy = OverloadDecl->getResultType();
876      }
877    }
878    return true;
879  }
880
881  if (const DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(&E)) {
882    if (const FunctionDecl *Fun = dyn_cast<FunctionDecl>(DeclRef->getDecl())) {
883      if (Fun->getMinRequiredArguments() == 0)
884        ZeroArgCallReturnTy = Fun->getResultType();
885      return true;
886    }
887  }
888
889  // We don't have an expression that's convenient to get a FunctionDecl from,
890  // but we can at least check if the type is "function of 0 arguments".
891  QualType ExprTy = E.getType();
892  const FunctionType *FunTy = NULL;
893  QualType PointeeTy = ExprTy->getPointeeType();
894  if (!PointeeTy.isNull())
895    FunTy = PointeeTy->getAs<FunctionType>();
896  if (!FunTy)
897    FunTy = ExprTy->getAs<FunctionType>();
898  if (!FunTy && ExprTy == Context.BoundMemberTy) {
899    // Look for the bound-member type.  If it's still overloaded, give up,
900    // although we probably should have fallen into the OverloadExpr case above
901    // if we actually have an overloaded bound member.
902    QualType BoundMemberTy = Expr::findBoundMemberType(&E);
903    if (!BoundMemberTy.isNull())
904      FunTy = BoundMemberTy->castAs<FunctionType>();
905  }
906
907  if (const FunctionProtoType *FPT =
908      dyn_cast_or_null<FunctionProtoType>(FunTy)) {
909    if (FPT->getNumArgs() == 0)
910      ZeroArgCallReturnTy = FunTy->getResultType();
911    return true;
912  }
913  return false;
914}
915
916/// \brief Give notes for a set of overloads.
917///
918/// A companion to isExprCallable. In cases when the name that the programmer
919/// wrote was an overloaded function, we may be able to make some guesses about
920/// plausible overloads based on their return types; such guesses can be handed
921/// off to this method to be emitted as notes.
922///
923/// \param Overloads - The overloads to note.
924/// \param FinalNoteLoc - If we've suppressed printing some overloads due to
925///  -fshow-overloads=best, this is the location to attach to the note about too
926///  many candidates. Typically this will be the location of the original
927///  ill-formed expression.
928void Sema::NoteOverloads(const UnresolvedSetImpl &Overloads,
929                         const SourceLocation FinalNoteLoc) {
930  int ShownOverloads = 0;
931  int SuppressedOverloads = 0;
932  for (UnresolvedSetImpl::iterator It = Overloads.begin(),
933       DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
934    // FIXME: Magic number for max shown overloads stolen from
935    // OverloadCandidateSet::NoteCandidates.
936    if (ShownOverloads >= 4 &&
937        Diags.getShowOverloads() == DiagnosticsEngine::Ovl_Best) {
938      ++SuppressedOverloads;
939      continue;
940    }
941    Diag(cast<FunctionDecl>(*It)->getSourceRange().getBegin(),
942         diag::note_member_ref_possible_intended_overload);
943    ++ShownOverloads;
944  }
945  if (SuppressedOverloads)
946    Diag(FinalNoteLoc, diag::note_ovl_too_many_candidates)
947        << SuppressedOverloads;
948}
949