blob: ed5c431da82f94f0fa063282664a3341a33b12f6 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- Sema.cpp - AST Builder and Semantic Analysis Implementation ------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
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 "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000017#include "clang/AST/DeclObjC.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000018#include "clang/AST/Expr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000019#include "clang/Lex/Preprocessor.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020using namespace clang;
21
Chris Lattnerda5c0872008-11-23 09:13:29 +000022/// ConvertQualTypeToStringFn - This function is used to pretty print the
23/// specified QualType as a string in diagnostics.
Chris Lattner254de7d2008-11-23 20:28:15 +000024static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val,
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000025 const char *Modifier, unsigned ModLen,
26 const char *Argument, unsigned ArgLen,
Chris Lattner0b53af22009-02-19 23:53:20 +000027 llvm::SmallVectorImpl<char> &Output,
28 void *Cookie) {
29 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
Chris Lattnerf5b269a2008-11-23 09:21:17 +000030
Chris Lattner254de7d2008-11-23 20:28:15 +000031 std::string S;
32 if (Kind == Diagnostic::ak_qualtype) {
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000033 assert(ModLen == 0 && ArgLen == 0 &&
34 "Invalid modifier for QualType argument");
35
Chris Lattner254de7d2008-11-23 20:28:15 +000036 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
Chris Lattner3a8f2942008-11-24 03:33:13 +000037
Chris Lattner254de7d2008-11-23 20:28:15 +000038 // FIXME: Playing with std::string is really slow.
39 S = Ty.getAsString();
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000040
41 // If this is a sugared type (like a typedef, typeof, etc), then unwrap one
42 // level of the sugar so that the type is more obvious to the user.
Douglas Gregorda0c4d22009-04-01 15:47:24 +000043 QualType DesugaredTy = Ty->getDesugaredType(true);
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000044 DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() |
45 Ty.getCVRQualifiers());
Chris Lattner3a8f2942008-11-24 03:33:13 +000046
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000047 if (Ty != DesugaredTy &&
48 // If the desugared type is a vector type, we don't want to expand it,
49 // it will turn into an attribute mess. People want their "vec4".
50 !isa<VectorType>(DesugaredTy) &&
51
Chris Lattner0b53af22009-02-19 23:53:20 +000052 // Don't desugar magic Objective-C types.
53 Ty.getUnqualifiedType() != Context.getObjCIdType() &&
54 Ty.getUnqualifiedType() != Context.getObjCSelType() &&
55 Ty.getUnqualifiedType() != Context.getObjCProtoType() &&
56 Ty.getUnqualifiedType() != Context.getObjCClassType() &&
57
58 // Not va_list.
59 Ty.getUnqualifiedType() != Context.getBuiltinVaListType()) {
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000060 S = "'"+S+"' (aka '";
61 S += DesugaredTy.getAsString();
62 S += "')";
63 Output.append(S.begin(), S.end());
64 return;
65 }
Chris Lattner3a8f2942008-11-24 03:33:13 +000066
Douglas Gregor09be81b2009-02-04 17:27:36 +000067 } else if (Kind == Diagnostic::ak_declarationname) {
Chris Lattner254de7d2008-11-23 20:28:15 +000068
69 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
70 S = N.getAsString();
Chris Lattner3a8f2942008-11-24 03:33:13 +000071
72 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
73 S = '+' + S;
74 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0)
75 S = '-' + S;
76 else
77 assert(ModLen == 0 && ArgLen == 0 &&
78 "Invalid modifier for DeclarationName argument");
Douglas Gregor09be81b2009-02-04 17:27:36 +000079 } else {
80 assert(Kind == Diagnostic::ak_nameddecl);
Douglas Gregorbe69b162009-02-04 22:46:25 +000081 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
82 S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString();
83 else {
84 assert(ModLen == 0 && ArgLen == 0 &&
Douglas Gregor09be81b2009-02-04 17:27:36 +000085 "Invalid modifier for NamedDecl* argument");
Douglas Gregorbe69b162009-02-04 22:46:25 +000086 S = reinterpret_cast<NamedDecl*>(Val)->getNameAsString();
87 }
Chris Lattner254de7d2008-11-23 20:28:15 +000088 }
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000089
90 Output.push_back('\'');
Chris Lattnerda5c0872008-11-23 09:13:29 +000091 Output.append(S.begin(), S.end());
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000092 Output.push_back('\'');
Chris Lattnerda5c0872008-11-23 09:13:29 +000093}
94
95
Chris Lattner6948ae62008-11-18 07:04:44 +000096static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
Anders Carlsson8930fb52008-08-23 22:20:38 +000097 if (C.getLangOptions().CPlusPlus)
98 return CXXRecordDecl::Create(C, TagDecl::TK_struct,
99 C.getTranslationUnitDecl(),
Ted Kremenek2c984042008-09-05 01:34:33 +0000100 SourceLocation(), &C.Idents.get(Name));
Chris Lattner8ba580c2008-11-19 05:08:23 +0000101
102 return RecordDecl::Create(C, TagDecl::TK_struct,
103 C.getTranslationUnitDecl(),
104 SourceLocation(), &C.Idents.get(Name));
Anders Carlsson8930fb52008-08-23 22:20:38 +0000105}
106
Steve Naroff9637a9b2007-10-09 22:01:59 +0000107void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
108 TUScope = S;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000109 PushDeclContext(S, Context.getTranslationUnitDecl());
Chris Lattnera8c2d592008-02-06 00:46:58 +0000110 if (!PP.getLangOptions().ObjC1) return;
111
Steve Naroff8f635e02008-02-24 16:25:02 +0000112 // Synthesize "typedef struct objc_selector *SEL;"
Anders Carlsson8930fb52008-08-23 22:20:38 +0000113 RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000114 PushOnScopeChains(SelTag, TUScope);
Steve Naroff8f635e02008-02-24 16:25:02 +0000115
116 QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag));
Chris Lattnereee57c02008-04-04 06:12:32 +0000117 TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext,
118 SourceLocation(),
Chris Lattnere4650482008-03-15 06:12:44 +0000119 &Context.Idents.get("SEL"),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000120 SelT);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000121 PushOnScopeChains(SelTypedef, TUScope);
Steve Naroff8f635e02008-02-24 16:25:02 +0000122 Context.setObjCSelType(SelTypedef);
Chris Lattner4e9553a2008-06-21 20:20:39 +0000123
Chris Lattner1062d3a2008-06-21 22:44:51 +0000124 // FIXME: Make sure these don't leak!
Anders Carlsson8930fb52008-08-23 22:20:38 +0000125 RecordDecl *ClassTag = CreateStructDecl(Context, "objc_class");
Chris Lattner4e9553a2008-06-21 20:20:39 +0000126 QualType ClassT = Context.getPointerType(Context.getTagDeclType(ClassTag));
127 TypedefDecl *ClassTypedef =
128 TypedefDecl::Create(Context, CurContext, SourceLocation(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000129 &Context.Idents.get("Class"), ClassT);
Chris Lattner4e9553a2008-06-21 20:20:39 +0000130 PushOnScopeChains(ClassTag, TUScope);
131 PushOnScopeChains(ClassTypedef, TUScope);
132 Context.setObjCClassType(ClassTypedef);
133 // Synthesize "@class Protocol;
134 ObjCInterfaceDecl *ProtocolDecl =
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000135 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
Chris Lattner4e9553a2008-06-21 20:20:39 +0000136 &Context.Idents.get("Protocol"),
137 SourceLocation(), true);
138 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
139 PushOnScopeChains(ProtocolDecl, TUScope);
140
141 // Synthesize "typedef struct objc_object { Class isa; } *id;"
Anders Carlsson8930fb52008-08-23 22:20:38 +0000142 RecordDecl *ObjectTag = CreateStructDecl(Context, "objc_object");
143
Chris Lattner4e9553a2008-06-21 20:20:39 +0000144 QualType ObjT = Context.getPointerType(Context.getTagDeclType(ObjectTag));
145 PushOnScopeChains(ObjectTag, TUScope);
146 TypedefDecl *IdTypedef = TypedefDecl::Create(Context, CurContext,
147 SourceLocation(),
148 &Context.Idents.get("id"),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000149 ObjT);
Chris Lattner4e9553a2008-06-21 20:20:39 +0000150 PushOnScopeChains(IdTypedef, TUScope);
151 Context.setObjCIdType(IdTypedef);
Steve Naroffee1de132007-10-10 21:53:07 +0000152}
153
Douglas Gregore0d5c562009-04-14 16:27:31 +0000154Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
155 bool CompleteTranslationUnit)
Chris Lattner6d89a8a2009-01-22 19:21:44 +0000156 : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
157 Diags(PP.getDiagnostics()),
Chris Lattnerf9ea6a42008-11-22 08:28:49 +0000158 SourceMgr(PP.getSourceManager()), CurContext(0), PreDeclaratorDC(0),
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000159 CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()),
Douglas Gregore0d5c562009-04-14 16:27:31 +0000160 GlobalNewDeleteDeclared(false),
161 CompleteTranslationUnit(CompleteTranslationUnit) {
Chris Lattner2e64c072007-08-10 20:18:51 +0000162
163 // Get IdentifierInfo objects for known functions for which we
164 // do extra checking.
Chris Lattnera8c2d592008-02-06 00:46:58 +0000165 IdentifierTable &IT = PP.getIdentifierTable();
Chris Lattner2e64c072007-08-10 20:18:51 +0000166
Daniel Dunbar0ab03e62008-10-02 18:44:07 +0000167 KnownFunctionIDs[id_NSLog] = &IT.get("NSLog");
Douglas Gregorb5af7382009-02-14 18:57:46 +0000168 KnownFunctionIDs[id_NSLogv] = &IT.get("NSLogv");
Douglas Gregor17429032009-02-14 00:32:47 +0000169 KnownFunctionIDs[id_asprintf] = &IT.get("asprintf");
Daniel Dunbar0ab03e62008-10-02 18:44:07 +0000170 KnownFunctionIDs[id_vasprintf] = &IT.get("vasprintf");
Steve Naroffae84af82007-10-31 18:42:27 +0000171
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000172 StdNamespace = 0;
Steve Naroffee1de132007-10-10 21:53:07 +0000173 TUScope = 0;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000174 if (getLangOptions().CPlusPlus)
175 FieldCollector.reset(new CXXFieldCollector());
Chris Lattnerda5c0872008-11-23 09:13:29 +0000176
177 // Tell diagnostics how to render things from the AST library.
Chris Lattner0b53af22009-02-19 23:53:20 +0000178 PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
Chris Lattner4b009652007-07-25 00:24:17 +0000179}
180
Chris Lattnere992d6c2008-01-16 19:17:22 +0000181/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
182/// If there is already an implicit cast, merge into the existing one.
Nate Begeman7903d052009-01-18 06:42:49 +0000183/// If isLvalue, the result of the cast is an lvalue.
Douglas Gregor70d26122008-11-12 17:17:38 +0000184void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) {
Mon P Wangc6c92742008-09-04 08:38:01 +0000185 QualType ExprTy = Context.getCanonicalType(Expr->getType());
186 QualType TypeTy = Context.getCanonicalType(Ty);
187
188 if (ExprTy == TypeTy)
189 return;
190
191 if (Expr->getType().getTypePtr()->isPointerType() &&
192 Ty.getTypePtr()->isPointerType()) {
193 QualType ExprBaseType =
194 cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType();
195 QualType BaseType =
196 cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType();
197 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000198 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
199 << Expr->getSourceRange();
Mon P Wangc6c92742008-09-04 08:38:01 +0000200 }
201 }
Chris Lattnere992d6c2008-01-16 19:17:22 +0000202
Douglas Gregor70d26122008-11-12 17:17:38 +0000203 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
Mon P Wangc6c92742008-09-04 08:38:01 +0000204 ImpCast->setType(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +0000205 ImpCast->setLvalueCast(isLvalue);
206 } else
Ted Kremenek0c97e042009-02-07 01:47:29 +0000207 Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue);
Chris Lattnere992d6c2008-01-16 19:17:22 +0000208}
209
Chris Lattnerb26b7ad2007-08-31 04:53:24 +0000210void Sema::DeleteExpr(ExprTy *E) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000211 if (E) static_cast<Expr*>(E)->Destroy(Context);
Chris Lattnerb26b7ad2007-08-31 04:53:24 +0000212}
213void Sema::DeleteStmt(StmtTy *S) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000214 if (S) static_cast<Stmt*>(S)->Destroy(Context);
Chris Lattnerb26b7ad2007-08-31 04:53:24 +0000215}
216
Chris Lattnerc1aea812008-08-23 03:19:52 +0000217/// ActOnEndOfTranslationUnit - This is called at the very end of the
218/// translation unit when EOF is reached and all but the top-level scope is
219/// popped.
220void Sema::ActOnEndOfTranslationUnit() {
Douglas Gregore0d5c562009-04-14 16:27:31 +0000221 if (!CompleteTranslationUnit)
222 return;
223
Douglas Gregor2f728b22009-03-10 23:43:53 +0000224 // C99 6.9.2p2:
225 // A declaration of an identifier for an object that has file
226 // scope without an initializer, and without a storage-class
227 // specifier or with the storage-class specifier static,
228 // constitutes a tentative definition. If a translation unit
229 // contains one or more tentative definitions for an identifier,
230 // and the translation unit contains no external definition for
231 // that identifier, then the behavior is exactly as if the
232 // translation unit contains a file scope declaration of that
233 // identifier, with the composite type as of the end of the
234 // translation unit, with an initializer equal to 0.
235 if (!getLangOptions().CPlusPlus) {
236 // Note: we traverse the scope's list of declarations rather than
237 // the DeclContext's list, because we only want to see the most
238 // recent declaration of each identifier.
Chris Lattner5261d0c2009-03-28 19:18:32 +0000239 for (Scope::decl_iterator I = TUScope->decl_begin(),
240 IEnd = TUScope->decl_end();
Douglas Gregor2f728b22009-03-10 23:43:53 +0000241 I != IEnd; ++I) {
Chris Lattner5261d0c2009-03-28 19:18:32 +0000242 Decl *D = (*I).getAs<Decl>();
Douglas Gregor2f728b22009-03-10 23:43:53 +0000243 if (D->isInvalidDecl())
244 continue;
Chris Lattnerc1aea812008-08-23 03:19:52 +0000245
Douglas Gregor2f728b22009-03-10 23:43:53 +0000246 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
247 if (VD->isTentativeDefinition(Context)) {
248 if (const IncompleteArrayType *ArrayT
249 = Context.getAsIncompleteArrayType(VD->getType())) {
250 if (RequireCompleteType(VD->getLocation(),
251 ArrayT->getElementType(),
252 diag::err_tentative_def_incomplete_type_arr))
253 VD->setInvalidDecl();
254 else {
255 // Set the length of the array to 1 (C99 6.9.2p5).
Daniel Dunbardca996f2009-04-15 21:35:27 +0000256 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
257 llvm::APInt One(Context.getTypeSize(Context.getSizeType()),
258 true);
Douglas Gregor2f728b22009-03-10 23:43:53 +0000259 QualType T
260 = Context.getConstantArrayType(ArrayT->getElementType(),
261 One, ArrayType::Normal, 0);
262 VD->setType(T);
263 }
264 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
265 diag::err_tentative_def_incomplete_type))
266 VD->setInvalidDecl();
267 }
268 }
269 }
270 }
Chris Lattnerc1aea812008-08-23 03:19:52 +0000271}
272
273
Chris Lattner4b009652007-07-25 00:24:17 +0000274//===----------------------------------------------------------------------===//
275// Helper functions.
276//===----------------------------------------------------------------------===//
277
Chris Lattnere5cb5862008-12-04 23:50:19 +0000278/// getCurFunctionDecl - If inside of a function body, this returns a pointer
279/// to the function decl for the function being parsed. If we're currently
280/// in a 'block', this returns the containing context.
281FunctionDecl *Sema::getCurFunctionDecl() {
282 DeclContext *DC = CurContext;
283 while (isa<BlockDecl>(DC))
284 DC = DC->getParent();
285 return dyn_cast<FunctionDecl>(DC);
286}
287
Daniel Dunbar64789f82008-08-11 05:35:13 +0000288ObjCMethodDecl *Sema::getCurMethodDecl() {
Steve Naroff55debea2008-11-17 16:28:52 +0000289 DeclContext *DC = CurContext;
290 while (isa<BlockDecl>(DC))
291 DC = DC->getParent();
292 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbar64789f82008-08-11 05:35:13 +0000293}
Chris Lattnere5cb5862008-12-04 23:50:19 +0000294
295NamedDecl *Sema::getCurFunctionOrMethodDecl() {
296 DeclContext *DC = CurContext;
297 while (isa<BlockDecl>(DC))
298 DC = DC->getParent();
299 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000300 return cast<NamedDecl>(DC);
Chris Lattnere5cb5862008-12-04 23:50:19 +0000301 return 0;
302}
303
Douglas Gregor46970ed2009-03-20 22:48:49 +0000304Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
305 this->Emit();
306
307 // If this is not a note, and we're in a template instantiation
308 // that is different from the last template instantiation where
309 // we emitted an error, print a template instantiation
310 // backtrace.
311 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
312 !SemaRef.ActiveTemplateInstantiations.empty() &&
313 SemaRef.ActiveTemplateInstantiations.back()
314 != SemaRef.LastTemplateInstantiationErrorContext) {
315 SemaRef.PrintInstantiationStack();
316 SemaRef.LastTemplateInstantiationErrorContext
317 = SemaRef.ActiveTemplateInstantiations.back();
318 }
319}