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