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