blob: 79e443d0b44232ee1d4293889e2ffd95f4df0b46 [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))
109 CurContext->addDecl(Context, SD);
110
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 Gregor44b43212008-12-11 16:49:14 +0000119 if (CurContext == TD->getDeclContext()) {
120 // We're pushing the tag into the current context, which might
121 // require some reshuffling in the identifier resolver.
122 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000123 I = IdResolver.begin(TD->getDeclName(), CurContext,
124 false/*LookInParentCtx*/),
125 IEnd = IdResolver.end();
126 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
127 NamedDecl *PrevDecl = *I;
128 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
129 PrevDecl = *I, ++I) {
130 if (TD->declarationReplaces(*I)) {
131 // This is a redeclaration. Remove it from the chain and
132 // break out, so that we'll add in the shadowed
133 // declaration.
134 S->RemoveDecl(*I);
135 if (PrevDecl == *I) {
136 IdResolver.RemoveDecl(*I);
137 IdResolver.AddDecl(TD);
138 return;
139 } else {
140 IdResolver.RemoveDecl(*I);
141 break;
142 }
143 }
144 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000145
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000146 // There is already a declaration with the same name in the same
147 // scope, which is not a tag declaration. It must be found
148 // before we find the new declaration, so insert the new
149 // declaration at the end of the chain.
150 IdResolver.AddShadowedDecl(TD, PrevDecl);
151
152 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000153 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000154 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000155 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000156 // We are pushing the name of a function, which might be an
157 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000158 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregorce356072009-01-06 23:51:29 +0000159 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000160 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000161 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000162 false/*LookInParentCtx*/),
163 IdResolver.end(),
164 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
165 FD));
166 if (Redecl != IdResolver.end()) {
167 // There is already a declaration of a function on our
168 // IdResolver chain. Replace it with this declaration.
169 S->RemoveDecl(*Redecl);
170 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000171 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000172 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000174 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000175}
176
Steve Naroffb216c882007-10-09 22:01:59 +0000177void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000178 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000179 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
180 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000181
Reid Spencer5f016e22007-07-11 17:01:13 +0000182 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
183 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000184 Decl *TmpD = static_cast<Decl*>(*I);
185 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000186
Douglas Gregor44b43212008-12-11 16:49:14 +0000187 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
188 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000189
Douglas Gregor44b43212008-12-11 16:49:14 +0000190 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000191
Douglas Gregor44b43212008-12-11 16:49:14 +0000192 // Remove this name from our lexical scope.
193 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 }
195}
196
Steve Naroffe8043c32008-04-01 23:04:06 +0000197/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
198/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000199ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000200 // The third "scope" argument is 0 since we aren't enabling lazy built-in
201 // creation from this context.
202 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000203
Steve Naroffb327ce02008-04-02 14:35:35 +0000204 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000205}
206
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000207/// MaybeConstructOverloadSet - Name lookup has determined that the
208/// elements in [I, IEnd) have the name that we are looking for, and
209/// *I is a match for the namespace. This routine returns an
210/// appropriate Decl for name lookup, which may either be *I or an
211/// OverloadeFunctionDecl that represents the overloaded functions in
212/// [I, IEnd).
213///
214/// The existance of this routine is temporary; LookupDecl should
215/// probably be able to return multiple results, to deal with cases of
216/// ambiguity and overloaded functions without needing to create a
217/// Decl node.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000218template<typename DeclIterator>
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000219static Decl *
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000220MaybeConstructOverloadSet(ASTContext &Context,
221 DeclIterator I, DeclIterator IEnd) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000222 assert(I != IEnd && "Iterator range cannot be empty");
223 assert(!isa<OverloadedFunctionDecl>(*I) &&
224 "Cannot have an overloaded function");
225
226 if (isa<FunctionDecl>(*I)) {
227 // If we found a function, there might be more functions. If
228 // so, collect them into an overload set.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000229 DeclIterator Last = I;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000230 OverloadedFunctionDecl *Ovl = 0;
231 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
232 if (!Ovl) {
233 // FIXME: We leak this overload set. Eventually, we want to
234 // stop building the declarations for these overload sets, so
235 // there will be nothing to leak.
236 Ovl = OverloadedFunctionDecl::Create(Context,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000237 cast<ScopedDecl>(*I)->getDeclContext(),
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000238 (*I)->getDeclName());
239 Ovl->addOverload(cast<FunctionDecl>(*I));
240 }
241 Ovl->addOverload(cast<FunctionDecl>(*Last));
242 }
243
244 // If we had more than one function, we built an overload
245 // set. Return it.
246 if (Ovl)
247 return Ovl;
248 }
249
250 return *I;
251}
252
Steve Naroffe8043c32008-04-01 23:04:06 +0000253/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000254/// namespace. NamespaceNameOnly - during lookup only namespace names
255/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
256/// 'When looking up a namespace-name in a using-directive or
257/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregor2def4832008-11-17 20:34:05 +0000258Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000259 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000260 bool enableLazyBuiltinCreation,
Douglas Gregorf780abc2008-12-30 03:27:21 +0000261 bool LookInParent,
262 bool NamespaceNameOnly) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000263 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000264 unsigned NS = NSI;
265 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
266 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000267
Douglas Gregore267ff32008-12-11 20:41:00 +0000268 if (LookupCtx == 0 &&
269 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
270 // Unqualified name lookup in C/Objective-C and name lookup for
271 // labels in C++ is purely lexical, so search in the
272 // declarations attached to the name.
273 assert(!LookupCtx && "Can't perform qualified name lookup here");
Douglas Gregorf780abc2008-12-30 03:27:21 +0000274 assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
Douglas Gregore267ff32008-12-11 20:41:00 +0000275 IdentifierResolver::iterator I
276 = IdResolver.begin(Name, CurContext, LookInParent);
277
278 // Scan up the scope chain looking for a decl that matches this
279 // identifier that is in the appropriate namespace. This search
280 // should not take long, as shadowing of names is uncommon, and
281 // deep shadowing is extremely uncommon.
282 for (; I != IdResolver.end(); ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000283 if ((*I)->isInIdentifierNamespace(NS))
Douglas Gregorf780abc2008-12-30 03:27:21 +0000284 return *I;
Douglas Gregore267ff32008-12-11 20:41:00 +0000285 } else if (LookupCtx) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000286 // Perform qualified name lookup into the LookupCtx.
287 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000288 DeclContext::lookup_const_iterator I, E;
289 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000290 if ((*I)->isInIdentifierNamespace(NS)) {
291 // Ignore non-namespace names if we're only looking for namespaces.
292 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) continue;
293
294 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000295 }
Douglas Gregore267ff32008-12-11 20:41:00 +0000296 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000297 // Name lookup for ordinary names and tag names in C++ requires
298 // looking into scopes that aren't strictly lexical, and
299 // therefore we walk through the context as well as walking
300 // through the scopes.
301 IdentifierResolver::iterator
302 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
303 IEnd = IdResolver.end();
304 for (; S; S = S->getParent()) {
305 // Check whether the IdResolver has anything in this scope.
306 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000307 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Chris Lattner7bea7662009-01-06 07:20:03 +0000308 if ((*I)->isInIdentifierNamespace(NS)) {
309 // Ignore non-namespace names if we're only looking for namespaces.
310 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
311 continue;
312
313 // We found something. Look for anything else in our scope
314 // with this same name and in an acceptable identifier
315 // namespace, so that we can construct an overload set if we
316 // need to.
317 IdentifierResolver::iterator LastI = I;
318 for (++LastI; LastI != IEnd; ++LastI) {
319 if (!(*LastI)->isInIdentifierNamespace(NS) ||
320 !S->isDeclScope(*LastI))
321 break;
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000322 }
Chris Lattner7bea7662009-01-06 07:20:03 +0000323 return MaybeConstructOverloadSet(Context, I, LastI);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000324 }
325 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000326
327 // If there is an entity associated with this scope, it's a
328 // DeclContext. We might need to perform qualified lookup into
329 // it.
330 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
331 while (Ctx && Ctx->isFunctionOrMethod())
332 Ctx = Ctx->getParent();
333 while (Ctx && (Ctx->isNamespace() || Ctx->isCXXRecord())) {
334 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000335 DeclContext::lookup_const_iterator I, E;
336 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000337 // FIXME: Cache this result in the IdResolver
Chris Lattner7bea7662009-01-06 07:20:03 +0000338 if ((*I)->isInIdentifierNamespace(NS)) {
339 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
340 continue;
341 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000342 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000343 }
344
345 Ctx = Ctx->getParent();
346 }
347
Douglas Gregor074149e2009-01-05 19:45:36 +0000348 if (!LookInParent && !Ctx->isTransparentContext())
Douglas Gregor44b43212008-12-11 16:49:14 +0000349 return 0;
350 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000351 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000352
Reid Spencer5f016e22007-07-11 17:01:13 +0000353 // If we didn't find a use of this identifier, and if the identifier
354 // corresponds to a compiler builtin, create the decl object for the builtin
355 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000356 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000357 IdentifierInfo *II = Name.getAsIdentifierInfo();
358 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000359 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000360 // If this is a builtin on this (or all) targets, create the decl.
361 if (unsigned BuiltinID = II->getBuiltinID())
362 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
363 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000364 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000365 // @interface and @compatibility_alias introduce typedef-like names.
366 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000367 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000368 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000369 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
370 if (IDI != ObjCInterfaceDecls.end())
371 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000372 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
373 if (I != ObjCAliasDecls.end())
374 return I->second->getClassInterface();
375 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000376 }
377 return 0;
378}
379
Chris Lattner95e2c712008-05-05 22:18:14 +0000380void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000381 if (!Context.getBuiltinVaListType().isNull())
382 return;
383
384 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000385 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000386 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000387 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
388}
389
Reid Spencer5f016e22007-07-11 17:01:13 +0000390/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
391/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000392ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
393 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000394 Builtin::ID BID = (Builtin::ID)bid;
395
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000396 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000397 InitBuiltinVaListType();
398
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000399 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000400 FunctionDecl *New = FunctionDecl::Create(Context,
401 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000402 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000403 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000404
Chris Lattner95e2c712008-05-05 22:18:14 +0000405 // Create Decl objects for each parameter, adding them to the
406 // FunctionDecl.
407 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
408 llvm::SmallVector<ParmVarDecl*, 16> Params;
409 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
410 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
411 FT->getArgType(i), VarDecl::None, 0,
412 0));
413 New->setParams(&Params[0], Params.size());
414 }
415
416
417
Chris Lattner7f925cc2008-04-11 07:00:53 +0000418 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000419 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000420 return New;
421}
422
Sebastian Redlc42e1182008-11-11 11:37:55 +0000423/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
424/// everything from the standard library is defined.
425NamespaceDecl *Sema::GetStdNamespace() {
426 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000427 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000428 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000429 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000430 0, Global, /*enableLazyBuiltinCreation=*/false);
431 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
432 }
433 return StdNamespace;
434}
435
Reid Spencer5f016e22007-07-11 17:01:13 +0000436/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
437/// and scope as a previous declaration 'Old'. Figure out how to resolve this
438/// situation, merging decls or emitting diagnostics as appropriate.
439///
Steve Naroffe8043c32008-04-01 23:04:06 +0000440TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000441 // Allow multiple definitions for ObjC built-in typedefs.
442 // FIXME: Verify the underlying types are equivalent!
443 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000444 const IdentifierInfo *TypeID = New->getIdentifier();
445 switch (TypeID->getLength()) {
446 default: break;
447 case 2:
448 if (!TypeID->isStr("id"))
449 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000450 Context.setObjCIdType(New);
451 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000452 case 5:
453 if (!TypeID->isStr("Class"))
454 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000455 Context.setObjCClassType(New);
456 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000457 case 3:
458 if (!TypeID->isStr("SEL"))
459 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000460 Context.setObjCSelType(New);
461 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000462 case 8:
463 if (!TypeID->isStr("Protocol"))
464 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000465 Context.setObjCProtoType(New->getUnderlyingType());
466 return New;
467 }
468 // Fall through - the typedef name was not a builtin type.
469 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 // Verify the old decl was also a typedef.
471 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
472 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000473 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000474 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000475 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 return New;
477 }
478
Chris Lattner99cb9972008-07-25 18:44:27 +0000479 // If the typedef types are not identical, reject them in all languages and
480 // with any extensions enabled.
481 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
482 Context.getCanonicalType(Old->getUnderlyingType()) !=
483 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000484 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000485 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000486 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner99cb9972008-07-25 18:44:27 +0000487 return Old;
488 }
489
Eli Friedman54ecfce2008-06-11 06:20:39 +0000490 if (getLangOptions().Microsoft) return New;
491
Douglas Gregorbbe27432008-11-21 16:29:06 +0000492 // C++ [dcl.typedef]p2:
493 // In a given non-class scope, a typedef specifier can be used to
494 // redefine the name of any type declared in that scope to refer
495 // to the type to which it already refers.
496 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
497 return New;
498
499 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000500 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
501 // *either* declaration is in a system header. The code below implements
502 // this adhoc compatibility rule. FIXME: The following code will not
503 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000504 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
505 SourceManager &SrcMgr = Context.getSourceManager();
506 if (SrcMgr.isInSystemHeader(Old->getLocation()))
507 return New;
508 if (SrcMgr.isInSystemHeader(New->getLocation()))
509 return New;
510 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000511
Chris Lattner08631c52008-11-23 21:45:46 +0000512 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000513 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 return New;
515}
516
Chris Lattner6b6b5372008-06-26 18:38:35 +0000517/// DeclhasAttr - returns true if decl Declaration already has the target
518/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000519static bool DeclHasAttr(const Decl *decl, const Attr *target) {
520 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
521 if (attr->getKind() == target->getKind())
522 return true;
523
524 return false;
525}
526
527/// MergeAttributes - append attributes from the Old decl to the New one.
528static void MergeAttributes(Decl *New, Decl *Old) {
529 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
530
Chris Lattnerddee4232008-03-03 03:28:21 +0000531 while (attr) {
532 tmp = attr;
533 attr = attr->getNext();
534
535 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000536 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000537 New->addAttr(tmp);
538 } else {
539 tmp->setNext(0);
540 delete(tmp);
541 }
542 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000543
544 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000545}
546
Chris Lattner04421082008-04-08 04:40:51 +0000547/// MergeFunctionDecl - We just parsed a function 'New' from
548/// declarator D which has the same name and scope as a previous
549/// declaration 'Old'. Figure out how to resolve this situation,
550/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000551/// Redeclaration will be set true if this New is a redeclaration OldD.
552///
553/// In C++, New and Old must be declarations that are not
554/// overloaded. Use IsOverload to determine whether New and Old are
555/// overloaded, and to select the Old declaration that New should be
556/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000557FunctionDecl *
558Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000559 assert(!isa<OverloadedFunctionDecl>(OldD) &&
560 "Cannot merge with an overloaded function declaration");
561
Douglas Gregorf0097952008-04-21 02:02:58 +0000562 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 // Verify the old decl was also a function.
564 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
565 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000566 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000567 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000568 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 return New;
570 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000571
572 // Determine whether the previous declaration was a definition,
573 // implicit declaration, or a declaration.
574 diag::kind PrevDiag;
575 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000576 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000577 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000578 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000579 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000580 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000581
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000582 QualType OldQType = Context.getCanonicalType(Old->getType());
583 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000584
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000585 if (getLangOptions().CPlusPlus) {
586 // (C++98 13.1p2):
587 // Certain function declarations cannot be overloaded:
588 // -- Function declarations that differ only in the return type
589 // cannot be overloaded.
590 QualType OldReturnType
591 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
592 QualType NewReturnType
593 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
594 if (OldReturnType != NewReturnType) {
595 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
596 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000597 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000598 return New;
599 }
600
601 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
602 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
603 if (OldMethod && NewMethod) {
604 // -- Member function declarations with the same name and the
605 // same parameter types cannot be overloaded if any of them
606 // is a static member function declaration.
607 if (OldMethod->isStatic() || NewMethod->isStatic()) {
608 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
609 Diag(Old->getLocation(), PrevDiag);
610 return New;
611 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000612
613 // C++ [class.mem]p1:
614 // [...] A member shall not be declared twice in the
615 // member-specification, except that a nested class or member
616 // class template can be declared and then later defined.
617 if (OldMethod->getLexicalDeclContext() ==
618 NewMethod->getLexicalDeclContext()) {
619 unsigned NewDiag;
620 if (isa<CXXConstructorDecl>(OldMethod))
621 NewDiag = diag::err_constructor_redeclared;
622 else if (isa<CXXDestructorDecl>(NewMethod))
623 NewDiag = diag::err_destructor_redeclared;
624 else if (isa<CXXConversionDecl>(NewMethod))
625 NewDiag = diag::err_conv_function_redeclared;
626 else
627 NewDiag = diag::err_member_redeclared;
628
629 Diag(New->getLocation(), NewDiag);
630 Diag(Old->getLocation(), PrevDiag);
631 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000632 }
633
634 // (C++98 8.3.5p3):
635 // All declarations for a function shall agree exactly in both the
636 // return type and the parameter-type-list.
637 if (OldQType == NewQType) {
638 // We have a redeclaration.
639 MergeAttributes(New, Old);
640 Redeclaration = true;
641 return MergeCXXFunctionDecl(New, Old);
642 }
643
644 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000645 }
Chris Lattner04421082008-04-08 04:40:51 +0000646
647 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000648 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000649 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000650 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000651 MergeAttributes(New, Old);
652 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000653 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000654 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000655
Steve Naroff837618c2008-01-16 15:01:34 +0000656 // A function that has already been declared has been redeclared or defined
657 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000658
Reid Spencer5f016e22007-07-11 17:01:13 +0000659 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
660 // TODO: This is totally simplistic. It should handle merging functions
661 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000662 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000663 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000664 return New;
665}
666
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000667/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000668static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000669 if (VD->isFileVarDecl())
670 return (!VD->getInit() &&
671 (VD->getStorageClass() == VarDecl::None ||
672 VD->getStorageClass() == VarDecl::Static));
673 return false;
674}
675
676/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
677/// when dealing with C "tentative" external object definitions (C99 6.9.2).
678void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
679 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000680 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000681
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000682 // FIXME: I don't this will actually see all of the
683 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000684 for (IdentifierResolver::iterator
685 I = IdResolver.begin(VD->getIdentifier(),
686 VD->getDeclContext(), false/*LookInParentCtx*/),
687 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000688 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000689 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
690
Steve Narofff855e6f2008-08-10 15:20:13 +0000691 // Handle the following case:
692 // int a[10];
693 // int a[]; - the code below makes sure we set the correct type.
694 // int a[11]; - this is an error, size isn't 10.
695 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
696 OldDecl->getType()->isConstantArrayType())
697 VD->setType(OldDecl->getType());
698
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000699 // Check for "tentative" definitions. We can't accomplish this in
700 // MergeVarDecl since the initializer hasn't been attached.
701 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
702 continue;
703
704 // Handle __private_extern__ just like extern.
705 if (OldDecl->getStorageClass() != VarDecl::Extern &&
706 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
707 VD->getStorageClass() != VarDecl::Extern &&
708 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000709 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000710 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000711 }
712 }
713 }
714}
715
Reid Spencer5f016e22007-07-11 17:01:13 +0000716/// MergeVarDecl - We just parsed a variable 'New' which has the same name
717/// and scope as a previous declaration 'Old'. Figure out how to resolve this
718/// situation, merging decls or emitting diagnostics as appropriate.
719///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000720/// Tentative definition rules (C99 6.9.2p2) are checked by
721/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
722/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000723///
Steve Naroffe8043c32008-04-01 23:04:06 +0000724VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 // Verify the old decl was also a variable.
726 VarDecl *Old = dyn_cast<VarDecl>(OldD);
727 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000728 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000729 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000730 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 return New;
732 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000733
734 MergeAttributes(New, Old);
735
Reid Spencer5f016e22007-07-11 17:01:13 +0000736 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000737 QualType OldCType = Context.getCanonicalType(Old->getType());
738 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000739 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000740 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000741 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000742 return New;
743 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000744 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
745 if (New->getStorageClass() == VarDecl::Static &&
746 (Old->getStorageClass() == VarDecl::None ||
747 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000748 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000749 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000750 return New;
751 }
752 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
753 if (New->getStorageClass() != VarDecl::Static &&
754 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000755 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000756 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000757 return New;
758 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000759 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
760 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000761 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000762 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000763 }
764 return New;
765}
766
Chris Lattner04421082008-04-08 04:40:51 +0000767/// CheckParmsForFunctionDef - Check that the parameters of the given
768/// function are appropriate for the definition of a function. This
769/// takes care of any checks that cannot be performed on the
770/// declaration itself, e.g., that the types of each of the function
771/// parameters are complete.
772bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
773 bool HasInvalidParm = false;
774 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
775 ParmVarDecl *Param = FD->getParamDecl(p);
776
777 // C99 6.7.5.3p4: the parameters in a parameter type list in a
778 // function declarator that is part of a function definition of
779 // that function shall not have incomplete type.
780 if (Param->getType()->isIncompleteType() &&
781 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000782 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000783 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000784 Param->setInvalidDecl();
785 HasInvalidParm = true;
786 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000787
788 // C99 6.9.1p5: If the declarator includes a parameter type list, the
789 // declaration of each parameter shall include an identifier.
790 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
791 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000792 }
793
794 return HasInvalidParm;
795}
796
Reid Spencer5f016e22007-07-11 17:01:13 +0000797/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
798/// no declarator (e.g. "struct foo;") is parsed.
799Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000800 // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
801 if (!DS.isMissingDeclaratorOk()) {
802 // FIXME: This diagnostic is emitted even when various previous
803 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
804 // DeclSpec has no means of communicating this information, and the
805 // responsible parser functions are quite far apart.
806 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
807 << DS.getSourceRange();
808 return 0;
809 }
810
Steve Naroff92199282007-11-17 21:37:36 +0000811 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000812}
813
Steve Naroffd0091aa2008-01-10 22:15:12 +0000814bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000815 // Get the type before calling CheckSingleAssignmentConstraints(), since
816 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000817 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000818
819 if (getLangOptions().CPlusPlus)
820 return PerformCopyInitialization(Init, DeclType, "initializing");
821
Chris Lattner5cf216b2008-01-04 18:04:52 +0000822 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
823 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
824 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000825}
826
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000827bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000828 const ArrayType *AT = Context.getAsArrayType(DeclT);
829
830 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000831 // C99 6.7.8p14. We have an array of character type with unknown size
832 // being initialized to a string literal.
833 llvm::APSInt ConstVal(32);
834 ConstVal = strLiteral->getByteLength() + 1;
835 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000836 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000837 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000838 } else {
839 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000840 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000841 // FIXME: Avoid truncation for 64-bit length strings.
842 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000843 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000844 diag::warn_initializer_string_for_char_array_too_long)
845 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000846 }
847 // Set type from "char *" to "constant array of char".
848 strLiteral->setType(DeclT);
849 // For now, we always return false (meaning success).
850 return false;
851}
852
853StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000854 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000855 if (AT && AT->getElementType()->isCharType()) {
856 return dyn_cast<StringLiteral>(Init);
857 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000858 return 0;
859}
860
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000861bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
862 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000863 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +0000864 if (DeclType->isDependentType() || Init->isTypeDependent())
865 return false;
866
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000867 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +0000868 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000869 // (8.3.2), shall be initialized by an object, or function, of
870 // type T or by an object that can be converted into a T.
871 if (DeclType->isReferenceType())
872 return CheckReferenceInit(Init, DeclType);
873
Steve Naroffca107302008-01-21 23:53:58 +0000874 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
875 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000876 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000877 return Diag(InitLoc, diag::err_variable_object_no_init)
878 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000879
Steve Naroff2fdc3742007-12-10 22:44:33 +0000880 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
881 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000882 // FIXME: Handle wide strings
883 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
884 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000885
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000886 // C++ [dcl.init]p14:
887 // -- If the destination type is a (possibly cv-qualified) class
888 // type:
889 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
890 QualType DeclTypeC = Context.getCanonicalType(DeclType);
891 QualType InitTypeC = Context.getCanonicalType(Init->getType());
892
893 // -- If the initialization is direct-initialization, or if it is
894 // copy-initialization where the cv-unqualified version of the
895 // source type is the same class as, or a derived class of, the
896 // class of the destination, constructors are considered.
897 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
898 IsDerivedFrom(InitTypeC, DeclTypeC)) {
899 CXXConstructorDecl *Constructor
900 = PerformInitializationByConstructor(DeclType, &Init, 1,
901 InitLoc, Init->getSourceRange(),
902 InitEntity, IK_Copy);
903 return Constructor == 0;
904 }
905
906 // -- Otherwise (i.e., for the remaining copy-initialization
907 // cases), user-defined conversion sequences that can
908 // convert from the source type to the destination type or
909 // (when a conversion function is used) to a derived class
910 // thereof are enumerated as described in 13.3.1.4, and the
911 // best one is chosen through overload resolution
912 // (13.3). If the conversion cannot be done or is
913 // ambiguous, the initialization is ill-formed. The
914 // function selected is called with the initializer
915 // expression as its argument; if the function is a
916 // constructor, the call initializes a temporary of the
917 // destination type.
918 // FIXME: We're pretending to do copy elision here; return to
919 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +0000920 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000921 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000922
Douglas Gregor61366e92008-12-24 00:01:03 +0000923 if (InitEntity)
924 return Diag(InitLoc, diag::err_cannot_initialize_decl)
925 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
926 << Init->getType() << Init->getSourceRange();
927 else
928 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
929 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
930 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000931 }
932
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000933 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000934 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000935 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
936 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000937
Steve Naroffd0091aa2008-01-10 22:15:12 +0000938 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000939 } else if (getLangOptions().CPlusPlus) {
940 // C++ [dcl.init]p14:
941 // [...] If the class is an aggregate (8.5.1), and the initializer
942 // is a brace-enclosed list, see 8.5.1.
943 //
944 // Note: 8.5.1 is handled below; here, we diagnose the case where
945 // we have an initializer list and a destination type that is not
946 // an aggregate.
947 // FIXME: In C++0x, this is yet another form of initialization.
948 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
949 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
950 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000951 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +0000952 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000953 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000954 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000955
Steve Naroff0cca7492008-05-01 22:18:59 +0000956 InitListChecker CheckInitList(this, InitList, DeclType);
957 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000958}
959
Douglas Gregor10bd3682008-11-17 22:58:34 +0000960/// GetNameForDeclarator - Determine the full declaration name for the
961/// given Declarator.
962DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
963 switch (D.getKind()) {
964 case Declarator::DK_Abstract:
965 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
966 return DeclarationName();
967
968 case Declarator::DK_Normal:
969 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
970 return DeclarationName(D.getIdentifier());
971
972 case Declarator::DK_Constructor: {
973 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
974 Ty = Context.getCanonicalType(Ty);
975 return Context.DeclarationNames.getCXXConstructorName(Ty);
976 }
977
978 case Declarator::DK_Destructor: {
979 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
980 Ty = Context.getCanonicalType(Ty);
981 return Context.DeclarationNames.getCXXDestructorName(Ty);
982 }
983
984 case Declarator::DK_Conversion: {
985 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
986 Ty = Context.getCanonicalType(Ty);
987 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
988 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000989
990 case Declarator::DK_Operator:
991 assert(D.getIdentifier() == 0 && "operator names have no identifier");
992 return Context.DeclarationNames.getCXXOperatorName(
993 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000994 }
995
996 assert(false && "Unknown name kind");
997 return DeclarationName();
998}
999
Douglas Gregor584049d2008-12-15 23:53:10 +00001000/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1001/// functions Declaration and Definition are "nearly" matching. This
1002/// heuristic is used to improve diagnostics in the case where an
1003/// out-of-line member function definition doesn't match any
1004/// declaration within the class.
1005static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1006 FunctionDecl *Declaration,
1007 FunctionDecl *Definition) {
1008 if (Declaration->param_size() != Definition->param_size())
1009 return false;
1010 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1011 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1012 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1013
1014 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1015 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1016 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1017 return false;
1018 }
1019
1020 return true;
1021}
1022
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001023Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001024Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1025 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +00001026 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001027 DeclarationName Name = GetNameForDeclarator(D);
1028
Chris Lattnere80a59c2007-07-25 00:24:17 +00001029 // All of these full declarators require an identifier. If it doesn't have
1030 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001031 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001032 if (!D.getInvalidType()) // Reject this if we think it is valid.
1033 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001034 diag::err_declarator_need_ident)
1035 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001036 return 0;
1037 }
1038
Chris Lattner31e05722007-08-26 06:24:45 +00001039 // The scope passed in may not be a decl scope. Zip up the scope tree until
1040 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001041 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1042 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001043 S = S->getParent();
1044
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001045 DeclContext *DC;
1046 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001047 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001048 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001049
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001050 // See if this is a redefinition of a variable in the same scope.
1051 if (!D.getCXXScopeSpec().isSet()) {
1052 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001053 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001054 } else { // Something like "int foo::x;"
1055 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001056 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001057
1058 // C++ 7.3.1.2p2:
1059 // Members (including explicit specializations of templates) of a named
1060 // namespace can also be defined outside that namespace by explicit
1061 // qualification of the name being defined, provided that the entity being
1062 // defined was already declared in the namespace and the definition appears
1063 // after the point of declaration in a namespace that encloses the
1064 // declarations namespace.
1065 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001066 // Note that we only check the context at this point. We don't yet
1067 // have enough information to make sure that PrevDecl is actually
1068 // the declaration we want to match. For example, given:
1069 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001070 // class X {
1071 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001072 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001073 // };
1074 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001075 // void X::f(int) { } // ill-formed
1076 //
1077 // In this case, PrevDecl will point to the overload set
1078 // containing the two f's declared in X, but neither of them
1079 // matches.
1080 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001081 // The qualifying scope doesn't enclose the original declaration.
1082 // Emit diagnostic based on current scope.
1083 SourceLocation L = D.getIdentifierLoc();
1084 SourceRange R = D.getCXXScopeSpec().getRange();
1085 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001086 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001087 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001088 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001089 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001090 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001091 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001092 }
1093 }
1094
Douglas Gregorf57172b2008-12-08 18:40:42 +00001095 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001096 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001097 InvalidDecl = InvalidDecl
1098 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001099 // Just pretend that we didn't see the previous declaration.
1100 PrevDecl = 0;
1101 }
1102
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001103 // In C++, the previous declaration we find might be a tag type
1104 // (class or enum). In this case, the new declaration will hide the
1105 // tag type.
1106 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1107 PrevDecl = 0;
1108
Chris Lattner41af0932007-11-14 06:34:38 +00001109 QualType R = GetTypeForDeclarator(D, S);
1110 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1111
Reid Spencer5f016e22007-07-11 17:01:13 +00001112 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001113 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1114 if (D.getCXXScopeSpec().isSet()) {
1115 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1116 << D.getCXXScopeSpec().getRange();
1117 InvalidDecl = true;
1118 // Pretend we didn't see the scope specifier.
1119 DC = 0;
1120 }
1121
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001122 // Check that there are no default arguments (C++ only).
1123 if (getLangOptions().CPlusPlus)
1124 CheckExtraCXXDefaultArguments(D);
1125
Chris Lattner41af0932007-11-14 06:34:38 +00001126 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001127 if (!NewTD) return 0;
1128
1129 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001130 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001131 // Merge the decl with the existing one if appropriate. If the decl is
1132 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001133 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001134 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1135 if (NewTD == 0) return 0;
1136 }
1137 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001138 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001139 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1140 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001141 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001142 if (NewTD->getUnderlyingType()->isVariableArrayType())
1143 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1144 else
1145 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1146
Steve Naroffd7444aa2007-08-31 17:20:07 +00001147 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001148 }
1149 }
Chris Lattner41af0932007-11-14 06:34:38 +00001150 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001151 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 switch (D.getDeclSpec().getStorageClassSpec()) {
1153 default: assert(0 && "Unknown storage class!");
Sebastian Redl64b45f72009-01-05 20:52:13 +00001154 case DeclSpec::SCS_auto:
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001156 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001157 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001158 InvalidDecl = true;
1159 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001160 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1161 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1162 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001163 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001164 }
1165
Chris Lattnera98e58d2008-03-15 21:24:04 +00001166 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001167 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001168 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1169
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001170 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001171 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001172 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001173 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001174 "Constructors can only be declared in a member context");
1175
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001176 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001177
1178 // Create the new declaration
1179 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001180 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001181 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001182 isExplicit, isInline,
1183 /*isImplicitlyDeclared=*/false);
1184
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001185 if (InvalidDecl)
Douglas Gregor42a552f2008-11-05 20:51:48 +00001186 NewFD->setInvalidDecl();
1187 } else if (D.getKind() == Declarator::DK_Destructor) {
1188 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001189 if (DC->isCXXRecord()) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001190 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001191
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001192 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001193 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001194 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001195 isInline,
1196 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001197
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001198 if (InvalidDecl)
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001199 NewFD->setInvalidDecl();
1200 } else {
1201 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001202
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001203 // Create a FunctionDecl to satisfy the function definition parsing
1204 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001205 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001206 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001207 // FIXME: Move to DeclGroup...
1208 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001209 InvalidDecl = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001210 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001211 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001212 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001213 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001214 Diag(D.getIdentifierLoc(),
1215 diag::err_conv_function_not_member);
1216 return 0;
1217 } else {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001218 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001219
Douglas Gregor70316a02008-12-26 15:00:45 +00001220 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001221 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001222 isInline, isExplicit);
1223
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001224 if (InvalidDecl)
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001225 NewFD->setInvalidDecl();
1226 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001227 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001228 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001229 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001230 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001231 (SC == FunctionDecl::Static), isInline,
1232 LastDeclarator);
1233 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001234 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001235 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001236 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001237 // FIXME: Move to DeclGroup...
1238 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001239 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001240
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001241 // Set the lexical context. If the declarator has a C++
1242 // scope specifier, the lexical context will be different
1243 // from the semantic context.
1244 NewFD->setLexicalDeclContext(CurContext);
1245
Daniel Dunbara80f8742008-08-05 01:35:17 +00001246 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001247 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001248 // The parser guarantees this is a string.
1249 StringLiteral *SE = cast<StringLiteral>(E);
1250 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1251 SE->getByteLength())));
1252 }
1253
Chris Lattner04421082008-04-08 04:40:51 +00001254 // Copy the parameter declarations from the declarator D to
1255 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001256 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001257 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1258
1259 // Create Decl objects for each parameter, adding them to the
1260 // FunctionDecl.
1261 llvm::SmallVector<ParmVarDecl*, 16> Params;
1262
1263 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1264 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001265 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001266 // We let through "const void" here because Sema::GetTypeForDeclarator
1267 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001268 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1269 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001270 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1271 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001272 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1273
Chris Lattnerdef026a2008-04-10 02:26:16 +00001274 // In C++, the empty parameter-type-list must be spelled "void"; a
1275 // typedef of void is not permitted.
1276 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001277 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001278 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1279 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001280 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001281 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1282 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1283 }
1284
1285 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001286 } else if (R->getAsTypedefType()) {
1287 // When we're declaring a function with a typedef, as in the
1288 // following example, we'll need to synthesize (unnamed)
1289 // parameters for use in the declaration.
1290 //
1291 // @code
1292 // typedef void fn(int);
1293 // fn f;
1294 // @endcode
1295 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1296 if (!FT) {
1297 // This is a typedef of a function with no prototype, so we
1298 // don't need to do anything.
1299 } else if ((FT->getNumArgs() == 0) ||
1300 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1301 FT->getArgType(0)->isVoidType())) {
1302 // This is a zero-argument function. We don't need to do anything.
1303 } else {
1304 // Synthesize a parameter for each argument type.
1305 llvm::SmallVector<ParmVarDecl*, 16> Params;
1306 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1307 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001308 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001309 SourceLocation(), 0,
1310 *ArgType, VarDecl::None,
1311 0, 0));
1312 }
1313
1314 NewFD->setParams(&Params[0], Params.size());
1315 }
Chris Lattner04421082008-04-08 04:40:51 +00001316 }
1317
Douglas Gregor72b505b2008-12-16 21:30:33 +00001318 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1319 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001320 else if (isa<CXXDestructorDecl>(NewFD)) {
1321 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1322 Record->setUserDeclaredDestructor(true);
1323 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1324 // user-defined destructor.
1325 Record->setPOD(false);
1326 } else if (CXXConversionDecl *Conversion =
1327 dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001328 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001329
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001330 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1331 if (NewFD->isOverloadedOperator() &&
1332 CheckOverloadedOperatorDeclaration(NewFD))
1333 NewFD->setInvalidDecl();
1334
Steve Naroffffce4d52008-01-09 23:34:55 +00001335 // Merge the decl with the existing one if appropriate. Since C functions
1336 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001337 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001338 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001339 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001340
1341 // If C++, determine whether NewFD is an overload of PrevDecl or
1342 // a declaration that requires merging. If it's an overload,
1343 // there's no more work to do here; we'll just add the new
1344 // function to the scope.
1345 OverloadedFunctionDecl::function_iterator MatchedDecl;
1346 if (!getLangOptions().CPlusPlus ||
1347 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1348 Decl *OldDecl = PrevDecl;
1349
1350 // If PrevDecl was an overloaded function, extract the
1351 // FunctionDecl that matched.
1352 if (isa<OverloadedFunctionDecl>(PrevDecl))
1353 OldDecl = *MatchedDecl;
1354
1355 // NewFD and PrevDecl represent declarations that need to be
1356 // merged.
1357 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1358
1359 if (NewFD == 0) return 0;
1360 if (Redeclaration) {
1361 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1362
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001363 // An out-of-line member function declaration must also be a
1364 // definition (C++ [dcl.meaning]p1).
1365 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1366 !InvalidDecl) {
1367 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1368 << D.getCXXScopeSpec().getRange();
1369 NewFD->setInvalidDecl();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001370 }
1371 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001372 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001373
1374 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1375 // The user tried to provide an out-of-line definition for a
1376 // member function, but there was no such member function
1377 // declared (C++ [class.mfct]p2). For example:
1378 //
1379 // class X {
1380 // void f() const;
1381 // };
1382 //
1383 // void X::f() { } // ill-formed
1384 //
1385 // Complain about this problem, and attempt to suggest close
1386 // matches (e.g., those that differ only in cv-qualifiers and
1387 // whether the parameter types are references).
1388 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1389 << cast<CXXRecordDecl>(DC)->getDeclName()
1390 << D.getCXXScopeSpec().getRange();
1391 InvalidDecl = true;
1392
1393 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1394 if (!PrevDecl) {
1395 // Nothing to suggest.
1396 } else if (OverloadedFunctionDecl *Ovl
1397 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1398 for (OverloadedFunctionDecl::function_iterator
1399 Func = Ovl->function_begin(),
1400 FuncEnd = Ovl->function_end();
1401 Func != FuncEnd; ++Func) {
1402 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1403 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1404
1405 }
1406 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1407 // Suggest this no matter how mismatched it is; it's the only
1408 // thing we have.
1409 unsigned diag;
1410 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1411 diag = diag::note_member_def_close_match;
1412 else if (Method->getBody())
1413 diag = diag::note_previous_definition;
1414 else
1415 diag = diag::note_previous_declaration;
1416 Diag(Method->getLocation(), diag);
1417 }
1418
1419 PrevDecl = 0;
1420 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001421 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +00001422 // Handle attributes. We need to have merged decls when handling attributes
1423 // (for example to check for conflicts, etc).
1424 ProcessDeclAttributes(NewFD, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001425 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001426
Douglas Gregor584049d2008-12-15 23:53:10 +00001427 if (getLangOptions().CPlusPlus) {
1428 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001429 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001430
1431 // An out-of-line member function declaration must also be a
1432 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001433 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001434 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1435 << D.getCXXScopeSpec().getRange();
1436 InvalidDecl = true;
1437 }
1438 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001439 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001440 // Check that there are no default arguments (C++ only).
1441 if (getLangOptions().CPlusPlus)
1442 CheckExtraCXXDefaultArguments(D);
1443
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001444 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001445 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1446 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001447 InvalidDecl = true;
1448 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001449
1450 VarDecl *NewVD;
1451 VarDecl::StorageClass SC;
1452 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001453 default: assert(0 && "Unknown storage class!");
1454 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1455 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1456 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1457 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1458 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1459 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001460 case DeclSpec::SCS_mutable:
1461 // mutable can only appear on non-static class members, so it's always
1462 // an error here
1463 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1464 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001465 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001466 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001467 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001468
1469 IdentifierInfo *II = Name.getAsIdentifierInfo();
1470 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001471 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1472 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001473 return 0;
1474 }
1475
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001476 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001477 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001478 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001479 D.getIdentifierLoc(), II,
1480 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001481 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001482 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001483 if (S->getFnParent() == 0) {
1484 // C99 6.9p2: The storage-class specifiers auto and register shall not
1485 // appear in the declaration specifiers in an external declaration.
1486 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001487 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001488 InvalidDecl = true;
1489 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001490 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001491 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1492 II, R, SC, LastDeclarator,
1493 // FIXME: Move to DeclGroup...
1494 D.getDeclSpec().getSourceRange().getBegin());
1495 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001496 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001498 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001499
Daniel Dunbara735ad82008-08-06 00:03:29 +00001500 // Handle GNU asm-label extension (encoded as an attribute).
1501 if (Expr *E = (Expr*) D.getAsmLabel()) {
1502 // The parser guarantees this is a string.
1503 StringLiteral *SE = cast<StringLiteral>(E);
1504 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1505 SE->getByteLength())));
1506 }
1507
Nate Begemanc8e89a82008-03-14 18:07:10 +00001508 // Emit an error if an address space was applied to decl with local storage.
1509 // This includes arrays of objects with address space qualifiers, but not
1510 // automatic variables that point to other address spaces.
1511 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001512 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1513 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1514 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001515 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001516 // Merge the decl with the existing one if appropriate. If the decl is
1517 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001518 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001519 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1520 // The user tried to define a non-static data member
1521 // out-of-line (C++ [dcl.meaning]p1).
1522 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1523 << D.getCXXScopeSpec().getRange();
1524 NewVD->Destroy(Context);
1525 return 0;
1526 }
1527
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 NewVD = MergeVarDecl(NewVD, PrevDecl);
1529 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001530
1531 if (D.getCXXScopeSpec().isSet()) {
1532 // No previous declaration in the qualifying scope.
1533 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1534 << Name << D.getCXXScopeSpec().getRange();
1535 InvalidDecl = true;
1536 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001537 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001538 New = NewVD;
1539 }
1540
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001541 // Set the lexical context. If the declarator has a C++ scope specifier, the
1542 // lexical context will be different from the semantic context.
1543 New->setLexicalDeclContext(CurContext);
1544
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001546 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001547 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001548 // If any semantic error occurred, mark the decl as invalid.
1549 if (D.getInvalidType() || InvalidDecl)
1550 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001551
1552 return New;
1553}
1554
Steve Naroff6594a702008-10-27 11:34:16 +00001555void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001556 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1557 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001558}
1559
Eli Friedmanc594b322008-05-20 13:48:25 +00001560bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1561 switch (Init->getStmtClass()) {
1562 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001563 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001564 return true;
1565 case Expr::ParenExprClass: {
1566 const ParenExpr* PE = cast<ParenExpr>(Init);
1567 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1568 }
1569 case Expr::CompoundLiteralExprClass:
1570 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001571 case Expr::DeclRefExprClass:
1572 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001573 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001574 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1575 if (VD->hasGlobalStorage())
1576 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001577 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001578 return true;
1579 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001580 if (isa<FunctionDecl>(D))
1581 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001582 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001583 return true;
1584 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001585 case Expr::MemberExprClass: {
1586 const MemberExpr *M = cast<MemberExpr>(Init);
1587 if (M->isArrow())
1588 return CheckAddressConstantExpression(M->getBase());
1589 return CheckAddressConstantExpressionLValue(M->getBase());
1590 }
1591 case Expr::ArraySubscriptExprClass: {
1592 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1593 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1594 return CheckAddressConstantExpression(ASE->getBase()) ||
1595 CheckArithmeticConstantExpression(ASE->getIdx());
1596 }
1597 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001598 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001599 return false;
1600 case Expr::UnaryOperatorClass: {
1601 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1602
1603 // C99 6.6p9
1604 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001605 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001606
Steve Naroff6594a702008-10-27 11:34:16 +00001607 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001608 return true;
1609 }
1610 }
1611}
1612
1613bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1614 switch (Init->getStmtClass()) {
1615 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001616 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001617 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001618 case Expr::ParenExprClass:
1619 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001620 case Expr::StringLiteralClass:
1621 case Expr::ObjCStringLiteralClass:
1622 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001623 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001624 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001625 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1626 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1627 Builtin::BI__builtin___CFStringMakeConstantString)
1628 return false;
1629
Steve Naroff6594a702008-10-27 11:34:16 +00001630 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001631 return true;
1632
Eli Friedmanc594b322008-05-20 13:48:25 +00001633 case Expr::UnaryOperatorClass: {
1634 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1635
1636 // C99 6.6p9
1637 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1638 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1639
1640 if (Exp->getOpcode() == UnaryOperator::Extension)
1641 return CheckAddressConstantExpression(Exp->getSubExpr());
1642
Steve Naroff6594a702008-10-27 11:34:16 +00001643 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001644 return true;
1645 }
1646 case Expr::BinaryOperatorClass: {
1647 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1648 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1649
1650 Expr *PExp = Exp->getLHS();
1651 Expr *IExp = Exp->getRHS();
1652 if (IExp->getType()->isPointerType())
1653 std::swap(PExp, IExp);
1654
1655 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1656 return CheckAddressConstantExpression(PExp) ||
1657 CheckArithmeticConstantExpression(IExp);
1658 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001659 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001660 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001661 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001662 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1663 // Check for implicit promotion
1664 if (SubExpr->getType()->isFunctionType() ||
1665 SubExpr->getType()->isArrayType())
1666 return CheckAddressConstantExpressionLValue(SubExpr);
1667 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001668
1669 // Check for pointer->pointer cast
1670 if (SubExpr->getType()->isPointerType())
1671 return CheckAddressConstantExpression(SubExpr);
1672
Eli Friedmanc3f07642008-08-25 20:46:57 +00001673 if (SubExpr->getType()->isIntegralType()) {
1674 // Check for the special-case of a pointer->int->pointer cast;
1675 // this isn't standard, but some code requires it. See
1676 // PR2720 for an example.
1677 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1678 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1679 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1680 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1681 if (IntWidth >= PointerWidth) {
1682 return CheckAddressConstantExpression(SubCast->getSubExpr());
1683 }
1684 }
1685 }
1686 }
1687 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001688 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001689 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001690
Steve Naroff6594a702008-10-27 11:34:16 +00001691 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001692 return true;
1693 }
1694 case Expr::ConditionalOperatorClass: {
1695 // FIXME: Should we pedwarn here?
1696 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1697 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001698 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001699 return true;
1700 }
1701 if (CheckArithmeticConstantExpression(Exp->getCond()))
1702 return true;
1703 if (Exp->getLHS() &&
1704 CheckAddressConstantExpression(Exp->getLHS()))
1705 return true;
1706 return CheckAddressConstantExpression(Exp->getRHS());
1707 }
1708 case Expr::AddrLabelExprClass:
1709 return false;
1710 }
1711}
1712
Eli Friedman4caf0552008-06-09 05:05:07 +00001713static const Expr* FindExpressionBaseAddress(const Expr* E);
1714
1715static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1716 switch (E->getStmtClass()) {
1717 default:
1718 return E;
1719 case Expr::ParenExprClass: {
1720 const ParenExpr* PE = cast<ParenExpr>(E);
1721 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1722 }
1723 case Expr::MemberExprClass: {
1724 const MemberExpr *M = cast<MemberExpr>(E);
1725 if (M->isArrow())
1726 return FindExpressionBaseAddress(M->getBase());
1727 return FindExpressionBaseAddressLValue(M->getBase());
1728 }
1729 case Expr::ArraySubscriptExprClass: {
1730 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1731 return FindExpressionBaseAddress(ASE->getBase());
1732 }
1733 case Expr::UnaryOperatorClass: {
1734 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1735
1736 if (Exp->getOpcode() == UnaryOperator::Deref)
1737 return FindExpressionBaseAddress(Exp->getSubExpr());
1738
1739 return E;
1740 }
1741 }
1742}
1743
1744static const Expr* FindExpressionBaseAddress(const Expr* E) {
1745 switch (E->getStmtClass()) {
1746 default:
1747 return E;
1748 case Expr::ParenExprClass: {
1749 const ParenExpr* PE = cast<ParenExpr>(E);
1750 return FindExpressionBaseAddress(PE->getSubExpr());
1751 }
1752 case Expr::UnaryOperatorClass: {
1753 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1754
1755 // C99 6.6p9
1756 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1757 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1758
1759 if (Exp->getOpcode() == UnaryOperator::Extension)
1760 return FindExpressionBaseAddress(Exp->getSubExpr());
1761
1762 return E;
1763 }
1764 case Expr::BinaryOperatorClass: {
1765 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1766
1767 Expr *PExp = Exp->getLHS();
1768 Expr *IExp = Exp->getRHS();
1769 if (IExp->getType()->isPointerType())
1770 std::swap(PExp, IExp);
1771
1772 return FindExpressionBaseAddress(PExp);
1773 }
1774 case Expr::ImplicitCastExprClass: {
1775 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1776
1777 // Check for implicit promotion
1778 if (SubExpr->getType()->isFunctionType() ||
1779 SubExpr->getType()->isArrayType())
1780 return FindExpressionBaseAddressLValue(SubExpr);
1781
1782 // Check for pointer->pointer cast
1783 if (SubExpr->getType()->isPointerType())
1784 return FindExpressionBaseAddress(SubExpr);
1785
1786 // We assume that we have an arithmetic expression here;
1787 // if we don't, we'll figure it out later
1788 return 0;
1789 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001790 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001791 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1792
1793 // Check for pointer->pointer cast
1794 if (SubExpr->getType()->isPointerType())
1795 return FindExpressionBaseAddress(SubExpr);
1796
1797 // We assume that we have an arithmetic expression here;
1798 // if we don't, we'll figure it out later
1799 return 0;
1800 }
1801 }
1802}
1803
Anders Carlsson51fe9962008-11-22 21:04:56 +00001804bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001805 switch (Init->getStmtClass()) {
1806 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001807 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001808 return true;
1809 case Expr::ParenExprClass: {
1810 const ParenExpr* PE = cast<ParenExpr>(Init);
1811 return CheckArithmeticConstantExpression(PE->getSubExpr());
1812 }
1813 case Expr::FloatingLiteralClass:
1814 case Expr::IntegerLiteralClass:
1815 case Expr::CharacterLiteralClass:
1816 case Expr::ImaginaryLiteralClass:
1817 case Expr::TypesCompatibleExprClass:
1818 case Expr::CXXBoolLiteralExprClass:
1819 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001820 case Expr::CallExprClass:
1821 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001822 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001823
1824 // Allow any constant foldable calls to builtins.
1825 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001826 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001827
Steve Naroff6594a702008-10-27 11:34:16 +00001828 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001829 return true;
1830 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00001831 case Expr::DeclRefExprClass:
1832 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001833 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1834 if (isa<EnumConstantDecl>(D))
1835 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001836 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001837 return true;
1838 }
1839 case Expr::CompoundLiteralExprClass:
1840 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1841 // but vectors are allowed to be magic.
1842 if (Init->getType()->isVectorType())
1843 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001844 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001845 return true;
1846 case Expr::UnaryOperatorClass: {
1847 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1848
1849 switch (Exp->getOpcode()) {
1850 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1851 // See C99 6.6p3.
1852 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001853 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001854 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001855 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001856 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1857 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001858 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001859 return true;
1860 case UnaryOperator::Extension:
1861 case UnaryOperator::LNot:
1862 case UnaryOperator::Plus:
1863 case UnaryOperator::Minus:
1864 case UnaryOperator::Not:
1865 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1866 }
1867 }
Sebastian Redl05189992008-11-11 17:56:53 +00001868 case Expr::SizeOfAlignOfExprClass: {
1869 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001870 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001871 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001872 return false;
1873 // alignof always evaluates to a constant.
1874 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001875 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001876 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001877 return true;
1878 }
1879 return false;
1880 }
1881 case Expr::BinaryOperatorClass: {
1882 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1883
1884 if (Exp->getLHS()->getType()->isArithmeticType() &&
1885 Exp->getRHS()->getType()->isArithmeticType()) {
1886 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1887 CheckArithmeticConstantExpression(Exp->getRHS());
1888 }
1889
Eli Friedman4caf0552008-06-09 05:05:07 +00001890 if (Exp->getLHS()->getType()->isPointerType() &&
1891 Exp->getRHS()->getType()->isPointerType()) {
1892 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1893 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1894
1895 // Only allow a null (constant integer) base; we could
1896 // allow some additional cases if necessary, but this
1897 // is sufficient to cover offsetof-like constructs.
1898 if (!LHSBase && !RHSBase) {
1899 return CheckAddressConstantExpression(Exp->getLHS()) ||
1900 CheckAddressConstantExpression(Exp->getRHS());
1901 }
1902 }
1903
Steve Naroff6594a702008-10-27 11:34:16 +00001904 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001905 return true;
1906 }
1907 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001908 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001909 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001910 if (SubExpr->getType()->isArithmeticType())
1911 return CheckArithmeticConstantExpression(SubExpr);
1912
Eli Friedmanb529d832008-09-02 09:37:00 +00001913 if (SubExpr->getType()->isPointerType()) {
1914 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1915 // If the pointer has a null base, this is an offsetof-like construct
1916 if (!Base)
1917 return CheckAddressConstantExpression(SubExpr);
1918 }
1919
Steve Naroff6594a702008-10-27 11:34:16 +00001920 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001921 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001922 }
1923 case Expr::ConditionalOperatorClass: {
1924 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001925
1926 // If GNU extensions are disabled, we require all operands to be arithmetic
1927 // constant expressions.
1928 if (getLangOptions().NoExtensions) {
1929 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1930 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1931 CheckArithmeticConstantExpression(Exp->getRHS());
1932 }
1933
1934 // Otherwise, we have to emulate some of the behavior of fold here.
1935 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1936 // because it can constant fold things away. To retain compatibility with
1937 // GCC code, we see if we can fold the condition to a constant (which we
1938 // should always be able to do in theory). If so, we only require the
1939 // specified arm of the conditional to be a constant. This is a horrible
1940 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001941 Expr::EvalResult EvalResult;
1942 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
1943 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001944 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001945 // won't be able to either. Use it to emit the diagnostic though.
1946 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001947 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001948 return Res;
1949 }
1950
1951 // Verify that the side following the condition is also a constant.
1952 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001953 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00001954 std::swap(TrueSide, FalseSide);
1955
1956 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001957 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001958
1959 // Okay, the evaluated side evaluates to a constant, so we accept this.
1960 // Check to see if the other side is obviously not a constant. If so,
1961 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001962 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001963 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001964 diag::ext_typecheck_expression_not_constant_but_accepted)
1965 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001966 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001967 }
1968 }
1969}
1970
1971bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001972 Expr::EvalResult Result;
1973
Nuno Lopes9a979c32008-07-07 16:46:50 +00001974 Init = Init->IgnoreParens();
1975
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001976 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1977 return false;
1978
Eli Friedmanc594b322008-05-20 13:48:25 +00001979 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1980 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1981 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1982
Nuno Lopes9a979c32008-07-07 16:46:50 +00001983 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1984 return CheckForConstantInitializer(e->getInitializer(), DclT);
1985
Eli Friedmanc594b322008-05-20 13:48:25 +00001986 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1987 unsigned numInits = Exp->getNumInits();
1988 for (unsigned i = 0; i < numInits; i++) {
1989 // FIXME: Need to get the type of the declaration for C++,
1990 // because it could be a reference?
1991 if (CheckForConstantInitializer(Exp->getInit(i),
1992 Exp->getInit(i)->getType()))
1993 return true;
1994 }
1995 return false;
1996 }
1997
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001998 // FIXME: We can probably remove some of this code below, now that
1999 // Expr::Evaluate is doing the heavy lifting for scalars.
2000
Eli Friedmanc594b322008-05-20 13:48:25 +00002001 if (Init->isNullPointerConstant(Context))
2002 return false;
2003 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002004 QualType InitTy = Context.getCanonicalType(Init->getType())
2005 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002006 if (InitTy == Context.BoolTy) {
2007 // Special handling for pointers implicitly cast to bool;
2008 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2009 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2010 Expr* SubE = ICE->getSubExpr();
2011 if (SubE->getType()->isPointerType() ||
2012 SubE->getType()->isArrayType() ||
2013 SubE->getType()->isFunctionType()) {
2014 return CheckAddressConstantExpression(Init);
2015 }
2016 }
2017 } else if (InitTy->isIntegralType()) {
2018 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002019 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002020 SubE = CE->getSubExpr();
2021 // Special check for pointer cast to int; we allow as an extension
2022 // an address constant cast to an integer if the integer
2023 // is of an appropriate width (this sort of code is apparently used
2024 // in some places).
2025 // FIXME: Add pedwarn?
2026 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2027 if (SubE && (SubE->getType()->isPointerType() ||
2028 SubE->getType()->isArrayType() ||
2029 SubE->getType()->isFunctionType())) {
2030 unsigned IntWidth = Context.getTypeSize(Init->getType());
2031 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2032 if (IntWidth >= PointerWidth)
2033 return CheckAddressConstantExpression(Init);
2034 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002035 }
2036
2037 return CheckArithmeticConstantExpression(Init);
2038 }
2039
2040 if (Init->getType()->isPointerType())
2041 return CheckAddressConstantExpression(Init);
2042
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002043 // An array type at the top level that isn't an init-list must
2044 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002045 if (Init->getType()->isArrayType())
2046 return false;
2047
Nuno Lopes73419bf2008-09-01 18:42:41 +00002048 if (Init->getType()->isFunctionType())
2049 return false;
2050
Steve Naroff8af6a452008-10-02 17:12:56 +00002051 // Allow block exprs at top level.
2052 if (Init->getType()->isBlockPointerType())
2053 return false;
2054
Steve Naroff6594a702008-10-27 11:34:16 +00002055 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002056 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002057}
2058
Sebastian Redl798d1192008-12-13 16:23:55 +00002059void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002060 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002061 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002062 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002063
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002064 // If there is no declaration, there was an error parsing it. Just ignore
2065 // the initializer.
2066 if (RealDecl == 0) {
2067 delete Init;
2068 return;
2069 }
Steve Naroffbb204692007-09-12 14:07:44 +00002070
Steve Naroff410e3e22007-09-12 20:13:48 +00002071 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2072 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002073 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2074 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002075 RealDecl->setInvalidDecl();
2076 return;
2077 }
Steve Naroffbb204692007-09-12 14:07:44 +00002078 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002079 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002080 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002081 if (VDecl->isBlockVarDecl()) {
2082 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002083 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002084 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002085 VDecl->setInvalidDecl();
2086 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002087 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002088 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002089 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002090
2091 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2092 if (!getLangOptions().CPlusPlus) {
2093 if (SC == VarDecl::Static) // C99 6.7.8p4.
2094 CheckForConstantInitializer(Init, DclT);
2095 }
Steve Naroffbb204692007-09-12 14:07:44 +00002096 }
Steve Naroff248a7532008-04-15 22:42:06 +00002097 } else if (VDecl->isFileVarDecl()) {
2098 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002099 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002100 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002101 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002102 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002103 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002104
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002105 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2106 if (!getLangOptions().CPlusPlus) {
2107 // C99 6.7.8p4. All file scoped initializers need to be constant.
2108 CheckForConstantInitializer(Init, DclT);
2109 }
Steve Naroffbb204692007-09-12 14:07:44 +00002110 }
2111 // If the type changed, it means we had an incomplete type that was
2112 // completed by the initializer. For example:
2113 // int ary[] = { 1, 3, 5 };
2114 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002115 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002116 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002117 Init->setType(DclT);
2118 }
Steve Naroffbb204692007-09-12 14:07:44 +00002119
2120 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002121 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002122 return;
2123}
2124
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002125void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2126 Decl *RealDecl = static_cast<Decl *>(dcl);
2127
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002128 // If there is no declaration, there was an error parsing it. Just ignore it.
2129 if (RealDecl == 0)
2130 return;
2131
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002132 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2133 QualType Type = Var->getType();
2134 // C++ [dcl.init.ref]p3:
2135 // The initializer can be omitted for a reference only in a
2136 // parameter declaration (8.3.5), in the declaration of a
2137 // function return type, in the declaration of a class member
2138 // within its class declaration (9.2), and where the extern
2139 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002140 if (Type->isReferenceType() &&
2141 Var->getStorageClass() != VarDecl::Extern &&
2142 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002143 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002144 << Var->getDeclName()
2145 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002146 Var->setInvalidDecl();
2147 return;
2148 }
2149
2150 // C++ [dcl.init]p9:
2151 //
2152 // If no initializer is specified for an object, and the object
2153 // is of (possibly cv-qualified) non-POD class type (or array
2154 // thereof), the object shall be default-initialized; if the
2155 // object is of const-qualified type, the underlying class type
2156 // shall have a user-declared default constructor.
2157 if (getLangOptions().CPlusPlus) {
2158 QualType InitType = Type;
2159 if (const ArrayType *Array = Context.getAsArrayType(Type))
2160 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002161 if (Var->getStorageClass() != VarDecl::Extern &&
2162 Var->getStorageClass() != VarDecl::PrivateExtern &&
2163 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002164 const CXXConstructorDecl *Constructor
2165 = PerformInitializationByConstructor(InitType, 0, 0,
2166 Var->getLocation(),
2167 SourceRange(Var->getLocation(),
2168 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002169 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002170 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002171 if (!Constructor)
2172 Var->setInvalidDecl();
2173 }
2174 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002175
Douglas Gregor818ce482008-10-29 13:50:18 +00002176#if 0
2177 // FIXME: Temporarily disabled because we are not properly parsing
2178 // linkage specifications on declarations, e.g.,
2179 //
2180 // extern "C" const CGPoint CGPointerZero;
2181 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002182 // C++ [dcl.init]p9:
2183 //
2184 // If no initializer is specified for an object, and the
2185 // object is of (possibly cv-qualified) non-POD class type (or
2186 // array thereof), the object shall be default-initialized; if
2187 // the object is of const-qualified type, the underlying class
2188 // type shall have a user-declared default
2189 // constructor. Otherwise, if no initializer is specified for
2190 // an object, the object and its subobjects, if any, have an
2191 // indeterminate initial value; if the object or any of its
2192 // subobjects are of const-qualified type, the program is
2193 // ill-formed.
2194 //
2195 // This isn't technically an error in C, so we don't diagnose it.
2196 //
2197 // FIXME: Actually perform the POD/user-defined default
2198 // constructor check.
2199 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002200 Context.getCanonicalType(Type).isConstQualified() &&
2201 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002202 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2203 << Var->getName()
2204 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002205#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002206 }
2207}
2208
Reid Spencer5f016e22007-07-11 17:01:13 +00002209/// The declarators are chained together backwards, reverse the list.
2210Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2211 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002212 Decl *GroupDecl = static_cast<Decl*>(group);
2213 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002214 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002215
2216 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2217 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002218 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002219 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002220 else { // reverse the list.
2221 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002222 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002223 Group->setNextDeclarator(NewGroup);
2224 NewGroup = Group;
2225 Group = Next;
2226 }
2227 }
2228 // Perform semantic analysis that depends on having fully processed both
2229 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002230 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002231 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2232 if (!IDecl)
2233 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002234 QualType T = IDecl->getType();
2235
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002236 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002237 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002238
2239 // FIXME: This won't give the correct result for
2240 // int a[10][n];
2241 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002242 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002243 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2244 SizeRange;
2245
Eli Friedmanc5773c42008-02-15 18:16:39 +00002246 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002247 } else {
2248 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2249 // static storage duration, it shall not have a variable length array.
2250 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002251 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2252 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002253 IDecl->setInvalidDecl();
2254 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002255 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2256 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002257 IDecl->setInvalidDecl();
2258 }
2259 }
2260 } else if (T->isVariablyModifiedType()) {
2261 if (IDecl->isFileVarDecl()) {
2262 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2263 IDecl->setInvalidDecl();
2264 } else {
2265 if (IDecl->getStorageClass() == VarDecl::Extern) {
2266 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2267 IDecl->setInvalidDecl();
2268 }
Steve Naroffbb204692007-09-12 14:07:44 +00002269 }
2270 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002271
Steve Naroffbb204692007-09-12 14:07:44 +00002272 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2273 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002274 if (IDecl->isBlockVarDecl() &&
2275 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002276 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002277 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002278 IDecl->setInvalidDecl();
2279 }
2280 }
2281 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2282 // object that has file scope without an initializer, and without a
2283 // storage-class specifier or with the storage-class specifier "static",
2284 // constitutes a tentative definition. Note: A tentative definition with
2285 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002286 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002287 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002288 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2289 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002290 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002291 // C99 6.9.2p3: If the declaration of an identifier for an object is
2292 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2293 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002294 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002295 IDecl->setInvalidDecl();
2296 }
2297 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002298 if (IDecl->isFileVarDecl())
2299 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 }
2301 return NewGroup;
2302}
Steve Naroffe1223f72007-08-28 03:03:08 +00002303
Chris Lattner04421082008-04-08 04:40:51 +00002304/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2305/// to introduce parameters into function prototype scope.
2306Sema::DeclTy *
2307Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002308 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002309
Chris Lattner04421082008-04-08 04:40:51 +00002310 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002311 VarDecl::StorageClass StorageClass = VarDecl::None;
2312 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2313 StorageClass = VarDecl::Register;
2314 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002315 Diag(DS.getStorageClassSpecLoc(),
2316 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002317 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002318 }
2319 if (DS.isThreadSpecified()) {
2320 Diag(DS.getThreadSpecLoc(),
2321 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002322 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002323 }
2324
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002325 // Check that there are no default arguments inside the type of this
2326 // parameter (C++ only).
2327 if (getLangOptions().CPlusPlus)
2328 CheckExtraCXXDefaultArguments(D);
2329
Chris Lattner04421082008-04-08 04:40:51 +00002330 // In this context, we *do not* check D.getInvalidType(). If the declarator
2331 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2332 // though it will not reflect the user specified type.
2333 QualType parmDeclType = GetTypeForDeclarator(D, S);
2334
2335 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2336
Reid Spencer5f016e22007-07-11 17:01:13 +00002337 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2338 // Can this happen for params? We already checked that they don't conflict
2339 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002340 IdentifierInfo *II = D.getIdentifier();
2341 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002342 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002343 // Maybe we will complain about the shadowed template parameter.
2344 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2345 // Just pretend that we didn't see the previous declaration.
2346 PrevDecl = 0;
2347 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002348 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002349
2350 // Recover by removing the name
2351 II = 0;
2352 D.SetIdentifier(0, D.getIdentifierLoc());
2353 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002354 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002355
2356 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2357 // Doing the promotion here has a win and a loss. The win is the type for
2358 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2359 // code generator). The loss is the orginal type isn't preserved. For example:
2360 //
2361 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2362 // int blockvardecl[5];
2363 // sizeof(parmvardecl); // size == 4
2364 // sizeof(blockvardecl); // size == 20
2365 // }
2366 //
2367 // For expressions, all implicit conversions are captured using the
2368 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2369 //
2370 // FIXME: If a source translation tool needs to see the original type, then
2371 // we need to consider storing both types (in ParmVarDecl)...
2372 //
Chris Lattnere6327742008-04-02 05:18:44 +00002373 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002374 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002375 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002376 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002377 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002378
Chris Lattner04421082008-04-08 04:40:51 +00002379 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2380 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002381 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002382 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002383
Chris Lattner04421082008-04-08 04:40:51 +00002384 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002385 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002386
Douglas Gregor584049d2008-12-15 23:53:10 +00002387 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2388 if (D.getCXXScopeSpec().isSet()) {
2389 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2390 << D.getCXXScopeSpec().getRange();
2391 New->setInvalidDecl();
2392 }
2393
Douglas Gregor44b43212008-12-11 16:49:14 +00002394 // Add the parameter declaration into this scope.
2395 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002396 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002397 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002398
Chris Lattner3ff30c82008-06-29 00:02:00 +00002399 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002400 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002401
Reid Spencer5f016e22007-07-11 17:01:13 +00002402}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002403
Chris Lattnerb652cea2007-10-09 17:14:05 +00002404Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002405 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002406 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2407 "Not a function declarator!");
2408 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002409
Reid Spencer5f016e22007-07-11 17:01:13 +00002410 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2411 // for a K&R function.
2412 if (!FTI.hasPrototype) {
2413 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002414 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002415 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2416 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002417 // Implicitly declare the argument as type 'int' for lack of a better
2418 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002419 DeclSpec DS;
2420 const char* PrevSpec; // unused
2421 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2422 PrevSpec);
2423 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2424 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2425 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002426 }
2427 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002428 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002429 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002430 }
2431
Douglas Gregor584049d2008-12-15 23:53:10 +00002432 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002433
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002434 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002435 ActOnDeclarator(ParentScope, D, 0,
2436 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002437}
2438
2439Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2440 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002441 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002442
2443 // See if this is a redefinition.
2444 const FunctionDecl *Definition;
2445 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002446 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002447 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002448 }
2449
Douglas Gregor44b43212008-12-11 16:49:14 +00002450 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002451
Chris Lattner04421082008-04-08 04:40:51 +00002452 // Check the validity of our function parameters
2453 CheckParmsForFunctionDef(FD);
2454
2455 // Introduce our parameters into the function scope
2456 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2457 ParmVarDecl *Param = FD->getParamDecl(p);
2458 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002459 if (Param->getIdentifier())
2460 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002461 }
Chris Lattner04421082008-04-08 04:40:51 +00002462
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002463 // Checking attributes of current function definition
2464 // dllimport attribute.
2465 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2466 // dllimport attribute cannot be applied to definition.
2467 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2468 Diag(FD->getLocation(),
2469 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2470 << "dllimport";
2471 FD->setInvalidDecl();
2472 return FD;
2473 } else {
2474 // If a symbol previously declared dllimport is later defined, the
2475 // attribute is ignored in subsequent references, and a warning is
2476 // emitted.
2477 Diag(FD->getLocation(),
2478 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2479 << FD->getNameAsCString() << "dllimport";
2480 }
2481 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002482 return FD;
2483}
2484
Sebastian Redl798d1192008-12-13 16:23:55 +00002485Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002486 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002487 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002488 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002489 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002490 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002491 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002492 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002493 } else
2494 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002495 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002496 // Verify and clean out per-function state.
2497
2498 // Check goto/label use.
2499 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2500 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2501 // Verify that we have no forward references left. If so, there was a goto
2502 // or address of a label taken, but no definition of it. Label fwd
2503 // definitions are indicated with a null substmt.
2504 if (I->second->getSubStmt() == 0) {
2505 LabelStmt *L = I->second;
2506 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002507 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002508
2509 // At this point, we have gotos that use the bogus label. Stitch it into
2510 // the function body so that they aren't leaked and that the AST is well
2511 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002512 if (Body) {
2513 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002514 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002515 } else {
2516 // The whole function wasn't parsed correctly, just delete this.
2517 delete L;
2518 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002519 }
2520 }
2521 LabelMap.clear();
2522
Steve Naroffd6d054d2007-11-11 23:20:51 +00002523 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002524}
2525
Reid Spencer5f016e22007-07-11 17:01:13 +00002526/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2527/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002528ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2529 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002530 // Extension in C99. Legal in C90, but warn about it.
2531 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002532 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002533 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002534 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002535
2536 // FIXME: handle stuff like:
2537 // void foo() { extern float X(); }
2538 // void bar() { X(); } <-- implicit decl for X in another scope.
2539
2540 // Set a Declarator for the implicit definition: int foo();
2541 const char *Dummy;
2542 DeclSpec DS;
2543 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2544 Error = Error; // Silence warning.
2545 assert(!Error && "Error setting up implicit decl!");
2546 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002547 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002548 D.SetIdentifier(&II, Loc);
2549
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002550 // Insert this function into translation-unit scope.
2551
2552 DeclContext *PrevDC = CurContext;
2553 CurContext = Context.getTranslationUnitDecl();
2554
Steve Naroffe2ef8152008-04-04 14:32:09 +00002555 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002556 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002557 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002558
2559 CurContext = PrevDC;
2560
Steve Naroffe2ef8152008-04-04 14:32:09 +00002561 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002562}
2563
2564
Chris Lattner41af0932007-11-14 06:34:38 +00002565TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002566 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002567 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002568 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002569
2570 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002571 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2572 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002573 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002574 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002575 if (D.getInvalidType())
2576 NewTD->setInvalidDecl();
2577 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002578}
2579
Steve Naroff08d92e42007-09-15 18:49:24 +00002580/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002581/// former case, Name will be non-null. In the later case, Name will be null.
2582/// TagType indicates what kind of tag this is. TK indicates whether this is a
2583/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002584Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002585 SourceLocation KWLoc, const CXXScopeSpec &SS,
2586 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002587 AttributeList *Attr,
2588 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002589 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002590 assert((Name != 0 || TK == TK_Definition) &&
2591 "Nameless record must be a definition!");
2592
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002593 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 switch (TagType) {
2595 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002596 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2597 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2598 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2599 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002600 }
2601
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002602 DeclContext *DC = CurContext;
2603 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002604
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002605 if (Name && SS.isNotEmpty()) {
2606 // We have a nested-name tag ('struct foo::bar').
2607
2608 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002609 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002610 Name = 0;
2611 goto CreateNewDecl;
2612 }
2613
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002614 DC = static_cast<DeclContext*>(SS.getScopeRep());
2615 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002616 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2617
2618 // A tag 'foo::bar' must already exist.
2619 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002620 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002621 Name = 0;
2622 goto CreateNewDecl;
2623 }
2624 } else {
2625 // If this is a named struct, check to see if there was a previous forward
2626 // declaration or definition.
2627 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2628 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2629 }
2630
Douglas Gregorf57172b2008-12-08 18:40:42 +00002631 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002632 // Maybe we will complain about the shadowed template parameter.
2633 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2634 // Just pretend that we didn't see the previous declaration.
2635 PrevDecl = 0;
2636 }
2637
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002638 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002639 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2640 "unexpected Decl type");
2641 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002642 // If this is a use of a previous tag, or if the tag is already declared
2643 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002644 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002645 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002646 // Make sure that this wasn't declared as an enum and now used as a
2647 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002648 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002649 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002650 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002651 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002652 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002653 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002654 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002655 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002656
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002657 // FIXME: In the future, return a variant or some other clue
2658 // for the consumer of this Decl to know it doesn't own it.
2659 // For our current ASTs this shouldn't be a problem, but will
2660 // need to be changed with DeclGroups.
2661 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002662 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002663
2664 // Diagnose attempts to redefine a tag.
2665 if (TK == TK_Definition) {
2666 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2667 Diag(NameLoc, diag::err_redefinition) << Name;
2668 Diag(Def->getLocation(), diag::note_previous_definition);
2669 // If this is a redefinition, recover by making this struct be
2670 // anonymous, which will make any later references get the previous
2671 // definition.
2672 Name = 0;
2673 PrevDecl = 0;
2674 }
2675 // Okay, this is definition of a previously declared or referenced
2676 // tag PrevDecl. We're going to create a new Decl for it.
2677 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002678 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002679 // If we get here we have (another) forward declaration or we
2680 // have a definition. Just create a new decl.
2681 } else {
2682 // If we get here, this is a definition of a new tag type in a nested
2683 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2684 // new decl/type. We set PrevDecl to NULL so that the entities
2685 // have distinct types.
2686 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002688 // If we get here, we're going to create a new Decl. If PrevDecl
2689 // is non-NULL, it's a definition of the tag declared by
2690 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002691 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002692 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002693 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002694 // The tag name clashes with a namespace name, issue an error and
2695 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002696 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002697 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002698 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002699 PrevDecl = 0;
2700 } else {
2701 // The existing declaration isn't relevant to us; we're in a
2702 // new scope, so clear out the previous declaration.
2703 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002704 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002706 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002707
Chris Lattnercc98eac2008-12-17 07:13:27 +00002708CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002709
2710 // If there is an identifier, use the location of the identifier as the
2711 // location of the decl, otherwise use the location of the struct/union
2712 // keyword.
2713 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2714
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002715 // Otherwise, create a new declaration. If there is a previous
2716 // declaration of the same entity, the two will be linked via
2717 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002718 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002719 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002720 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2721 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002722 New = EnumDecl::Create(Context, DC, Loc, Name,
2723 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002724 // If this is an undefined enum, warn.
2725 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002726 } else {
2727 // struct/union/class
2728
Reid Spencer5f016e22007-07-11 17:01:13 +00002729 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2730 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002731 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002732 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002733 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2734 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002735 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002736 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2737 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002738 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002739
2740 if (Kind != TagDecl::TK_enum) {
2741 // Handle #pragma pack: if the #pragma pack stack has non-default
2742 // alignment, make up a packed attribute for this decl. These
2743 // attributes are checked when the ASTContext lays out the
2744 // structure.
2745 //
2746 // It is important for implementing the correct semantics that this
2747 // happen here (in act on tag decl). The #pragma pack stack is
2748 // maintained as a result of parser callbacks which can occur at
2749 // many points during the parsing of a struct declaration (because
2750 // the #pragma tokens are effectively skipped over during the
2751 // parsing of the struct).
2752 if (unsigned Alignment = PackContext.getAlignment())
2753 New->addAttr(new PackedAttr(Alignment * 8));
2754 }
2755
2756 if (Attr)
2757 ProcessDeclAttributeList(New, Attr);
2758
2759 // Set the lexical context. If the tag has a C++ scope specifier, the
2760 // lexical context will be different from the semantic context.
2761 New->setLexicalDeclContext(CurContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002762
2763 // If this has an identifier, add it to the scope stack.
2764 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002765 // The scope passed in may not be a decl scope. Zip up the scope tree until
2766 // we find one that is.
2767 while ((S->getFlags() & Scope::DeclScope) == 0)
2768 S = S->getParent();
2769
2770 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002771 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002773
Reid Spencer5f016e22007-07-11 17:01:13 +00002774 return New;
2775}
2776
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002777
Chris Lattner1d353ba2008-11-12 21:17:48 +00002778/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2779/// types into constant array types in certain situations which would otherwise
2780/// be errors (for GCC compatibility).
2781static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2782 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002783 // This method tries to turn a variable array into a constant
2784 // array even when the size isn't an ICE. This is necessary
2785 // for compatibility with code that depends on gcc's buggy
2786 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002787 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2788 if (!VLATy) return QualType();
2789
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002790 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00002791 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002792 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002793 return QualType();
2794
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002795 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
2796 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00002797 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2798 return Context.getConstantArrayType(VLATy->getElementType(),
2799 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002800 return QualType();
2801}
2802
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002803bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00002804 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002805 // FIXME: 6.7.2.1p4 - verify the field type.
2806
2807 llvm::APSInt Value;
2808 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2809 return true;
2810
Chris Lattnercd087072008-12-12 04:56:04 +00002811 // Zero-width bitfield is ok for anonymous field.
2812 if (Value == 0 && FieldName)
2813 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2814
2815 if (Value.isNegative())
2816 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002817
2818 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2819 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00002820 if (TypeSize && Value.getZExtValue() > TypeSize)
2821 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2822 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002823
2824 return false;
2825}
2826
Steve Naroff08d92e42007-09-15 18:49:24 +00002827/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002828/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00002829Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00002830 SourceLocation DeclStart,
2831 Declarator &D, ExprTy *BitfieldWidth) {
2832 IdentifierInfo *II = D.getIdentifier();
2833 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002834 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00002835 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 if (II) Loc = D.getIdentifierLoc();
2837
2838 // FIXME: Unnamed fields can be handled in various different ways, for
2839 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00002840
Reid Spencer5f016e22007-07-11 17:01:13 +00002841 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002842 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2843 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00002844
Reid Spencer5f016e22007-07-11 17:01:13 +00002845 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2846 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002847 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002848 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002849 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002850 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002851 T = FixedTy;
2852 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002853 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002854 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002855 InvalidDecl = true;
2856 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002857 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002858
2859 if (BitWidth) {
2860 if (VerifyBitField(Loc, II, T, BitWidth))
2861 InvalidDecl = true;
2862 } else {
2863 // Not a bitfield.
2864
2865 // validate II.
2866
2867 }
2868
Reid Spencer5f016e22007-07-11 17:01:13 +00002869 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002870 FieldDecl *NewFD;
2871
Douglas Gregor44b43212008-12-11 16:49:14 +00002872 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2873 // other way to determine the current RecordDecl.
2874 NewFD = FieldDecl::Create(Context, Record,
2875 Loc, II, T, BitWidth,
2876 D.getDeclSpec().getStorageClassSpec() ==
2877 DeclSpec::SCS_mutable,
2878 /*PrevDecl=*/0);
2879
Sebastian Redl64b45f72009-01-05 20:52:13 +00002880 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00002881 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00002882 if (!T->isPODType())
2883 cast<CXXRecordDecl>(Record)->setPOD(false);
2884 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00002885
Chris Lattner3ff30c82008-06-29 00:02:00 +00002886 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002887
Steve Naroff5912a352007-08-28 20:14:24 +00002888 if (D.getInvalidType() || InvalidDecl)
2889 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002890
2891 if (II && getLangOptions().CPlusPlus)
2892 PushOnScopeChains(NewFD, S);
2893 else
2894 Record->addDecl(Context, NewFD);
2895
Steve Naroff5912a352007-08-28 20:14:24 +00002896 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002897}
2898
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002899/// TranslateIvarVisibility - Translate visibility from a token ID to an
2900/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002901static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002902TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002903 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002904 default: assert(0 && "Unknown visitibility kind");
2905 case tok::objc_private: return ObjCIvarDecl::Private;
2906 case tok::objc_public: return ObjCIvarDecl::Public;
2907 case tok::objc_protected: return ObjCIvarDecl::Protected;
2908 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002909 }
2910}
2911
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002912/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2913/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002914Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002915 SourceLocation DeclStart,
2916 Declarator &D, ExprTy *BitfieldWidth,
2917 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002918 IdentifierInfo *II = D.getIdentifier();
2919 Expr *BitWidth = (Expr*)BitfieldWidth;
2920 SourceLocation Loc = DeclStart;
2921 if (II) Loc = D.getIdentifierLoc();
2922
2923 // FIXME: Unnamed fields can be handled in various different ways, for
2924 // example, unnamed unions inject all members into the struct namespace!
2925
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002926 QualType T = GetTypeForDeclarator(D, S);
2927 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2928 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002929
2930 if (BitWidth) {
2931 // TODO: Validate.
2932 //printf("WARNING: BITFIELDS IGNORED!\n");
2933
2934 // 6.7.2.1p3
2935 // 6.7.2.1p4
2936
2937 } else {
2938 // Not a bitfield.
2939
2940 // validate II.
2941
2942 }
2943
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002944 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2945 // than a variably modified type.
2946 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002947 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002948 InvalidDecl = true;
2949 }
2950
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002951 // Get the visibility (access control) for this ivar.
2952 ObjCIvarDecl::AccessControl ac =
2953 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2954 : ObjCIvarDecl::None;
2955
2956 // Construct the decl.
2957 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002958 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002959
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002960 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002961 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002962
2963 if (D.getInvalidType() || InvalidDecl)
2964 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002965
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002966 return NewID;
2967}
2968
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002969void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002970 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002971 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002972 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002973 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002974 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2975 assert(EnclosingDecl && "missing record or interface decl");
2976 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2977
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002978 if (Record)
2979 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2980 // Diagnose code like:
2981 // struct S { struct S {} X; };
2982 // We discover this when we complete the outer S. Reject and ignore the
2983 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002984 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002985 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002986 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002987 Record->setInvalidDecl();
2988 return;
2989 }
2990
Reid Spencer5f016e22007-07-11 17:01:13 +00002991 // Verify that all the fields are okay.
2992 unsigned NumNamedMembers = 0;
2993 llvm::SmallVector<FieldDecl*, 32> RecFields;
2994 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002995
Reid Spencer5f016e22007-07-11 17:01:13 +00002996 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002997
Steve Naroff74216642007-09-14 22:20:54 +00002998 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2999 assert(FD && "missing field decl");
3000
3001 // Remember all fields.
3002 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00003003
3004 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003005 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00003006
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003008 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003009 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003010 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003011 FD->setInvalidDecl();
3012 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003013 continue;
3014 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003015 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3016 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003017 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003018 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003019 FD->setInvalidDecl();
3020 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003021 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003022 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003023 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003024 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003025 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003026 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003027 FD->setInvalidDecl();
3028 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003029 continue;
3030 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003031 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003032 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003033 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003034 FD->setInvalidDecl();
3035 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003036 continue;
3037 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003038 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003039 if (Record)
3040 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003041 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003042 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3043 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003044 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003045 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3046 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003047 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003048 Record->setHasFlexibleArrayMember(true);
3049 } else {
3050 // If this is a struct/class and this is not the last element, reject
3051 // it. Note that GCC supports variable sized arrays in the middle of
3052 // structures.
3053 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003054 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003055 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003056 FD->setInvalidDecl();
3057 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003058 continue;
3059 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003060 // We support flexible arrays at the end of structs in other structs
3061 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003062 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003063 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003064 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003065 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003066 }
3067 }
3068 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003069 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003070 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003071 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003072 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003073 FD->setInvalidDecl();
3074 EnclosingDecl->setInvalidDecl();
3075 continue;
3076 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003077 // Keep track of the number of named members.
3078 if (IdentifierInfo *II = FD->getIdentifier()) {
3079 // Detect duplicate member names.
3080 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003081 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003082 // Find the previous decl.
3083 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00003084 for (unsigned i = 0; ; ++i) {
3085 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00003086 if (RecFields[i]->getIdentifier() == II) {
3087 PrevLoc = RecFields[i]->getLocation();
3088 break;
3089 }
3090 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00003091 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003092 FD->setInvalidDecl();
3093 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003094 continue;
3095 }
3096 ++NumNamedMembers;
3097 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003099
Reid Spencer5f016e22007-07-11 17:01:13 +00003100 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003101 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003102 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003103 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3104 // Sema::ActOnFinishCXXClassDef.
3105 if (!isa<CXXRecordDecl>(Record))
3106 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003107 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003108 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003109 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003110 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003111 // Must enforce the rule that ivars in the base classes may not be
3112 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003113 if (ID->getSuperClass()) {
3114 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3115 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3116 ObjCIvarDecl* Ivar = (*IVI);
3117 IdentifierInfo *II = Ivar->getIdentifier();
3118 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3119 if (prevIvar) {
3120 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3121 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003122 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003123 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003124 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003125 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003126 else if (ObjCImplementationDecl *IMPDecl =
3127 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003128 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3129 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003130 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003131 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003132 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003133
3134 if (Attr)
3135 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003136}
3137
Douglas Gregor074149e2009-01-05 19:45:36 +00003138void Sema::ActOnEnumStartDefinition(Scope *S, DeclTy *EnumD) {
Douglas Gregor4f3b8f82009-01-06 07:17:58 +00003139 EnumDecl *Enum = cast<EnumDecl>((Decl *)EnumD);
Douglas Gregor074149e2009-01-05 19:45:36 +00003140
Douglas Gregor4f3b8f82009-01-06 07:17:58 +00003141 // Enter the enumeration context.
3142 PushDeclContext(S, Enum);
Douglas Gregor074149e2009-01-05 19:45:36 +00003143}
3144
Steve Naroff08d92e42007-09-15 18:49:24 +00003145Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003146 DeclTy *lastEnumConst,
3147 SourceLocation IdLoc, IdentifierInfo *Id,
3148 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003149 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003150 EnumConstantDecl *LastEnumConst =
3151 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3152 Expr *Val = static_cast<Expr*>(val);
3153
Chris Lattner31e05722007-08-26 06:24:45 +00003154 // The scope passed in may not be a decl scope. Zip up the scope tree until
3155 // we find one that is.
3156 while ((S->getFlags() & Scope::DeclScope) == 0)
3157 S = S->getParent();
3158
Reid Spencer5f016e22007-07-11 17:01:13 +00003159 // Verify that there isn't already something declared with this name in this
3160 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003161 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003162 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003163 // Maybe we will complain about the shadowed template parameter.
3164 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3165 // Just pretend that we didn't see the previous declaration.
3166 PrevDecl = 0;
3167 }
3168
3169 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003170 // When in C++, we may get a TagDecl with the same name; in this case the
3171 // enum constant will 'hide' the tag.
3172 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3173 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003174 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003175 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003176 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003177 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003178 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003179 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003180 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003181 return 0;
3182 }
3183 }
3184
3185 llvm::APSInt EnumVal(32);
3186 QualType EltTy;
3187 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003188 // Make sure to promote the operand type to int.
3189 UsualUnaryConversions(Val);
3190
Reid Spencer5f016e22007-07-11 17:01:13 +00003191 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3192 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003193 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003194 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003195 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003196 } else {
3197 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003198 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003199 }
3200
3201 if (!Val) {
3202 if (LastEnumConst) {
3203 // Assign the last value + 1.
3204 EnumVal = LastEnumConst->getInitVal();
3205 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003206
3207 // Check for overflow on increment.
3208 if (EnumVal < LastEnumConst->getInitVal())
3209 Diag(IdLoc, diag::warn_enum_value_overflow);
3210
Chris Lattnerb7416f92007-08-27 17:37:24 +00003211 EltTy = LastEnumConst->getType();
3212 } else {
3213 // First value, set to zero.
3214 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003215 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003216 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003217 }
3218
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003219 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003220 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3221 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003222 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003223
3224 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003225 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003226
3227 // Add this enumerator into the enum itself.
3228 // FIXME: This means that the enumerator is stored in two
3229 // DeclContexts. This is not a long-term solution.
3230 New->setLexicalDeclContext(TheEnumDecl);
3231 TheEnumDecl->addDecl(Context, New, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003232 return New;
3233}
3234
Steve Naroff02408c62008-08-07 14:08:16 +00003235// FIXME: For consistency with ActOnFields(), we should have the parser
3236// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003237void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003238 DeclTy **Elements, unsigned NumElements) {
3239 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003240 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003241
Douglas Gregor074149e2009-01-05 19:45:36 +00003242 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3243 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3244 // Diagnose code like:
3245 // enum e0 {
3246 // E0 = sizeof(enum e0 { E1 })
3247 // };
3248 Diag(Def->getLocation(), diag::err_nested_redefinition)
3249 << Enum->getDeclName();
3250 Diag(Enum->getLocation(), diag::note_previous_definition);
3251 Enum->setInvalidDecl();
3252 PopDeclContext();
3253 return;
Steve Naroff02408c62008-08-07 14:08:16 +00003254 }
Douglas Gregor074149e2009-01-05 19:45:36 +00003255
Chris Lattnere37f0be2007-08-28 05:10:31 +00003256 // TODO: If the result value doesn't fit in an int, it must be a long or long
3257 // long value. ISO C does not support this, but GCC does as an extension,
3258 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003259 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003260
Chris Lattnerac609682007-08-28 06:15:15 +00003261 // Verify that all the values are okay, compute the size of the values, and
3262 // reverse the list.
3263 unsigned NumNegativeBits = 0;
3264 unsigned NumPositiveBits = 0;
3265
3266 // Keep track of whether all elements have type int.
3267 bool AllElementsInt = true;
3268
Reid Spencer5f016e22007-07-11 17:01:13 +00003269 EnumConstantDecl *EltList = 0;
3270 for (unsigned i = 0; i != NumElements; ++i) {
3271 EnumConstantDecl *ECD =
3272 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3273 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003274
3275 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003276 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003277 assert(InitVal.getBitWidth() >= IntWidth &&
3278 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003279 if (InitVal.getBitWidth() > IntWidth) {
3280 llvm::APSInt V(InitVal);
3281 V.trunc(IntWidth);
3282 V.extend(InitVal.getBitWidth());
3283 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003284 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3285 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003286 }
Chris Lattnerac609682007-08-28 06:15:15 +00003287
3288 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003289 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003290 NumPositiveBits = std::max(NumPositiveBits,
3291 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003292 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003293 NumNegativeBits = std::max(NumNegativeBits,
3294 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003295
Chris Lattnerac609682007-08-28 06:15:15 +00003296 // Keep track of whether every enum element has type int (very commmon).
3297 if (AllElementsInt)
3298 AllElementsInt = ECD->getType() == Context.IntTy;
3299
Reid Spencer5f016e22007-07-11 17:01:13 +00003300 ECD->setNextDeclarator(EltList);
3301 EltList = ECD;
3302 }
3303
Chris Lattnerac609682007-08-28 06:15:15 +00003304 // Figure out the type that should be used for this enum.
3305 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3306 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003307 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003308
3309 if (NumNegativeBits) {
3310 // If there is a negative value, figure out the smallest integer type (of
3311 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003312 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003313 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003314 BestWidth = IntWidth;
3315 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003316 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003317
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003318 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003319 BestType = Context.LongTy;
3320 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003321 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003322
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003323 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003324 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3325 BestType = Context.LongLongTy;
3326 }
3327 }
3328 } else {
3329 // If there is no negative value, figure out which of uint, ulong, ulonglong
3330 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003331 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003332 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003333 BestWidth = IntWidth;
3334 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003335 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003336 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003337 } else {
3338 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003339 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003340 "How could an initializer get larger than ULL?");
3341 BestType = Context.UnsignedLongLongTy;
3342 }
3343 }
3344
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003345 // Loop over all of the enumerator constants, changing their types to match
3346 // the type of the enum if needed.
3347 for (unsigned i = 0; i != NumElements; ++i) {
3348 EnumConstantDecl *ECD =
3349 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3350 if (!ECD) continue; // Already issued a diagnostic.
3351
3352 // Standard C says the enumerators have int type, but we allow, as an
3353 // extension, the enumerators to be larger than int size. If each
3354 // enumerator value fits in an int, type it as an int, otherwise type it the
3355 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3356 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003357 if (ECD->getType() == Context.IntTy) {
3358 // Make sure the init value is signed.
3359 llvm::APSInt IV = ECD->getInitVal();
3360 IV.setIsSigned(true);
3361 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003362
3363 if (getLangOptions().CPlusPlus)
3364 // C++ [dcl.enum]p4: Following the closing brace of an
3365 // enum-specifier, each enumerator has the type of its
3366 // enumeration.
3367 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003368 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003369 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003370
3371 // Determine whether the value fits into an int.
3372 llvm::APSInt InitVal = ECD->getInitVal();
3373 bool FitsInInt;
3374 if (InitVal.isUnsigned() || !InitVal.isNegative())
3375 FitsInInt = InitVal.getActiveBits() < IntWidth;
3376 else
3377 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3378
3379 // If it fits into an integer type, force it. Otherwise force it to match
3380 // the enum decl type.
3381 QualType NewTy;
3382 unsigned NewWidth;
3383 bool NewSign;
3384 if (FitsInInt) {
3385 NewTy = Context.IntTy;
3386 NewWidth = IntWidth;
3387 NewSign = true;
3388 } else if (ECD->getType() == BestType) {
3389 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003390 if (getLangOptions().CPlusPlus)
3391 // C++ [dcl.enum]p4: Following the closing brace of an
3392 // enum-specifier, each enumerator has the type of its
3393 // enumeration.
3394 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003395 continue;
3396 } else {
3397 NewTy = BestType;
3398 NewWidth = BestWidth;
3399 NewSign = BestType->isSignedIntegerType();
3400 }
3401
3402 // Adjust the APSInt value.
3403 InitVal.extOrTrunc(NewWidth);
3404 InitVal.setIsSigned(NewSign);
3405 ECD->setInitVal(InitVal);
3406
3407 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003408 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3409 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003410 if (getLangOptions().CPlusPlus)
3411 // C++ [dcl.enum]p4: Following the closing brace of an
3412 // enum-specifier, each enumerator has the type of its
3413 // enumeration.
3414 ECD->setType(EnumType);
3415 else
3416 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003417 }
Chris Lattnerac609682007-08-28 06:15:15 +00003418
Douglas Gregor44b43212008-12-11 16:49:14 +00003419 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003420 Consumer.HandleTagDeclDefinition(Enum);
Douglas Gregor074149e2009-01-05 19:45:36 +00003421
3422 // Leave the context of the enumeration.
3423 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00003424}
3425
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003426Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003427 ExprArg expr) {
3428 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3429
Chris Lattner8e25d862008-03-16 00:16:02 +00003430 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003431}
3432
Douglas Gregorf44515a2008-12-16 22:23:02 +00003433
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003434void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3435 ExprTy *alignment, SourceLocation PragmaLoc,
3436 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3437 Expr *Alignment = static_cast<Expr *>(alignment);
3438
3439 // If specified then alignment must be a "small" power of two.
3440 unsigned AlignmentVal = 0;
3441 if (Alignment) {
3442 llvm::APSInt Val;
3443 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3444 !Val.isPowerOf2() ||
3445 Val.getZExtValue() > 16) {
3446 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3447 delete Alignment;
3448 return; // Ignore
3449 }
3450
3451 AlignmentVal = (unsigned) Val.getZExtValue();
3452 }
3453
3454 switch (Kind) {
3455 case Action::PPK_Default: // pack([n])
3456 PackContext.setAlignment(AlignmentVal);
3457 break;
3458
3459 case Action::PPK_Show: // pack(show)
3460 // Show the current alignment, making sure to show the right value
3461 // for the default.
3462 AlignmentVal = PackContext.getAlignment();
3463 // FIXME: This should come from the target.
3464 if (AlignmentVal == 0)
3465 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003466 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003467 break;
3468
3469 case Action::PPK_Push: // pack(push [, id] [, [n])
3470 PackContext.push(Name);
3471 // Set the new alignment if specified.
3472 if (Alignment)
3473 PackContext.setAlignment(AlignmentVal);
3474 break;
3475
3476 case Action::PPK_Pop: // pack(pop [, id] [, n])
3477 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3478 // "#pragma pack(pop, identifier, n) is undefined"
3479 if (Alignment && Name)
3480 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3481
3482 // Do the pop.
3483 if (!PackContext.pop(Name)) {
3484 // If a name was specified then failure indicates the name
3485 // wasn't found. Otherwise failure indicates the stack was
3486 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003487 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3488 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003489
3490 // FIXME: Warn about popping named records as MSVC does.
3491 } else {
3492 // Pop succeeded, set the new alignment if specified.
3493 if (Alignment)
3494 PackContext.setAlignment(AlignmentVal);
3495 }
3496 break;
3497
3498 default:
3499 assert(0 && "Invalid #pragma pack kind.");
3500 }
3501}
3502
3503bool PragmaPackStack::pop(IdentifierInfo *Name) {
3504 if (Stack.empty())
3505 return false;
3506
3507 // If name is empty just pop top.
3508 if (!Name) {
3509 Alignment = Stack.back().first;
3510 Stack.pop_back();
3511 return true;
3512 }
3513
3514 // Otherwise, find the named record.
3515 for (unsigned i = Stack.size(); i != 0; ) {
3516 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003517 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003518 // Found it, pop up to and including this record.
3519 Alignment = Stack[i].first;
3520 Stack.erase(Stack.begin() + i, Stack.end());
3521 return true;
3522 }
3523 }
3524
3525 return false;
3526}