Sema.cpp revision 48b89590f61575cbf365ba996a2bd1ba1561a4ab
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/StmtCXX.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Basic/PartialDiagnostic.h"
37#include "clang/Basic/TargetInfo.h"
38using namespace clang;
39using namespace sema;
40
41FunctionScopeInfo::~FunctionScopeInfo() { }
42
43void FunctionScopeInfo::Clear() {
44  HasBranchProtectedScope = false;
45  HasBranchIntoScope = false;
46  HasIndirectGoto = false;
47
48  SwitchStack.clear();
49  Returns.clear();
50  ErrorTrap.reset();
51  PossiblyUnreachableDiags.clear();
52}
53
54BlockScopeInfo::~BlockScopeInfo() { }
55
56void Sema::ActOnTranslationUnitScope(Scope *S) {
57  TUScope = S;
58  PushDeclContext(S, Context.getTranslationUnitDecl());
59
60  VAListTagName = PP.getIdentifierInfo("__va_list_tag");
61
62  if (!Context.isInt128Installed() && // May be set by ASTReader.
63      PP.getTargetInfo().getPointerWidth(0) >= 64) {
64    TypeSourceInfo *TInfo;
65
66    // Install [u]int128_t for 64-bit targets.
67    TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
68    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
69                                          SourceLocation(),
70                                          &Context.Idents.get("__int128_t"),
71                                          TInfo), TUScope);
72
73    TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
74    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
75                                          SourceLocation(),
76                                          &Context.Idents.get("__uint128_t"),
77                                          TInfo), TUScope);
78    Context.setInt128Installed();
79  }
80
81
82  if (!PP.getLangOptions().ObjC1) return;
83
84  // Built-in ObjC types may already be set by ASTReader (hence isNull checks).
85  if (Context.getObjCSelType().isNull()) {
86    // Create the built-in typedef for 'SEL'.
87    QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
88    TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
89    TypedefDecl *SelTypedef
90      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
91                            &Context.Idents.get("SEL"), SelInfo);
92    PushOnScopeChains(SelTypedef, TUScope);
93    Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
94    Context.ObjCSelRedefinitionType = Context.getObjCSelType();
95  }
96
97  // Synthesize "@class Protocol;
98  if (Context.getObjCProtoType().isNull()) {
99    ObjCInterfaceDecl *ProtocolDecl =
100      ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
101                                &Context.Idents.get("Protocol"),
102                                SourceLocation(), true);
103    Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
104    PushOnScopeChains(ProtocolDecl, TUScope, false);
105  }
106  // Create the built-in typedef for 'id'.
107  if (Context.getObjCIdType().isNull()) {
108    QualType T = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 0, 0);
109    T = Context.getObjCObjectPointerType(T);
110    TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(T);
111    TypedefDecl *IdTypedef
112      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
113                            &Context.Idents.get("id"), IdInfo);
114    PushOnScopeChains(IdTypedef, TUScope);
115    Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
116    Context.ObjCIdRedefinitionType = Context.getObjCIdType();
117  }
118  // Create the built-in typedef for 'Class'.
119  if (Context.getObjCClassType().isNull()) {
120    QualType T = Context.getObjCObjectType(Context.ObjCBuiltinClassTy, 0, 0);
121    T = Context.getObjCObjectPointerType(T);
122    TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(T);
123    TypedefDecl *ClassTypedef
124      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
125                            &Context.Idents.get("Class"), ClassInfo);
126    PushOnScopeChains(ClassTypedef, TUScope);
127    Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
128    Context.ObjCClassRedefinitionType = Context.getObjCClassType();
129  }
130}
131
132Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
133           bool CompleteTranslationUnit,
134           CodeCompleteConsumer *CodeCompleter)
135  : TheTargetAttributesSema(0), FPFeatures(pp.getLangOptions()),
136    LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
137    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
138    ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
139    PackContext(0), VisContext(0),
140    IdResolver(pp.getLangOptions()), CXXTypeInfoDecl(0), MSVCGuidDecl(0),
141    GlobalNewDeleteDeclared(false),
142    CompleteTranslationUnit(CompleteTranslationUnit),
143    NumSFINAEErrors(0), SuppressAccessChecking(false),
144    AccessCheckingSFINAE(false), InNonInstantiationSFINAEContext(false),
145    NonInstantiationEntries(0), ArgumentPackSubstitutionIndex(-1),
146    CurrentInstantiationScope(0), TyposCorrected(0),
147    AnalysisWarnings(*this)
148{
149  TUScope = 0;
150  if (getLangOptions().CPlusPlus)
151    FieldCollector.reset(new CXXFieldCollector());
152
153  // Tell diagnostics how to render things from the AST library.
154  PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
155                                       &Context);
156
157  ExprEvalContexts.push_back(
158                  ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
159
160  FunctionScopes.push_back(new FunctionScopeInfo(Diags));
161}
162
163void Sema::Initialize() {
164  // Tell the AST consumer about this Sema object.
165  Consumer.Initialize(Context);
166
167  // FIXME: Isn't this redundant with the initialization above?
168  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
169    SC->InitializeSema(*this);
170
171  // Tell the external Sema source about this Sema object.
172  if (ExternalSemaSource *ExternalSema
173      = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
174    ExternalSema->InitializeSema(*this);
175}
176
177Sema::~Sema() {
178  if (PackContext) FreePackedContext();
179  if (VisContext) FreeVisContext();
180  delete TheTargetAttributesSema;
181
182  // Kill all the active scopes.
183  for (unsigned I = 1, E = FunctionScopes.size(); I != E; ++I)
184    delete FunctionScopes[I];
185  if (FunctionScopes.size() == 1)
186    delete FunctionScopes[0];
187
188  // Tell the SemaConsumer to forget about us; we're going out of scope.
189  if (SemaConsumer *SC = dyn_cast<SemaConsumer>(&Consumer))
190    SC->ForgetSema();
191
192  // Detach from the external Sema source.
193  if (ExternalSemaSource *ExternalSema
194        = dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
195    ExternalSema->ForgetSema();
196}
197
198/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
199/// If there is already an implicit cast, merge into the existing one.
200/// The result is of the given category.
201void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
202                             CastKind Kind, ExprValueKind VK,
203                             const CXXCastPath *BasePath) {
204  QualType ExprTy = Context.getCanonicalType(Expr->getType());
205  QualType TypeTy = Context.getCanonicalType(Ty);
206
207  if (ExprTy == TypeTy)
208    return;
209
210  // If this is a derived-to-base cast to a through a virtual base, we
211  // need a vtable.
212  if (Kind == CK_DerivedToBase &&
213      BasePathInvolvesVirtualBase(*BasePath)) {
214    QualType T = Expr->getType();
215    if (const PointerType *Pointer = T->getAs<PointerType>())
216      T = Pointer->getPointeeType();
217    if (const RecordType *RecordTy = T->getAs<RecordType>())
218      MarkVTableUsed(Expr->getLocStart(),
219                     cast<CXXRecordDecl>(RecordTy->getDecl()));
220  }
221
222  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
223    if (ImpCast->getCastKind() == Kind && (!BasePath || BasePath->empty())) {
224      ImpCast->setType(Ty);
225      ImpCast->setValueKind(VK);
226      return;
227    }
228  }
229
230  Expr = ImplicitCastExpr::Create(Context, Ty, Kind, Expr, BasePath, VK);
231}
232
233ExprValueKind Sema::CastCategory(Expr *E) {
234  Expr::Classification Classification = E->Classify(Context);
235  return Classification.isRValue() ? VK_RValue :
236      (Classification.isLValue() ? VK_LValue : VK_XValue);
237}
238
239/// \brief Used to prune the decls of Sema's UnusedFileScopedDecls vector.
240static bool ShouldRemoveFromUnused(Sema *SemaRef, const DeclaratorDecl *D) {
241  if (D->isUsed())
242    return true;
243
244  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245    // UnusedFileScopedDecls stores the first declaration.
246    // The declaration may have become definition so check again.
247    const FunctionDecl *DeclToCheck;
248    if (FD->hasBody(DeclToCheck))
249      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
250
251    // Later redecls may add new information resulting in not having to warn,
252    // so check again.
253    DeclToCheck = FD->getMostRecentDeclaration();
254    if (DeclToCheck != FD)
255      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
256  }
257
258  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
259    // UnusedFileScopedDecls stores the first declaration.
260    // The declaration may have become definition so check again.
261    const VarDecl *DeclToCheck = VD->getDefinition();
262    if (DeclToCheck)
263      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
264
265    // Later redecls may add new information resulting in not having to warn,
266    // so check again.
267    DeclToCheck = VD->getMostRecentDeclaration();
268    if (DeclToCheck != VD)
269      return !SemaRef->ShouldWarnIfUnusedFileScopedDecl(DeclToCheck);
270  }
271
272  return false;
273}
274
275namespace {
276  struct UndefinedInternal {
277    NamedDecl *decl;
278    FullSourceLoc useLoc;
279
280    UndefinedInternal(NamedDecl *decl, FullSourceLoc useLoc)
281      : decl(decl), useLoc(useLoc) {}
282  };
283
284  bool operator<(const UndefinedInternal &l, const UndefinedInternal &r) {
285    return l.useLoc.isBeforeInTranslationUnitThan(r.useLoc);
286  }
287}
288
289/// checkUndefinedInternals - Check for undefined objects with internal linkage.
290static void checkUndefinedInternals(Sema &S) {
291  if (S.UndefinedInternals.empty()) return;
292
293  // Collect all the still-undefined entities with internal linkage.
294  llvm::SmallVector<UndefinedInternal, 16> undefined;
295  for (llvm::DenseMap<NamedDecl*,SourceLocation>::iterator
296         i = S.UndefinedInternals.begin(), e = S.UndefinedInternals.end();
297       i != e; ++i) {
298    NamedDecl *decl = i->first;
299
300    // Ignore attributes that have become invalid.
301    if (decl->isInvalidDecl()) continue;
302
303    // __attribute__((weakref)) is basically a definition.
304    if (decl->hasAttr<WeakRefAttr>()) continue;
305
306    if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
307      if (fn->isPure() || fn->hasBody())
308        continue;
309    } else {
310      if (cast<VarDecl>(decl)->hasDefinition() != VarDecl::DeclarationOnly)
311        continue;
312    }
313
314    // We build a FullSourceLoc so that we can sort with array_pod_sort.
315    FullSourceLoc loc(i->second, S.Context.getSourceManager());
316    undefined.push_back(UndefinedInternal(decl, loc));
317  }
318
319  if (undefined.empty()) return;
320
321  // Sort (in order of use site) so that we're not (as) dependent on
322  // the iteration order through an llvm::DenseMap.
323  llvm::array_pod_sort(undefined.begin(), undefined.end());
324
325  for (llvm::SmallVectorImpl<UndefinedInternal>::iterator
326         i = undefined.begin(), e = undefined.end(); i != e; ++i) {
327    NamedDecl *decl = i->decl;
328    S.Diag(decl->getLocation(), diag::warn_undefined_internal)
329      << isa<VarDecl>(decl) << decl;
330    S.Diag(i->useLoc, diag::note_used_here);
331  }
332}
333
334/// ActOnEndOfTranslationUnit - This is called at the very end of the
335/// translation unit when EOF is reached and all but the top-level scope is
336/// popped.
337void Sema::ActOnEndOfTranslationUnit() {
338  // At PCH writing, implicit instantiations and VTable handling info are
339  // stored and performed when the PCH is included.
340  if (CompleteTranslationUnit) {
341    // If any dynamic classes have their key function defined within
342    // this translation unit, then those vtables are considered "used" and must
343    // be emitted.
344    for (unsigned I = 0, N = DynamicClasses.size(); I != N; ++I) {
345      assert(!DynamicClasses[I]->isDependentType() &&
346             "Should not see dependent types here!");
347      if (const CXXMethodDecl *KeyFunction
348          = Context.getKeyFunction(DynamicClasses[I])) {
349        const FunctionDecl *Definition = 0;
350        if (KeyFunction->hasBody(Definition))
351          MarkVTableUsed(Definition->getLocation(), DynamicClasses[I], true);
352      }
353    }
354
355    // If DefinedUsedVTables ends up marking any virtual member functions it
356    // might lead to more pending template instantiations, which we then need
357    // to instantiate.
358    DefineUsedVTables();
359
360    // C++: Perform implicit template instantiations.
361    //
362    // FIXME: When we perform these implicit instantiations, we do not
363    // carefully keep track of the point of instantiation (C++ [temp.point]).
364    // This means that name lookup that occurs within the template
365    // instantiation will always happen at the end of the translation unit,
366    // so it will find some names that should not be found. Although this is
367    // common behavior for C++ compilers, it is technically wrong. In the
368    // future, we either need to be able to filter the results of name lookup
369    // or we need to perform template instantiations earlier.
370    PerformPendingInstantiations();
371  }
372
373  // Remove file scoped decls that turned out to be used.
374  UnusedFileScopedDecls.erase(std::remove_if(UnusedFileScopedDecls.begin(),
375                                             UnusedFileScopedDecls.end(),
376                              std::bind1st(std::ptr_fun(ShouldRemoveFromUnused),
377                                           this)),
378                              UnusedFileScopedDecls.end());
379
380  if (!CompleteTranslationUnit) {
381    TUScope = 0;
382    return;
383  }
384
385  // Check for #pragma weak identifiers that were never declared
386  // FIXME: This will cause diagnostics to be emitted in a non-determinstic
387  // order!  Iterating over a densemap like this is bad.
388  for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
389       I = WeakUndeclaredIdentifiers.begin(),
390       E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
391    if (I->second.getUsed()) continue;
392
393    Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
394      << I->first;
395  }
396
397  // C99 6.9.2p2:
398  //   A declaration of an identifier for an object that has file
399  //   scope without an initializer, and without a storage-class
400  //   specifier or with the storage-class specifier static,
401  //   constitutes a tentative definition. If a translation unit
402  //   contains one or more tentative definitions for an identifier,
403  //   and the translation unit contains no external definition for
404  //   that identifier, then the behavior is exactly as if the
405  //   translation unit contains a file scope declaration of that
406  //   identifier, with the composite type as of the end of the
407  //   translation unit, with an initializer equal to 0.
408  llvm::SmallSet<VarDecl *, 32> Seen;
409  for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
410    VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
411
412    // If the tentative definition was completed, getActingDefinition() returns
413    // null. If we've already seen this variable before, insert()'s second
414    // return value is false.
415    if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
416      continue;
417
418    if (const IncompleteArrayType *ArrayT
419        = Context.getAsIncompleteArrayType(VD->getType())) {
420      if (RequireCompleteType(VD->getLocation(),
421                              ArrayT->getElementType(),
422                              diag::err_tentative_def_incomplete_type_arr)) {
423        VD->setInvalidDecl();
424        continue;
425      }
426
427      // Set the length of the array to 1 (C99 6.9.2p5).
428      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
429      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
430      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
431                                                One, ArrayType::Normal, 0);
432      VD->setType(T);
433    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
434                                   diag::err_tentative_def_incomplete_type))
435      VD->setInvalidDecl();
436
437    // Notify the consumer that we've completed a tentative definition.
438    if (!VD->isInvalidDecl())
439      Consumer.CompleteTentativeDefinition(VD);
440
441  }
442
443  // If there were errors, disable 'unused' warnings since they will mostly be
444  // noise.
445  if (!Diags.hasErrorOccurred()) {
446    // Output warning for unused file scoped decls.
447    for (llvm::SmallVectorImpl<const DeclaratorDecl*>::iterator
448           I = UnusedFileScopedDecls.begin(),
449           E = UnusedFileScopedDecls.end(); I != E; ++I) {
450      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
451        const FunctionDecl *DiagD;
452        if (!FD->hasBody(DiagD))
453          DiagD = FD;
454        if (DiagD->isDeleted())
455          continue; // Deleted functions are supposed to be unused.
456        Diag(DiagD->getLocation(),
457             isa<CXXMethodDecl>(DiagD) ? diag::warn_unused_member_function
458                                       : diag::warn_unused_function)
459              << DiagD->getDeclName();
460      } else {
461        const VarDecl *DiagD = cast<VarDecl>(*I)->getDefinition();
462        if (!DiagD)
463          DiagD = cast<VarDecl>(*I);
464        Diag(DiagD->getLocation(), diag::warn_unused_variable)
465              << DiagD->getDeclName();
466      }
467    }
468
469    checkUndefinedInternals(*this);
470  }
471
472  // Check we've noticed that we're no longer parsing the initializer for every
473  // variable. If we miss cases, then at best we have a performance issue and
474  // at worst a rejects-valid bug.
475  assert(ParsingInitForAutoVars.empty() &&
476         "Didn't unmark var as having its initializer parsed");
477
478  TUScope = 0;
479}
480
481
482//===----------------------------------------------------------------------===//
483// Helper functions.
484//===----------------------------------------------------------------------===//
485
486DeclContext *Sema::getFunctionLevelDeclContext() {
487  DeclContext *DC = CurContext;
488
489  while (isa<BlockDecl>(DC) || isa<EnumDecl>(DC))
490    DC = DC->getParent();
491
492  return DC;
493}
494
495/// getCurFunctionDecl - If inside of a function body, this returns a pointer
496/// to the function decl for the function being parsed.  If we're currently
497/// in a 'block', this returns the containing context.
498FunctionDecl *Sema::getCurFunctionDecl() {
499  DeclContext *DC = getFunctionLevelDeclContext();
500  return dyn_cast<FunctionDecl>(DC);
501}
502
503ObjCMethodDecl *Sema::getCurMethodDecl() {
504  DeclContext *DC = getFunctionLevelDeclContext();
505  return dyn_cast<ObjCMethodDecl>(DC);
506}
507
508NamedDecl *Sema::getCurFunctionOrMethodDecl() {
509  DeclContext *DC = getFunctionLevelDeclContext();
510  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
511    return cast<NamedDecl>(DC);
512  return 0;
513}
514
515Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
516  if (!isActive())
517    return;
518
519  if (llvm::Optional<TemplateDeductionInfo*> Info = SemaRef.isSFINAEContext()) {
520    switch (DiagnosticIDs::getDiagnosticSFINAEResponse(getDiagID())) {
521    case DiagnosticIDs::SFINAE_Report:
522      // Fall through; we'll report the diagnostic below.
523      break;
524
525    case DiagnosticIDs::SFINAE_AccessControl:
526      // Unless access checking is specifically called out as a SFINAE
527      // error, report this diagnostic.
528      if (!SemaRef.AccessCheckingSFINAE)
529        break;
530
531    case DiagnosticIDs::SFINAE_SubstitutionFailure:
532      // Count this failure so that we know that template argument deduction
533      // has failed.
534      ++SemaRef.NumSFINAEErrors;
535      SemaRef.Diags.setLastDiagnosticIgnored();
536      SemaRef.Diags.Clear();
537      Clear();
538      return;
539
540    case DiagnosticIDs::SFINAE_Suppress:
541      // Make a copy of this suppressed diagnostic and store it with the
542      // template-deduction information;
543      FlushCounts();
544      DiagnosticInfo DiagInfo(&SemaRef.Diags);
545
546      if (*Info)
547        (*Info)->addSuppressedDiagnostic(DiagInfo.getLocation(),
548                        PartialDiagnostic(DiagInfo,
549                                          SemaRef.Context.getDiagAllocator()));
550
551      // Suppress this diagnostic.
552      SemaRef.Diags.setLastDiagnosticIgnored();
553      SemaRef.Diags.Clear();
554      Clear();
555      return;
556    }
557  }
558
559  // Emit the diagnostic.
560  if (!this->Emit())
561    return;
562
563  // If this is not a note, and we're in a template instantiation
564  // that is different from the last template instantiation where
565  // we emitted an error, print a template instantiation
566  // backtrace.
567  if (!DiagnosticIDs::isBuiltinNote(DiagID) &&
568      !SemaRef.ActiveTemplateInstantiations.empty() &&
569      SemaRef.ActiveTemplateInstantiations.back()
570        != SemaRef.LastTemplateInstantiationErrorContext) {
571    SemaRef.PrintInstantiationStack();
572    SemaRef.LastTemplateInstantiationErrorContext
573      = SemaRef.ActiveTemplateInstantiations.back();
574  }
575}
576
577Sema::SemaDiagnosticBuilder Sema::Diag(SourceLocation Loc, unsigned DiagID) {
578  DiagnosticBuilder DB = Diags.Report(Loc, DiagID);
579  return SemaDiagnosticBuilder(DB, *this, DiagID);
580}
581
582Sema::SemaDiagnosticBuilder
583Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
584  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
585  PD.Emit(Builder);
586
587  return Builder;
588}
589
590/// \brief Determines the active Scope associated with the given declaration
591/// context.
592///
593/// This routine maps a declaration context to the active Scope object that
594/// represents that declaration context in the parser. It is typically used
595/// from "scope-less" code (e.g., template instantiation, lazy creation of
596/// declarations) that injects a name for name-lookup purposes and, therefore,
597/// must update the Scope.
598///
599/// \returns The scope corresponding to the given declaraion context, or NULL
600/// if no such scope is open.
601Scope *Sema::getScopeForContext(DeclContext *Ctx) {
602
603  if (!Ctx)
604    return 0;
605
606  Ctx = Ctx->getPrimaryContext();
607  for (Scope *S = getCurScope(); S; S = S->getParent()) {
608    // Ignore scopes that cannot have declarations. This is important for
609    // out-of-line definitions of static class members.
610    if (S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope))
611      if (DeclContext *Entity = static_cast<DeclContext *> (S->getEntity()))
612        if (Ctx == Entity->getPrimaryContext())
613          return S;
614  }
615
616  return 0;
617}
618
619/// \brief Enter a new function scope
620void Sema::PushFunctionScope() {
621  if (FunctionScopes.size() == 1) {
622    // Use the "top" function scope rather than having to allocate
623    // memory for a new scope.
624    FunctionScopes.back()->Clear();
625    FunctionScopes.push_back(FunctionScopes.back());
626    return;
627  }
628
629  FunctionScopes.push_back(new FunctionScopeInfo(getDiagnostics()));
630}
631
632void Sema::PushBlockScope(Scope *BlockScope, BlockDecl *Block) {
633  FunctionScopes.push_back(new BlockScopeInfo(getDiagnostics(),
634                                              BlockScope, Block));
635}
636
637void Sema::PopFunctionOrBlockScope(const AnalysisBasedWarnings::Policy *WP,
638                                   const Decl *D, const BlockExpr *blkExpr) {
639  FunctionScopeInfo *Scope = FunctionScopes.pop_back_val();
640  assert(!FunctionScopes.empty() && "mismatched push/pop!");
641
642  // Issue any analysis-based warnings.
643  if (WP && D)
644    AnalysisWarnings.IssueWarnings(*WP, Scope, D, blkExpr);
645  else {
646    for (llvm::SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
647         i = Scope->PossiblyUnreachableDiags.begin(),
648         e = Scope->PossiblyUnreachableDiags.end();
649         i != e; ++i) {
650      const sema::PossiblyUnreachableDiag &D = *i;
651      Diag(D.Loc, D.PD);
652    }
653  }
654
655  if (FunctionScopes.back() != Scope) {
656    delete Scope;
657  }
658}
659
660/// \brief Determine whether any errors occurred within this function/method/
661/// block.
662bool Sema::hasAnyErrorsInThisFunction() const {
663  return getCurFunction()->ErrorTrap.hasErrorOccurred();
664}
665
666BlockScopeInfo *Sema::getCurBlock() {
667  if (FunctionScopes.empty())
668    return 0;
669
670  return dyn_cast<BlockScopeInfo>(FunctionScopes.back());
671}
672
673// Pin this vtable to this file.
674ExternalSemaSource::~ExternalSemaSource() {}
675
676std::pair<ObjCMethodList, ObjCMethodList>
677ExternalSemaSource::ReadMethodPool(Selector Sel) {
678  return std::pair<ObjCMethodList, ObjCMethodList>();
679}
680
681void PrettyDeclStackTraceEntry::print(llvm::raw_ostream &OS) const {
682  SourceLocation Loc = this->Loc;
683  if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
684  if (Loc.isValid()) {
685    Loc.print(OS, S.getSourceManager());
686    OS << ": ";
687  }
688  OS << Message;
689
690  if (TheDecl && isa<NamedDecl>(TheDecl)) {
691    std::string Name = cast<NamedDecl>(TheDecl)->getNameAsString();
692    if (!Name.empty())
693      OS << " '" << Name << '\'';
694  }
695
696  OS << '\n';
697}
698