blob: 9b58e477462729c49b0a28b4ae88f147c1045ce2 [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 Lattnerd196f752009-04-30 06:18:40 +000021#include "clang/Basic/TargetInfo.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022using namespace clang;
23
Chris Lattnerda5c0872008-11-23 09:13:29 +000024/// ConvertQualTypeToStringFn - This function is used to pretty print the
25/// specified QualType as a string in diagnostics.
Chris Lattner254de7d2008-11-23 20:28:15 +000026static void ConvertArgToStringFn(Diagnostic::ArgumentKind Kind, intptr_t Val,
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000027 const char *Modifier, unsigned ModLen,
28 const char *Argument, unsigned ArgLen,
Chris Lattner0b53af22009-02-19 23:53:20 +000029 llvm::SmallVectorImpl<char> &Output,
30 void *Cookie) {
31 ASTContext &Context = *static_cast<ASTContext*>(Cookie);
Chris Lattnerf5b269a2008-11-23 09:21:17 +000032
Chris Lattner254de7d2008-11-23 20:28:15 +000033 std::string S;
34 if (Kind == Diagnostic::ak_qualtype) {
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000035 assert(ModLen == 0 && ArgLen == 0 &&
36 "Invalid modifier for QualType argument");
37
Chris Lattner254de7d2008-11-23 20:28:15 +000038 QualType Ty(QualType::getFromOpaquePtr(reinterpret_cast<void*>(Val)));
Chris Lattner3a8f2942008-11-24 03:33:13 +000039
Chris Lattner254de7d2008-11-23 20:28:15 +000040 // FIXME: Playing with std::string is really slow.
Douglas Gregor3bf3bbc2009-05-29 20:38:28 +000041 S = Ty.getAsString(Context.PrintingPolicy);
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000042
43 // If this is a sugared type (like a typedef, typeof, etc), then unwrap one
44 // level of the sugar so that the type is more obvious to the user.
Douglas Gregorda0c4d22009-04-01 15:47:24 +000045 QualType DesugaredTy = Ty->getDesugaredType(true);
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000046 DesugaredTy.setCVRQualifiers(DesugaredTy.getCVRQualifiers() |
47 Ty.getCVRQualifiers());
Chris Lattner3a8f2942008-11-24 03:33:13 +000048
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000049 if (Ty != DesugaredTy &&
50 // If the desugared type is a vector type, we don't want to expand it,
51 // it will turn into an attribute mess. People want their "vec4".
52 !isa<VectorType>(DesugaredTy) &&
53
Chris Lattner0b53af22009-02-19 23:53:20 +000054 // Don't desugar magic Objective-C types.
55 Ty.getUnqualifiedType() != Context.getObjCIdType() &&
Steve Naroff329ec222009-07-10 23:34:53 +000056 Ty.getUnqualifiedType() != Context.getObjCClassType() &&
Chris Lattner0b53af22009-02-19 23:53:20 +000057 Ty.getUnqualifiedType() != Context.getObjCSelType() &&
58 Ty.getUnqualifiedType() != Context.getObjCProtoType() &&
Chris Lattner0b53af22009-02-19 23:53:20 +000059
60 // Not va_list.
61 Ty.getUnqualifiedType() != Context.getBuiltinVaListType()) {
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000062 S = "'"+S+"' (aka '";
Argiris Kirtzidis31231ee2009-06-03 02:06:50 +000063 S += DesugaredTy.getAsString(Context.PrintingPolicy);
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000064 S += "')";
65 Output.append(S.begin(), S.end());
66 return;
67 }
Chris Lattner3a8f2942008-11-24 03:33:13 +000068
Douglas Gregor09be81b2009-02-04 17:27:36 +000069 } else if (Kind == Diagnostic::ak_declarationname) {
Chris Lattner254de7d2008-11-23 20:28:15 +000070
71 DeclarationName N = DeclarationName::getFromOpaqueInteger(Val);
72 S = N.getAsString();
Chris Lattner3a8f2942008-11-24 03:33:13 +000073
74 if (ModLen == 9 && !memcmp(Modifier, "objcclass", 9) && ArgLen == 0)
75 S = '+' + S;
76 else if (ModLen == 12 && !memcmp(Modifier, "objcinstance", 12) && ArgLen==0)
77 S = '-' + S;
78 else
79 assert(ModLen == 0 && ArgLen == 0 &&
80 "Invalid modifier for DeclarationName argument");
Douglas Gregor09be81b2009-02-04 17:27:36 +000081 } else {
82 assert(Kind == Diagnostic::ak_nameddecl);
Douglas Gregorbe69b162009-02-04 22:46:25 +000083 if (ModLen == 1 && Modifier[0] == 'q' && ArgLen == 0)
84 S = reinterpret_cast<NamedDecl*>(Val)->getQualifiedNameAsString();
85 else {
86 assert(ModLen == 0 && ArgLen == 0 &&
Douglas Gregor09be81b2009-02-04 17:27:36 +000087 "Invalid modifier for NamedDecl* argument");
Douglas Gregorbe69b162009-02-04 22:46:25 +000088 S = reinterpret_cast<NamedDecl*>(Val)->getNameAsString();
89 }
Chris Lattner254de7d2008-11-23 20:28:15 +000090 }
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000091
92 Output.push_back('\'');
Chris Lattnerda5c0872008-11-23 09:13:29 +000093 Output.append(S.begin(), S.end());
Chris Lattner2bd4a5a2009-02-19 23:45:49 +000094 Output.push_back('\'');
Chris Lattnerda5c0872008-11-23 09:13:29 +000095}
96
97
Chris Lattner6948ae62008-11-18 07:04:44 +000098static inline RecordDecl *CreateStructDecl(ASTContext &C, const char *Name) {
Anders Carlsson8930fb52008-08-23 22:20:38 +000099 if (C.getLangOptions().CPlusPlus)
100 return CXXRecordDecl::Create(C, TagDecl::TK_struct,
101 C.getTranslationUnitDecl(),
Ted Kremenek2c984042008-09-05 01:34:33 +0000102 SourceLocation(), &C.Idents.get(Name));
Chris Lattner8ba580c2008-11-19 05:08:23 +0000103
104 return RecordDecl::Create(C, TagDecl::TK_struct,
105 C.getTranslationUnitDecl(),
106 SourceLocation(), &C.Idents.get(Name));
Anders Carlsson8930fb52008-08-23 22:20:38 +0000107}
108
Steve Naroff9637a9b2007-10-09 22:01:59 +0000109void Sema::ActOnTranslationUnitScope(SourceLocation Loc, Scope *S) {
110 TUScope = S;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000111 PushDeclContext(S, Context.getTranslationUnitDecl());
Chris Lattner6cc7e412009-04-30 02:43:43 +0000112
Chris Lattnerd196f752009-04-30 06:18:40 +0000113 if (PP.getTargetInfo().getPointerWidth(0) >= 64) {
114 // Install [u]int128_t for 64-bit targets.
115 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
116 SourceLocation(),
117 &Context.Idents.get("__int128_t"),
118 Context.Int128Ty), TUScope);
119 PushOnScopeChains(TypedefDecl::Create(Context, CurContext,
120 SourceLocation(),
121 &Context.Idents.get("__uint128_t"),
122 Context.UnsignedInt128Ty), TUScope);
123 }
Chris Lattner6cc7e412009-04-30 02:43:43 +0000124
125
Chris Lattnera8c2d592008-02-06 00:46:58 +0000126 if (!PP.getLangOptions().ObjC1) return;
127
Steve Naroff89b0a052009-06-16 00:20:10 +0000128 // Built-in ObjC types may already be set by PCHReader (hence isNull checks).
Douglas Gregorbb21d4b2009-04-23 22:29:11 +0000129 if (Context.getObjCSelType().isNull()) {
130 // Synthesize "typedef struct objc_selector *SEL;"
131 RecordDecl *SelTag = CreateStructDecl(Context, "objc_selector");
132 PushOnScopeChains(SelTag, TUScope);
Steve Naroff8f635e02008-02-24 16:25:02 +0000133
Douglas Gregorbb21d4b2009-04-23 22:29:11 +0000134 QualType SelT = Context.getPointerType(Context.getTagDeclType(SelTag));
135 TypedefDecl *SelTypedef = TypedefDecl::Create(Context, CurContext,
136 SourceLocation(),
137 &Context.Idents.get("SEL"),
138 SelT);
139 PushOnScopeChains(SelTypedef, TUScope);
140 Context.setObjCSelType(Context.getTypeDeclType(SelTypedef));
141 }
Chris Lattner4e9553a2008-06-21 20:20:39 +0000142
Chris Lattner4e9553a2008-06-21 20:20:39 +0000143 // Synthesize "@class Protocol;
Douglas Gregorbb21d4b2009-04-23 22:29:11 +0000144 if (Context.getObjCProtoType().isNull()) {
145 ObjCInterfaceDecl *ProtocolDecl =
146 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
147 &Context.Idents.get("Protocol"),
148 SourceLocation(), true);
149 Context.setObjCProtoType(Context.getObjCInterfaceType(ProtocolDecl));
150 PushOnScopeChains(ProtocolDecl, TUScope);
151 }
Steve Naroff329ec222009-07-10 23:34:53 +0000152 // Create the built-in decls/typedefs for 'id' and 'Class'.
Douglas Gregorbb21d4b2009-04-23 22:29:11 +0000153 if (Context.getObjCIdType().isNull()) {
Steve Naroff329ec222009-07-10 23:34:53 +0000154 ObjCInterfaceDecl *IdIDecl =
155 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
156 &Context.Idents.get("id"),
157 SourceLocation(), true);
158 QualType IdIType = Context.getObjCInterfaceType(IdIDecl);
159 QualType ObjCIdType = Context.getObjCObjectPointerType(IdIType);
Steve Naroffc75c1a82009-06-17 22:40:22 +0000160
Douglas Gregorbb21d4b2009-04-23 22:29:11 +0000161 TypedefDecl *IdTypedef = TypedefDecl::Create(Context, CurContext,
162 SourceLocation(),
163 &Context.Idents.get("id"),
Steve Naroff329ec222009-07-10 23:34:53 +0000164 ObjCIdType);
Douglas Gregorbb21d4b2009-04-23 22:29:11 +0000165 PushOnScopeChains(IdTypedef, TUScope);
166 Context.setObjCIdType(Context.getTypeDeclType(IdTypedef));
167 }
Steve Naroff329ec222009-07-10 23:34:53 +0000168 // Create the built-in decls/typedefs and type for "Class".
169 if (Context.getObjCClassType().isNull()) {
170 ObjCInterfaceDecl *ClassIDecl =
171 ObjCInterfaceDecl::Create(Context, CurContext, SourceLocation(),
172 &Context.Idents.get("Class"),
173 SourceLocation(), true);
174 QualType ClassIType = Context.getObjCInterfaceType(ClassIDecl);
175 QualType ObjCClassType = Context.getObjCObjectPointerType(ClassIType);
176
177 TypedefDecl *ClassTypedef = TypedefDecl::Create(Context, CurContext,
178 SourceLocation(),
179 &Context.Idents.get("Class"),
180 ObjCClassType);
181 PushOnScopeChains(ClassTypedef, TUScope);
182 Context.setObjCClassType(Context.getTypeDeclType(ClassTypedef));
183 }
Steve Naroffee1de132007-10-10 21:53:07 +0000184}
185
Douglas Gregore0d5c562009-04-14 16:27:31 +0000186Sema::Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
187 bool CompleteTranslationUnit)
Chris Lattner6d89a8a2009-01-22 19:21:44 +0000188 : LangOpts(pp.getLangOptions()), PP(pp), Context(ctxt), Consumer(consumer),
Douglas Gregorc3221aa2009-04-24 21:10:55 +0000189 Diags(PP.getDiagnostics()), SourceMgr(PP.getSourceManager()),
190 ExternalSource(0), CurContext(0), PreDeclaratorDC(0),
Sebastian Redlb5ee8742008-12-03 20:26:15 +0000191 CurBlock(0), PackContext(0), IdResolver(pp.getLangOptions()),
Douglas Gregora8b2fbf2009-06-22 20:57:11 +0000192 GlobalNewDeleteDeclared(false), ExprEvalContext(PotentiallyEvaluated),
Douglas Gregorf036aa72009-05-14 21:44:34 +0000193 CompleteTranslationUnit(CompleteTranslationUnit),
Douglas Gregor003d7402009-06-14 08:02:22 +0000194 NumSFINAEErrors(0), CurrentInstantiationScope(0) {
Chris Lattner2e64c072007-08-10 20:18:51 +0000195
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000196 StdNamespace = 0;
Steve Naroffee1de132007-10-10 21:53:07 +0000197 TUScope = 0;
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000198 if (getLangOptions().CPlusPlus)
199 FieldCollector.reset(new CXXFieldCollector());
Chris Lattnerda5c0872008-11-23 09:13:29 +0000200
201 // Tell diagnostics how to render things from the AST library.
Chris Lattner0b53af22009-02-19 23:53:20 +0000202 PP.getDiagnostics().SetArgToStringFn(ConvertArgToStringFn, &Context);
Chris Lattner4b009652007-07-25 00:24:17 +0000203}
204
Chris Lattnere992d6c2008-01-16 19:17:22 +0000205/// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
206/// If there is already an implicit cast, merge into the existing one.
Nate Begeman7903d052009-01-18 06:42:49 +0000207/// If isLvalue, the result of the cast is an lvalue.
Douglas Gregor70d26122008-11-12 17:17:38 +0000208void Sema::ImpCastExprToType(Expr *&Expr, QualType Ty, bool isLvalue) {
Mon P Wangc6c92742008-09-04 08:38:01 +0000209 QualType ExprTy = Context.getCanonicalType(Expr->getType());
210 QualType TypeTy = Context.getCanonicalType(Ty);
211
212 if (ExprTy == TypeTy)
213 return;
214
215 if (Expr->getType().getTypePtr()->isPointerType() &&
216 Ty.getTypePtr()->isPointerType()) {
217 QualType ExprBaseType =
218 cast<PointerType>(ExprTy.getUnqualifiedType())->getPointeeType();
219 QualType BaseType =
220 cast<PointerType>(TypeTy.getUnqualifiedType())->getPointeeType();
221 if (ExprBaseType.getAddressSpace() != BaseType.getAddressSpace()) {
Chris Lattner9d2cf082008-11-19 05:27:50 +0000222 Diag(Expr->getExprLoc(), diag::err_implicit_pointer_address_space_cast)
223 << Expr->getSourceRange();
Mon P Wangc6c92742008-09-04 08:38:01 +0000224 }
225 }
Chris Lattnere992d6c2008-01-16 19:17:22 +0000226
Douglas Gregor70d26122008-11-12 17:17:38 +0000227 if (ImplicitCastExpr *ImpCast = dyn_cast<ImplicitCastExpr>(Expr)) {
Mon P Wangc6c92742008-09-04 08:38:01 +0000228 ImpCast->setType(Ty);
Douglas Gregor70d26122008-11-12 17:17:38 +0000229 ImpCast->setLvalueCast(isLvalue);
230 } else
Ted Kremenek0c97e042009-02-07 01:47:29 +0000231 Expr = new (Context) ImplicitCastExpr(Ty, Expr, isLvalue);
Chris Lattnere992d6c2008-01-16 19:17:22 +0000232}
233
Chris Lattnerb26b7ad2007-08-31 04:53:24 +0000234void Sema::DeleteExpr(ExprTy *E) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000235 if (E) static_cast<Expr*>(E)->Destroy(Context);
Chris Lattnerb26b7ad2007-08-31 04:53:24 +0000236}
237void Sema::DeleteStmt(StmtTy *S) {
Douglas Gregorc5a6bdc2009-01-22 00:58:24 +0000238 if (S) static_cast<Stmt*>(S)->Destroy(Context);
Chris Lattnerb26b7ad2007-08-31 04:53:24 +0000239}
240
Chris Lattnerc1aea812008-08-23 03:19:52 +0000241/// ActOnEndOfTranslationUnit - This is called at the very end of the
242/// translation unit when EOF is reached and all but the top-level scope is
243/// popped.
244void Sema::ActOnEndOfTranslationUnit() {
Douglas Gregorcad27f62009-06-22 23:06:13 +0000245 // C++: Perform implicit template instantiations.
246 //
247 // FIXME: When we perform these implicit instantiations, we do not carefully
248 // keep track of the point of instantiation (C++ [temp.point]). This means
249 // that name lookup that occurs within the template instantiation will
250 // always happen at the end of the translation unit, so it will find
251 // some names that should not be found. Although this is common behavior
252 // for C++ compilers, it is technically wrong. In the future, we either need
253 // to be able to filter the results of name lookup or we need to perform
254 // template instantiations earlier.
255 PerformPendingImplicitInstantiations();
256
Douglas Gregore0d5c562009-04-14 16:27:31 +0000257 if (!CompleteTranslationUnit)
258 return;
259
Douglas Gregor2f728b22009-03-10 23:43:53 +0000260 // C99 6.9.2p2:
261 // A declaration of an identifier for an object that has file
262 // scope without an initializer, and without a storage-class
263 // specifier or with the storage-class specifier static,
264 // constitutes a tentative definition. If a translation unit
265 // contains one or more tentative definitions for an identifier,
266 // and the translation unit contains no external definition for
267 // that identifier, then the behavior is exactly as if the
268 // translation unit contains a file scope declaration of that
269 // identifier, with the composite type as of the end of the
270 // translation unit, with an initializer equal to 0.
Douglas Gregor9cdb4a12009-04-21 17:11:58 +0000271 for (llvm::DenseMap<DeclarationName, VarDecl *>::iterator
272 D = TentativeDefinitions.begin(),
273 DEnd = TentativeDefinitions.end();
274 D != DEnd; ++D) {
275 VarDecl *VD = D->second;
Chris Lattnerc1aea812008-08-23 03:19:52 +0000276
Douglas Gregor9cdb4a12009-04-21 17:11:58 +0000277 if (VD->isInvalidDecl() || !VD->isTentativeDefinition(Context))
278 continue;
279
280 if (const IncompleteArrayType *ArrayT
281 = Context.getAsIncompleteArrayType(VD->getType())) {
282 if (RequireCompleteType(VD->getLocation(),
283 ArrayT->getElementType(),
284 diag::err_tentative_def_incomplete_type_arr))
285 VD->setInvalidDecl();
286 else {
287 // Set the length of the array to 1 (C99 6.9.2p5).
288 Diag(VD->getLocation(), diag::warn_tentative_incomplete_array);
289 llvm::APInt One(Context.getTypeSize(Context.getSizeType()),
290 true);
291 QualType T
Douglas Gregor1d381132009-07-06 15:59:29 +0000292 = Context.getConstantArrayWithoutExprType(ArrayT->getElementType(),
293 One, ArrayType::Normal, 0);
Douglas Gregor9cdb4a12009-04-21 17:11:58 +0000294 VD->setType(T);
Douglas Gregor2f728b22009-03-10 23:43:53 +0000295 }
Douglas Gregor9cdb4a12009-04-21 17:11:58 +0000296 } else if (RequireCompleteType(VD->getLocation(), VD->getType(),
297 diag::err_tentative_def_incomplete_type))
298 VD->setInvalidDecl();
299
300 // Notify the consumer that we've completed a tentative definition.
301 if (!VD->isInvalidDecl())
302 Consumer.CompleteTentativeDefinition(VD);
303
Douglas Gregor2f728b22009-03-10 23:43:53 +0000304 }
Chris Lattnerc1aea812008-08-23 03:19:52 +0000305}
306
307
Chris Lattner4b009652007-07-25 00:24:17 +0000308//===----------------------------------------------------------------------===//
309// Helper functions.
310//===----------------------------------------------------------------------===//
311
Chris Lattnere5cb5862008-12-04 23:50:19 +0000312/// getCurFunctionDecl - If inside of a function body, this returns a pointer
313/// to the function decl for the function being parsed. If we're currently
314/// in a 'block', this returns the containing context.
315FunctionDecl *Sema::getCurFunctionDecl() {
316 DeclContext *DC = CurContext;
317 while (isa<BlockDecl>(DC))
318 DC = DC->getParent();
319 return dyn_cast<FunctionDecl>(DC);
320}
321
Daniel Dunbar64789f82008-08-11 05:35:13 +0000322ObjCMethodDecl *Sema::getCurMethodDecl() {
Steve Naroff55debea2008-11-17 16:28:52 +0000323 DeclContext *DC = CurContext;
324 while (isa<BlockDecl>(DC))
325 DC = DC->getParent();
326 return dyn_cast<ObjCMethodDecl>(DC);
Daniel Dunbar64789f82008-08-11 05:35:13 +0000327}
Chris Lattnere5cb5862008-12-04 23:50:19 +0000328
329NamedDecl *Sema::getCurFunctionOrMethodDecl() {
330 DeclContext *DC = CurContext;
331 while (isa<BlockDecl>(DC))
332 DC = DC->getParent();
333 if (isa<ObjCMethodDecl>(DC) || isa<FunctionDecl>(DC))
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000334 return cast<NamedDecl>(DC);
Chris Lattnere5cb5862008-12-04 23:50:19 +0000335 return 0;
336}
337
Douglas Gregor46970ed2009-03-20 22:48:49 +0000338Sema::SemaDiagnosticBuilder::~SemaDiagnosticBuilder() {
Douglas Gregor95d6c952009-06-14 07:33:30 +0000339 if (!this->Emit())
340 return;
Douglas Gregor46970ed2009-03-20 22:48:49 +0000341
342 // If this is not a note, and we're in a template instantiation
343 // that is different from the last template instantiation where
344 // we emitted an error, print a template instantiation
345 // backtrace.
346 if (!SemaRef.Diags.isBuiltinNote(DiagID) &&
347 !SemaRef.ActiveTemplateInstantiations.empty() &&
348 SemaRef.ActiveTemplateInstantiations.back()
349 != SemaRef.LastTemplateInstantiationErrorContext) {
350 SemaRef.PrintInstantiationStack();
351 SemaRef.LastTemplateInstantiationErrorContext
352 = SemaRef.ActiveTemplateInstantiations.back();
353 }
354}
Douglas Gregora252b232009-07-02 17:08:52 +0000355
356void Sema::ActOnComment(SourceRange Comment) {
357 Context.Comments.push_back(Comment);
358}