Sema.cpp revision 6d97e5e4b7abdae710c2548b51f4ed0298e86d80
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
30static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
31  if (C.getLangOptions().CPlusPlus)
32    return CXXRecordDecl::Create(C, TagDecl::TK_struct,
33                                 C.getTranslationUnitDecl(),
34                                 SourceLocation(), &C.Idents.get(Name));
35
36  return RecordDecl::Create(C, TagDecl::TK_struct,
37                            C.getTranslationUnitDecl(),
38                            SourceLocation(), &C.Idents.get(Name));
39}
40
41void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
42  TUScope = S;
43  PushDeclContext(S, Context.getTranslationUnitDecl());
44
45  if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
46    TypeSourceInfo *TInfo;
47
48    // Install [u]int128_t for 64-bit targets.
49    TInfo = Context.getTrivialTypeSourceInfo(Context.Int128Ty);
50    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
51                                          SourceLocation(),
52                                          &Context.Idents.get("__int128_t"),
53                                          TInfo), TUScope);
54
55    TInfo = Context.getTrivialTypeSourceInfo(Context.UnsignedInt128Ty);
56    PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
57                                          SourceLocation(),
58                                          &Context.Idents.get("__uint128_t"),
59                                          TInfo), TUScope);
60  }
61
62
63  if (!PP.getLangOptions().ObjC1) return;
64
65  // Built-in ObjC types may already be set by PCHReader (hence isNull checks).
66  if (Context.getObjCSelType().isNull()) {
67    // Create the built-in typedef for 'SEL'.
68    QualType SelT = Context.getPointerType(Context.ObjCBuiltinSelTy);
69    TypeSourceInfo *SelInfo = Context.getTrivialTypeSourceInfo(SelT);
70    TypedefDecl *SelTypedef
71      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
72                            &Context.Idents.get("SEL"), SelInfo);
73    PushOnScopeChains(SelTypedef, TUScope);
74    Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
75    Context.ObjCSelRedefinitionType = Context.getObjCSelType();
76  }
77
78  // Synthesize "@class Protocol;
79  if (Context.getObjCProtoType().isNull()) {
80    ObjCInterfaceDecl *ProtocolDecl =
81      ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
82                                &Context.Idents.get("Protocol"),
83                                SourceLocation(), true);
84    Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
85    PushOnScopeChains(ProtocolDecl, TUScope, false);
86  }
87  // Create the built-in typedef for 'id'.
88  if (Context.getObjCIdType().isNull()) {
89    QualType IdT = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy);
90    TypeSourceInfo *IdInfo = Context.getTrivialTypeSourceInfo(IdT);
91    TypedefDecl *IdTypedef
92      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
93                            &Context.Idents.get("id"), IdInfo);
94    PushOnScopeChains(IdTypedef, TUScope);
95    Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
96    Context.ObjCIdRedefinitionType = Context.getObjCIdType();
97  }
98  // Create the built-in typedef for 'Class'.
99  if (Context.getObjCClassType().isNull()) {
100    QualType ClassType
101      = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy);
102    TypeSourceInfo *ClassInfo = Context.getTrivialTypeSourceInfo(ClassType);
103    TypedefDecl *ClassTypedef
104      = TypedefDecl::Create(Context, CurContext, SourceLocation(),
105                            &Context.Idents.get("Class"), ClassInfo);
106    PushOnScopeChains(ClassTypedef, TUScope);
107    Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
108    Context.ObjCClassRedefinitionType = Context.getObjCClassType();
109  }
110}
111
112Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
113           bool CompleteTranslationUnit,
114           CodeCompleteConsumer *CodeCompleter)
115  : TheTargetAttributesSema(0),
116    LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
117    Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
118    ExternalSource(0), CodeCompleter(CodeCompleter), CurContext(0),
119    CurBlock(0), PackContext(0), ParsingDeclDepth(0),
120    IdResolver(pp.getLangOptions()), StdNamespace(0), StdBadAlloc(0),
121    GlobalNewDeleteDeclared(false),
122    CompleteTranslationUnit(CompleteTranslationUnit),
123    NumSFINAEErrors(0), NonInstantiationEntries(0),
124    CurrentInstantiationScope(0), TyposCorrected(0)
125{
126  TUScope = 0;
127  if (getLangOptions().CPlusPlus)
128    FieldCollector.reset(new CXXFieldCollector());
129
130  NumErrorsAtStartOfFunction = 0;
131
132  // Tell diagnostics how to render things from the AST library.
133  PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
134                                       &Context);
135
136  ExprEvalContexts.push_back(
137                  ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
138}
139
140Sema::~Sema() {
141  if (PackContext) FreePackedContext();
142  delete TheTargetAttributesSema;
143}
144
145/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
146/// If there is already an implicit cast, merge into the existing one.
147/// If isLvalue, the result of the cast is an lvalue.
148void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
149                             CastExpr::CastKind Kind, bool isLvalue) {
150  QualType ExprTy = Context.getCanonicalType(Expr->getType());
151  QualType TypeTy = Context.getCanonicalType(Ty);
152
153  if (ExprTy == TypeTy)
154    return;
155
156  if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
157    QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
158    QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
159    if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
160      Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
161        << Expr->getSourceRange();
162    }
163  }
164
165  CheckImplicitConversion(Expr, Ty);
166
167  if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
168    if (ImpCast->getCastKind() == Kind) {
169      ImpCast->setType(Ty);
170      ImpCast->setLvalueCast(isLvalue);
171      return;
172    }
173  }
174
175  Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, isLvalue);
176}
177
178void Sema::DeleteExpr(ExprTy *E) {
179  if (E) static_cast<Expr*>(E)->Destroy(Context);
180}
181void Sema::DeleteStmt(StmtTy *S) {
182  if (S) static_cast<Stmt*>(S)->Destroy(Context);
183}
184
185/// ActOnEndOfTranslationUnit - This is called at the very end of the
186/// translation unit when EOF is reached and all but the top-level scope is
187/// popped.
188void Sema::ActOnEndOfTranslationUnit() {
189
190  // Remove functions that turned out to be used.
191  UnusedStaticFuncs.erase(std::remove_if(UnusedStaticFuncs.begin(),
192                                         UnusedStaticFuncs.end(),
193                                         std::mem_fun(&FunctionDecl::isUsed)),
194                          UnusedStaticFuncs.end());
195
196  while (1) {
197    // C++: Perform implicit template instantiations.
198    //
199    // FIXME: When we perform these implicit instantiations, we do not carefully
200    // keep track of the point of instantiation (C++ [temp.point]). This means
201    // that name lookup that occurs within the template instantiation will
202    // always happen at the end of the translation unit, so it will find
203    // some names that should not be found. Although this is common behavior
204    // for C++ compilers, it is technically wrong. In the future, we either need
205    // to be able to filter the results of name lookup or we need to perform
206    // template instantiations earlier.
207    PerformPendingImplicitInstantiations();
208
209    /// If ProcessPendingClassesWithUnmarkedVirtualMembers ends up marking
210    /// any virtual member functions it might lead to more pending template
211    /// instantiations, which is why we need to loop here.
212    if (!ProcessPendingClassesWithUnmarkedVirtualMembers())
213      break;
214  }
215
216  // Check for #pragma weak identifiers that were never declared
217  // FIXME: This will cause diagnostics to be emitted in a non-determinstic
218  // order!  Iterating over a densemap like this is bad.
219  for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
220       I = WeakUndeclaredIdentifiers.begin(),
221       E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
222    if (I->second.getUsed()) continue;
223
224    Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
225      << I->first;
226  }
227
228  if (!CompleteTranslationUnit)
229    return;
230
231  // C99 6.9.2p2:
232  //   A declaration of an identifier for an object that has file
233  //   scope without an initializer, and without a storage-class
234  //   specifier or with the storage-class specifier static,
235  //   constitutes a tentative definition. If a translation unit
236  //   contains one or more tentative definitions for an identifier,
237  //   and the translation unit contains no external definition for
238  //   that identifier, then the behavior is exactly as if the
239  //   translation unit contains a file scope declaration of that
240  //   identifier, with the composite type as of the end of the
241  //   translation unit, with an initializer equal to 0.
242  llvm::SmallSet<VarDecl *, 32> Seen;
243  for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
244    VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
245
246    // If the tentative definition was completed, getActingDefinition() returns
247    // null. If we've already seen this variable before, insert()'s second
248    // return value is false.
249    if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
250      continue;
251
252    if (const IncompleteArrayType *ArrayT
253        = Context.getAsIncompleteArrayType(VD->getType())) {
254      if (RequireCompleteType(VD->getLocation(),
255                              ArrayT->getElementType(),
256                              diag::err_tentative_def_incomplete_type_arr)) {
257        VD->setInvalidDecl();
258        continue;
259      }
260
261      // Set the length of the array to 1 (C99 6.9.2p5).
262      Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
263      llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
264      QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
265                                                One, ArrayType::Normal, 0);
266      VD->setType(T);
267    } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
268                                   diag::err_tentative_def_incomplete_type))
269      VD->setInvalidDecl();
270
271    // Notify the consumer that we've completed a tentative definition.
272    if (!VD->isInvalidDecl())
273      Consumer.CompleteTentativeDefinition(VD);
274
275  }
276
277  // Output warning for unused functions.
278  for (std::vector<FunctionDecl*>::iterator
279       F = UnusedStaticFuncs.begin(),
280       FEnd = UnusedStaticFuncs.end();
281       F != FEnd;
282       ++F)
283    Diag((*F)->getLocation(), diag::warn_unused_function) << (*F)->getDeclName();
284
285}
286
287
288//===----------------------------------------------------------------------===//
289// Helper functions.
290//===----------------------------------------------------------------------===//
291
292DeclContext *Sema::getFunctionLevelDeclContext() {
293  DeclContext *DC = CurContext;
294
295  while (isa<BlockDecl>(DC))
296    DC = DC->getParent();
297
298  return DC;
299}
300
301/// getCurFunctionDecl - If inside of a function body, this returns a pointer
302/// to the function decl for the function being parsed.  If we're currently
303/// in a 'block', this returns the containing context.
304FunctionDecl *Sema::getCurFunctionDecl() {
305  DeclContext *DC = getFunctionLevelDeclContext();
306  return dyn_cast<FunctionDecl>(DC);
307}
308
309ObjCMethodDecl *Sema::getCurMethodDecl() {
310  DeclContext *DC = getFunctionLevelDeclContext();
311  return dyn_cast<ObjCMethodDecl>(DC);
312}
313
314NamedDecl *Sema::getCurFunctionOrMethodDecl() {
315  DeclContext *DC = getFunctionLevelDeclContext();
316  if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
317    return cast<NamedDecl>(DC);
318  return 0;
319}
320
321Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
322  if (!this->Emit())
323    return;
324
325  // If this is not a note, and we're in a template instantiation
326  // that is different from the last template instantiation where
327  // we emitted an error, print a template instantiation
328  // backtrace.
329  if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
330      !SemaRef.ActiveTemplateInstantiations.empty() &&
331      SemaRef.ActiveTemplateInstantiations.back()
332        != SemaRef.LastTemplateInstantiationErrorContext) {
333    SemaRef.PrintInstantiationStack();
334    SemaRef.LastTemplateInstantiationErrorContext
335      = SemaRef.ActiveTemplateInstantiations.back();
336  }
337}
338
339Sema::SemaDiagnosticBuilder
340Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
341  SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
342  PD.Emit(Builder);
343
344  return Builder;
345}
346
347void Sema::ActOnComment(SourceRange Comment) {
348  Context.Comments.push_back(Comment);
349}
350
351