blob: e9a1d9c5fc178d9a4eae8411424677ae8448ff4c [file] [log] [blame]
Shih-wei Liaof8fd82b2010-02-10 11:10:31 -08001//===--- 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 // Tell diagnostics how to render things from the AST library.
131 PP.getDiagnostics().SetArgToStringFn(&FormatASTNodeDiagnosticArgument,
132 &Context);
133
134 ExprEvalContexts.push_back(
135 ExpressionEvaluationContextRecord(PotentiallyEvaluated, 0));
136}
137
138Sema::~Sema() {
139 if (PackContext) FreePackedContext();
140 delete TheTargetAttributesSema;
141}
142
143/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
144/// If there is already an implicit cast, merge into the existing one.
145/// If isLvalue, the result of the cast is an lvalue.
146void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty,
147 CastExpr::CastKind Kind, bool isLvalue) {
148 QualType ExprTy = Context.getCanonicalType(Expr->getType());
149 QualType TypeTy = Context.getCanonicalType(Ty);
150
151 if (ExprTy == TypeTy)
152 return;
153
154 if (Expr->getType()->isPointerType() && Ty->isPointerType()) {
155 QualType ExprBaseType = cast<PointerType>(ExprTy)->getPointeeType();
156 QualType BaseType = cast<PointerType>(TypeTy)->getPointeeType();
157 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
158 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
159 << Expr->getSourceRange();
160 }
161 }
162
163 CheckImplicitConversion(Expr, Ty);
164
165 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
166 if (ImpCast->getCastKind() == Kind) {
167 ImpCast->setType(Ty);
168 ImpCast->setLvalueCast(isLvalue);
169 return;
170 }
171 }
172
173 Expr = new (Context) ImplicitCastExpr(Ty, Kind, Expr, isLvalue);
174}
175
176void Sema::DeleteExpr(ExprTy *E) {
177 if (E) static_cast<Expr*>(E)->Destroy(Context);
178}
179void Sema::DeleteStmt(StmtTy *S) {
180 if (S) static_cast<Stmt*>(S)->Destroy(Context);
181}
182
183/// ActOnEndOfTranslationUnit - This is called at the very end of the
184/// translation unit when EOF is reached and all but the top-level scope is
185/// popped.
186void Sema::ActOnEndOfTranslationUnit() {
187
188 while (1) {
189 // C++: Perform implicit template instantiations.
190 //
191 // FIXME: When we perform these implicit instantiations, we do not carefully
192 // keep track of the point of instantiation (C++ [temp.point]). This means
193 // that name lookup that occurs within the template instantiation will
194 // always happen at the end of the translation unit, so it will find
195 // some names that should not be found. Although this is common behavior
196 // for C++ compilers, it is technically wrong. In the future, we either need
197 // to be able to filter the results of name lookup or we need to perform
198 // template instantiations earlier.
199 PerformPendingImplicitInstantiations();
200
201 /// If ProcessPendingClassesWithUnmarkedVirtualMembers ends up marking
202 /// any virtual member functions it might lead to more pending template
203 /// instantiations, which is why we need to loop here.
204 if (!ProcessPendingClassesWithUnmarkedVirtualMembers())
205 break;
206 }
207
208 // Check for #pragma weak identifiers that were never declared
209 // FIXME: This will cause diagnostics to be emitted in a non-determinstic
210 // order! Iterating over a densemap like this is bad.
211 for (llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator
212 I = WeakUndeclaredIdentifiers.begin(),
213 E = WeakUndeclaredIdentifiers.end(); I != E; ++I) {
214 if (I->second.getUsed()) continue;
215
216 Diag(I->second.getLocation(), diag::warn_weak_identifier_undeclared)
217 << I->first;
218 }
219
220 if (!CompleteTranslationUnit)
221 return;
222
223 // C99 6.9.2p2:
224 // A declaration of an identifier for an object that has file
225 // scope without an initializer, and without a storage-class
226 // specifier or with the storage-class specifier static,
227 // constitutes a tentative definition. If a translation unit
228 // contains one or more tentative definitions for an identifier,
229 // and the translation unit contains no external definition for
230 // that identifier, then the behavior is exactly as if the
231 // translation unit contains a file scope declaration of that
232 // identifier, with the composite type as of the end of the
233 // translation unit, with an initializer equal to 0.
234 llvm::SmallSet<VarDecl *, 32> Seen;
235 for (unsigned i = 0, e = TentativeDefinitions.size(); i != e; ++i) {
236 VarDecl *VD = TentativeDefinitions[i]->getActingDefinition();
237
238 // If the tentative definition was completed, getActingDefinition() returns
239 // null. If we've already seen this variable before, insert()'s second
240 // return value is false.
241 if (VD == 0 || VD->isInvalidDecl() || !Seen.insert(VD))
242 continue;
243
244 if (const IncompleteArrayType *ArrayT
245 = Context.getAsIncompleteArrayType(VD->getType())) {
246 if (RequireCompleteType(VD->getLocation(),
247 ArrayT->getElementType(),
248 diag::err_tentative_def_incomplete_type_arr)) {
249 VD->setInvalidDecl();
250 continue;
251 }
252
253 // Set the length of the array to 1 (C99 6.9.2p5).
254 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
255 llvm::APInt One(Context.getTypeSize(Context.getSizeType()), true);
256 QualType T = Context.getConstantArrayType(ArrayT->getElementType(),
257 One, ArrayType::Normal, 0);
258 VD->setType(T);
259 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
260 diag::err_tentative_def_incomplete_type))
261 VD->setInvalidDecl();
262
263 // Notify the consumer that we've completed a tentative definition.
264 if (!VD->isInvalidDecl())
265 Consumer.CompleteTentativeDefinition(VD);
266
267 }
268}
269
270
271//===----------------------------------------------------------------------===//
272// Helper functions.
273//===----------------------------------------------------------------------===//
274
275DeclContext *Sema::getFunctionLevelDeclContext() {
276 DeclContext *DC = CurContext;
277
278 while (isa<BlockDecl>(DC))
279 DC = DC->getParent();
280
281 return DC;
282}
283
284/// getCurFunctionDecl - If inside of a function body, this returns a pointer
285/// to the function decl for the function being parsed. If we're currently
286/// in a 'block', this returns the containing context.
287FunctionDecl *Sema::getCurFunctionDecl() {
288 DeclContext *DC = getFunctionLevelDeclContext();
289 return dyn_cast<FunctionDecl>(DC);
290}
291
292ObjCMethodDecl *Sema::getCurMethodDecl() {
293 DeclContext *DC = getFunctionLevelDeclContext();
294 return dyn_cast<ObjCMethodDecl>(DC);
295}
296
297NamedDecl *Sema::getCurFunctionOrMethodDecl() {
298 DeclContext *DC = getFunctionLevelDeclContext();
299 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
300 return cast<NamedDecl>(DC);
301 return 0;
302}
303
304Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
305 if (!this->Emit())
306 return;
307
308 // If this is not a note, and we're in a template instantiation
309 // that is different from the last template instantiation where
310 // we emitted an error, print a template instantiation
311 // backtrace.
312 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
313 !SemaRef.ActiveTemplateInstantiations.empty() &&
314 SemaRef.ActiveTemplateInstantiations.back()
315 != SemaRef.LastTemplateInstantiationErrorContext) {
316 SemaRef.PrintInstantiationStack();
317 SemaRef.LastTemplateInstantiationErrorContext
318 = SemaRef.ActiveTemplateInstantiations.back();
319 }
320}
321
322Sema::SemaDiagnosticBuilder
323Sema::Diag(SourceLocation Loc, const PartialDiagnostic& PD) {
324 SemaDiagnosticBuilder Builder(Diag(Loc, PD.getDiagID()));
325 PD.Emit(Builder);
326
327 return Builder;
328}
329
330void Sema::ActOnComment(SourceRange Comment) {
331 Context.Comments.push_back(Comment);
332}
333