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