blob: 8ba6f31da80dc653386226006ece8f60624b35e2 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor2def4832008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000036 DeclContext *DC = 0;
37 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
42 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000043
Douglas Gregor2ce52f32008-04-13 21:07:44 +000044 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
45 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregor72c3f312008-12-05 18:15:24 +000046 isa<TagDecl>(IIDecl) ||
47 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000048 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000049 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000050}
51
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000053 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000054 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000055 if (MD->isOutOfLineDefinition())
56 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000057
58 // A C++ inline method is parsed *after* the topmost class it was declared in
59 // is fully parsed (it's "complete").
60 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000061 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000062 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
63 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000064 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000065 DC = RD;
66
67 // Return the declaration context of the topmost class the inline method is
68 // declared in.
69 return DC;
70 }
71
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000072 if (isa<ObjCMethodDecl>(DC))
73 return Context.getTranslationUnitDecl();
74
75 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
76 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000077
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000078 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000079}
80
Douglas Gregor44b43212008-12-11 16:49:14 +000081void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000082 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000083 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000084 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +000085 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +000086}
87
Chris Lattnerb048c982008-04-06 04:47:34 +000088void Sema::PopDeclContext() {
89 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +000090
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000091 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000092}
93
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000094/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +000096 // Move up the scope chain until we find the nearest enclosing
97 // non-transparent context. The declaration will be introduced into this
98 // scope.
99 while (S->getEntity() &&
100 ((DeclContext *)S->getEntity())->isTransparentContext())
101 S = S->getParent();
102
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000103 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000104
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000105 // Add scoped declarations into their context, so that they can be
106 // found later. Declarations without a context won't be inserted
107 // into any context.
108 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
Douglas Gregor482b77d2009-01-12 23:27:07 +0000109 CurContext->addDecl(SD);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000110
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000111 // C++ [basic.scope]p4:
112 // -- exactly one declaration shall declare a class name or
113 // enumeration name that is not a typedef name and the other
114 // declarations shall all refer to the same object or
115 // enumerator, or all refer to functions and function templates;
116 // in this case the class name or enumeration name is hidden.
117 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
118 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000119 if (CurContext->getLookupContext()
120 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000121 // We're pushing the tag into the current context, which might
122 // require some reshuffling in the identifier resolver.
123 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000124 I = IdResolver.begin(TD->getDeclName(), CurContext,
125 false/*LookInParentCtx*/),
126 IEnd = IdResolver.end();
127 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
128 NamedDecl *PrevDecl = *I;
129 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
130 PrevDecl = *I, ++I) {
131 if (TD->declarationReplaces(*I)) {
132 // This is a redeclaration. Remove it from the chain and
133 // break out, so that we'll add in the shadowed
134 // declaration.
135 S->RemoveDecl(*I);
136 if (PrevDecl == *I) {
137 IdResolver.RemoveDecl(*I);
138 IdResolver.AddDecl(TD);
139 return;
140 } else {
141 IdResolver.RemoveDecl(*I);
142 break;
143 }
144 }
145 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000146
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000147 // There is already a declaration with the same name in the same
148 // scope, which is not a tag declaration. It must be found
149 // before we find the new declaration, so insert the new
150 // declaration at the end of the chain.
151 IdResolver.AddShadowedDecl(TD, PrevDecl);
152
153 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000154 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000155 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000156 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000157 // We are pushing the name of a function, which might be an
158 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000159 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregorce356072009-01-06 23:51:29 +0000160 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000161 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000162 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000163 false/*LookInParentCtx*/),
164 IdResolver.end(),
165 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
166 FD));
167 if (Redecl != IdResolver.end()) {
168 // There is already a declaration of a function on our
169 // IdResolver chain. Replace it with this declaration.
170 S->RemoveDecl(*Redecl);
171 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000173 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000174
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000175 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000176}
177
Steve Naroffb216c882007-10-09 22:01:59 +0000178void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000179 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000180 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
181 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
184 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000185 Decl *TmpD = static_cast<Decl*>(*I);
186 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000187
Douglas Gregor44b43212008-12-11 16:49:14 +0000188 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
189 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000190
Douglas Gregor44b43212008-12-11 16:49:14 +0000191 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000192
Douglas Gregor44b43212008-12-11 16:49:14 +0000193 // Remove this name from our lexical scope.
194 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 }
196}
197
Steve Naroffe8043c32008-04-01 23:04:06 +0000198/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
199/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000200ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000201 // The third "scope" argument is 0 since we aren't enabling lazy built-in
202 // creation from this context.
203 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000204
Steve Naroffb327ce02008-04-02 14:35:35 +0000205 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000206}
207
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000208/// MaybeConstructOverloadSet - Name lookup has determined that the
209/// elements in [I, IEnd) have the name that we are looking for, and
210/// *I is a match for the namespace. This routine returns an
211/// appropriate Decl for name lookup, which may either be *I or an
212/// OverloadeFunctionDecl that represents the overloaded functions in
213/// [I, IEnd).
214///
215/// The existance of this routine is temporary; LookupDecl should
216/// probably be able to return multiple results, to deal with cases of
217/// ambiguity and overloaded functions without needing to create a
218/// Decl node.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000219template<typename DeclIterator>
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000220static Decl *
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000221MaybeConstructOverloadSet(ASTContext &Context,
222 DeclIterator I, DeclIterator IEnd) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000223 assert(I != IEnd && "Iterator range cannot be empty");
224 assert(!isa<OverloadedFunctionDecl>(*I) &&
225 "Cannot have an overloaded function");
226
227 if (isa<FunctionDecl>(*I)) {
228 // If we found a function, there might be more functions. If
229 // so, collect them into an overload set.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000230 DeclIterator Last = I;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000231 OverloadedFunctionDecl *Ovl = 0;
232 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
233 if (!Ovl) {
234 // FIXME: We leak this overload set. Eventually, we want to
235 // stop building the declarations for these overload sets, so
236 // there will be nothing to leak.
237 Ovl = OverloadedFunctionDecl::Create(Context,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000238 cast<ScopedDecl>(*I)->getDeclContext(),
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000239 (*I)->getDeclName());
240 Ovl->addOverload(cast<FunctionDecl>(*I));
241 }
242 Ovl->addOverload(cast<FunctionDecl>(*Last));
243 }
244
245 // If we had more than one function, we built an overload
246 // set. Return it.
247 if (Ovl)
248 return Ovl;
249 }
250
251 return *I;
252}
253
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000254/// getNonFieldDeclScope - Retrieves the innermost scope, starting
255/// from S, where a non-field would be declared. This routine copes
256/// with the difference between C and C++ scoping rules in structs and
257/// unions. For example, the following code is well-formed in C but
258/// ill-formed in C++:
259/// @code
260/// struct S6 {
261/// enum { BAR } e;
262/// };
263///
264/// void test_S6() {
265/// struct S6 a;
266/// a.e = BAR;
267/// }
268/// @endcode
269/// For the declaration of BAR, this routine will return a different
270/// scope. The scope S will be the scope of the unnamed enumeration
271/// within S6. In C++, this routine will return the scope associated
272/// with S6, because the enumeration's scope is a transparent
273/// context but structures can contain non-field names. In C, this
274/// routine will return the translation unit scope, since the
275/// enumeration's scope is a transparent context and structures cannot
276/// contain non-field names.
277Scope *Sema::getNonFieldDeclScope(Scope *S) {
278 while (((S->getFlags() & Scope::DeclScope) == 0) ||
279 (S->getEntity() &&
280 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
281 (S->isClassScope() && !getLangOptions().CPlusPlus))
282 S = S->getParent();
283 return S;
284}
285
Steve Naroffe8043c32008-04-01 23:04:06 +0000286/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000287/// namespace. NamespaceNameOnly - during lookup only namespace names
288/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
289/// 'When looking up a namespace-name in a using-directive or
290/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregor2def4832008-11-17 20:34:05 +0000291Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000292 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000293 bool enableLazyBuiltinCreation,
Douglas Gregorf780abc2008-12-30 03:27:21 +0000294 bool LookInParent,
295 bool NamespaceNameOnly) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000296 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000297 unsigned NS = NSI;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000298
Douglas Gregor72de6672009-01-08 20:45:30 +0000299 // In C++, ordinary and member lookup will always find all
300 // kinds of names.
301 if (getLangOptions().CPlusPlus &&
302 (NS & (Decl::IDNS_Ordinary | Decl::IDNS_Member)))
303 NS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Ordinary;
304
305 if (LookupCtx == 0 && !getLangOptions().CPlusPlus) {
306 // Unqualified name lookup in C/Objective-C is purely lexical, so
307 // search in the declarations attached to the name.
Douglas Gregore267ff32008-12-11 20:41:00 +0000308 assert(!LookupCtx && "Can't perform qualified name lookup here");
Douglas Gregorf780abc2008-12-30 03:27:21 +0000309 assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
Douglas Gregor72de6672009-01-08 20:45:30 +0000310
311 // For the purposes of unqualified name lookup, structs and unions
312 // don't have scopes at all. For example:
313 //
314 // struct X {
315 // struct T { int i; } x;
316 // };
317 //
318 // void f() {
319 // struct T t; // okay: T is defined lexically within X, but
320 // // semantically at global scope
321 // };
322 //
323 // FIXME: Is there a better way to deal with this?
324 DeclContext *SearchCtx = CurContext;
325 while (isa<RecordDecl>(SearchCtx) || isa<EnumDecl>(SearchCtx))
326 SearchCtx = SearchCtx->getParent();
Douglas Gregore267ff32008-12-11 20:41:00 +0000327 IdentifierResolver::iterator I
Douglas Gregor72de6672009-01-08 20:45:30 +0000328 = IdResolver.begin(Name, SearchCtx, LookInParent);
Douglas Gregore267ff32008-12-11 20:41:00 +0000329
330 // Scan up the scope chain looking for a decl that matches this
331 // identifier that is in the appropriate namespace. This search
332 // should not take long, as shadowing of names is uncommon, and
333 // deep shadowing is extremely uncommon.
334 for (; I != IdResolver.end(); ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000335 if ((*I)->isInIdentifierNamespace(NS))
Douglas Gregorf780abc2008-12-30 03:27:21 +0000336 return *I;
Douglas Gregore267ff32008-12-11 20:41:00 +0000337 } else if (LookupCtx) {
Douglas Gregor72de6672009-01-08 20:45:30 +0000338 // If we're performing qualified name lookup (e.g., lookup into a
339 // struct), find fields as part of ordinary name lookup.
340 if (NS & Decl::IDNS_Ordinary)
341 NS |= Decl::IDNS_Member;
342
Douglas Gregor44b43212008-12-11 16:49:14 +0000343 // Perform qualified name lookup into the LookupCtx.
344 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000345 DeclContext::lookup_const_iterator I, E;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000346 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000347 if ((*I)->isInIdentifierNamespace(NS)) {
348 // Ignore non-namespace names if we're only looking for namespaces.
349 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) continue;
350
351 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000352 }
Douglas Gregore267ff32008-12-11 20:41:00 +0000353 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000354 // Name lookup for ordinary names and tag names in C++ requires
355 // looking into scopes that aren't strictly lexical, and
356 // therefore we walk through the context as well as walking
357 // through the scopes.
358 IdentifierResolver::iterator
359 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
360 IEnd = IdResolver.end();
361 for (; S; S = S->getParent()) {
362 // Check whether the IdResolver has anything in this scope.
363 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000364 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Chris Lattner7bea7662009-01-06 07:20:03 +0000365 if ((*I)->isInIdentifierNamespace(NS)) {
366 // Ignore non-namespace names if we're only looking for namespaces.
367 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
368 continue;
369
370 // We found something. Look for anything else in our scope
371 // with this same name and in an acceptable identifier
372 // namespace, so that we can construct an overload set if we
373 // need to.
374 IdentifierResolver::iterator LastI = I;
375 for (++LastI; LastI != IEnd; ++LastI) {
376 if (!(*LastI)->isInIdentifierNamespace(NS) ||
377 !S->isDeclScope(*LastI))
378 break;
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000379 }
Chris Lattner7bea7662009-01-06 07:20:03 +0000380 return MaybeConstructOverloadSet(Context, I, LastI);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000381 }
382 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000383
384 // If there is an entity associated with this scope, it's a
385 // DeclContext. We might need to perform qualified lookup into
386 // it.
387 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
388 while (Ctx && Ctx->isFunctionOrMethod())
389 Ctx = Ctx->getParent();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000390 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000391 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000392 DeclContext::lookup_const_iterator I, E;
Steve Naroff0701bbb2009-01-08 17:28:14 +0000393 for (llvm::tie(I, E) = Ctx->lookup(Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000394 // FIXME: Cache this result in the IdResolver
Chris Lattner7bea7662009-01-06 07:20:03 +0000395 if ((*I)->isInIdentifierNamespace(NS)) {
396 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
397 continue;
398 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000399 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000400 }
401
Douglas Gregorbc468ba2009-01-07 21:36:02 +0000402 if (!LookInParent && !Ctx->isTransparentContext())
403 return 0;
404
Douglas Gregor44b43212008-12-11 16:49:14 +0000405 Ctx = Ctx->getParent();
406 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000407 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000408 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000409
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 // If we didn't find a use of this identifier, and if the identifier
411 // corresponds to a compiler builtin, create the decl object for the builtin
412 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000413 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000414 IdentifierInfo *II = Name.getAsIdentifierInfo();
415 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000416 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000417 // If this is a builtin on this (or all) targets, create the decl.
418 if (unsigned BuiltinID = II->getBuiltinID())
419 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
420 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000421 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000422 // @interface and @compatibility_alias introduce typedef-like names.
423 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000424 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000425 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000426 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
427 if (IDI != ObjCInterfaceDecls.end())
428 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000429 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
430 if (I != ObjCAliasDecls.end())
431 return I->second->getClassInterface();
432 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 }
434 return 0;
435}
436
Chris Lattner95e2c712008-05-05 22:18:14 +0000437void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000438 if (!Context.getBuiltinVaListType().isNull())
439 return;
440
441 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000442 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000443 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000444 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
445}
446
Reid Spencer5f016e22007-07-11 17:01:13 +0000447/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
448/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000449ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
450 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 Builtin::ID BID = (Builtin::ID)bid;
452
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000453 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000454 InitBuiltinVaListType();
455
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000456 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000457 FunctionDecl *New = FunctionDecl::Create(Context,
458 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000459 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000460 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000461
Chris Lattner95e2c712008-05-05 22:18:14 +0000462 // Create Decl objects for each parameter, adding them to the
463 // FunctionDecl.
464 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
465 llvm::SmallVector<ParmVarDecl*, 16> Params;
466 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
467 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
468 FT->getArgType(i), VarDecl::None, 0,
469 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000470 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000471 }
472
473
474
Chris Lattner7f925cc2008-04-11 07:00:53 +0000475 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000476 // FIXME: This is hideous. We need to teach PushOnScopeChains to
477 // relate Scopes to DeclContexts, and probably eliminate CurContext
478 // entirely, but we're not there yet.
479 DeclContext *SavedContext = CurContext;
480 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000481 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000482 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000483 return New;
484}
485
Sebastian Redlc42e1182008-11-11 11:37:55 +0000486/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
487/// everything from the standard library is defined.
488NamespaceDecl *Sema::GetStdNamespace() {
489 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000490 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000491 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000492 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000493 0, Global, /*enableLazyBuiltinCreation=*/false);
494 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
495 }
496 return StdNamespace;
497}
498
Reid Spencer5f016e22007-07-11 17:01:13 +0000499/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
500/// and scope as a previous declaration 'Old'. Figure out how to resolve this
501/// situation, merging decls or emitting diagnostics as appropriate.
502///
Steve Naroffe8043c32008-04-01 23:04:06 +0000503TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000504 // Allow multiple definitions for ObjC built-in typedefs.
505 // FIXME: Verify the underlying types are equivalent!
506 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000507 const IdentifierInfo *TypeID = New->getIdentifier();
508 switch (TypeID->getLength()) {
509 default: break;
510 case 2:
511 if (!TypeID->isStr("id"))
512 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000513 Context.setObjCIdType(New);
514 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000515 case 5:
516 if (!TypeID->isStr("Class"))
517 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000518 Context.setObjCClassType(New);
519 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000520 case 3:
521 if (!TypeID->isStr("SEL"))
522 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000523 Context.setObjCSelType(New);
524 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000525 case 8:
526 if (!TypeID->isStr("Protocol"))
527 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000528 Context.setObjCProtoType(New->getUnderlyingType());
529 return New;
530 }
531 // Fall through - the typedef name was not a builtin type.
532 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000533 // Verify the old decl was also a typedef.
534 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
535 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000536 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000537 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000538 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000539 return New;
540 }
541
Chris Lattner99cb9972008-07-25 18:44:27 +0000542 // If the typedef types are not identical, reject them in all languages and
543 // with any extensions enabled.
544 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
545 Context.getCanonicalType(Old->getUnderlyingType()) !=
546 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000547 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000548 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000549 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000550 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000551 }
552
Eli Friedman54ecfce2008-06-11 06:20:39 +0000553 if (getLangOptions().Microsoft) return New;
554
Douglas Gregorbbe27432008-11-21 16:29:06 +0000555 // C++ [dcl.typedef]p2:
556 // In a given non-class scope, a typedef specifier can be used to
557 // redefine the name of any type declared in that scope to refer
558 // to the type to which it already refers.
559 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
560 return New;
561
562 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000563 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
564 // *either* declaration is in a system header. The code below implements
565 // this adhoc compatibility rule. FIXME: The following code will not
566 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000567 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
568 SourceManager &SrcMgr = Context.getSourceManager();
569 if (SrcMgr.isInSystemHeader(Old->getLocation()))
570 return New;
571 if (SrcMgr.isInSystemHeader(New->getLocation()))
572 return New;
573 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000574
Chris Lattner08631c52008-11-23 21:45:46 +0000575 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000576 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 return New;
578}
579
Chris Lattner6b6b5372008-06-26 18:38:35 +0000580/// DeclhasAttr - returns true if decl Declaration already has the target
581/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000582static bool DeclHasAttr(const Decl *decl, const Attr *target) {
583 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
584 if (attr->getKind() == target->getKind())
585 return true;
586
587 return false;
588}
589
590/// MergeAttributes - append attributes from the Old decl to the New one.
591static void MergeAttributes(Decl *New, Decl *Old) {
592 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
593
Chris Lattnerddee4232008-03-03 03:28:21 +0000594 while (attr) {
595 tmp = attr;
596 attr = attr->getNext();
597
598 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000599 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000600 New->addAttr(tmp);
601 } else {
602 tmp->setNext(0);
603 delete(tmp);
604 }
605 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000606
607 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000608}
609
Chris Lattner04421082008-04-08 04:40:51 +0000610/// MergeFunctionDecl - We just parsed a function 'New' from
611/// declarator D which has the same name and scope as a previous
612/// declaration 'Old'. Figure out how to resolve this situation,
613/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000614/// Redeclaration will be set true if this New is a redeclaration OldD.
615///
616/// In C++, New and Old must be declarations that are not
617/// overloaded. Use IsOverload to determine whether New and Old are
618/// overloaded, and to select the Old declaration that New should be
619/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000620FunctionDecl *
621Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000622 assert(!isa<OverloadedFunctionDecl>(OldD) &&
623 "Cannot merge with an overloaded function declaration");
624
Douglas Gregorf0097952008-04-21 02:02:58 +0000625 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000626 // Verify the old decl was also a function.
627 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
628 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000629 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000630 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000631 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000632 return New;
633 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000634
635 // Determine whether the previous declaration was a definition,
636 // implicit declaration, or a declaration.
637 diag::kind PrevDiag;
638 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000639 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000640 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000641 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000642 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000643 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000644
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000645 QualType OldQType = Context.getCanonicalType(Old->getType());
646 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000647
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000648 if (getLangOptions().CPlusPlus) {
649 // (C++98 13.1p2):
650 // Certain function declarations cannot be overloaded:
651 // -- Function declarations that differ only in the return type
652 // cannot be overloaded.
653 QualType OldReturnType
654 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
655 QualType NewReturnType
656 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
657 if (OldReturnType != NewReturnType) {
658 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
659 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000660 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000661 return New;
662 }
663
664 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
665 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
666 if (OldMethod && NewMethod) {
667 // -- Member function declarations with the same name and the
668 // same parameter types cannot be overloaded if any of them
669 // is a static member function declaration.
670 if (OldMethod->isStatic() || NewMethod->isStatic()) {
671 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
672 Diag(Old->getLocation(), PrevDiag);
673 return New;
674 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000675
676 // C++ [class.mem]p1:
677 // [...] A member shall not be declared twice in the
678 // member-specification, except that a nested class or member
679 // class template can be declared and then later defined.
680 if (OldMethod->getLexicalDeclContext() ==
681 NewMethod->getLexicalDeclContext()) {
682 unsigned NewDiag;
683 if (isa<CXXConstructorDecl>(OldMethod))
684 NewDiag = diag::err_constructor_redeclared;
685 else if (isa<CXXDestructorDecl>(NewMethod))
686 NewDiag = diag::err_destructor_redeclared;
687 else if (isa<CXXConversionDecl>(NewMethod))
688 NewDiag = diag::err_conv_function_redeclared;
689 else
690 NewDiag = diag::err_member_redeclared;
691
692 Diag(New->getLocation(), NewDiag);
693 Diag(Old->getLocation(), PrevDiag);
694 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000695 }
696
697 // (C++98 8.3.5p3):
698 // All declarations for a function shall agree exactly in both the
699 // return type and the parameter-type-list.
700 if (OldQType == NewQType) {
701 // We have a redeclaration.
702 MergeAttributes(New, Old);
703 Redeclaration = true;
704 return MergeCXXFunctionDecl(New, Old);
705 }
706
707 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000708 }
Chris Lattner04421082008-04-08 04:40:51 +0000709
710 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000711 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000712 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000713 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000714 MergeAttributes(New, Old);
715 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000716 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000717 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000718
Steve Naroff837618c2008-01-16 15:01:34 +0000719 // A function that has already been declared has been redeclared or defined
720 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000721
Reid Spencer5f016e22007-07-11 17:01:13 +0000722 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
723 // TODO: This is totally simplistic. It should handle merging functions
724 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000725 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000726 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000727 return New;
728}
729
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000730/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000731static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000732 if (VD->isFileVarDecl())
733 return (!VD->getInit() &&
734 (VD->getStorageClass() == VarDecl::None ||
735 VD->getStorageClass() == VarDecl::Static));
736 return false;
737}
738
739/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
740/// when dealing with C "tentative" external object definitions (C99 6.9.2).
741void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
742 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000743 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000744
Douglas Gregore21b9942009-01-07 16:34:42 +0000745 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000746 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000747 for (IdentifierResolver::iterator
748 I = IdResolver.begin(VD->getIdentifier(),
749 VD->getDeclContext(), false/*LookInParentCtx*/),
750 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000751 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000752 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
753
Steve Narofff855e6f2008-08-10 15:20:13 +0000754 // Handle the following case:
755 // int a[10];
756 // int a[]; - the code below makes sure we set the correct type.
757 // int a[11]; - this is an error, size isn't 10.
758 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
759 OldDecl->getType()->isConstantArrayType())
760 VD->setType(OldDecl->getType());
761
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000762 // Check for "tentative" definitions. We can't accomplish this in
763 // MergeVarDecl since the initializer hasn't been attached.
764 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
765 continue;
766
767 // Handle __private_extern__ just like extern.
768 if (OldDecl->getStorageClass() != VarDecl::Extern &&
769 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
770 VD->getStorageClass() != VarDecl::Extern &&
771 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000772 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000773 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000774 }
775 }
776 }
777}
778
Reid Spencer5f016e22007-07-11 17:01:13 +0000779/// MergeVarDecl - We just parsed a variable 'New' which has the same name
780/// and scope as a previous declaration 'Old'. Figure out how to resolve this
781/// situation, merging decls or emitting diagnostics as appropriate.
782///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000783/// Tentative definition rules (C99 6.9.2p2) are checked by
784/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
785/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000786///
Steve Naroffe8043c32008-04-01 23:04:06 +0000787VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 // Verify the old decl was also a variable.
789 VarDecl *Old = dyn_cast<VarDecl>(OldD);
790 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000791 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000792 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000793 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000794 return New;
795 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000796
797 MergeAttributes(New, Old);
798
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000800 QualType OldCType = Context.getCanonicalType(Old->getType());
801 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000802 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000803 Diag(New->getLocation(), diag::err_redefinition_different_type)
804 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000805 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000806 return New;
807 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000808 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
809 if (New->getStorageClass() == VarDecl::Static &&
810 (Old->getStorageClass() == VarDecl::None ||
811 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000812 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000813 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000814 return New;
815 }
816 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
817 if (New->getStorageClass() != VarDecl::Static &&
818 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000819 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000820 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000821 return New;
822 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000823 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
824 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000825 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000826 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000827 }
828 return New;
829}
830
Chris Lattner04421082008-04-08 04:40:51 +0000831/// CheckParmsForFunctionDef - Check that the parameters of the given
832/// function are appropriate for the definition of a function. This
833/// takes care of any checks that cannot be performed on the
834/// declaration itself, e.g., that the types of each of the function
835/// parameters are complete.
836bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
837 bool HasInvalidParm = false;
838 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
839 ParmVarDecl *Param = FD->getParamDecl(p);
840
841 // C99 6.7.5.3p4: the parameters in a parameter type list in a
842 // function declarator that is part of a function definition of
843 // that function shall not have incomplete type.
844 if (Param->getType()->isIncompleteType() &&
845 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000846 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000847 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000848 Param->setInvalidDecl();
849 HasInvalidParm = true;
850 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000851
852 // C99 6.9.1p5: If the declarator includes a parameter type list, the
853 // declaration of each parameter shall include an identifier.
854 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
855 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000856 }
857
858 return HasInvalidParm;
859}
860
Reid Spencer5f016e22007-07-11 17:01:13 +0000861/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
862/// no declarator (e.g. "struct foo;") is parsed.
863Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000864 TagDecl *Tag
865 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
866 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
867 if (!Record->getDeclName() && Record->isDefinition() &&
868 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
869 return BuildAnonymousStructOrUnion(S, DS, Record);
870
871 // Microsoft allows unnamed struct/union fields. Don't complain
872 // about them.
873 // FIXME: Should we support Microsoft's extensions in this area?
874 if (Record->getDeclName() && getLangOptions().Microsoft)
875 return Tag;
876 }
877
Douglas Gregoree159c12009-01-13 23:10:51 +0000878 // Permit typedefs without declarators as a Microsoft extension.
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000879 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregoree159c12009-01-13 23:10:51 +0000880 if (getLangOptions().Microsoft &&
881 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
882 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
883 << DS.getSourceRange();
884 return Tag;
885 }
886
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000887 // FIXME: This diagnostic is emitted even when various previous
888 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
889 // DeclSpec has no means of communicating this information, and the
890 // responsible parser functions are quite far apart.
891 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
892 << DS.getSourceRange();
893 return 0;
894 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000895
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000896 return Tag;
897}
898
899/// InjectAnonymousStructOrUnionMembers - Inject the members of the
900/// anonymous struct or union AnonRecord into the owning context Owner
901/// and scope S. This routine will be invoked just after we realize
902/// that an unnamed union or struct is actually an anonymous union or
903/// struct, e.g.,
904///
905/// @code
906/// union {
907/// int i;
908/// float f;
909/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
910/// // f into the surrounding scope.x
911/// @endcode
912///
913/// This routine is recursive, injecting the names of nested anonymous
914/// structs/unions into the owning context and scope as well.
915bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
916 RecordDecl *AnonRecord) {
917 bool Invalid = false;
918 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
919 FEnd = AnonRecord->field_end();
920 F != FEnd; ++F) {
921 if ((*F)->getDeclName()) {
922 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
923 S, Owner, false, false, false);
924 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
925 // C++ [class.union]p2:
926 // The names of the members of an anonymous union shall be
927 // distinct from the names of any other entity in the
928 // scope in which the anonymous union is declared.
929 unsigned diagKind
930 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
931 : diag::err_anonymous_struct_member_redecl;
932 Diag((*F)->getLocation(), diagKind)
933 << (*F)->getDeclName();
934 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
935 Invalid = true;
936 } else {
937 // C++ [class.union]p2:
938 // For the purpose of name lookup, after the anonymous union
939 // definition, the members of the anonymous union are
940 // considered to have been defined in the scope in which the
941 // anonymous union is declared.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000942 Owner->insert(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000943 S->AddDecl(*F);
944 IdResolver.AddDecl(*F);
945 }
946 } else if (const RecordType *InnerRecordType
947 = (*F)->getType()->getAsRecordType()) {
948 RecordDecl *InnerRecord = InnerRecordType->getDecl();
949 if (InnerRecord->isAnonymousStructOrUnion())
950 Invalid = Invalid ||
951 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
952 }
953 }
954
955 return Invalid;
956}
957
958/// ActOnAnonymousStructOrUnion - Handle the declaration of an
959/// anonymous structure or union. Anonymous unions are a C++ feature
960/// (C++ [class.union]) and a GNU C extension; anonymous structures
961/// are a GNU C and GNU C++ extension.
962Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
963 RecordDecl *Record) {
964 DeclContext *Owner = Record->getDeclContext();
965
966 // Diagnose whether this anonymous struct/union is an extension.
967 if (Record->isUnion() && !getLangOptions().CPlusPlus)
968 Diag(Record->getLocation(), diag::ext_anonymous_union);
969 else if (!Record->isUnion())
970 Diag(Record->getLocation(), diag::ext_anonymous_struct);
971
972 // C and C++ require different kinds of checks for anonymous
973 // structs/unions.
974 bool Invalid = false;
975 if (getLangOptions().CPlusPlus) {
976 const char* PrevSpec = 0;
977 // C++ [class.union]p3:
978 // Anonymous unions declared in a named namespace or in the
979 // global namespace shall be declared static.
980 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
981 (isa<TranslationUnitDecl>(Owner) ||
982 (isa<NamespaceDecl>(Owner) &&
983 cast<NamespaceDecl>(Owner)->getDeclName()))) {
984 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
985 Invalid = true;
986
987 // Recover by adding 'static'.
988 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
989 }
990 // C++ [class.union]p3:
991 // A storage class is not allowed in a declaration of an
992 // anonymous union in a class scope.
993 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
994 isa<RecordDecl>(Owner)) {
995 Diag(DS.getStorageClassSpecLoc(),
996 diag::err_anonymous_union_with_storage_spec);
997 Invalid = true;
998
999 // Recover by removing the storage specifier.
1000 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1001 PrevSpec);
1002 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001003
1004 // C++ [class.union]p2:
1005 // The member-specification of an anonymous union shall only
1006 // define non-static data members. [Note: nested types and
1007 // functions cannot be declared within an anonymous union. ]
1008 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1009 MemEnd = Record->decls_end();
1010 Mem != MemEnd; ++Mem) {
1011 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1012 // C++ [class.union]p3:
1013 // An anonymous union shall not have private or protected
1014 // members (clause 11).
1015 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1016 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1017 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1018 Invalid = true;
1019 }
1020 } else if ((*Mem)->isImplicit()) {
1021 // Any implicit members are fine.
1022 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1023 if (!MemRecord->isAnonymousStructOrUnion() &&
1024 MemRecord->getDeclName()) {
1025 // This is a nested type declaration.
1026 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1027 << (int)Record->isUnion();
1028 Invalid = true;
1029 }
1030 } else {
1031 // We have something that isn't a non-static data
1032 // member. Complain about it.
1033 unsigned DK = diag::err_anonymous_record_bad_member;
1034 if (isa<TypeDecl>(*Mem))
1035 DK = diag::err_anonymous_record_with_type;
1036 else if (isa<FunctionDecl>(*Mem))
1037 DK = diag::err_anonymous_record_with_function;
1038 else if (isa<VarDecl>(*Mem))
1039 DK = diag::err_anonymous_record_with_static;
1040 Diag((*Mem)->getLocation(), DK)
1041 << (int)Record->isUnion();
1042 Invalid = true;
1043 }
1044 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001045 } else {
1046 // FIXME: Check GNU C semantics
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001047 if (Record->isUnion() && !Owner->isRecord()) {
1048 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
1049 << (int)getLangOptions().CPlusPlus;
1050 Invalid = true;
1051 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001052 }
1053
1054 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001055 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1056 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001057 Invalid = true;
1058 }
1059
1060 // Create a declaration for this anonymous struct/union.
1061 ScopedDecl *Anon = 0;
1062 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1063 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1064 /*IdentifierInfo=*/0,
1065 Context.getTypeDeclType(Record),
1066 /*BitWidth=*/0, /*Mutable=*/false,
1067 /*PrevDecl=*/0);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001068 Anon->setAccess(AS_public);
1069 if (getLangOptions().CPlusPlus)
1070 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001071 } else {
1072 VarDecl::StorageClass SC;
1073 switch (DS.getStorageClassSpec()) {
1074 default: assert(0 && "Unknown storage class!");
1075 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1076 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1077 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1078 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1079 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1080 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1081 case DeclSpec::SCS_mutable:
1082 // mutable can only appear on non-static class members, so it's always
1083 // an error here
1084 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1085 Invalid = true;
1086 SC = VarDecl::None;
1087 break;
1088 }
1089
1090 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1091 /*IdentifierInfo=*/0,
1092 Context.getTypeDeclType(Record),
1093 SC, /*FIXME:LastDeclarator=*/0,
1094 DS.getSourceRange().getBegin());
1095 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001096 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001097
1098 // Add the anonymous struct/union object to the current
1099 // context. We'll be referencing this object when we refer to one of
1100 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +00001101 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001102
1103 // Inject the members of the anonymous struct/union into the owning
1104 // context and into the identifier resolver chain for name lookup
1105 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001106 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1107 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001108
1109 // Mark this as an anonymous struct/union type. Note that we do not
1110 // do this until after we have already checked and injected the
1111 // members of this anonymous struct/union type, because otherwise
1112 // the members could be injected twice: once by DeclContext when it
1113 // builds its lookup table, and once by
1114 // InjectAnonymousStructOrUnionMembers.
1115 Record->setAnonymousStructOrUnion(true);
1116
1117 if (Invalid)
1118 Anon->setInvalidDecl();
1119
1120 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001121}
1122
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001123bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
1124 bool DirectInit) {
Steve Narofff0090632007-09-02 02:04:30 +00001125 // Get the type before calling CheckSingleAssignmentConstraints(), since
1126 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001127 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +00001128
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001129 if (getLangOptions().CPlusPlus) {
1130 // FIXME: I dislike this error message. A lot.
1131 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
1132 return Diag(Init->getSourceRange().getBegin(),
1133 diag::err_typecheck_convert_incompatible)
1134 << DeclType << Init->getType() << "initializing"
1135 << Init->getSourceRange();
1136
1137 return false;
1138 }
Douglas Gregor45920e82008-12-19 17:40:08 +00001139
Chris Lattner5cf216b2008-01-04 18:04:52 +00001140 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1141 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1142 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +00001143}
1144
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001145bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001146 const ArrayType *AT = Context.getAsArrayType(DeclT);
1147
1148 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001149 // C99 6.7.8p14. We have an array of character type with unknown size
1150 // being initialized to a string literal.
1151 llvm::APSInt ConstVal(32);
1152 ConstVal = strLiteral->getByteLength() + 1;
1153 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001154 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001155 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001156 } else {
1157 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001158 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001159 // FIXME: Avoid truncation for 64-bit length strings.
1160 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001161 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001162 diag::warn_initializer_string_for_char_array_too_long)
1163 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001164 }
1165 // Set type from "char *" to "constant array of char".
1166 strLiteral->setType(DeclT);
1167 // For now, we always return false (meaning success).
1168 return false;
1169}
1170
1171StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001172 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001173 if (AT && AT->getElementType()->isCharType()) {
1174 return dyn_cast<StringLiteral>(Init);
1175 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001176 return 0;
1177}
1178
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001179bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1180 SourceLocation InitLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001181 DeclarationName InitEntity,
1182 bool DirectInit) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001183 if (DeclType->isDependentType() || Init->isTypeDependent())
1184 return false;
1185
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001186 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001187 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001188 // (8.3.2), shall be initialized by an object, or function, of
1189 // type T or by an object that can be converted into a T.
1190 if (DeclType->isReferenceType())
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001191 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001192
Steve Naroffca107302008-01-21 23:53:58 +00001193 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1194 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001195 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001196 return Diag(InitLoc, diag::err_variable_object_no_init)
1197 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001198
Steve Naroff2fdc3742007-12-10 22:44:33 +00001199 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1200 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001201 // FIXME: Handle wide strings
1202 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1203 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001204
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001205 // C++ [dcl.init]p14:
1206 // -- If the destination type is a (possibly cv-qualified) class
1207 // type:
1208 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1209 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1210 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1211
1212 // -- If the initialization is direct-initialization, or if it is
1213 // copy-initialization where the cv-unqualified version of the
1214 // source type is the same class as, or a derived class of, the
1215 // class of the destination, constructors are considered.
1216 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1217 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1218 CXXConstructorDecl *Constructor
1219 = PerformInitializationByConstructor(DeclType, &Init, 1,
1220 InitLoc, Init->getSourceRange(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001221 InitEntity,
1222 DirectInit? IK_Direct : IK_Copy);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001223 return Constructor == 0;
1224 }
1225
1226 // -- Otherwise (i.e., for the remaining copy-initialization
1227 // cases), user-defined conversion sequences that can
1228 // convert from the source type to the destination type or
1229 // (when a conversion function is used) to a derived class
1230 // thereof are enumerated as described in 13.3.1.4, and the
1231 // best one is chosen through overload resolution
1232 // (13.3). If the conversion cannot be done or is
1233 // ambiguous, the initialization is ill-formed. The
1234 // function selected is called with the initializer
1235 // expression as its argument; if the function is a
1236 // constructor, the call initializes a temporary of the
1237 // destination type.
1238 // FIXME: We're pretending to do copy elision here; return to
1239 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001240 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001241 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001242
Douglas Gregor61366e92008-12-24 00:01:03 +00001243 if (InitEntity)
1244 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1245 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1246 << Init->getType() << Init->getSourceRange();
1247 else
1248 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1249 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1250 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001251 }
1252
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001253 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001254 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001255 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1256 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001257
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001258 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001259 } else if (getLangOptions().CPlusPlus) {
1260 // C++ [dcl.init]p14:
1261 // [...] If the class is an aggregate (8.5.1), and the initializer
1262 // is a brace-enclosed list, see 8.5.1.
1263 //
1264 // Note: 8.5.1 is handled below; here, we diagnose the case where
1265 // we have an initializer list and a destination type that is not
1266 // an aggregate.
1267 // FIXME: In C++0x, this is yet another form of initialization.
1268 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1269 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1270 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001271 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001272 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001273 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001274 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001275
Steve Naroff0cca7492008-05-01 22:18:59 +00001276 InitListChecker CheckInitList(this, InitList, DeclType);
1277 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +00001278}
1279
Douglas Gregor10bd3682008-11-17 22:58:34 +00001280/// GetNameForDeclarator - Determine the full declaration name for the
1281/// given Declarator.
1282DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1283 switch (D.getKind()) {
1284 case Declarator::DK_Abstract:
1285 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1286 return DeclarationName();
1287
1288 case Declarator::DK_Normal:
1289 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1290 return DeclarationName(D.getIdentifier());
1291
1292 case Declarator::DK_Constructor: {
1293 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1294 Ty = Context.getCanonicalType(Ty);
1295 return Context.DeclarationNames.getCXXConstructorName(Ty);
1296 }
1297
1298 case Declarator::DK_Destructor: {
1299 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1300 Ty = Context.getCanonicalType(Ty);
1301 return Context.DeclarationNames.getCXXDestructorName(Ty);
1302 }
1303
1304 case Declarator::DK_Conversion: {
1305 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1306 Ty = Context.getCanonicalType(Ty);
1307 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1308 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001309
1310 case Declarator::DK_Operator:
1311 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1312 return Context.DeclarationNames.getCXXOperatorName(
1313 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001314 }
1315
1316 assert(false && "Unknown name kind");
1317 return DeclarationName();
1318}
1319
Douglas Gregor584049d2008-12-15 23:53:10 +00001320/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1321/// functions Declaration and Definition are "nearly" matching. This
1322/// heuristic is used to improve diagnostics in the case where an
1323/// out-of-line member function definition doesn't match any
1324/// declaration within the class.
1325static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1326 FunctionDecl *Declaration,
1327 FunctionDecl *Definition) {
1328 if (Declaration->param_size() != Definition->param_size())
1329 return false;
1330 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1331 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1332 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1333
1334 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1335 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1336 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1337 return false;
1338 }
1339
1340 return true;
1341}
1342
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001343Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001344Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1345 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +00001346 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001347 DeclarationName Name = GetNameForDeclarator(D);
1348
Chris Lattnere80a59c2007-07-25 00:24:17 +00001349 // All of these full declarators require an identifier. If it doesn't have
1350 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001351 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001352 if (!D.getInvalidType()) // Reject this if we think it is valid.
1353 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001354 diag::err_declarator_need_ident)
1355 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001356 return 0;
1357 }
1358
Chris Lattner31e05722007-08-26 06:24:45 +00001359 // The scope passed in may not be a decl scope. Zip up the scope tree until
1360 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001361 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1362 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001363 S = S->getParent();
1364
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001365 DeclContext *DC;
1366 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001367 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001368 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001369
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001370 // See if this is a redefinition of a variable in the same scope.
1371 if (!D.getCXXScopeSpec().isSet()) {
1372 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001373 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001374 } else { // Something like "int foo::x;"
1375 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001376 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001377
1378 // C++ 7.3.1.2p2:
1379 // Members (including explicit specializations of templates) of a named
1380 // namespace can also be defined outside that namespace by explicit
1381 // qualification of the name being defined, provided that the entity being
1382 // defined was already declared in the namespace and the definition appears
1383 // after the point of declaration in a namespace that encloses the
1384 // declarations namespace.
1385 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001386 // Note that we only check the context at this point. We don't yet
1387 // have enough information to make sure that PrevDecl is actually
1388 // the declaration we want to match. For example, given:
1389 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001390 // class X {
1391 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001392 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001393 // };
1394 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001395 // void X::f(int) { } // ill-formed
1396 //
1397 // In this case, PrevDecl will point to the overload set
1398 // containing the two f's declared in X, but neither of them
1399 // matches.
1400 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001401 // The qualifying scope doesn't enclose the original declaration.
1402 // Emit diagnostic based on current scope.
1403 SourceLocation L = D.getIdentifierLoc();
1404 SourceRange R = D.getCXXScopeSpec().getRange();
1405 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001406 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001407 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001408 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001409 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001410 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001411 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001412 }
1413 }
1414
Douglas Gregorf57172b2008-12-08 18:40:42 +00001415 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001416 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001417 InvalidDecl = InvalidDecl
1418 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001419 // Just pretend that we didn't see the previous declaration.
1420 PrevDecl = 0;
1421 }
1422
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001423 // In C++, the previous declaration we find might be a tag type
1424 // (class or enum). In this case, the new declaration will hide the
1425 // tag type.
1426 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1427 PrevDecl = 0;
1428
Chris Lattner41af0932007-11-14 06:34:38 +00001429 QualType R = GetTypeForDeclarator(D, S);
1430 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1431
Reid Spencer5f016e22007-07-11 17:01:13 +00001432 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001433 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1434 if (D.getCXXScopeSpec().isSet()) {
1435 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1436 << D.getCXXScopeSpec().getRange();
1437 InvalidDecl = true;
1438 // Pretend we didn't see the scope specifier.
1439 DC = 0;
1440 }
1441
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001442 // Check that there are no default arguments (C++ only).
1443 if (getLangOptions().CPlusPlus)
1444 CheckExtraCXXDefaultArguments(D);
1445
Chris Lattner41af0932007-11-14 06:34:38 +00001446 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001447 if (!NewTD) return 0;
1448
1449 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001450 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001451 // Merge the decl with the existing one if appropriate. If the decl is
1452 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001453 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001454 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1455 if (NewTD == 0) return 0;
1456 }
1457 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001458 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001459 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1460 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001461 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001462 if (NewTD->getUnderlyingType()->isVariableArrayType())
1463 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1464 else
1465 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1466
Steve Naroffd7444aa2007-08-31 17:20:07 +00001467 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001468 }
1469 }
Chris Lattner41af0932007-11-14 06:34:38 +00001470 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001471 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001472 switch (D.getDeclSpec().getStorageClassSpec()) {
1473 default: assert(0 && "Unknown storage class!");
Sebastian Redl64b45f72009-01-05 20:52:13 +00001474 case DeclSpec::SCS_auto:
Reid Spencer5f016e22007-07-11 17:01:13 +00001475 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001476 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001477 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001478 InvalidDecl = true;
1479 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1481 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1482 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001483 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001484 }
1485
Chris Lattnera98e58d2008-03-15 21:24:04 +00001486 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001487 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001488 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1489
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001490 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001491 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001492 // This is a C++ constructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001493 assert(DC->isRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001494 "Constructors can only be declared in a member context");
1495
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001496 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001497
1498 // Create the new declaration
1499 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001500 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001501 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001502 isExplicit, isInline,
1503 /*isImplicitlyDeclared=*/false);
1504
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001505 if (InvalidDecl)
Douglas Gregor42a552f2008-11-05 20:51:48 +00001506 NewFD->setInvalidDecl();
1507 } else if (D.getKind() == Declarator::DK_Destructor) {
1508 // This is a C++ destructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001509 if (DC->isRecord()) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001510 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001511
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001512 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001513 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001514 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001515 isInline,
1516 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001517
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001518 if (InvalidDecl)
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001519 NewFD->setInvalidDecl();
1520 } else {
1521 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001522
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001523 // Create a FunctionDecl to satisfy the function definition parsing
1524 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001525 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001526 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001527 // FIXME: Move to DeclGroup...
1528 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001529 InvalidDecl = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001530 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001531 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001532 } else if (D.getKind() == Declarator::DK_Conversion) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001533 if (!DC->isRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001534 Diag(D.getIdentifierLoc(),
1535 diag::err_conv_function_not_member);
1536 return 0;
1537 } else {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001538 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001539
Douglas Gregor70316a02008-12-26 15:00:45 +00001540 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001541 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001542 isInline, isExplicit);
1543
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001544 if (InvalidDecl)
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001545 NewFD->setInvalidDecl();
1546 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001547 } else if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001548 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001549 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001550 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001551 (SC == FunctionDecl::Static), isInline,
1552 LastDeclarator);
1553 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001554 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001555 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001556 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001557 // FIXME: Move to DeclGroup...
1558 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001559 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001560
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001561 // Set the lexical context. If the declarator has a C++
1562 // scope specifier, the lexical context will be different
1563 // from the semantic context.
1564 NewFD->setLexicalDeclContext(CurContext);
1565
Daniel Dunbara80f8742008-08-05 01:35:17 +00001566 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001567 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001568 // The parser guarantees this is a string.
1569 StringLiteral *SE = cast<StringLiteral>(E);
1570 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1571 SE->getByteLength())));
1572 }
1573
Chris Lattner04421082008-04-08 04:40:51 +00001574 // Copy the parameter declarations from the declarator D to
1575 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001576 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001577 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1578
1579 // Create Decl objects for each parameter, adding them to the
1580 // FunctionDecl.
1581 llvm::SmallVector<ParmVarDecl*, 16> Params;
1582
1583 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1584 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001585 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001586 // We let through "const void" here because Sema::GetTypeForDeclarator
1587 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001588 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1589 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001590 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1591 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001592 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1593
Chris Lattnerdef026a2008-04-10 02:26:16 +00001594 // In C++, the empty parameter-type-list must be spelled "void"; a
1595 // typedef of void is not permitted.
1596 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001597 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001598 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1599 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001600 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001601 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1602 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1603 }
1604
Ted Kremenekfc767612009-01-14 00:42:25 +00001605 NewFD->setParams(Context, &Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001606 } else if (R->getAsTypedefType()) {
1607 // When we're declaring a function with a typedef, as in the
1608 // following example, we'll need to synthesize (unnamed)
1609 // parameters for use in the declaration.
1610 //
1611 // @code
1612 // typedef void fn(int);
1613 // fn f;
1614 // @endcode
1615 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1616 if (!FT) {
1617 // This is a typedef of a function with no prototype, so we
1618 // don't need to do anything.
1619 } else if ((FT->getNumArgs() == 0) ||
1620 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1621 FT->getArgType(0)->isVoidType())) {
1622 // This is a zero-argument function. We don't need to do anything.
1623 } else {
1624 // Synthesize a parameter for each argument type.
1625 llvm::SmallVector<ParmVarDecl*, 16> Params;
1626 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1627 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001628 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001629 SourceLocation(), 0,
1630 *ArgType, VarDecl::None,
1631 0, 0));
1632 }
1633
Ted Kremenekfc767612009-01-14 00:42:25 +00001634 NewFD->setParams(Context, &Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001635 }
Chris Lattner04421082008-04-08 04:40:51 +00001636 }
1637
Douglas Gregor72b505b2008-12-16 21:30:33 +00001638 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1639 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001640 else if (isa<CXXDestructorDecl>(NewFD)) {
1641 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1642 Record->setUserDeclaredDestructor(true);
1643 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1644 // user-defined destructor.
1645 Record->setPOD(false);
1646 } else if (CXXConversionDecl *Conversion =
1647 dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001648 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001649
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001650 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1651 if (NewFD->isOverloadedOperator() &&
1652 CheckOverloadedOperatorDeclaration(NewFD))
1653 NewFD->setInvalidDecl();
1654
Steve Naroffffce4d52008-01-09 23:34:55 +00001655 // Merge the decl with the existing one if appropriate. Since C functions
1656 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001657 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001658 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001659 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001660
1661 // If C++, determine whether NewFD is an overload of PrevDecl or
1662 // a declaration that requires merging. If it's an overload,
1663 // there's no more work to do here; we'll just add the new
1664 // function to the scope.
1665 OverloadedFunctionDecl::function_iterator MatchedDecl;
1666 if (!getLangOptions().CPlusPlus ||
1667 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1668 Decl *OldDecl = PrevDecl;
1669
1670 // If PrevDecl was an overloaded function, extract the
1671 // FunctionDecl that matched.
1672 if (isa<OverloadedFunctionDecl>(PrevDecl))
1673 OldDecl = *MatchedDecl;
1674
1675 // NewFD and PrevDecl represent declarations that need to be
1676 // merged.
1677 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1678
1679 if (NewFD == 0) return 0;
1680 if (Redeclaration) {
1681 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1682
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001683 // An out-of-line member function declaration must also be a
1684 // definition (C++ [dcl.meaning]p1).
1685 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1686 !InvalidDecl) {
1687 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1688 << D.getCXXScopeSpec().getRange();
1689 NewFD->setInvalidDecl();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001690 }
1691 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001692 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001693
1694 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1695 // The user tried to provide an out-of-line definition for a
1696 // member function, but there was no such member function
1697 // declared (C++ [class.mfct]p2). For example:
1698 //
1699 // class X {
1700 // void f() const;
1701 // };
1702 //
1703 // void X::f() { } // ill-formed
1704 //
1705 // Complain about this problem, and attempt to suggest close
1706 // matches (e.g., those that differ only in cv-qualifiers and
1707 // whether the parameter types are references).
1708 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1709 << cast<CXXRecordDecl>(DC)->getDeclName()
1710 << D.getCXXScopeSpec().getRange();
1711 InvalidDecl = true;
1712
1713 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1714 if (!PrevDecl) {
1715 // Nothing to suggest.
1716 } else if (OverloadedFunctionDecl *Ovl
1717 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1718 for (OverloadedFunctionDecl::function_iterator
1719 Func = Ovl->function_begin(),
1720 FuncEnd = Ovl->function_end();
1721 Func != FuncEnd; ++Func) {
1722 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1723 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1724
1725 }
1726 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1727 // Suggest this no matter how mismatched it is; it's the only
1728 // thing we have.
1729 unsigned diag;
1730 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1731 diag = diag::note_member_def_close_match;
1732 else if (Method->getBody())
1733 diag = diag::note_previous_definition;
1734 else
1735 diag = diag::note_previous_declaration;
1736 Diag(Method->getLocation(), diag);
1737 }
1738
1739 PrevDecl = 0;
1740 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001741 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +00001742 // Handle attributes. We need to have merged decls when handling attributes
1743 // (for example to check for conflicts, etc).
1744 ProcessDeclAttributes(NewFD, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001745 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001746
Douglas Gregor584049d2008-12-15 23:53:10 +00001747 if (getLangOptions().CPlusPlus) {
1748 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001749 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001750
1751 // An out-of-line member function declaration must also be a
1752 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001753 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001754 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1755 << D.getCXXScopeSpec().getRange();
1756 InvalidDecl = true;
1757 }
1758 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001759 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001760 // Check that there are no default arguments (C++ only).
1761 if (getLangOptions().CPlusPlus)
1762 CheckExtraCXXDefaultArguments(D);
1763
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001764 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001765 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1766 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001767 InvalidDecl = true;
1768 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001769
1770 VarDecl *NewVD;
1771 VarDecl::StorageClass SC;
1772 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001773 default: assert(0 && "Unknown storage class!");
1774 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1775 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1776 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1777 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1778 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1779 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001780 case DeclSpec::SCS_mutable:
1781 // mutable can only appear on non-static class members, so it's always
1782 // an error here
1783 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1784 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001785 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001786 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001787 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001788
1789 IdentifierInfo *II = Name.getAsIdentifierInfo();
1790 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001791 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1792 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001793 return 0;
1794 }
1795
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001796 if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001797 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001798 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001799 D.getIdentifierLoc(), II,
1800 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001801 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001802 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001803 if (S->getFnParent() == 0) {
1804 // C99 6.9p2: The storage-class specifiers auto and register shall not
1805 // appear in the declaration specifiers in an external declaration.
1806 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001807 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001808 InvalidDecl = true;
1809 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001810 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001811 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1812 II, R, SC, LastDeclarator,
1813 // FIXME: Move to DeclGroup...
1814 D.getDeclSpec().getSourceRange().getBegin());
1815 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001816 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001817 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001818 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001819
Daniel Dunbara735ad82008-08-06 00:03:29 +00001820 // Handle GNU asm-label extension (encoded as an attribute).
1821 if (Expr *E = (Expr*) D.getAsmLabel()) {
1822 // The parser guarantees this is a string.
1823 StringLiteral *SE = cast<StringLiteral>(E);
1824 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1825 SE->getByteLength())));
1826 }
1827
Nate Begemanc8e89a82008-03-14 18:07:10 +00001828 // Emit an error if an address space was applied to decl with local storage.
1829 // This includes arrays of objects with address space qualifiers, but not
1830 // automatic variables that point to other address spaces.
1831 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001832 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1833 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1834 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001835 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001836 // Merge the decl with the existing one if appropriate. If the decl is
1837 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001838 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001839 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1840 // The user tried to define a non-static data member
1841 // out-of-line (C++ [dcl.meaning]p1).
1842 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1843 << D.getCXXScopeSpec().getRange();
1844 NewVD->Destroy(Context);
1845 return 0;
1846 }
1847
Reid Spencer5f016e22007-07-11 17:01:13 +00001848 NewVD = MergeVarDecl(NewVD, PrevDecl);
1849 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001850
1851 if (D.getCXXScopeSpec().isSet()) {
1852 // No previous declaration in the qualifying scope.
1853 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1854 << Name << D.getCXXScopeSpec().getRange();
1855 InvalidDecl = true;
1856 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001857 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001858 New = NewVD;
1859 }
1860
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001861 // Set the lexical context. If the declarator has a C++ scope specifier, the
1862 // lexical context will be different from the semantic context.
1863 New->setLexicalDeclContext(CurContext);
1864
Reid Spencer5f016e22007-07-11 17:01:13 +00001865 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001866 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001867 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001868 // If any semantic error occurred, mark the decl as invalid.
1869 if (D.getInvalidType() || InvalidDecl)
1870 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001871
1872 return New;
1873}
1874
Steve Naroff6594a702008-10-27 11:34:16 +00001875void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001876 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1877 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001878}
1879
Eli Friedmanc594b322008-05-20 13:48:25 +00001880bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1881 switch (Init->getStmtClass()) {
1882 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001883 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001884 return true;
1885 case Expr::ParenExprClass: {
1886 const ParenExpr* PE = cast<ParenExpr>(Init);
1887 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1888 }
1889 case Expr::CompoundLiteralExprClass:
1890 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001891 case Expr::DeclRefExprClass:
1892 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001893 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001894 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1895 if (VD->hasGlobalStorage())
1896 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001897 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001898 return true;
1899 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001900 if (isa<FunctionDecl>(D))
1901 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001902 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001903 return true;
1904 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001905 case Expr::MemberExprClass: {
1906 const MemberExpr *M = cast<MemberExpr>(Init);
1907 if (M->isArrow())
1908 return CheckAddressConstantExpression(M->getBase());
1909 return CheckAddressConstantExpressionLValue(M->getBase());
1910 }
1911 case Expr::ArraySubscriptExprClass: {
1912 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1913 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1914 return CheckAddressConstantExpression(ASE->getBase()) ||
1915 CheckArithmeticConstantExpression(ASE->getIdx());
1916 }
1917 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001918 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001919 return false;
1920 case Expr::UnaryOperatorClass: {
1921 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1922
1923 // C99 6.6p9
1924 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001925 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001926
Steve Naroff6594a702008-10-27 11:34:16 +00001927 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001928 return true;
1929 }
1930 }
1931}
1932
1933bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1934 switch (Init->getStmtClass()) {
1935 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001936 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001937 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001938 case Expr::ParenExprClass:
1939 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001940 case Expr::StringLiteralClass:
1941 case Expr::ObjCStringLiteralClass:
1942 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001943 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001944 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001945 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1946 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1947 Builtin::BI__builtin___CFStringMakeConstantString)
1948 return false;
1949
Steve Naroff6594a702008-10-27 11:34:16 +00001950 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001951 return true;
1952
Eli Friedmanc594b322008-05-20 13:48:25 +00001953 case Expr::UnaryOperatorClass: {
1954 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1955
1956 // C99 6.6p9
1957 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1958 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1959
1960 if (Exp->getOpcode() == UnaryOperator::Extension)
1961 return CheckAddressConstantExpression(Exp->getSubExpr());
1962
Steve Naroff6594a702008-10-27 11:34:16 +00001963 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001964 return true;
1965 }
1966 case Expr::BinaryOperatorClass: {
1967 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1968 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1969
1970 Expr *PExp = Exp->getLHS();
1971 Expr *IExp = Exp->getRHS();
1972 if (IExp->getType()->isPointerType())
1973 std::swap(PExp, IExp);
1974
1975 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1976 return CheckAddressConstantExpression(PExp) ||
1977 CheckArithmeticConstantExpression(IExp);
1978 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001979 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001980 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001981 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001982 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1983 // Check for implicit promotion
1984 if (SubExpr->getType()->isFunctionType() ||
1985 SubExpr->getType()->isArrayType())
1986 return CheckAddressConstantExpressionLValue(SubExpr);
1987 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001988
1989 // Check for pointer->pointer cast
1990 if (SubExpr->getType()->isPointerType())
1991 return CheckAddressConstantExpression(SubExpr);
1992
Eli Friedmanc3f07642008-08-25 20:46:57 +00001993 if (SubExpr->getType()->isIntegralType()) {
1994 // Check for the special-case of a pointer->int->pointer cast;
1995 // this isn't standard, but some code requires it. See
1996 // PR2720 for an example.
1997 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1998 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1999 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
2000 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2001 if (IntWidth >= PointerWidth) {
2002 return CheckAddressConstantExpression(SubCast->getSubExpr());
2003 }
2004 }
2005 }
2006 }
2007 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002008 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00002009 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002010
Steve Naroff6594a702008-10-27 11:34:16 +00002011 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002012 return true;
2013 }
2014 case Expr::ConditionalOperatorClass: {
2015 // FIXME: Should we pedwarn here?
2016 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
2017 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002018 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002019 return true;
2020 }
2021 if (CheckArithmeticConstantExpression(Exp->getCond()))
2022 return true;
2023 if (Exp->getLHS() &&
2024 CheckAddressConstantExpression(Exp->getLHS()))
2025 return true;
2026 return CheckAddressConstantExpression(Exp->getRHS());
2027 }
2028 case Expr::AddrLabelExprClass:
2029 return false;
2030 }
2031}
2032
Eli Friedman4caf0552008-06-09 05:05:07 +00002033static const Expr* FindExpressionBaseAddress(const Expr* E);
2034
2035static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
2036 switch (E->getStmtClass()) {
2037 default:
2038 return E;
2039 case Expr::ParenExprClass: {
2040 const ParenExpr* PE = cast<ParenExpr>(E);
2041 return FindExpressionBaseAddressLValue(PE->getSubExpr());
2042 }
2043 case Expr::MemberExprClass: {
2044 const MemberExpr *M = cast<MemberExpr>(E);
2045 if (M->isArrow())
2046 return FindExpressionBaseAddress(M->getBase());
2047 return FindExpressionBaseAddressLValue(M->getBase());
2048 }
2049 case Expr::ArraySubscriptExprClass: {
2050 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
2051 return FindExpressionBaseAddress(ASE->getBase());
2052 }
2053 case Expr::UnaryOperatorClass: {
2054 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2055
2056 if (Exp->getOpcode() == UnaryOperator::Deref)
2057 return FindExpressionBaseAddress(Exp->getSubExpr());
2058
2059 return E;
2060 }
2061 }
2062}
2063
2064static const Expr* FindExpressionBaseAddress(const Expr* E) {
2065 switch (E->getStmtClass()) {
2066 default:
2067 return E;
2068 case Expr::ParenExprClass: {
2069 const ParenExpr* PE = cast<ParenExpr>(E);
2070 return FindExpressionBaseAddress(PE->getSubExpr());
2071 }
2072 case Expr::UnaryOperatorClass: {
2073 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2074
2075 // C99 6.6p9
2076 if (Exp->getOpcode() == UnaryOperator::AddrOf)
2077 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
2078
2079 if (Exp->getOpcode() == UnaryOperator::Extension)
2080 return FindExpressionBaseAddress(Exp->getSubExpr());
2081
2082 return E;
2083 }
2084 case Expr::BinaryOperatorClass: {
2085 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2086
2087 Expr *PExp = Exp->getLHS();
2088 Expr *IExp = Exp->getRHS();
2089 if (IExp->getType()->isPointerType())
2090 std::swap(PExp, IExp);
2091
2092 return FindExpressionBaseAddress(PExp);
2093 }
2094 case Expr::ImplicitCastExprClass: {
2095 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2096
2097 // Check for implicit promotion
2098 if (SubExpr->getType()->isFunctionType() ||
2099 SubExpr->getType()->isArrayType())
2100 return FindExpressionBaseAddressLValue(SubExpr);
2101
2102 // Check for pointer->pointer cast
2103 if (SubExpr->getType()->isPointerType())
2104 return FindExpressionBaseAddress(SubExpr);
2105
2106 // We assume that we have an arithmetic expression here;
2107 // if we don't, we'll figure it out later
2108 return 0;
2109 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002110 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00002111 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2112
2113 // Check for pointer->pointer cast
2114 if (SubExpr->getType()->isPointerType())
2115 return FindExpressionBaseAddress(SubExpr);
2116
2117 // We assume that we have an arithmetic expression here;
2118 // if we don't, we'll figure it out later
2119 return 0;
2120 }
2121 }
2122}
2123
Anders Carlsson51fe9962008-11-22 21:04:56 +00002124bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002125 switch (Init->getStmtClass()) {
2126 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002127 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002128 return true;
2129 case Expr::ParenExprClass: {
2130 const ParenExpr* PE = cast<ParenExpr>(Init);
2131 return CheckArithmeticConstantExpression(PE->getSubExpr());
2132 }
2133 case Expr::FloatingLiteralClass:
2134 case Expr::IntegerLiteralClass:
2135 case Expr::CharacterLiteralClass:
2136 case Expr::ImaginaryLiteralClass:
2137 case Expr::TypesCompatibleExprClass:
2138 case Expr::CXXBoolLiteralExprClass:
2139 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002140 case Expr::CallExprClass:
2141 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002142 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002143
2144 // Allow any constant foldable calls to builtins.
2145 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002146 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002147
Steve Naroff6594a702008-10-27 11:34:16 +00002148 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002149 return true;
2150 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002151 case Expr::DeclRefExprClass:
2152 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002153 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2154 if (isa<EnumConstantDecl>(D))
2155 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002156 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002157 return true;
2158 }
2159 case Expr::CompoundLiteralExprClass:
2160 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2161 // but vectors are allowed to be magic.
2162 if (Init->getType()->isVectorType())
2163 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002164 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002165 return true;
2166 case Expr::UnaryOperatorClass: {
2167 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2168
2169 switch (Exp->getOpcode()) {
2170 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2171 // See C99 6.6p3.
2172 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002173 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002174 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002175 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002176 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2177 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002178 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002179 return true;
2180 case UnaryOperator::Extension:
2181 case UnaryOperator::LNot:
2182 case UnaryOperator::Plus:
2183 case UnaryOperator::Minus:
2184 case UnaryOperator::Not:
2185 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2186 }
2187 }
Sebastian Redl05189992008-11-11 17:56:53 +00002188 case Expr::SizeOfAlignOfExprClass: {
2189 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002190 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002191 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002192 return false;
2193 // alignof always evaluates to a constant.
2194 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002195 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002196 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002197 return true;
2198 }
2199 return false;
2200 }
2201 case Expr::BinaryOperatorClass: {
2202 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2203
2204 if (Exp->getLHS()->getType()->isArithmeticType() &&
2205 Exp->getRHS()->getType()->isArithmeticType()) {
2206 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2207 CheckArithmeticConstantExpression(Exp->getRHS());
2208 }
2209
Eli Friedman4caf0552008-06-09 05:05:07 +00002210 if (Exp->getLHS()->getType()->isPointerType() &&
2211 Exp->getRHS()->getType()->isPointerType()) {
2212 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2213 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2214
2215 // Only allow a null (constant integer) base; we could
2216 // allow some additional cases if necessary, but this
2217 // is sufficient to cover offsetof-like constructs.
2218 if (!LHSBase && !RHSBase) {
2219 return CheckAddressConstantExpression(Exp->getLHS()) ||
2220 CheckAddressConstantExpression(Exp->getRHS());
2221 }
2222 }
2223
Steve Naroff6594a702008-10-27 11:34:16 +00002224 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002225 return true;
2226 }
2227 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002228 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002229 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002230 if (SubExpr->getType()->isArithmeticType())
2231 return CheckArithmeticConstantExpression(SubExpr);
2232
Eli Friedmanb529d832008-09-02 09:37:00 +00002233 if (SubExpr->getType()->isPointerType()) {
2234 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2235 // If the pointer has a null base, this is an offsetof-like construct
2236 if (!Base)
2237 return CheckAddressConstantExpression(SubExpr);
2238 }
2239
Steve Naroff6594a702008-10-27 11:34:16 +00002240 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002241 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002242 }
2243 case Expr::ConditionalOperatorClass: {
2244 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002245
2246 // If GNU extensions are disabled, we require all operands to be arithmetic
2247 // constant expressions.
2248 if (getLangOptions().NoExtensions) {
2249 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2250 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2251 CheckArithmeticConstantExpression(Exp->getRHS());
2252 }
2253
2254 // Otherwise, we have to emulate some of the behavior of fold here.
2255 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2256 // because it can constant fold things away. To retain compatibility with
2257 // GCC code, we see if we can fold the condition to a constant (which we
2258 // should always be able to do in theory). If so, we only require the
2259 // specified arm of the conditional to be a constant. This is a horrible
2260 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002261 Expr::EvalResult EvalResult;
2262 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2263 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002264 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002265 // won't be able to either. Use it to emit the diagnostic though.
2266 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002267 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002268 return Res;
2269 }
2270
2271 // Verify that the side following the condition is also a constant.
2272 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002273 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002274 std::swap(TrueSide, FalseSide);
2275
2276 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002277 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002278
2279 // Okay, the evaluated side evaluates to a constant, so we accept this.
2280 // Check to see if the other side is obviously not a constant. If so,
2281 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002282 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002283 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002284 diag::ext_typecheck_expression_not_constant_but_accepted)
2285 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002286 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002287 }
2288 }
2289}
2290
2291bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002292 Expr::EvalResult Result;
2293
Nuno Lopes9a979c32008-07-07 16:46:50 +00002294 Init = Init->IgnoreParens();
2295
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002296 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2297 return false;
2298
Eli Friedmanc594b322008-05-20 13:48:25 +00002299 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2300 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2301 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2302
Nuno Lopes9a979c32008-07-07 16:46:50 +00002303 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2304 return CheckForConstantInitializer(e->getInitializer(), DclT);
2305
Eli Friedmanc594b322008-05-20 13:48:25 +00002306 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2307 unsigned numInits = Exp->getNumInits();
2308 for (unsigned i = 0; i < numInits; i++) {
2309 // FIXME: Need to get the type of the declaration for C++,
2310 // because it could be a reference?
2311 if (CheckForConstantInitializer(Exp->getInit(i),
2312 Exp->getInit(i)->getType()))
2313 return true;
2314 }
2315 return false;
2316 }
2317
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002318 // FIXME: We can probably remove some of this code below, now that
2319 // Expr::Evaluate is doing the heavy lifting for scalars.
2320
Eli Friedmanc594b322008-05-20 13:48:25 +00002321 if (Init->isNullPointerConstant(Context))
2322 return false;
2323 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002324 QualType InitTy = Context.getCanonicalType(Init->getType())
2325 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002326 if (InitTy == Context.BoolTy) {
2327 // Special handling for pointers implicitly cast to bool;
2328 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2329 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2330 Expr* SubE = ICE->getSubExpr();
2331 if (SubE->getType()->isPointerType() ||
2332 SubE->getType()->isArrayType() ||
2333 SubE->getType()->isFunctionType()) {
2334 return CheckAddressConstantExpression(Init);
2335 }
2336 }
2337 } else if (InitTy->isIntegralType()) {
2338 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002339 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002340 SubE = CE->getSubExpr();
2341 // Special check for pointer cast to int; we allow as an extension
2342 // an address constant cast to an integer if the integer
2343 // is of an appropriate width (this sort of code is apparently used
2344 // in some places).
2345 // FIXME: Add pedwarn?
2346 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2347 if (SubE && (SubE->getType()->isPointerType() ||
2348 SubE->getType()->isArrayType() ||
2349 SubE->getType()->isFunctionType())) {
2350 unsigned IntWidth = Context.getTypeSize(Init->getType());
2351 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2352 if (IntWidth >= PointerWidth)
2353 return CheckAddressConstantExpression(Init);
2354 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002355 }
2356
2357 return CheckArithmeticConstantExpression(Init);
2358 }
2359
2360 if (Init->getType()->isPointerType())
2361 return CheckAddressConstantExpression(Init);
2362
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002363 // An array type at the top level that isn't an init-list must
2364 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002365 if (Init->getType()->isArrayType())
2366 return false;
2367
Nuno Lopes73419bf2008-09-01 18:42:41 +00002368 if (Init->getType()->isFunctionType())
2369 return false;
2370
Steve Naroff8af6a452008-10-02 17:12:56 +00002371 // Allow block exprs at top level.
2372 if (Init->getType()->isBlockPointerType())
2373 return false;
2374
Steve Naroff6594a702008-10-27 11:34:16 +00002375 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002376 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002377}
2378
Sebastian Redl798d1192008-12-13 16:23:55 +00002379void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002380 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2381}
2382
2383/// AddInitializerToDecl - Adds the initializer Init to the
2384/// declaration dcl. If DirectInit is true, this is C++ direct
2385/// initialization rather than copy initialization.
2386void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002387 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002388 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002389 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002390
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002391 // If there is no declaration, there was an error parsing it. Just ignore
2392 // the initializer.
2393 if (RealDecl == 0) {
2394 delete Init;
2395 return;
2396 }
Steve Naroffbb204692007-09-12 14:07:44 +00002397
Steve Naroff410e3e22007-09-12 20:13:48 +00002398 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2399 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002400 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2401 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002402 RealDecl->setInvalidDecl();
2403 return;
2404 }
Steve Naroffbb204692007-09-12 14:07:44 +00002405 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002406 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002407 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002408 if (VDecl->isBlockVarDecl()) {
2409 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002410 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002411 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002412 VDecl->setInvalidDecl();
2413 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002414 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002415 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002416 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002417
2418 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2419 if (!getLangOptions().CPlusPlus) {
2420 if (SC == VarDecl::Static) // C99 6.7.8p4.
2421 CheckForConstantInitializer(Init, DclT);
2422 }
Steve Naroffbb204692007-09-12 14:07:44 +00002423 }
Steve Naroff248a7532008-04-15 22:42:06 +00002424 } else if (VDecl->isFileVarDecl()) {
2425 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002426 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002427 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002428 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002429 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002430 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002431
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002432 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2433 if (!getLangOptions().CPlusPlus) {
2434 // C99 6.7.8p4. All file scoped initializers need to be constant.
2435 CheckForConstantInitializer(Init, DclT);
2436 }
Steve Naroffbb204692007-09-12 14:07:44 +00002437 }
2438 // If the type changed, it means we had an incomplete type that was
2439 // completed by the initializer. For example:
2440 // int ary[] = { 1, 3, 5 };
2441 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002442 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002443 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002444 Init->setType(DclT);
2445 }
Steve Naroffbb204692007-09-12 14:07:44 +00002446
2447 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002448 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002449 return;
2450}
2451
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002452void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2453 Decl *RealDecl = static_cast<Decl *>(dcl);
2454
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002455 // If there is no declaration, there was an error parsing it. Just ignore it.
2456 if (RealDecl == 0)
2457 return;
2458
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002459 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2460 QualType Type = Var->getType();
2461 // C++ [dcl.init.ref]p3:
2462 // The initializer can be omitted for a reference only in a
2463 // parameter declaration (8.3.5), in the declaration of a
2464 // function return type, in the declaration of a class member
2465 // within its class declaration (9.2), and where the extern
2466 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002467 if (Type->isReferenceType() &&
2468 Var->getStorageClass() != VarDecl::Extern &&
2469 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002470 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002471 << Var->getDeclName()
2472 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002473 Var->setInvalidDecl();
2474 return;
2475 }
2476
2477 // C++ [dcl.init]p9:
2478 //
2479 // If no initializer is specified for an object, and the object
2480 // is of (possibly cv-qualified) non-POD class type (or array
2481 // thereof), the object shall be default-initialized; if the
2482 // object is of const-qualified type, the underlying class type
2483 // shall have a user-declared default constructor.
2484 if (getLangOptions().CPlusPlus) {
2485 QualType InitType = Type;
2486 if (const ArrayType *Array = Context.getAsArrayType(Type))
2487 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002488 if (Var->getStorageClass() != VarDecl::Extern &&
2489 Var->getStorageClass() != VarDecl::PrivateExtern &&
2490 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002491 const CXXConstructorDecl *Constructor
2492 = PerformInitializationByConstructor(InitType, 0, 0,
2493 Var->getLocation(),
2494 SourceRange(Var->getLocation(),
2495 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002496 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002497 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002498 if (!Constructor)
2499 Var->setInvalidDecl();
2500 }
2501 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002502
Douglas Gregor818ce482008-10-29 13:50:18 +00002503#if 0
2504 // FIXME: Temporarily disabled because we are not properly parsing
2505 // linkage specifications on declarations, e.g.,
2506 //
2507 // extern "C" const CGPoint CGPointerZero;
2508 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002509 // C++ [dcl.init]p9:
2510 //
2511 // If no initializer is specified for an object, and the
2512 // object is of (possibly cv-qualified) non-POD class type (or
2513 // array thereof), the object shall be default-initialized; if
2514 // the object is of const-qualified type, the underlying class
2515 // type shall have a user-declared default
2516 // constructor. Otherwise, if no initializer is specified for
2517 // an object, the object and its subobjects, if any, have an
2518 // indeterminate initial value; if the object or any of its
2519 // subobjects are of const-qualified type, the program is
2520 // ill-formed.
2521 //
2522 // This isn't technically an error in C, so we don't diagnose it.
2523 //
2524 // FIXME: Actually perform the POD/user-defined default
2525 // constructor check.
2526 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002527 Context.getCanonicalType(Type).isConstQualified() &&
2528 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002529 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2530 << Var->getName()
2531 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002532#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002533 }
2534}
2535
Reid Spencer5f016e22007-07-11 17:01:13 +00002536/// The declarators are chained together backwards, reverse the list.
2537Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2538 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002539 Decl *GroupDecl = static_cast<Decl*>(group);
2540 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002541 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002542
2543 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2544 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002545 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002546 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002547 else { // reverse the list.
2548 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002549 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002550 Group->setNextDeclarator(NewGroup);
2551 NewGroup = Group;
2552 Group = Next;
2553 }
2554 }
2555 // Perform semantic analysis that depends on having fully processed both
2556 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002557 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002558 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2559 if (!IDecl)
2560 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002561 QualType T = IDecl->getType();
2562
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002563 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002564 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002565
2566 // FIXME: This won't give the correct result for
2567 // int a[10][n];
2568 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002569 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002570 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2571 SizeRange;
2572
Eli Friedmanc5773c42008-02-15 18:16:39 +00002573 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002574 } else {
2575 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2576 // static storage duration, it shall not have a variable length array.
2577 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002578 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2579 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002580 IDecl->setInvalidDecl();
2581 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002582 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2583 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002584 IDecl->setInvalidDecl();
2585 }
2586 }
2587 } else if (T->isVariablyModifiedType()) {
2588 if (IDecl->isFileVarDecl()) {
2589 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2590 IDecl->setInvalidDecl();
2591 } else {
2592 if (IDecl->getStorageClass() == VarDecl::Extern) {
2593 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2594 IDecl->setInvalidDecl();
2595 }
Steve Naroffbb204692007-09-12 14:07:44 +00002596 }
2597 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002598
Steve Naroffbb204692007-09-12 14:07:44 +00002599 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2600 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002601 if (IDecl->isBlockVarDecl() &&
2602 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002603 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002604 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002605 IDecl->setInvalidDecl();
2606 }
2607 }
2608 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2609 // object that has file scope without an initializer, and without a
2610 // storage-class specifier or with the storage-class specifier "static",
2611 // constitutes a tentative definition. Note: A tentative definition with
2612 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002613 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002614 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002615 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2616 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002617 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002618 // C99 6.9.2p3: If the declaration of an identifier for an object is
2619 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2620 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002621 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002622 IDecl->setInvalidDecl();
2623 }
2624 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002625 if (IDecl->isFileVarDecl())
2626 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002627 }
2628 return NewGroup;
2629}
Steve Naroffe1223f72007-08-28 03:03:08 +00002630
Chris Lattner04421082008-04-08 04:40:51 +00002631/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2632/// to introduce parameters into function prototype scope.
2633Sema::DeclTy *
2634Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002635 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002636
Chris Lattner04421082008-04-08 04:40:51 +00002637 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002638 VarDecl::StorageClass StorageClass = VarDecl::None;
2639 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2640 StorageClass = VarDecl::Register;
2641 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002642 Diag(DS.getStorageClassSpecLoc(),
2643 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002644 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002645 }
2646 if (DS.isThreadSpecified()) {
2647 Diag(DS.getThreadSpecLoc(),
2648 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002649 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002650 }
2651
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002652 // Check that there are no default arguments inside the type of this
2653 // parameter (C++ only).
2654 if (getLangOptions().CPlusPlus)
2655 CheckExtraCXXDefaultArguments(D);
2656
Chris Lattner04421082008-04-08 04:40:51 +00002657 // In this context, we *do not* check D.getInvalidType(). If the declarator
2658 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2659 // though it will not reflect the user specified type.
2660 QualType parmDeclType = GetTypeForDeclarator(D, S);
2661
2662 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2663
Reid Spencer5f016e22007-07-11 17:01:13 +00002664 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2665 // Can this happen for params? We already checked that they don't conflict
2666 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002667 IdentifierInfo *II = D.getIdentifier();
2668 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002669 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002670 // Maybe we will complain about the shadowed template parameter.
2671 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2672 // Just pretend that we didn't see the previous declaration.
2673 PrevDecl = 0;
2674 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002675 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002676
2677 // Recover by removing the name
2678 II = 0;
2679 D.SetIdentifier(0, D.getIdentifierLoc());
2680 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002681 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002682
2683 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2684 // Doing the promotion here has a win and a loss. The win is the type for
2685 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2686 // code generator). The loss is the orginal type isn't preserved. For example:
2687 //
2688 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2689 // int blockvardecl[5];
2690 // sizeof(parmvardecl); // size == 4
2691 // sizeof(blockvardecl); // size == 20
2692 // }
2693 //
2694 // For expressions, all implicit conversions are captured using the
2695 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2696 //
2697 // FIXME: If a source translation tool needs to see the original type, then
2698 // we need to consider storing both types (in ParmVarDecl)...
2699 //
Chris Lattnere6327742008-04-02 05:18:44 +00002700 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002701 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002702 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002703 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002704 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002705
Chris Lattner04421082008-04-08 04:40:51 +00002706 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2707 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002708 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002709 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002710
Chris Lattner04421082008-04-08 04:40:51 +00002711 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002712 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002713
Douglas Gregor584049d2008-12-15 23:53:10 +00002714 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2715 if (D.getCXXScopeSpec().isSet()) {
2716 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2717 << D.getCXXScopeSpec().getRange();
2718 New->setInvalidDecl();
2719 }
2720
Douglas Gregor44b43212008-12-11 16:49:14 +00002721 // Add the parameter declaration into this scope.
2722 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002723 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002724 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002725
Chris Lattner3ff30c82008-06-29 00:02:00 +00002726 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002728
Reid Spencer5f016e22007-07-11 17:01:13 +00002729}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002730
Chris Lattnerb652cea2007-10-09 17:14:05 +00002731Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002732 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002733 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2734 "Not a function declarator!");
2735 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002736
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2738 // for a K&R function.
2739 if (!FTI.hasPrototype) {
2740 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002741 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002742 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2743 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002744 // Implicitly declare the argument as type 'int' for lack of a better
2745 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002746 DeclSpec DS;
2747 const char* PrevSpec; // unused
2748 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2749 PrevSpec);
2750 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2751 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2752 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002753 }
2754 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002756 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 }
2758
Douglas Gregor584049d2008-12-15 23:53:10 +00002759 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002760
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002761 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002762 ActOnDeclarator(ParentScope, D, 0,
2763 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002764}
2765
2766Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2767 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002768 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002769
2770 // See if this is a redefinition.
2771 const FunctionDecl *Definition;
2772 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002773 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002774 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002775 }
2776
Douglas Gregor44b43212008-12-11 16:49:14 +00002777 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002778
Chris Lattner04421082008-04-08 04:40:51 +00002779 // Check the validity of our function parameters
2780 CheckParmsForFunctionDef(FD);
2781
2782 // Introduce our parameters into the function scope
2783 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2784 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002785 Param->setOwningFunction(FD);
2786
Chris Lattner04421082008-04-08 04:40:51 +00002787 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002788 if (Param->getIdentifier())
2789 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 }
Chris Lattner04421082008-04-08 04:40:51 +00002791
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002792 // Checking attributes of current function definition
2793 // dllimport attribute.
2794 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2795 // dllimport attribute cannot be applied to definition.
2796 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2797 Diag(FD->getLocation(),
2798 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2799 << "dllimport";
2800 FD->setInvalidDecl();
2801 return FD;
2802 } else {
2803 // If a symbol previously declared dllimport is later defined, the
2804 // attribute is ignored in subsequent references, and a warning is
2805 // emitted.
2806 Diag(FD->getLocation(),
2807 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2808 << FD->getNameAsCString() << "dllimport";
2809 }
2810 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002811 return FD;
2812}
2813
Sebastian Redl798d1192008-12-13 16:23:55 +00002814Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002815 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002816 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002817 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002818 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002819 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002820 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002821 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002822 } else
2823 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002824 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002825 // Verify and clean out per-function state.
2826
2827 // Check goto/label use.
2828 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2829 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2830 // Verify that we have no forward references left. If so, there was a goto
2831 // or address of a label taken, but no definition of it. Label fwd
2832 // definitions are indicated with a null substmt.
2833 if (I->second->getSubStmt() == 0) {
2834 LabelStmt *L = I->second;
2835 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002836 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002837
2838 // At this point, we have gotos that use the bogus label. Stitch it into
2839 // the function body so that they aren't leaked and that the AST is well
2840 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002841 if (Body) {
2842 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002843 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002844 } else {
2845 // The whole function wasn't parsed correctly, just delete this.
2846 delete L;
2847 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002848 }
2849 }
2850 LabelMap.clear();
2851
Steve Naroffd6d054d2007-11-11 23:20:51 +00002852 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002853}
2854
Reid Spencer5f016e22007-07-11 17:01:13 +00002855/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2856/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002857ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2858 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002859 // Extension in C99. Legal in C90, but warn about it.
2860 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002861 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002862 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002863 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002864
2865 // FIXME: handle stuff like:
2866 // void foo() { extern float X(); }
2867 // void bar() { X(); } <-- implicit decl for X in another scope.
2868
2869 // Set a Declarator for the implicit definition: int foo();
2870 const char *Dummy;
2871 DeclSpec DS;
2872 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2873 Error = Error; // Silence warning.
2874 assert(!Error && "Error setting up implicit decl!");
2875 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002876 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002877 D.SetIdentifier(&II, Loc);
2878
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002879 // Insert this function into translation-unit scope.
2880
2881 DeclContext *PrevDC = CurContext;
2882 CurContext = Context.getTranslationUnitDecl();
2883
Steve Naroffe2ef8152008-04-04 14:32:09 +00002884 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002885 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002886 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002887
2888 CurContext = PrevDC;
2889
Steve Naroffe2ef8152008-04-04 14:32:09 +00002890 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002891}
2892
2893
Chris Lattner41af0932007-11-14 06:34:38 +00002894TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002895 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002896 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002897 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002898
2899 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002900 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2901 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002902 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002903 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002904 if (D.getInvalidType())
2905 NewTD->setInvalidDecl();
2906 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002907}
2908
Steve Naroff08d92e42007-09-15 18:49:24 +00002909/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002910/// former case, Name will be non-null. In the later case, Name will be null.
2911/// TagType indicates what kind of tag this is. TK indicates whether this is a
2912/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002913Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002914 SourceLocation KWLoc, const CXXScopeSpec &SS,
2915 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002916 AttributeList *Attr,
2917 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002918 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 assert((Name != 0 || TK == TK_Definition) &&
2920 "Nameless record must be a definition!");
2921
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002922 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002923 switch (TagType) {
2924 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002925 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2926 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2927 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2928 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002929 }
2930
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002931 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002932 DeclContext *DC = CurContext;
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002933 DeclContext *LexicalContext = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002934 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002935
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002936 if (Name && SS.isNotEmpty()) {
2937 // We have a nested-name tag ('struct foo::bar').
2938
2939 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002940 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002941 Name = 0;
2942 goto CreateNewDecl;
2943 }
2944
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002945 DC = static_cast<DeclContext*>(SS.getScopeRep());
2946 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002947 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2948
2949 // A tag 'foo::bar' must already exist.
2950 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002951 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002952 Name = 0;
2953 goto CreateNewDecl;
2954 }
2955 } else {
2956 // If this is a named struct, check to see if there was a previous forward
2957 // declaration or definition.
2958 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2959 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
Douglas Gregor72de6672009-01-08 20:45:30 +00002960
2961 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2962 // FIXME: This makes sure that we ignore the contexts associated
2963 // with C structs, unions, and enums when looking for a matching
2964 // tag declaration or definition. See the similar lookup tweak
2965 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002966 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2967 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00002968 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002969 }
2970
Douglas Gregorf57172b2008-12-08 18:40:42 +00002971 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002972 // Maybe we will complain about the shadowed template parameter.
2973 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2974 // Just pretend that we didn't see the previous declaration.
2975 PrevDecl = 0;
2976 }
2977
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002978 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002979 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2980 "unexpected Decl type");
2981 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002982 // If this is a use of a previous tag, or if the tag is already declared
2983 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002984 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002985 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002986 // Make sure that this wasn't declared as an enum and now used as a
2987 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002988 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002989 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002990 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002991 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002992 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002993 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002994 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002995 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002996
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002997 // FIXME: In the future, return a variant or some other clue
2998 // for the consumer of this Decl to know it doesn't own it.
2999 // For our current ASTs this shouldn't be a problem, but will
3000 // need to be changed with DeclGroups.
3001 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00003002 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003003
3004 // Diagnose attempts to redefine a tag.
3005 if (TK == TK_Definition) {
3006 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
3007 Diag(NameLoc, diag::err_redefinition) << Name;
3008 Diag(Def->getLocation(), diag::note_previous_definition);
3009 // If this is a redefinition, recover by making this struct be
3010 // anonymous, which will make any later references get the previous
3011 // definition.
3012 Name = 0;
3013 PrevDecl = 0;
3014 }
3015 // Okay, this is definition of a previously declared or referenced
3016 // tag PrevDecl. We're going to create a new Decl for it.
3017 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003018 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003019 // If we get here we have (another) forward declaration or we
3020 // have a definition. Just create a new decl.
3021 } else {
3022 // If we get here, this is a definition of a new tag type in a nested
3023 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
3024 // new decl/type. We set PrevDecl to NULL so that the entities
3025 // have distinct types.
3026 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00003027 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003028 // If we get here, we're going to create a new Decl. If PrevDecl
3029 // is non-NULL, it's a definition of the tag declared by
3030 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003031 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00003032 // PrevDecl is a namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003033 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00003034 // The tag name clashes with a namespace name, issue an error and
3035 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00003036 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003037 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00003038 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003039 PrevDecl = 0;
3040 } else {
3041 // The existing declaration isn't relevant to us; we're in a
3042 // new scope, so clear out the previous declaration.
3043 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00003044 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003045 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003046 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
3047 (Kind != TagDecl::TK_enum)) {
3048 // C++ [basic.scope.pdecl]p5:
3049 // -- for an elaborated-type-specifier of the form
3050 //
3051 // class-key identifier
3052 //
3053 // if the elaborated-type-specifier is used in the
3054 // decl-specifier-seq or parameter-declaration-clause of a
3055 // function defined in namespace scope, the identifier is
3056 // declared as a class-name in the namespace that contains
3057 // the declaration; otherwise, except as a friend
3058 // declaration, the identifier is declared in the smallest
3059 // non-class, non-function-prototype scope that contains the
3060 // declaration.
3061 //
3062 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3063 // C structs and unions.
3064
3065 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003066 // FIXME: We would like to maintain the current DeclContext as the
3067 // lexical context,
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003068 while (DC->isRecord())
3069 DC = DC->getParent();
3070 LexicalContext = DC;
3071
3072 // Find the scope where we'll be declaring the tag.
3073 while (S->isClassScope() ||
3074 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003075 ((S->getFlags() & Scope::DeclScope) == 0) ||
3076 (S->getEntity() &&
3077 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003078 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00003079 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003080
Chris Lattnercc98eac2008-12-17 07:13:27 +00003081CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00003082
3083 // If there is an identifier, use the location of the identifier as the
3084 // location of the decl, otherwise use the location of the struct/union
3085 // keyword.
3086 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3087
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003088 // Otherwise, create a new declaration. If there is a previous
3089 // declaration of the same entity, the two will be linked via
3090 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00003091 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003092
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003093 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003094 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3095 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003096 New = EnumDecl::Create(Context, DC, Loc, Name,
3097 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 // If this is an undefined enum, warn.
3099 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003100 } else {
3101 // struct/union/class
3102
Reid Spencer5f016e22007-07-11 17:01:13 +00003103 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3104 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003105 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003106 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003107 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3108 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003109 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003110 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3111 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003112 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003113
3114 if (Kind != TagDecl::TK_enum) {
3115 // Handle #pragma pack: if the #pragma pack stack has non-default
3116 // alignment, make up a packed attribute for this decl. These
3117 // attributes are checked when the ASTContext lays out the
3118 // structure.
3119 //
3120 // It is important for implementing the correct semantics that this
3121 // happen here (in act on tag decl). The #pragma pack stack is
3122 // maintained as a result of parser callbacks which can occur at
3123 // many points during the parsing of a struct declaration (because
3124 // the #pragma tokens are effectively skipped over during the
3125 // parsing of the struct).
3126 if (unsigned Alignment = PackContext.getAlignment())
3127 New->addAttr(new PackedAttr(Alignment * 8));
3128 }
3129
3130 if (Attr)
3131 ProcessDeclAttributeList(New, Attr);
3132
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003133 // If we're declaring or defining
3134 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3135 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3136
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003137 // Set the lexical context. If the tag has a C++ scope specifier, the
3138 // lexical context will be different from the semantic context.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003139 New->setLexicalDeclContext(LexicalContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00003140
3141 // If this has an identifier, add it to the scope stack.
3142 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003143 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003144
3145 // Add it to the decl chain.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003146 if (LexicalContext != CurContext) {
3147 // FIXME: PushOnScopeChains should not rely on CurContext!
3148 DeclContext *OldContext = CurContext;
3149 CurContext = LexicalContext;
3150 PushOnScopeChains(New, S);
3151 CurContext = OldContext;
3152 } else
3153 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003154 } else {
Douglas Gregor482b77d2009-01-12 23:27:07 +00003155 LexicalContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003156 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003157
Reid Spencer5f016e22007-07-11 17:01:13 +00003158 return New;
3159}
3160
Douglas Gregor72de6672009-01-08 20:45:30 +00003161void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3162 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3163
3164 // Enter the tag context.
3165 PushDeclContext(S, Tag);
3166
3167 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3168 FieldCollector->StartClass();
3169
3170 if (Record->getIdentifier()) {
3171 // C++ [class]p2:
3172 // [...] The class-name is also inserted into the scope of the
3173 // class itself; this is known as the injected-class-name. For
3174 // purposes of access checking, the injected-class-name is treated
3175 // as if it were a public member name.
3176 RecordDecl *InjectedClassName
3177 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3178 CurContext, Record->getLocation(),
3179 Record->getIdentifier(), Record);
3180 InjectedClassName->setImplicit();
3181 PushOnScopeChains(InjectedClassName, S);
3182 }
3183 }
3184}
3185
3186void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3187 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3188
3189 if (isa<CXXRecordDecl>(Tag))
3190 FieldCollector->FinishClass();
3191
3192 // Exit this scope of this tag's definition.
3193 PopDeclContext();
3194
3195 // Notify the consumer that we've defined a tag.
3196 Consumer.HandleTagDeclDefinition(Tag);
3197}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003198
Chris Lattner1d353ba2008-11-12 21:17:48 +00003199/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3200/// types into constant array types in certain situations which would otherwise
3201/// be errors (for GCC compatibility).
3202static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3203 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003204 // This method tries to turn a variable array into a constant
3205 // array even when the size isn't an ICE. This is necessary
3206 // for compatibility with code that depends on gcc's buggy
3207 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003208 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3209 if (!VLATy) return QualType();
3210
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003211 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003212 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003213 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003214 return QualType();
3215
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003216 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3217 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00003218 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3219 return Context.getConstantArrayType(VLATy->getElementType(),
3220 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003221 return QualType();
3222}
3223
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003224bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003225 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003226 // FIXME: 6.7.2.1p4 - verify the field type.
3227
3228 llvm::APSInt Value;
3229 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3230 return true;
3231
Chris Lattnercd087072008-12-12 04:56:04 +00003232 // Zero-width bitfield is ok for anonymous field.
3233 if (Value == 0 && FieldName)
3234 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3235
3236 if (Value.isNegative())
3237 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003238
3239 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3240 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003241 if (TypeSize && Value.getZExtValue() > TypeSize)
3242 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3243 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003244
3245 return false;
3246}
3247
Steve Naroff08d92e42007-09-15 18:49:24 +00003248/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003249/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003250Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003251 SourceLocation DeclStart,
3252 Declarator &D, ExprTy *BitfieldWidth) {
3253 IdentifierInfo *II = D.getIdentifier();
3254 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003255 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003256 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003257 if (II) Loc = D.getIdentifierLoc();
3258
3259 // FIXME: Unnamed fields can be handled in various different ways, for
3260 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003261
Reid Spencer5f016e22007-07-11 17:01:13 +00003262 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003263 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3264 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003265
Reid Spencer5f016e22007-07-11 17:01:13 +00003266 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3267 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003268 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003269 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003270 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003271 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003272 T = FixedTy;
3273 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003274 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003275 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003276 InvalidDecl = true;
3277 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003278 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003279
3280 if (BitWidth) {
3281 if (VerifyBitField(Loc, II, T, BitWidth))
3282 InvalidDecl = true;
3283 } else {
3284 // Not a bitfield.
3285
3286 // validate II.
3287
3288 }
3289
Reid Spencer5f016e22007-07-11 17:01:13 +00003290 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003291 FieldDecl *NewFD;
3292
Douglas Gregor44b43212008-12-11 16:49:14 +00003293 NewFD = FieldDecl::Create(Context, Record,
3294 Loc, II, T, BitWidth,
3295 D.getDeclSpec().getStorageClassSpec() ==
3296 DeclSpec::SCS_mutable,
3297 /*PrevDecl=*/0);
3298
Douglas Gregor72de6672009-01-08 20:45:30 +00003299 if (II) {
3300 Decl *PrevDecl
3301 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3302 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3303 && !isa<TagDecl>(PrevDecl)) {
3304 Diag(Loc, diag::err_duplicate_member) << II;
3305 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3306 NewFD->setInvalidDecl();
3307 Record->setInvalidDecl();
3308 }
3309 }
3310
Sebastian Redl64b45f72009-01-05 20:52:13 +00003311 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003312 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003313 if (!T->isPODType())
3314 cast<CXXRecordDecl>(Record)->setPOD(false);
3315 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003316
Chris Lattner3ff30c82008-06-29 00:02:00 +00003317 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003318
Steve Naroff5912a352007-08-28 20:14:24 +00003319 if (D.getInvalidType() || InvalidDecl)
3320 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003321
Douglas Gregor72de6672009-01-08 20:45:30 +00003322 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003323 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003324 } else
Douglas Gregor482b77d2009-01-12 23:27:07 +00003325 Record->addDecl(NewFD);
Douglas Gregor44b43212008-12-11 16:49:14 +00003326
Steve Naroff5912a352007-08-28 20:14:24 +00003327 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003328}
3329
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003330/// TranslateIvarVisibility - Translate visibility from a token ID to an
3331/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003332static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003333TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003334 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003335 default: assert(0 && "Unknown visitibility kind");
3336 case tok::objc_private: return ObjCIvarDecl::Private;
3337 case tok::objc_public: return ObjCIvarDecl::Public;
3338 case tok::objc_protected: return ObjCIvarDecl::Protected;
3339 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003340 }
3341}
3342
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003343/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3344/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003345Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003346 SourceLocation DeclStart,
3347 Declarator &D, ExprTy *BitfieldWidth,
3348 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003349
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003350 IdentifierInfo *II = D.getIdentifier();
3351 Expr *BitWidth = (Expr*)BitfieldWidth;
3352 SourceLocation Loc = DeclStart;
3353 if (II) Loc = D.getIdentifierLoc();
3354
3355 // FIXME: Unnamed fields can be handled in various different ways, for
3356 // example, unnamed unions inject all members into the struct namespace!
3357
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003358 QualType T = GetTypeForDeclarator(D, S);
3359 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3360 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003361
3362 if (BitWidth) {
3363 // TODO: Validate.
3364 //printf("WARNING: BITFIELDS IGNORED!\n");
3365
3366 // 6.7.2.1p3
3367 // 6.7.2.1p4
3368
3369 } else {
3370 // Not a bitfield.
3371
3372 // validate II.
3373
3374 }
3375
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003376 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3377 // than a variably modified type.
3378 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003379 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003380 InvalidDecl = true;
3381 }
3382
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003383 // Get the visibility (access control) for this ivar.
3384 ObjCIvarDecl::AccessControl ac =
3385 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3386 : ObjCIvarDecl::None;
3387
3388 // Construct the decl.
3389 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003390 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003391
Douglas Gregor72de6672009-01-08 20:45:30 +00003392 if (II) {
3393 Decl *PrevDecl
3394 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3395 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3396 && !isa<TagDecl>(PrevDecl)) {
3397 Diag(Loc, diag::err_duplicate_member) << II;
3398 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3399 NewID->setInvalidDecl();
3400 }
3401 }
3402
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003403 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003404 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003405
3406 if (D.getInvalidType() || InvalidDecl)
3407 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003408
Douglas Gregor72de6672009-01-08 20:45:30 +00003409 if (II) {
3410 // FIXME: When interfaces are DeclContexts, we'll need to add
3411 // these to the interface.
3412 S->AddDecl(NewID);
3413 IdResolver.AddDecl(NewID);
3414 }
3415
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003416 return NewID;
3417}
3418
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003419void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003420 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003421 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003422 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003423 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003424 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3425 assert(EnclosingDecl && "missing record or interface decl");
3426 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3427
Douglas Gregor72de6672009-01-08 20:45:30 +00003428 if (Record) {
3429 QualType RecordType = Context.getTypeDeclType(Record);
3430 if (RecordType->getAsRecordType()->getDecl()->isDefinition()) {
3431 RecordDecl *Def = RecordType->getAsRecordType()->getDecl();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003432 // Diagnose code like:
3433 // struct S { struct S {} X; };
3434 // We discover this when we complete the outer S. Reject and ignore the
3435 // outer S.
Douglas Gregor72de6672009-01-08 20:45:30 +00003436 Diag(Def->getLocation(), diag::err_nested_redefinition)
3437 << Def->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003438 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003439 Record->setInvalidDecl();
3440 return;
3441 }
Douglas Gregor72de6672009-01-08 20:45:30 +00003442 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003443
Reid Spencer5f016e22007-07-11 17:01:13 +00003444 // Verify that all the fields are okay.
3445 unsigned NumNamedMembers = 0;
3446 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003447
Reid Spencer5f016e22007-07-11 17:01:13 +00003448 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003449 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3450 assert(FD && "missing field decl");
3451
Reid Spencer5f016e22007-07-11 17:01:13 +00003452 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003453 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003454
Douglas Gregor72de6672009-01-08 20:45:30 +00003455 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003456 // Remember all fields written by the user.
3457 RecFields.push_back(FD);
3458 }
Steve Narofff13271f2007-09-14 23:09:53 +00003459
Reid Spencer5f016e22007-07-11 17:01:13 +00003460 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003461 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003462 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003463 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003464 FD->setInvalidDecl();
3465 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003466 continue;
3467 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003468 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3469 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003470 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003471 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003472 FD->setInvalidDecl();
3473 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003474 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003475 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003476 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003477 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003478 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003479 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003480 FD->setInvalidDecl();
3481 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003482 continue;
3483 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003484 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003485 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003486 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003487 FD->setInvalidDecl();
3488 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003489 continue;
3490 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003491 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003492 if (Record)
3493 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003494 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003495 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3496 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003497 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003498 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3499 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003500 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003501 Record->setHasFlexibleArrayMember(true);
3502 } else {
3503 // If this is a struct/class and this is not the last element, reject
3504 // it. Note that GCC supports variable sized arrays in the middle of
3505 // structures.
3506 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003507 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003508 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003509 FD->setInvalidDecl();
3510 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003511 continue;
3512 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003513 // We support flexible arrays at the end of structs in other structs
3514 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003515 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003516 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003517 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003518 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003519 }
3520 }
3521 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003522 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003523 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003524 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003525 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003526 FD->setInvalidDecl();
3527 EnclosingDecl->setInvalidDecl();
3528 continue;
3529 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003530 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003531 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003532 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003533 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003534
Reid Spencer5f016e22007-07-11 17:01:13 +00003535 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003536 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003537 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003538 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003539 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003540 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003541 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003542 // Must enforce the rule that ivars in the base classes may not be
3543 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003544 if (ID->getSuperClass()) {
3545 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3546 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3547 ObjCIvarDecl* Ivar = (*IVI);
3548 IdentifierInfo *II = Ivar->getIdentifier();
3549 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3550 if (prevIvar) {
3551 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003552 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003553 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003554 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003555 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003556 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003557 else if (ObjCImplementationDecl *IMPDecl =
3558 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003559 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3560 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003561 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003562 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003563 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003564
3565 if (Attr)
3566 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003567}
3568
Steve Naroff08d92e42007-09-15 18:49:24 +00003569Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003570 DeclTy *lastEnumConst,
3571 SourceLocation IdLoc, IdentifierInfo *Id,
3572 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003573 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003574 EnumConstantDecl *LastEnumConst =
3575 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3576 Expr *Val = static_cast<Expr*>(val);
3577
Chris Lattner31e05722007-08-26 06:24:45 +00003578 // The scope passed in may not be a decl scope. Zip up the scope tree until
3579 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003580 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003581
Reid Spencer5f016e22007-07-11 17:01:13 +00003582 // Verify that there isn't already something declared with this name in this
3583 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003584 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003585 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003586 // Maybe we will complain about the shadowed template parameter.
3587 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3588 // Just pretend that we didn't see the previous declaration.
3589 PrevDecl = 0;
3590 }
3591
3592 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003593 // When in C++, we may get a TagDecl with the same name; in this case the
3594 // enum constant will 'hide' the tag.
3595 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3596 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003597 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003598 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003599 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003600 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003601 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003602 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003603 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003604 return 0;
3605 }
3606 }
3607
3608 llvm::APSInt EnumVal(32);
3609 QualType EltTy;
3610 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003611 // Make sure to promote the operand type to int.
3612 UsualUnaryConversions(Val);
3613
Reid Spencer5f016e22007-07-11 17:01:13 +00003614 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3615 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003616 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003617 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003618 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003619 } else {
3620 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003621 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003622 }
3623
3624 if (!Val) {
3625 if (LastEnumConst) {
3626 // Assign the last value + 1.
3627 EnumVal = LastEnumConst->getInitVal();
3628 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003629
3630 // Check for overflow on increment.
3631 if (EnumVal < LastEnumConst->getInitVal())
3632 Diag(IdLoc, diag::warn_enum_value_overflow);
3633
Chris Lattnerb7416f92007-08-27 17:37:24 +00003634 EltTy = LastEnumConst->getType();
3635 } else {
3636 // First value, set to zero.
3637 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003638 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003639 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003640 }
3641
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003642 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003643 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3644 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003645 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003646
3647 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003648 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003649
Reid Spencer5f016e22007-07-11 17:01:13 +00003650 return New;
3651}
3652
Steve Naroff02408c62008-08-07 14:08:16 +00003653// FIXME: For consistency with ActOnFields(), we should have the parser
3654// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003655void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003656 DeclTy **Elements, unsigned NumElements) {
3657 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003658 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003659
Douglas Gregor074149e2009-01-05 19:45:36 +00003660 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3661 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3662 // Diagnose code like:
3663 // enum e0 {
3664 // E0 = sizeof(enum e0 { E1 })
3665 // };
3666 Diag(Def->getLocation(), diag::err_nested_redefinition)
3667 << Enum->getDeclName();
3668 Diag(Enum->getLocation(), diag::note_previous_definition);
3669 Enum->setInvalidDecl();
Douglas Gregor074149e2009-01-05 19:45:36 +00003670 return;
Steve Naroff02408c62008-08-07 14:08:16 +00003671 }
Douglas Gregor074149e2009-01-05 19:45:36 +00003672
Chris Lattnere37f0be2007-08-28 05:10:31 +00003673 // TODO: If the result value doesn't fit in an int, it must be a long or long
3674 // long value. ISO C does not support this, but GCC does as an extension,
3675 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003676 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003677
Chris Lattnerac609682007-08-28 06:15:15 +00003678 // Verify that all the values are okay, compute the size of the values, and
3679 // reverse the list.
3680 unsigned NumNegativeBits = 0;
3681 unsigned NumPositiveBits = 0;
3682
3683 // Keep track of whether all elements have type int.
3684 bool AllElementsInt = true;
3685
Reid Spencer5f016e22007-07-11 17:01:13 +00003686 for (unsigned i = 0; i != NumElements; ++i) {
3687 EnumConstantDecl *ECD =
3688 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3689 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003690
3691 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003692 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003693 assert(InitVal.getBitWidth() >= IntWidth &&
3694 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003695 if (InitVal.getBitWidth() > IntWidth) {
3696 llvm::APSInt V(InitVal);
3697 V.trunc(IntWidth);
3698 V.extend(InitVal.getBitWidth());
3699 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003700 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3701 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003702 }
Chris Lattnerac609682007-08-28 06:15:15 +00003703
3704 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003705 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003706 NumPositiveBits = std::max(NumPositiveBits,
3707 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003708 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003709 NumNegativeBits = std::max(NumNegativeBits,
3710 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003711
Chris Lattnerac609682007-08-28 06:15:15 +00003712 // Keep track of whether every enum element has type int (very commmon).
3713 if (AllElementsInt)
3714 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003715 }
3716
Chris Lattnerac609682007-08-28 06:15:15 +00003717 // Figure out the type that should be used for this enum.
3718 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3719 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003720 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003721
3722 if (NumNegativeBits) {
3723 // If there is a negative value, figure out the smallest integer type (of
3724 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003725 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003726 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003727 BestWidth = IntWidth;
3728 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003729 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003730
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003731 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003732 BestType = Context.LongTy;
3733 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003734 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003735
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003736 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003737 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3738 BestType = Context.LongLongTy;
3739 }
3740 }
3741 } else {
3742 // If there is no negative value, figure out which of uint, ulong, ulonglong
3743 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003744 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003745 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003746 BestWidth = IntWidth;
3747 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003748 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003749 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003750 } else {
3751 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003752 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003753 "How could an initializer get larger than ULL?");
3754 BestType = Context.UnsignedLongLongTy;
3755 }
3756 }
3757
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003758 // Loop over all of the enumerator constants, changing their types to match
3759 // the type of the enum if needed.
3760 for (unsigned i = 0; i != NumElements; ++i) {
3761 EnumConstantDecl *ECD =
3762 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3763 if (!ECD) continue; // Already issued a diagnostic.
3764
3765 // Standard C says the enumerators have int type, but we allow, as an
3766 // extension, the enumerators to be larger than int size. If each
3767 // enumerator value fits in an int, type it as an int, otherwise type it the
3768 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3769 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003770 if (ECD->getType() == Context.IntTy) {
3771 // Make sure the init value is signed.
3772 llvm::APSInt IV = ECD->getInitVal();
3773 IV.setIsSigned(true);
3774 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003775
3776 if (getLangOptions().CPlusPlus)
3777 // C++ [dcl.enum]p4: Following the closing brace of an
3778 // enum-specifier, each enumerator has the type of its
3779 // enumeration.
3780 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003781 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003782 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003783
3784 // Determine whether the value fits into an int.
3785 llvm::APSInt InitVal = ECD->getInitVal();
3786 bool FitsInInt;
3787 if (InitVal.isUnsigned() || !InitVal.isNegative())
3788 FitsInInt = InitVal.getActiveBits() < IntWidth;
3789 else
3790 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3791
3792 // If it fits into an integer type, force it. Otherwise force it to match
3793 // the enum decl type.
3794 QualType NewTy;
3795 unsigned NewWidth;
3796 bool NewSign;
3797 if (FitsInInt) {
3798 NewTy = Context.IntTy;
3799 NewWidth = IntWidth;
3800 NewSign = true;
3801 } else if (ECD->getType() == BestType) {
3802 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003803 if (getLangOptions().CPlusPlus)
3804 // C++ [dcl.enum]p4: Following the closing brace of an
3805 // enum-specifier, each enumerator has the type of its
3806 // enumeration.
3807 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003808 continue;
3809 } else {
3810 NewTy = BestType;
3811 NewWidth = BestWidth;
3812 NewSign = BestType->isSignedIntegerType();
3813 }
3814
3815 // Adjust the APSInt value.
3816 InitVal.extOrTrunc(NewWidth);
3817 InitVal.setIsSigned(NewSign);
3818 ECD->setInitVal(InitVal);
3819
3820 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003821 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3822 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003823 if (getLangOptions().CPlusPlus)
3824 // C++ [dcl.enum]p4: Following the closing brace of an
3825 // enum-specifier, each enumerator has the type of its
3826 // enumeration.
3827 ECD->setType(EnumType);
3828 else
3829 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003830 }
Chris Lattnerac609682007-08-28 06:15:15 +00003831
Douglas Gregor44b43212008-12-11 16:49:14 +00003832 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003833}
3834
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003835Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003836 ExprArg expr) {
3837 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3838
Chris Lattner8e25d862008-03-16 00:16:02 +00003839 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003840}
3841
Douglas Gregorf44515a2008-12-16 22:23:02 +00003842
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003843void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3844 ExprTy *alignment, SourceLocation PragmaLoc,
3845 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3846 Expr *Alignment = static_cast<Expr *>(alignment);
3847
3848 // If specified then alignment must be a "small" power of two.
3849 unsigned AlignmentVal = 0;
3850 if (Alignment) {
3851 llvm::APSInt Val;
3852 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3853 !Val.isPowerOf2() ||
3854 Val.getZExtValue() > 16) {
3855 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3856 delete Alignment;
3857 return; // Ignore
3858 }
3859
3860 AlignmentVal = (unsigned) Val.getZExtValue();
3861 }
3862
3863 switch (Kind) {
3864 case Action::PPK_Default: // pack([n])
3865 PackContext.setAlignment(AlignmentVal);
3866 break;
3867
3868 case Action::PPK_Show: // pack(show)
3869 // Show the current alignment, making sure to show the right value
3870 // for the default.
3871 AlignmentVal = PackContext.getAlignment();
3872 // FIXME: This should come from the target.
3873 if (AlignmentVal == 0)
3874 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003875 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003876 break;
3877
3878 case Action::PPK_Push: // pack(push [, id] [, [n])
3879 PackContext.push(Name);
3880 // Set the new alignment if specified.
3881 if (Alignment)
3882 PackContext.setAlignment(AlignmentVal);
3883 break;
3884
3885 case Action::PPK_Pop: // pack(pop [, id] [, n])
3886 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3887 // "#pragma pack(pop, identifier, n) is undefined"
3888 if (Alignment && Name)
3889 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3890
3891 // Do the pop.
3892 if (!PackContext.pop(Name)) {
3893 // If a name was specified then failure indicates the name
3894 // wasn't found. Otherwise failure indicates the stack was
3895 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003896 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3897 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003898
3899 // FIXME: Warn about popping named records as MSVC does.
3900 } else {
3901 // Pop succeeded, set the new alignment if specified.
3902 if (Alignment)
3903 PackContext.setAlignment(AlignmentVal);
3904 }
3905 break;
3906
3907 default:
3908 assert(0 && "Invalid #pragma pack kind.");
3909 }
3910}
3911
3912bool PragmaPackStack::pop(IdentifierInfo *Name) {
3913 if (Stack.empty())
3914 return false;
3915
3916 // If name is empty just pop top.
3917 if (!Name) {
3918 Alignment = Stack.back().first;
3919 Stack.pop_back();
3920 return true;
3921 }
3922
3923 // Otherwise, find the named record.
3924 for (unsigned i = Stack.size(); i != 0; ) {
3925 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003926 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003927 // Found it, pop up to and including this record.
3928 Alignment = Stack[i].first;
3929 Stack.erase(Stack.begin() + i, Stack.end());
3930 return true;
3931 }
3932 }
3933
3934 return false;
3935}