blob: a5b30cc72aca7c4354d5d28f25a720eeb8cebb31 [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"
Douglas Gregor9cdb4a12009-04-21 17:11:58 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Daniel Dunbarde300732008-08-11 04:54:23 +000019#include "clang/AST/Expr.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Lex/Preprocessor.h"
Chris Lattner4b009652007-07-25 00:24:17 +000021using namespace clang;
22
Chris Lattnerda5c0872008-11-23 09:13:29 +000023/// ConvertQualTypeToStringFn - This function is used to pretty print the
24/// specified QualType as a string in diagnostics.
Chris Lattner254de7d2008-11-23 20:28:15 +000025static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val,
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000026 const char *Modifier, unsigned ModLen,
27 const char *Argument, unsigned ArgLen,
Chris Lattner0b53af22009-02-19 23:53:20 +000028 llvm::SmallVectorImpl<char> &Output,
29 void *Cookie) {
30 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
Chris Lattnerf5b269a2008-11-23 09:21:17 +000031
Chris Lattner254de7d2008-11-23 20:28:15 +000032 std::string S;
33 if (Kind == Diagnostic::ak_qualtype) {
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000034 assert(ModLen == 0 && ArgLen == 0 &&
35 "Invalid modifier for QualType argument");
36
Chris Lattner254de7d2008-11-23 20:28:15 +000037 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
Chris Lattner3a8f2942008-11-24 03:33:13 +000038
Chris Lattner254de7d2008-11-23 20:28:15 +000039 // FIXME: Playing with std::string is really slow.
40 S = Ty.getAsString();
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000041
42 // If this is a sugared type (like a typedef, typeof, etc), then unwrap one
43 // level of the sugar so that the type is more obvious to the user.
Douglas Gregorda0c4d22009-04-01 15:47:24 +000044 QualType DesugaredTy = Ty->getDesugaredType(true);
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000045 DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() |
46 Ty.getCVRQualifiers());
Chris Lattner3a8f2942008-11-24 03:33:13 +000047
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000048 if (Ty != DesugaredTy &&
49 // If the desugared type is a vector type, we don't want to expand it,
50 // it will turn into an attribute mess. People want their "vec4".
51 !isa<VectorType>(DesugaredTy) &&
52
Chris Lattner0b53af22009-02-19 23:53:20 +000053 // Don't desugar magic Objective-C types.
54 Ty.getUnqualifiedType() != Context.getObjCIdType() &&
55 Ty.getUnqualifiedType() != Context.getObjCSelType() &&
56 Ty.getUnqualifiedType() != Context.getObjCProtoType() &&
57 Ty.getUnqualifiedType() != Context.getObjCClassType() &&
58
59 // Not va_list.
60 Ty.getUnqualifiedType() != Context.getBuiltinVaListType()) {
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000061 S = "'"+S+"' (aka '";
62 S += DesugaredTy.getAsString();
63 S += "')";
64 Output.append(S.begin(), S.end());
65 return;
66 }
Chris Lattner3a8f2942008-11-24 03:33:13 +000067
Douglas Gregor09be81b2009-02-04 17:27:36 +000068 } else if (Kind == Diagnostic::ak_declarationname) {
Chris Lattner254de7d2008-11-23 20:28:15 +000069
70 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
71 S = N.getAsString();
Chris Lattner3a8f2942008-11-24 03:33:13 +000072
73 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
74 S = '+' + S;
75 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0)
76 S = '-' + S;
77 else
78 assert(ModLen == 0 && ArgLen == 0 &&
79 "Invalid modifier for DeclarationName argument");
Douglas Gregor09be81b2009-02-04 17:27:36 +000080 } else {
81 assert(Kind == Diagnostic::ak_nameddecl);
Douglas Gregorbe69b162009-02-04 22:46:25 +000082 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
83 S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString();
84 else {
85 assert(ModLen == 0 && ArgLen == 0 &&
Douglas Gregor09be81b2009-02-04 17:27:36 +000086 "Invalid modifier for NamedDecl* argument");
Douglas Gregorbe69b162009-02-04 22:46:25 +000087 S = reinterpret_cast<NamedDecl*>(Val)->getNameAsString();
88 }
Chris Lattner254de7d2008-11-23 20:28:15 +000089 }
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000090
91 Output.push_back('\'');
Chris Lattnerda5c0872008-11-23 09:13:29 +000092 Output.append(S.begin(), S.end());
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000093 Output.push_back('\'');
Chris Lattnerda5c0872008-11-23 09:13:29 +000094}
95
96
Chris Lattner6948ae62008-11-18 07:04:44 +000097static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
Anders Carlsson8930fb52008-08-23 22:20:38 +000098 if (C.getLangOptions().CPlusPlus)
99 return CXXRecordDecl::Create(C, TagDecl::TK_struct,
100 C.getTranslationUnitDecl(),
Ted Kremenek2c984042008-09-05 01:34:33 +0000101 SourceLocation(), &C.Idents.get(Name));
Chris Lattner8ba580c2008-11-19 05:08:23 +0000102
103 return RecordDecl::Create(C, TagDecl::TK_struct,
104 C.getTranslationUnitDecl(),
105 SourceLocation(), &C.Idents.get(Name));
Anders Carlsson8930fb52008-08-23 22:20:38 +0000106}
107
Steve Naroff9637a9b2007-10-09 22:01:59 +0000108void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
109 TUScope = S;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000110 PushDeclContext(S, Context.getTranslationUnitDecl());
Chris Lattnera8c2d592008-02-06 00:46:58 +0000111 if (!PP.getLangOptions().ObjC1) return;
112
Steve Naroff8f635e02008-02-24 16:25:02 +0000113 // Synthesize "typedef struct objc_selector *SEL;"
Anders Carlsson8930fb52008-08-23 22:20:38 +0000114 RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000115 PushOnScopeChains(SelTag, TUScope);
Steve Naroff8f635e02008-02-24 16:25:02 +0000116
117 QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag));
Chris Lattnereee57c02008-04-04 06:12:32 +0000118 TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext,
119 SourceLocation(),
Chris Lattnere4650482008-03-15 06:12:44 +0000120 &Context.Idents.get("SEL"),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000121 SelT);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000122 PushOnScopeChains(SelTypedef, TUScope);
Steve Naroff8f635e02008-02-24 16:25:02 +0000123 Context.setObjCSelType(SelTypedef);
Chris Lattner4e9553a2008-06-21 20:20:39 +0000124
Chris Lattner1062d3a2008-06-21 22:44:51 +0000125 // FIXME: Make sure these don't leak!
Anders Carlsson8930fb52008-08-23 22:20:38 +0000126 RecordDecl *ClassTag = CreateStructDecl(Context, "objc_class");
Chris Lattner4e9553a2008-06-21 20:20:39 +0000127 QualType ClassT = Context.getPointerType(Context.getTagDeclType(ClassTag));
128 TypedefDecl *ClassTypedef =
129 TypedefDecl::Create(Context, CurContext, SourceLocation(),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000130 &Context.Idents.get("Class"), ClassT);
Chris Lattner4e9553a2008-06-21 20:20:39 +0000131 PushOnScopeChains(ClassTag, TUScope);
132 PushOnScopeChains(ClassTypedef, TUScope);
133 Context.setObjCClassType(ClassTypedef);
134 // Synthesize "@class Protocol;
135 ObjCInterfaceDecl *ProtocolDecl =
Douglas Gregor6e4fa2c2009-01-09 00:49:46 +0000136 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
Chris Lattner4e9553a2008-06-21 20:20:39 +0000137 &Context.Idents.get("Protocol"),
138 SourceLocation(), true);
139 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
140 PushOnScopeChains(ProtocolDecl, TUScope);
141
142 // Synthesize "typedef struct objc_object { Class isa; } *id;"
Anders Carlsson8930fb52008-08-23 22:20:38 +0000143 RecordDecl *ObjectTag = CreateStructDecl(Context, "objc_object");
144
Chris Lattner4e9553a2008-06-21 20:20:39 +0000145 QualType ObjT = Context.getPointerType(Context.getTagDeclType(ObjectTag));
146 PushOnScopeChains(ObjectTag, TUScope);
147 TypedefDecl *IdTypedef = TypedefDecl::Create(Context, CurContext,
148 SourceLocation(),
149 &Context.Idents.get("id"),
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000150 ObjT);
Chris Lattner4e9553a2008-06-21 20:20:39 +0000151 PushOnScopeChains(IdTypedef, TUScope);
152 Context.setObjCIdType(IdTypedef);
Steve Naroffee1de132007-10-10 21:53:07 +0000153}
154
Douglas Gregore0d5c562009-04-14 16:27:31 +0000155Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
156 bool CompleteTranslationUnit)
Chris Lattner6d89a8a2009-01-22 19:21:44 +0000157 : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
158 Diags(PP.getDiagnostics()),
Chris Lattnerf9ea6a42008-11-22 08:28:49 +0000159 SourceMgr(PP.getSourceManager()), CurContext(0), PreDeclaratorDC(0),
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000160 CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()),
Douglas Gregore0d5c562009-04-14 16:27:31 +0000161 GlobalNewDeleteDeclared(false),
162 CompleteTranslationUnit(CompleteTranslationUnit) {
Chris Lattner2e64c072007-08-10 20:18:51 +0000163
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000164 StdNamespace = 0;
Steve Naroffee1de132007-10-10 21:53:07 +0000165 TUScope = 0;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000166 if (getLangOptions().CPlusPlus)
167 FieldCollector.reset(new CXXFieldCollector());
Chris Lattnerda5c0872008-11-23 09:13:29 +0000168
169 // Tell diagnostics how to render things from the AST library.
Chris Lattner0b53af22009-02-19 23:53:20 +0000170 PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
Chris Lattner4b009652007-07-25 00:24:17 +0000171}
172
Chris Lattnere992d6c2008-01-16 19:17:22 +0000173/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
174/// If there is already an implicit cast, merge into the existing one.
Nate Begeman7903d052009-01-18 06:42:49 +0000175/// If isLvalue, the result of the cast is an lvalue.
Douglas Gregor70d26122008-11-12 17:17:38 +0000176void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) {
Mon P Wangc6c92742008-09-04 08:38:01 +0000177 QualType ExprTy = Context.getCanonicalType(Expr->getType());
178 QualType TypeTy = Context.getCanonicalType(Ty);
179
180 if (ExprTy == TypeTy)
181 return;
182
183 if (Expr->getType().getTypePtr()->isPointerType() &&
184 Ty.getTypePtr()->isPointerType()) {
185 QualType ExprBaseType =
186 cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType();
187 QualType BaseType =
188 cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType();
189 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000190 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
191 << Expr->getSourceRange();
Mon P Wangc6c92742008-09-04 08:38:01 +0000192 }
193 }
Chris Lattnere992d6c2008-01-16 19:17:22 +0000194
Douglas Gregor70d26122008-11-12 17:17:38 +0000195 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
Mon P Wangc6c92742008-09-04 08:38:01 +0000196 ImpCast->setType(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +0000197 ImpCast->setLvalueCast(isLvalue);
198 } else
Ted Kremenek0c97e042009-02-07 01:47:29 +0000199 Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue);
Chris Lattnere992d6c2008-01-16 19:17:22 +0000200}
201
Chris Lattnerb26b7ad2007-08-31 04:53:24 +0000202void Sema::DeleteExpr(ExprTy *E) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000203 if (E) static_cast<Expr*>(E)->Destroy(Context);
Chris Lattnerb26b7ad2007-08-31 04:53:24 +0000204}
205void Sema::DeleteStmt(StmtTy *S) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000206 if (S) static_cast<Stmt*>(S)->Destroy(Context);
Chris Lattnerb26b7ad2007-08-31 04:53:24 +0000207}
208
Chris Lattnerc1aea812008-08-23 03:19:52 +0000209/// ActOnEndOfTranslationUnit - This is called at the very end of the
210/// translation unit when EOF is reached and all but the top-level scope is
211/// popped.
212void Sema::ActOnEndOfTranslationUnit() {
Douglas Gregore0d5c562009-04-14 16:27:31 +0000213 if (!CompleteTranslationUnit)
214 return;
215
Douglas Gregor2f728b22009-03-10 23:43:53 +0000216 // C99 6.9.2p2:
217 // A declaration of an identifier for an object that has file
218 // scope without an initializer, and without a storage-class
219 // specifier or with the storage-class specifier static,
220 // constitutes a tentative definition. If a translation unit
221 // contains one or more tentative definitions for an identifier,
222 // and the translation unit contains no external definition for
223 // that identifier, then the behavior is exactly as if the
224 // translation unit contains a file scope declaration of that
225 // identifier, with the composite type as of the end of the
226 // translation unit, with an initializer equal to 0.
Douglas Gregor9cdb4a12009-04-21 17:11:58 +0000227 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
228 D = TentativeDefinitions.begin(),
229 DEnd = TentativeDefinitions.end();
230 D != DEnd; ++D) {
231 VarDecl *VD = D->second;
Chris Lattnerc1aea812008-08-23 03:19:52 +0000232
Douglas Gregor9cdb4a12009-04-21 17:11:58 +0000233 if (VD->isInvalidDecl() || !VD->isTentativeDefinition(Context))
234 continue;
235
236 if (const IncompleteArrayType *ArrayT
237 = Context.getAsIncompleteArrayType(VD->getType())) {
238 if (RequireCompleteType(VD->getLocation(),
239 ArrayT->getElementType(),
240 diag::err_tentative_def_incomplete_type_arr))
241 VD->setInvalidDecl();
242 else {
243 // Set the length of the array to 1 (C99 6.9.2p5).
244 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
245 llvm::APInt One(Context.getTypeSize(Context.getSizeType()),
246 true);
247 QualType T
248 = Context.getConstantArrayType(ArrayT->getElementType(),
249 One, ArrayType::Normal, 0);
250 VD->setType(T);
Douglas Gregor2f728b22009-03-10 23:43:53 +0000251 }
Douglas Gregor9cdb4a12009-04-21 17:11:58 +0000252 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
253 diag::err_tentative_def_incomplete_type))
254 VD->setInvalidDecl();
255
256 // Notify the consumer that we've completed a tentative definition.
257 if (!VD->isInvalidDecl())
258 Consumer.CompleteTentativeDefinition(VD);
259
Douglas Gregor2f728b22009-03-10 23:43:53 +0000260 }
Chris Lattnerc1aea812008-08-23 03:19:52 +0000261}
262
263
Chris Lattner4b009652007-07-25 00:24:17 +0000264//===----------------------------------------------------------------------===//
265// Helper functions.
266//===----------------------------------------------------------------------===//
267
Chris Lattnere5cb5862008-12-04 23:50:19 +0000268/// getCurFunctionDecl - If inside of a function body, this returns a pointer
269/// to the function decl for the function being parsed. If we're currently
270/// in a 'block', this returns the containing context.
271FunctionDecl *Sema::getCurFunctionDecl() {
272 DeclContext *DC = CurContext;
273 while (isa<BlockDecl>(DC))
274 DC = DC->getParent();
275 return dyn_cast<FunctionDecl>(DC);
276}
277
Daniel Dunbar64789f82008-08-11 05:35:13 +0000278ObjCMethodDecl *Sema::getCurMethodDecl() {
Steve Naroff55debea2008-11-17 16:28:52 +0000279 DeclContext *DC = CurContext;
280 while (isa<BlockDecl>(DC))
281 DC = DC->getParent();
282 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbar64789f82008-08-11 05:35:13 +0000283}
Chris Lattnere5cb5862008-12-04 23:50:19 +0000284
285NamedDecl *Sema::getCurFunctionOrMethodDecl() {
286 DeclContext *DC = CurContext;
287 while (isa<BlockDecl>(DC))
288 DC = DC->getParent();
289 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000290 return cast<NamedDecl>(DC);
Chris Lattnere5cb5862008-12-04 23:50:19 +0000291 return 0;
292}
293
Douglas Gregor46970ed2009-03-20 22:48:49 +0000294Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
295 this->Emit();
296
297 // If this is not a note, and we're in a template instantiation
298 // that is different from the last template instantiation where
299 // we emitted an error, print a template instantiation
300 // backtrace.
301 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
302 !SemaRef.ActiveTemplateInstantiations.empty() &&
303 SemaRef.ActiveTemplateInstantiations.back()
304 != SemaRef.LastTemplateInstantiationErrorContext) {
305 SemaRef.PrintInstantiationStack();
306 SemaRef.LastTemplateInstantiationErrorContext
307 = SemaRef.ActiveTemplateInstantiations.back();
308 }
309}