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