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