blob: c6e4336a3dc8f246d11001866817dca01cbe9fab [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-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 Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregor39677622008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6e71edc2008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregor39677622008-12-11 20:41:00 +000031
Chris Lattner4b009652007-07-25 00:24:17 +000032using namespace clang;
33
Douglas Gregorb0212bd2008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-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 Naroff6384a012008-04-02 14:35:35 +000043
Douglas Gregor1d661552008-04-13 21:07:44 +000044 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
45 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregordd861062008-12-05 18:15:24 +000046 isa<TagDecl>(IIDecl) ||
47 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000048 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000049 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000050}
51
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000052DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000053 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000054 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000055 if (MD->isOutOfLineDefinition())
56 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-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
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000061 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000062 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
63 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000064 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-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
Argiris Kirtzidis881964b2008-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();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000077
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000078 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000079}
80
Douglas Gregor8acb7272008-12-11 16:49:14 +000081void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000082 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +000083 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000084 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +000085 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +000086}
87
Chris Lattnerf3874bc2008-04-06 04:47:34 +000088void Sema::PopDeclContext() {
89 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +000090
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000091 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000092}
93
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000094/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregord8028382009-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
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000103 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000104
Douglas Gregor6e71edc2008-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
Argiris Kirtzidis59a9afb2008-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 Gregor3a423132009-01-07 16:34:42 +0000119 if (CurContext->getLookupContext()
120 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000121 // We're pushing the tag into the current context, which might
122 // require some reshuffling in the identifier resolver.
123 IdentifierResolver::iterator
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000124 I = IdResolver.begin(TD->getDeclName(), CurContext,
125 false/*LookInParentCtx*/),
126 IEnd = IdResolver.end();
127 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
128 NamedDecl *PrevDecl = *I;
129 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
130 PrevDecl = *I, ++I) {
131 if (TD->declarationReplaces(*I)) {
132 // This is a redeclaration. Remove it from the chain and
133 // break out, so that we'll add in the shadowed
134 // declaration.
135 S->RemoveDecl(*I);
136 if (PrevDecl == *I) {
137 IdResolver.RemoveDecl(*I);
138 IdResolver.AddDecl(TD);
139 return;
140 } else {
141 IdResolver.RemoveDecl(*I);
142 break;
143 }
144 }
145 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000146
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000147 // There is already a declaration with the same name in the same
148 // scope, which is not a tag declaration. It must be found
149 // before we find the new declaration, so insert the new
150 // declaration at the end of the chain.
151 IdResolver.AddShadowedDecl(TD, PrevDecl);
152
153 return;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000154 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000155 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000156 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000157 // We are pushing the name of a function, which might be an
158 // overloaded name.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000159 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor69e781f2009-01-06 23:51:29 +0000160 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000161 IdentifierResolver::iterator Redecl
Douglas Gregord8028382009-01-05 19:45:36 +0000162 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000163 false/*LookInParentCtx*/),
164 IdResolver.end(),
165 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
166 FD));
167 if (Redecl != IdResolver.end()) {
168 // There is already a declaration of a function on our
169 // IdResolver chain. Replace it with this declaration.
170 S->RemoveDecl(*Redecl);
171 IdResolver.RemoveDecl(*Redecl);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000172 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000173 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000174
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000175 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000176}
177
Steve Naroff9637a9b2007-10-09 22:01:59 +0000178void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000179 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000180 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
181 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000182
Chris Lattner4b009652007-07-25 00:24:17 +0000183 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
184 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000185 Decl *TmpD = static_cast<Decl*>(*I);
186 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000187
Douglas Gregor8acb7272008-12-11 16:49:14 +0000188 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
189 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000190
Douglas Gregor8acb7272008-12-11 16:49:14 +0000191 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000192
Douglas Gregor8acb7272008-12-11 16:49:14 +0000193 // Remove this name from our lexical scope.
194 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000195 }
196}
197
Steve Naroffe57c21a2008-04-01 23:04:06 +0000198/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
199/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000200ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000201 // The third "scope" argument is 0 since we aren't enabling lazy built-in
202 // creation from this context.
203 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000204
Steve Naroff6384a012008-04-02 14:35:35 +0000205 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000206}
207
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000208/// MaybeConstructOverloadSet - Name lookup has determined that the
209/// elements in [I, IEnd) have the name that we are looking for, and
210/// *I is a match for the namespace. This routine returns an
211/// appropriate Decl for name lookup, which may either be *I or an
212/// OverloadeFunctionDecl that represents the overloaded functions in
213/// [I, IEnd).
214///
215/// The existance of this routine is temporary; LookupDecl should
216/// probably be able to return multiple results, to deal with cases of
217/// ambiguity and overloaded functions without needing to create a
218/// Decl node.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000219template<typename DeclIterator>
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000220static Decl *
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000221MaybeConstructOverloadSet(ASTContext &Context,
222 DeclIterator I, DeclIterator IEnd) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000223 assert(I != IEnd && "Iterator range cannot be empty");
224 assert(!isa<OverloadedFunctionDecl>(*I) &&
225 "Cannot have an overloaded function");
226
227 if (isa<FunctionDecl>(*I)) {
228 // If we found a function, there might be more functions. If
229 // so, collect them into an overload set.
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000230 DeclIterator Last = I;
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000231 OverloadedFunctionDecl *Ovl = 0;
232 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
233 if (!Ovl) {
234 // FIXME: We leak this overload set. Eventually, we want to
235 // stop building the declarations for these overload sets, so
236 // there will be nothing to leak.
237 Ovl = OverloadedFunctionDecl::Create(Context,
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000238 cast<ScopedDecl>(*I)->getDeclContext(),
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000239 (*I)->getDeclName());
240 Ovl->addOverload(cast<FunctionDecl>(*I));
241 }
242 Ovl->addOverload(cast<FunctionDecl>(*Last));
243 }
244
245 // If we had more than one function, we built an overload
246 // set. Return it.
247 if (Ovl)
248 return Ovl;
249 }
250
251 return *I;
252}
253
Steve Naroffe57c21a2008-04-01 23:04:06 +0000254/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000255/// namespace. NamespaceNameOnly - during lookup only namespace names
256/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
257/// 'When looking up a namespace-name in a using-directive or
258/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000259Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000260 const DeclContext *LookupCtx,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000261 bool enableLazyBuiltinCreation,
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000262 bool LookInParent,
263 bool NamespaceNameOnly) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000264 if (!Name) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000265 unsigned NS = NSI;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000266
Douglas Gregordb568cf2009-01-08 20:45:30 +0000267 // In C++, ordinary and member lookup will always find all
268 // kinds of names.
269 if (getLangOptions().CPlusPlus &&
270 (NS & (Decl::IDNS_Ordinary | Decl::IDNS_Member)))
271 NS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Ordinary;
272
273 if (LookupCtx == 0 && !getLangOptions().CPlusPlus) {
274 // Unqualified name lookup in C/Objective-C is purely lexical, so
275 // search in the declarations attached to the name.
Douglas Gregor39677622008-12-11 20:41:00 +0000276 assert(!LookupCtx && "Can't perform qualified name lookup here");
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000277 assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
Douglas Gregordb568cf2009-01-08 20:45:30 +0000278
279 // For the purposes of unqualified name lookup, structs and unions
280 // don't have scopes at all. For example:
281 //
282 // struct X {
283 // struct T { int i; } x;
284 // };
285 //
286 // void f() {
287 // struct T t; // okay: T is defined lexically within X, but
288 // // semantically at global scope
289 // };
290 //
291 // FIXME: Is there a better way to deal with this?
292 DeclContext *SearchCtx = CurContext;
293 while (isa<RecordDecl>(SearchCtx) || isa<EnumDecl>(SearchCtx))
294 SearchCtx = SearchCtx->getParent();
Douglas Gregor39677622008-12-11 20:41:00 +0000295 IdentifierResolver::iterator I
Douglas Gregordb568cf2009-01-08 20:45:30 +0000296 = IdResolver.begin(Name, SearchCtx, LookInParent);
Douglas Gregor39677622008-12-11 20:41:00 +0000297
298 // Scan up the scope chain looking for a decl that matches this
299 // identifier that is in the appropriate namespace. This search
300 // should not take long, as shadowing of names is uncommon, and
301 // deep shadowing is extremely uncommon.
302 for (; I != IdResolver.end(); ++I)
Chris Lattner093e31b2009-01-06 07:20:03 +0000303 if ((*I)->isInIdentifierNamespace(NS))
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000304 return *I;
Douglas Gregor39677622008-12-11 20:41:00 +0000305 } else if (LookupCtx) {
Douglas Gregordb568cf2009-01-08 20:45:30 +0000306 // If we're performing qualified name lookup (e.g., lookup into a
307 // struct), find fields as part of ordinary name lookup.
308 if (NS & Decl::IDNS_Ordinary)
309 NS |= Decl::IDNS_Member;
310
Douglas Gregor8acb7272008-12-11 16:49:14 +0000311 // Perform qualified name lookup into the LookupCtx.
312 // FIXME: Will need to look into base classes and such.
Douglas Gregor39677622008-12-11 20:41:00 +0000313 DeclContext::lookup_const_iterator I, E;
Steve Naroffab63fd62009-01-08 17:28:14 +0000314 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Chris Lattner093e31b2009-01-06 07:20:03 +0000315 if ((*I)->isInIdentifierNamespace(NS)) {
316 // Ignore non-namespace names if we're only looking for namespaces.
317 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) continue;
318
319 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000320 }
Douglas Gregor39677622008-12-11 20:41:00 +0000321 } else {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000322 // Name lookup for ordinary names and tag names in C++ requires
323 // looking into scopes that aren't strictly lexical, and
324 // therefore we walk through the context as well as walking
325 // through the scopes.
326 IdentifierResolver::iterator
327 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
328 IEnd = IdResolver.end();
329 for (; S; S = S->getParent()) {
330 // Check whether the IdResolver has anything in this scope.
331 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000332 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Chris Lattner093e31b2009-01-06 07:20:03 +0000333 if ((*I)->isInIdentifierNamespace(NS)) {
334 // Ignore non-namespace names if we're only looking for namespaces.
335 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
336 continue;
337
338 // We found something. Look for anything else in our scope
339 // with this same name and in an acceptable identifier
340 // namespace, so that we can construct an overload set if we
341 // need to.
342 IdentifierResolver::iterator LastI = I;
343 for (++LastI; LastI != IEnd; ++LastI) {
344 if (!(*LastI)->isInIdentifierNamespace(NS) ||
345 !S->isDeclScope(*LastI))
346 break;
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000347 }
Chris Lattner093e31b2009-01-06 07:20:03 +0000348 return MaybeConstructOverloadSet(Context, I, LastI);
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000349 }
350 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000351
352 // If there is an entity associated with this scope, it's a
353 // DeclContext. We might need to perform qualified lookup into
354 // it.
355 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
356 while (Ctx && Ctx->isFunctionOrMethod())
357 Ctx = Ctx->getParent();
Douglas Gregor723d3332009-01-07 00:43:41 +0000358 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000359 // Look for declarations of this name in this scope.
Douglas Gregor39677622008-12-11 20:41:00 +0000360 DeclContext::lookup_const_iterator I, E;
Steve Naroffab63fd62009-01-08 17:28:14 +0000361 for (llvm::tie(I, E) = Ctx->lookup(Name); I != E; ++I) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000362 // FIXME: Cache this result in the IdResolver
Chris Lattner093e31b2009-01-06 07:20:03 +0000363 if ((*I)->isInIdentifierNamespace(NS)) {
364 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
365 continue;
366 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregor5ff0ee52008-12-30 03:27:21 +0000367 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000368 }
369
Douglas Gregor1ae27702009-01-07 21:36:02 +0000370 if (!LookInParent && !Ctx->isTransparentContext())
371 return 0;
372
Douglas Gregor8acb7272008-12-11 16:49:14 +0000373 Ctx = Ctx->getParent();
374 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000375 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000376 }
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000377
Chris Lattner4b009652007-07-25 00:24:17 +0000378 // If we didn't find a use of this identifier, and if the identifier
379 // corresponds to a compiler builtin, create the decl object for the builtin
380 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000381 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000382 IdentifierInfo *II = Name.getAsIdentifierInfo();
383 if (enableLazyBuiltinCreation && II &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000384 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroff6384a012008-04-02 14:35:35 +0000385 // If this is a builtin on this (or all) targets, create the decl.
386 if (unsigned BuiltinID = II->getBuiltinID())
387 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
388 }
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000389 if (getLangOptions().ObjC1 && II) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000390 // @interface and @compatibility_alias introduce typedef-like names.
391 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000392 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000393 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000394 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
395 if (IDI != ObjCInterfaceDecls.end())
396 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000397 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
398 if (I != ObjCAliasDecls.end())
399 return I->second->getClassInterface();
400 }
Chris Lattner4b009652007-07-25 00:24:17 +0000401 }
402 return 0;
403}
404
Chris Lattnera9c87f22008-05-05 22:18:14 +0000405void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000406 if (!Context.getBuiltinVaListType().isNull())
407 return;
408
409 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000410 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000411 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000412 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
413}
414
Chris Lattner4b009652007-07-25 00:24:17 +0000415/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
416/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000417ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
418 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000419 Builtin::ID BID = (Builtin::ID)bid;
420
Chris Lattnerb23469f2008-09-28 05:54:29 +0000421 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000422 InitBuiltinVaListType();
423
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000424 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000425 FunctionDecl *New = FunctionDecl::Create(Context,
426 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000427 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000428 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000429
Chris Lattnera9c87f22008-05-05 22:18:14 +0000430 // Create Decl objects for each parameter, adding them to the
431 // FunctionDecl.
432 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
433 llvm::SmallVector<ParmVarDecl*, 16> Params;
434 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
435 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
436 FT->getArgType(i), VarDecl::None, 0,
437 0));
438 New->setParams(&Params[0], Params.size());
439 }
440
441
442
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000443 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000444 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000445 return New;
446}
447
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000448/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
449/// everything from the standard library is defined.
450NamespaceDecl *Sema::GetStdNamespace() {
451 if (!StdNamespace) {
Chris Lattnerf0939602008-11-20 05:45:14 +0000452 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000453 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattnerf0939602008-11-20 05:45:14 +0000454 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000455 0, Global, /*enableLazyBuiltinCreation=*/false);
456 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
457 }
458 return StdNamespace;
459}
460
Chris Lattner4b009652007-07-25 00:24:17 +0000461/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
462/// and scope as a previous declaration 'Old'. Figure out how to resolve this
463/// situation, merging decls or emitting diagnostics as appropriate.
464///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000465TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-09-09 14:32:20 +0000466 // Allow multiple definitions for ObjC built-in typedefs.
467 // FIXME: Verify the underlying types are equivalent!
468 if (getLangOptions().ObjC1) {
Chris Lattner6d16b052008-11-20 05:41:43 +0000469 const IdentifierInfo *TypeID = New->getIdentifier();
470 switch (TypeID->getLength()) {
471 default: break;
472 case 2:
473 if (!TypeID->isStr("id"))
474 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000475 Context.setObjCIdType(New);
476 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000477 case 5:
478 if (!TypeID->isStr("Class"))
479 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000480 Context.setObjCClassType(New);
481 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000482 case 3:
483 if (!TypeID->isStr("SEL"))
484 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000485 Context.setObjCSelType(New);
486 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000487 case 8:
488 if (!TypeID->isStr("Protocol"))
489 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000490 Context.setObjCProtoType(New->getUnderlyingType());
491 return New;
492 }
493 // Fall through - the typedef name was not a builtin type.
494 }
Chris Lattner4b009652007-07-25 00:24:17 +0000495 // Verify the old decl was also a typedef.
496 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
497 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000498 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000499 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000500 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000501 return New;
502 }
503
Chris Lattnerbef8d622008-07-25 18:44:27 +0000504 // If the typedef types are not identical, reject them in all languages and
505 // with any extensions enabled.
506 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
507 Context.getCanonicalType(Old->getUnderlyingType()) !=
508 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner8d756812008-11-20 06:13:02 +0000509 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000510 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner1336cab2008-11-23 23:12:31 +0000511 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerbef8d622008-07-25 18:44:27 +0000512 return Old;
513 }
514
Eli Friedman324d5032008-06-11 06:20:39 +0000515 if (getLangOptions().Microsoft) return New;
516
Douglas Gregor49ba1b72008-11-21 16:29:06 +0000517 // C++ [dcl.typedef]p2:
518 // In a given non-class scope, a typedef specifier can be used to
519 // redefine the name of any type declared in that scope to refer
520 // to the type to which it already refers.
521 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
522 return New;
523
524 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffa9eae582008-01-30 23:46:05 +0000525 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
526 // *either* declaration is in a system header. The code below implements
527 // this adhoc compatibility rule. FIXME: The following code will not
528 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000529 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
530 SourceManager &SrcMgr = Context.getSourceManager();
531 if (SrcMgr.isInSystemHeader(Old->getLocation()))
532 return New;
533 if (SrcMgr.isInSystemHeader(New->getLocation()))
534 return New;
535 }
Eli Friedman324d5032008-06-11 06:20:39 +0000536
Chris Lattnerb1753422008-11-23 21:45:46 +0000537 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000538 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000539 return New;
540}
541
Chris Lattner6953a072008-06-26 18:38:35 +0000542/// DeclhasAttr - returns true if decl Declaration already has the target
543/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000544static bool DeclHasAttr(const Decl *decl, const Attr *target) {
545 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
546 if (attr->getKind() == target->getKind())
547 return true;
548
549 return false;
550}
551
552/// MergeAttributes - append attributes from the Old decl to the New one.
553static void MergeAttributes(Decl *New, Decl *Old) {
554 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
555
Chris Lattner402b3372008-03-03 03:28:21 +0000556 while (attr) {
557 tmp = attr;
558 attr = attr->getNext();
559
560 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikovb27a8702008-12-26 00:52:02 +0000561 tmp->setInherited(true);
Chris Lattner402b3372008-03-03 03:28:21 +0000562 New->addAttr(tmp);
563 } else {
564 tmp->setNext(0);
565 delete(tmp);
566 }
567 }
Nuno Lopes77654342008-06-01 22:53:53 +0000568
569 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000570}
571
Chris Lattner3e254fb2008-04-08 04:40:51 +0000572/// MergeFunctionDecl - We just parsed a function 'New' from
573/// declarator D which has the same name and scope as a previous
574/// declaration 'Old'. Figure out how to resolve this situation,
575/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000576/// Redeclaration will be set true if this New is a redeclaration OldD.
577///
578/// In C++, New and Old must be declarations that are not
579/// overloaded. Use IsOverload to determine whether New and Old are
580/// overloaded, and to select the Old declaration that New should be
581/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000582FunctionDecl *
583Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000584 assert(!isa<OverloadedFunctionDecl>(OldD) &&
585 "Cannot merge with an overloaded function declaration");
586
Douglas Gregor42214c52008-04-21 02:02:58 +0000587 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000588 // Verify the old decl was also a function.
589 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
590 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000591 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000592 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000593 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000594 return New;
595 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000596
597 // Determine whether the previous declaration was a definition,
598 // implicit declaration, or a declaration.
599 diag::kind PrevDiag;
600 if (Old->isThisDeclarationADefinition())
Chris Lattner1336cab2008-11-23 23:12:31 +0000601 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000602 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000603 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000604 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000605 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000606
Chris Lattner42a21742008-04-06 23:10:54 +0000607 QualType OldQType = Context.getCanonicalType(Old->getType());
608 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000609
Douglas Gregord2baafd2008-10-21 16:13:35 +0000610 if (getLangOptions().CPlusPlus) {
611 // (C++98 13.1p2):
612 // Certain function declarations cannot be overloaded:
613 // -- Function declarations that differ only in the return type
614 // cannot be overloaded.
615 QualType OldReturnType
616 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
617 QualType NewReturnType
618 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
619 if (OldReturnType != NewReturnType) {
620 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
621 Diag(Old->getLocation(), PrevDiag);
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000622 Redeclaration = true;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000623 return New;
624 }
625
626 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
627 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
628 if (OldMethod && NewMethod) {
629 // -- Member function declarations with the same name and the
630 // same parameter types cannot be overloaded if any of them
631 // is a static member function declaration.
632 if (OldMethod->isStatic() || NewMethod->isStatic()) {
633 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
634 Diag(Old->getLocation(), PrevDiag);
635 return New;
636 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000637
638 // C++ [class.mem]p1:
639 // [...] A member shall not be declared twice in the
640 // member-specification, except that a nested class or member
641 // class template can be declared and then later defined.
642 if (OldMethod->getLexicalDeclContext() ==
643 NewMethod->getLexicalDeclContext()) {
644 unsigned NewDiag;
645 if (isa<CXXConstructorDecl>(OldMethod))
646 NewDiag = diag::err_constructor_redeclared;
647 else if (isa<CXXDestructorDecl>(NewMethod))
648 NewDiag = diag::err_destructor_redeclared;
649 else if (isa<CXXConversionDecl>(NewMethod))
650 NewDiag = diag::err_conv_function_redeclared;
651 else
652 NewDiag = diag::err_member_redeclared;
653
654 Diag(New->getLocation(), NewDiag);
655 Diag(Old->getLocation(), PrevDiag);
656 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000657 }
658
659 // (C++98 8.3.5p3):
660 // All declarations for a function shall agree exactly in both the
661 // return type and the parameter-type-list.
662 if (OldQType == NewQType) {
663 // We have a redeclaration.
664 MergeAttributes(New, Old);
665 Redeclaration = true;
666 return MergeCXXFunctionDecl(New, Old);
667 }
668
669 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000670 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000671
672 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000673 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000674 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000675 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000676 MergeAttributes(New, Old);
677 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000678 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000679 }
Chris Lattner1470b072007-11-06 06:07:26 +0000680
Steve Naroff6c9e7922008-01-16 15:01:34 +0000681 // A function that has already been declared has been redeclared or defined
682 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000683
Chris Lattner4b009652007-07-25 00:24:17 +0000684 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
685 // TODO: This is totally simplistic. It should handle merging functions
686 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000687 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000688 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000689 return New;
690}
691
Steve Naroffb5e78152008-08-08 17:50:35 +0000692/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000693static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000694 if (VD->isFileVarDecl())
695 return (!VD->getInit() &&
696 (VD->getStorageClass() == VarDecl::None ||
697 VD->getStorageClass() == VarDecl::Static));
698 return false;
699}
700
701/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
702/// when dealing with C "tentative" external object definitions (C99 6.9.2).
703void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
704 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000705 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000706
Douglas Gregor3a423132009-01-07 16:34:42 +0000707 // FIXME: I don't think this will actually see all of the
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000708 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffb5e78152008-08-08 17:50:35 +0000709 for (IdentifierResolver::iterator
710 I = IdResolver.begin(VD->getIdentifier(),
711 VD->getDeclContext(), false/*LookInParentCtx*/),
712 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000713 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000714 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
715
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000716 // Handle the following case:
717 // int a[10];
718 // int a[]; - the code below makes sure we set the correct type.
719 // int a[11]; - this is an error, size isn't 10.
720 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
721 OldDecl->getType()->isConstantArrayType())
722 VD->setType(OldDecl->getType());
723
Steve Naroffb5e78152008-08-08 17:50:35 +0000724 // Check for "tentative" definitions. We can't accomplish this in
725 // MergeVarDecl since the initializer hasn't been attached.
726 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
727 continue;
728
729 // Handle __private_extern__ just like extern.
730 if (OldDecl->getStorageClass() != VarDecl::Extern &&
731 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
732 VD->getStorageClass() != VarDecl::Extern &&
733 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000734 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000735 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000736 }
737 }
738 }
739}
740
Chris Lattner4b009652007-07-25 00:24:17 +0000741/// MergeVarDecl - We just parsed a variable 'New' which has the same name
742/// and scope as a previous declaration 'Old'. Figure out how to resolve this
743/// situation, merging decls or emitting diagnostics as appropriate.
744///
Steve Naroffb5e78152008-08-08 17:50:35 +0000745/// Tentative definition rules (C99 6.9.2p2) are checked by
746/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
747/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000748///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000749VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000750 // Verify the old decl was also a variable.
751 VarDecl *Old = dyn_cast<VarDecl>(OldD);
752 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000753 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000754 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000755 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000756 return New;
757 }
Chris Lattner402b3372008-03-03 03:28:21 +0000758
759 MergeAttributes(New, Old);
760
Chris Lattner4b009652007-07-25 00:24:17 +0000761 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000762 QualType OldCType = Context.getCanonicalType(Old->getType());
763 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000764 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000765 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000766 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000767 return New;
768 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000769 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
770 if (New->getStorageClass() == VarDecl::Static &&
771 (Old->getStorageClass() == VarDecl::None ||
772 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000773 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000774 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000775 return New;
776 }
777 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
778 if (New->getStorageClass() != VarDecl::Static &&
779 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000780 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000781 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000782 return New;
783 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000784 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
785 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000786 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000787 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000788 }
789 return New;
790}
791
Chris Lattner3e254fb2008-04-08 04:40:51 +0000792/// CheckParmsForFunctionDef - Check that the parameters of the given
793/// function are appropriate for the definition of a function. This
794/// takes care of any checks that cannot be performed on the
795/// declaration itself, e.g., that the types of each of the function
796/// parameters are complete.
797bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
798 bool HasInvalidParm = false;
799 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
800 ParmVarDecl *Param = FD->getParamDecl(p);
801
802 // C99 6.7.5.3p4: the parameters in a parameter type list in a
803 // function declarator that is part of a function definition of
804 // that function shall not have incomplete type.
805 if (Param->getType()->isIncompleteType() &&
806 !Param->isInvalidDecl()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000807 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +0000808 << Param->getType();
Chris Lattner3e254fb2008-04-08 04:40:51 +0000809 Param->setInvalidDecl();
810 HasInvalidParm = true;
811 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000812
813 // C99 6.9.1p5: If the declarator includes a parameter type list, the
814 // declaration of each parameter shall include an identifier.
815 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
816 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000817 }
818
819 return HasInvalidParm;
820}
821
Chris Lattner4b009652007-07-25 00:24:17 +0000822/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
823/// no declarator (e.g. "struct foo;") is parsed.
824Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Sebastian Redlb7605e82008-12-28 15:28:59 +0000825 // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
826 if (!DS.isMissingDeclaratorOk()) {
827 // FIXME: This diagnostic is emitted even when various previous
828 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
829 // DeclSpec has no means of communicating this information, and the
830 // responsible parser functions are quite far apart.
831 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
832 << DS.getSourceRange();
833 return 0;
834 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000835
836 TagDecl *Tag
837 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
838 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
839 if (!Record->getDeclName() && Record->isDefinition() &&
840 !Record->isInvalidDecl())
841 return BuildAnonymousStructOrUnion(S, DS, Record);
842 }
Sebastian Redlb7605e82008-12-28 15:28:59 +0000843
Douglas Gregor723d3332009-01-07 00:43:41 +0000844 return Tag;
845}
846
847/// InjectAnonymousStructOrUnionMembers - Inject the members of the
848/// anonymous struct or union AnonRecord into the owning context Owner
849/// and scope S. This routine will be invoked just after we realize
850/// that an unnamed union or struct is actually an anonymous union or
851/// struct, e.g.,
852///
853/// @code
854/// union {
855/// int i;
856/// float f;
857/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
858/// // f into the surrounding scope.x
859/// @endcode
860///
861/// This routine is recursive, injecting the names of nested anonymous
862/// structs/unions into the owning context and scope as well.
863bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
864 RecordDecl *AnonRecord) {
865 bool Invalid = false;
866 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
867 FEnd = AnonRecord->field_end();
868 F != FEnd; ++F) {
869 if ((*F)->getDeclName()) {
870 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
871 S, Owner, false, false, false);
872 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
873 // C++ [class.union]p2:
874 // The names of the members of an anonymous union shall be
875 // distinct from the names of any other entity in the
876 // scope in which the anonymous union is declared.
877 unsigned diagKind
878 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
879 : diag::err_anonymous_struct_member_redecl;
880 Diag((*F)->getLocation(), diagKind)
881 << (*F)->getDeclName();
882 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
883 Invalid = true;
884 } else {
885 // C++ [class.union]p2:
886 // For the purpose of name lookup, after the anonymous union
887 // definition, the members of the anonymous union are
888 // considered to have been defined in the scope in which the
889 // anonymous union is declared.
890 Owner->insert(Context, *F);
891 S->AddDecl(*F);
892 IdResolver.AddDecl(*F);
893 }
894 } else if (const RecordType *InnerRecordType
895 = (*F)->getType()->getAsRecordType()) {
896 RecordDecl *InnerRecord = InnerRecordType->getDecl();
897 if (InnerRecord->isAnonymousStructOrUnion())
898 Invalid = Invalid ||
899 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
900 }
901 }
902
903 return Invalid;
904}
905
906/// ActOnAnonymousStructOrUnion - Handle the declaration of an
907/// anonymous structure or union. Anonymous unions are a C++ feature
908/// (C++ [class.union]) and a GNU C extension; anonymous structures
909/// are a GNU C and GNU C++ extension.
910Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
911 RecordDecl *Record) {
912 DeclContext *Owner = Record->getDeclContext();
913
914 // Diagnose whether this anonymous struct/union is an extension.
915 if (Record->isUnion() && !getLangOptions().CPlusPlus)
916 Diag(Record->getLocation(), diag::ext_anonymous_union);
917 else if (!Record->isUnion())
918 Diag(Record->getLocation(), diag::ext_anonymous_struct);
919
920 // C and C++ require different kinds of checks for anonymous
921 // structs/unions.
922 bool Invalid = false;
923 if (getLangOptions().CPlusPlus) {
924 const char* PrevSpec = 0;
925 // C++ [class.union]p3:
926 // Anonymous unions declared in a named namespace or in the
927 // global namespace shall be declared static.
928 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
929 (isa<TranslationUnitDecl>(Owner) ||
930 (isa<NamespaceDecl>(Owner) &&
931 cast<NamespaceDecl>(Owner)->getDeclName()))) {
932 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
933 Invalid = true;
934
935 // Recover by adding 'static'.
936 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
937 }
938 // C++ [class.union]p3:
939 // A storage class is not allowed in a declaration of an
940 // anonymous union in a class scope.
941 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
942 isa<RecordDecl>(Owner)) {
943 Diag(DS.getStorageClassSpecLoc(),
944 diag::err_anonymous_union_with_storage_spec);
945 Invalid = true;
946
947 // Recover by removing the storage specifier.
948 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
949 PrevSpec);
950 }
Douglas Gregorc7f01612009-01-07 19:46:03 +0000951
952 // C++ [class.union]p2:
953 // The member-specification of an anonymous union shall only
954 // define non-static data members. [Note: nested types and
955 // functions cannot be declared within an anonymous union. ]
956 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
957 MemEnd = Record->decls_end();
958 Mem != MemEnd; ++Mem) {
959 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
960 // C++ [class.union]p3:
961 // An anonymous union shall not have private or protected
962 // members (clause 11).
963 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
964 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
965 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
966 Invalid = true;
967 }
968 } else if ((*Mem)->isImplicit()) {
969 // Any implicit members are fine.
970 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
971 if (!MemRecord->isAnonymousStructOrUnion() &&
972 MemRecord->getDeclName()) {
973 // This is a nested type declaration.
974 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
975 << (int)Record->isUnion();
976 Invalid = true;
977 }
978 } else {
979 // We have something that isn't a non-static data
980 // member. Complain about it.
981 unsigned DK = diag::err_anonymous_record_bad_member;
982 if (isa<TypeDecl>(*Mem))
983 DK = diag::err_anonymous_record_with_type;
984 else if (isa<FunctionDecl>(*Mem))
985 DK = diag::err_anonymous_record_with_function;
986 else if (isa<VarDecl>(*Mem))
987 DK = diag::err_anonymous_record_with_static;
988 Diag((*Mem)->getLocation(), DK)
989 << (int)Record->isUnion();
990 Invalid = true;
991 }
992 }
Douglas Gregor723d3332009-01-07 00:43:41 +0000993 } else {
994 // FIXME: Check GNU C semantics
995 }
996
997 if (!Record->isUnion() && !Owner->isRecord()) {
998 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member);
999 Invalid = true;
1000 }
1001
1002 // Create a declaration for this anonymous struct/union.
1003 ScopedDecl *Anon = 0;
1004 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1005 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1006 /*IdentifierInfo=*/0,
1007 Context.getTypeDeclType(Record),
1008 /*BitWidth=*/0, /*Mutable=*/false,
1009 /*PrevDecl=*/0);
Douglas Gregorc7f01612009-01-07 19:46:03 +00001010 Anon->setAccess(AS_public);
1011 if (getLangOptions().CPlusPlus)
1012 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor723d3332009-01-07 00:43:41 +00001013 } else {
1014 VarDecl::StorageClass SC;
1015 switch (DS.getStorageClassSpec()) {
1016 default: assert(0 && "Unknown storage class!");
1017 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1018 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1019 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1020 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1021 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1022 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1023 case DeclSpec::SCS_mutable:
1024 // mutable can only appear on non-static class members, so it's always
1025 // an error here
1026 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1027 Invalid = true;
1028 SC = VarDecl::None;
1029 break;
1030 }
1031
1032 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1033 /*IdentifierInfo=*/0,
1034 Context.getTypeDeclType(Record),
1035 SC, /*FIXME:LastDeclarator=*/0,
1036 DS.getSourceRange().getBegin());
1037 }
Douglas Gregorc7f01612009-01-07 19:46:03 +00001038 Anon->setImplicit();
Douglas Gregor723d3332009-01-07 00:43:41 +00001039
1040 // Add the anonymous struct/union object to the current
1041 // context. We'll be referencing this object when we refer to one of
1042 // its members.
1043 Owner->addDecl(Context, Anon);
1044
1045 // Inject the members of the anonymous struct/union into the owning
1046 // context and into the identifier resolver chain for name lookup
1047 // purposes.
1048 Invalid = Invalid || InjectAnonymousStructOrUnionMembers(S, Owner, Record);
1049
1050 // Mark this as an anonymous struct/union type. Note that we do not
1051 // do this until after we have already checked and injected the
1052 // members of this anonymous struct/union type, because otherwise
1053 // the members could be injected twice: once by DeclContext when it
1054 // builds its lookup table, and once by
1055 // InjectAnonymousStructOrUnionMembers.
1056 Record->setAnonymousStructOrUnion(true);
1057
1058 if (Invalid)
1059 Anon->setInvalidDecl();
1060
1061 return Anon;
Chris Lattner4b009652007-07-25 00:24:17 +00001062}
1063
Steve Narofff0b23542008-01-10 22:15:12 +00001064bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +00001065 // Get the type before calling CheckSingleAssignmentConstraints(), since
1066 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +00001067 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +00001068
1069 if (getLangOptions().CPlusPlus)
1070 return PerformCopyInitialization(Init, DeclType, "initializing");
1071
Chris Lattner005ed752008-01-04 18:04:52 +00001072 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1073 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1074 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +00001075}
1076
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001077bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001078 const ArrayType *AT = Context.getAsArrayType(DeclT);
1079
1080 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001081 // C99 6.7.8p14. We have an array of character type with unknown size
1082 // being initialized to a string literal.
1083 llvm::APSInt ConstVal(32);
1084 ConstVal = strLiteral->getByteLength() + 1;
1085 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +00001086 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001087 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +00001088 } else {
1089 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001090 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +00001091 // FIXME: Avoid truncation for 64-bit length strings.
1092 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001093 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001094 diag::warn_initializer_string_for_char_array_too_long)
1095 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001096 }
1097 // Set type from "char *" to "constant array of char".
1098 strLiteral->setType(DeclT);
1099 // For now, we always return false (meaning success).
1100 return false;
1101}
1102
1103StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001104 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +00001105 if (AT && AT->getElementType()->isCharType()) {
1106 return dyn_cast<StringLiteral>(Init);
1107 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001108 return 0;
1109}
1110
Douglas Gregor6428e762008-11-05 15:29:30 +00001111bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1112 SourceLocation InitLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +00001113 DeclarationName InitEntity) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +00001114 if (DeclType->isDependentType() || Init->isTypeDependent())
1115 return false;
1116
Douglas Gregor81c29152008-10-29 00:13:59 +00001117 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +00001118 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +00001119 // (8.3.2), shall be initialized by an object, or function, of
1120 // type T or by an object that can be converted into a T.
1121 if (DeclType->isReferenceType())
1122 return CheckReferenceInit(Init, DeclType);
1123
Steve Naroff8e9337f2008-01-21 23:53:58 +00001124 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1125 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +00001126 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +00001127 return Diag(InitLoc, diag::err_variable_object_no_init)
1128 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +00001129
Steve Naroffcb69fb72007-12-10 22:44:33 +00001130 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1131 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +00001132 // FIXME: Handle wide strings
1133 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1134 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +00001135
Douglas Gregor6428e762008-11-05 15:29:30 +00001136 // C++ [dcl.init]p14:
1137 // -- If the destination type is a (possibly cv-qualified) class
1138 // type:
1139 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1140 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1141 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1142
1143 // -- If the initialization is direct-initialization, or if it is
1144 // copy-initialization where the cv-unqualified version of the
1145 // source type is the same class as, or a derived class of, the
1146 // class of the destination, constructors are considered.
1147 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1148 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1149 CXXConstructorDecl *Constructor
1150 = PerformInitializationByConstructor(DeclType, &Init, 1,
1151 InitLoc, Init->getSourceRange(),
1152 InitEntity, IK_Copy);
1153 return Constructor == 0;
1154 }
1155
1156 // -- Otherwise (i.e., for the remaining copy-initialization
1157 // cases), user-defined conversion sequences that can
1158 // convert from the source type to the destination type or
1159 // (when a conversion function is used) to a derived class
1160 // thereof are enumerated as described in 13.3.1.4, and the
1161 // best one is chosen through overload resolution
1162 // (13.3). If the conversion cannot be done or is
1163 // ambiguous, the initialization is ill-formed. The
1164 // function selected is called with the initializer
1165 // expression as its argument; if the function is a
1166 // constructor, the call initializes a temporary of the
1167 // destination type.
1168 // FIXME: We're pretending to do copy elision here; return to
1169 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +00001170 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +00001171 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +00001172
Douglas Gregor62ae25a2008-12-24 00:01:03 +00001173 if (InitEntity)
1174 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1175 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1176 << Init->getType() << Init->getSourceRange();
1177 else
1178 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1179 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1180 << Init->getType() << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +00001181 }
1182
Steve Naroffb2f72412008-09-29 20:07:05 +00001183 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +00001184 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001185 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1186 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +00001187
Steve Narofff0b23542008-01-10 22:15:12 +00001188 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor15e04622008-11-05 16:20:31 +00001189 } else if (getLangOptions().CPlusPlus) {
1190 // C++ [dcl.init]p14:
1191 // [...] If the class is an aggregate (8.5.1), and the initializer
1192 // is a brace-enclosed list, see 8.5.1.
1193 //
1194 // Note: 8.5.1 is handled below; here, we diagnose the case where
1195 // we have an initializer list and a destination type that is not
1196 // an aggregate.
1197 // FIXME: In C++0x, this is yet another form of initialization.
1198 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1199 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1200 if (!ClassDecl->isAggregate())
Chris Lattner9d2cf082008-11-19 05:27:50 +00001201 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +00001202 << DeclType << Init->getSourceRange();
Douglas Gregor15e04622008-11-05 16:20:31 +00001203 }
Steve Naroffcb69fb72007-12-10 22:44:33 +00001204 }
Eli Friedman38b7a912008-06-06 19:40:52 +00001205
Steve Naroffc4d4a482008-05-01 22:18:59 +00001206 InitListChecker CheckInitList(this, InitList, DeclType);
1207 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +00001208}
1209
Douglas Gregor6704b312008-11-17 22:58:34 +00001210/// GetNameForDeclarator - Determine the full declaration name for the
1211/// given Declarator.
1212DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1213 switch (D.getKind()) {
1214 case Declarator::DK_Abstract:
1215 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1216 return DeclarationName();
1217
1218 case Declarator::DK_Normal:
1219 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1220 return DeclarationName(D.getIdentifier());
1221
1222 case Declarator::DK_Constructor: {
1223 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1224 Ty = Context.getCanonicalType(Ty);
1225 return Context.DeclarationNames.getCXXConstructorName(Ty);
1226 }
1227
1228 case Declarator::DK_Destructor: {
1229 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1230 Ty = Context.getCanonicalType(Ty);
1231 return Context.DeclarationNames.getCXXDestructorName(Ty);
1232 }
1233
1234 case Declarator::DK_Conversion: {
1235 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1236 Ty = Context.getCanonicalType(Ty);
1237 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1238 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +00001239
1240 case Declarator::DK_Operator:
1241 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1242 return Context.DeclarationNames.getCXXOperatorName(
1243 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +00001244 }
1245
1246 assert(false && "Unknown name kind");
1247 return DeclarationName();
1248}
1249
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001250/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1251/// functions Declaration and Definition are "nearly" matching. This
1252/// heuristic is used to improve diagnostics in the case where an
1253/// out-of-line member function definition doesn't match any
1254/// declaration within the class.
1255static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1256 FunctionDecl *Declaration,
1257 FunctionDecl *Definition) {
1258 if (Declaration->param_size() != Definition->param_size())
1259 return false;
1260 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1261 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1262 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1263
1264 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1265 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1266 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1267 return false;
1268 }
1269
1270 return true;
1271}
1272
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001273Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001274Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1275 bool IsFunctionDefinition) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001276 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +00001277 DeclarationName Name = GetNameForDeclarator(D);
1278
Chris Lattner4b009652007-07-25 00:24:17 +00001279 // All of these full declarators require an identifier. If it doesn't have
1280 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +00001281 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +00001282 if (!D.getInvalidType()) // Reject this if we think it is valid.
1283 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +00001284 diag::err_declarator_need_ident)
1285 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +00001286 return 0;
1287 }
1288
Chris Lattnera7549902007-08-26 06:24:45 +00001289 // The scope passed in may not be a decl scope. Zip up the scope tree until
1290 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +00001291 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1292 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +00001293 S = S->getParent();
1294
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001295 DeclContext *DC;
1296 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +00001297 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001298 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +00001299
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001300 // See if this is a redefinition of a variable in the same scope.
1301 if (!D.getCXXScopeSpec().isSet()) {
1302 DC = CurContext;
Douglas Gregor6704b312008-11-17 22:58:34 +00001303 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001304 } else { // Something like "int foo::x;"
1305 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor6704b312008-11-17 22:58:34 +00001306 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001307
1308 // C++ 7.3.1.2p2:
1309 // Members (including explicit specializations of templates) of a named
1310 // namespace can also be defined outside that namespace by explicit
1311 // qualification of the name being defined, provided that the entity being
1312 // defined was already declared in the namespace and the definition appears
1313 // after the point of declaration in a namespace that encloses the
1314 // declarations namespace.
1315 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001316 // Note that we only check the context at this point. We don't yet
1317 // have enough information to make sure that PrevDecl is actually
1318 // the declaration we want to match. For example, given:
1319 //
Douglas Gregor98341042008-12-12 08:25:50 +00001320 // class X {
1321 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001322 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +00001323 // };
1324 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001325 // void X::f(int) { } // ill-formed
1326 //
1327 // In this case, PrevDecl will point to the overload set
1328 // containing the two f's declared in X, but neither of them
1329 // matches.
1330 if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001331 // The qualifying scope doesn't enclose the original declaration.
1332 // Emit diagnostic based on current scope.
1333 SourceLocation L = D.getIdentifierLoc();
1334 SourceRange R = D.getCXXScopeSpec().getRange();
1335 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +00001336 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001337 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +00001338 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +00001339 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001340 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001341 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001342 }
1343 }
1344
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001345 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001346 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001347 InvalidDecl = InvalidDecl
1348 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001349 // Just pretend that we didn't see the previous declaration.
1350 PrevDecl = 0;
1351 }
1352
Douglas Gregor1d661552008-04-13 21:07:44 +00001353 // In C++, the previous declaration we find might be a tag type
1354 // (class or enum). In this case, the new declaration will hide the
1355 // tag type.
1356 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1357 PrevDecl = 0;
1358
Chris Lattner82bb4792007-11-14 06:34:38 +00001359 QualType R = GetTypeForDeclarator(D, S);
1360 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1361
Chris Lattner4b009652007-07-25 00:24:17 +00001362 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001363 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1364 if (D.getCXXScopeSpec().isSet()) {
1365 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1366 << D.getCXXScopeSpec().getRange();
1367 InvalidDecl = true;
1368 // Pretend we didn't see the scope specifier.
1369 DC = 0;
1370 }
1371
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001372 // Check that there are no default arguments (C++ only).
1373 if (getLangOptions().CPlusPlus)
1374 CheckExtraCXXDefaultArguments(D);
1375
Chris Lattner82bb4792007-11-14 06:34:38 +00001376 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +00001377 if (!NewTD) return 0;
1378
1379 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001380 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +00001381 // Merge the decl with the existing one if appropriate. If the decl is
1382 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001383 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001384 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1385 if (NewTD == 0) return 0;
1386 }
1387 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001388 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001389 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1390 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +00001391 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00001392 if (NewTD->getUnderlyingType()->isVariableArrayType())
1393 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1394 else
1395 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1396
Steve Naroff5eb879b2007-08-31 17:20:07 +00001397 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001398 }
1399 }
Chris Lattner82bb4792007-11-14 06:34:38 +00001400 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +00001401 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +00001402 switch (D.getDeclSpec().getStorageClassSpec()) {
1403 default: assert(0 && "Unknown storage class!");
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001404 case DeclSpec::SCS_auto:
Chris Lattner4b009652007-07-25 00:24:17 +00001405 case DeclSpec::SCS_register:
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001406 case DeclSpec::SCS_mutable:
Chris Lattner4bfd2232008-11-24 06:25:27 +00001407 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001408 InvalidDecl = true;
1409 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001410 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1411 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1412 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +00001413 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +00001414 }
1415
Chris Lattner4c7802b2008-03-15 21:24:04 +00001416 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001417 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001418 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1419
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001420 FunctionDecl *NewFD;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001421 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001422 // This is a C++ constructor declaration.
Douglas Gregor723d3332009-01-07 00:43:41 +00001423 assert(DC->isRecord() &&
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001424 "Constructors can only be declared in a member context");
1425
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001426 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001427
1428 // Create the new declaration
1429 NewFD = CXXConstructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001430 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001431 D.getIdentifierLoc(), Name, R,
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001432 isExplicit, isInline,
1433 /*isImplicitlyDeclared=*/false);
1434
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001435 if (InvalidDecl)
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001436 NewFD->setInvalidDecl();
1437 } else if (D.getKind() == Declarator::DK_Destructor) {
1438 // This is a C++ destructor declaration.
Douglas Gregor723d3332009-01-07 00:43:41 +00001439 if (DC->isRecord()) {
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001440 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001441
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001442 NewFD = CXXDestructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001443 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001444 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001445 isInline,
1446 /*isImplicitlyDeclared=*/false);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001447
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001448 if (InvalidDecl)
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001449 NewFD->setInvalidDecl();
1450 } else {
1451 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001452
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001453 // Create a FunctionDecl to satisfy the function definition parsing
1454 // code path.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001455 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +00001456 Name, R, SC, isInline, LastDeclarator,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001457 // FIXME: Move to DeclGroup...
1458 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001459 InvalidDecl = true;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001460 NewFD->setInvalidDecl();
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001461 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001462 } else if (D.getKind() == Declarator::DK_Conversion) {
Douglas Gregor723d3332009-01-07 00:43:41 +00001463 if (!DC->isRecord()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001464 Diag(D.getIdentifierLoc(),
1465 diag::err_conv_function_not_member);
1466 return 0;
1467 } else {
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001468 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001469
Douglas Gregor853dd392008-12-26 15:00:45 +00001470 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001471 D.getIdentifierLoc(), Name, R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001472 isInline, isExplicit);
1473
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001474 if (InvalidDecl)
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001475 NewFD->setInvalidDecl();
1476 }
Douglas Gregor723d3332009-01-07 00:43:41 +00001477 } else if (DC->isRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001478 // This is a C++ method declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001479 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001480 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001481 (SC == FunctionDecl::Static), isInline,
1482 LastDeclarator);
1483 } else {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001484 NewFD = FunctionDecl::Create(Context, DC,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001485 D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +00001486 Name, R, SC, isInline, LastDeclarator,
Steve Naroff71cd7762008-10-03 00:02:03 +00001487 // FIXME: Move to DeclGroup...
1488 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001489 }
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001490
Douglas Gregorb9213832008-12-15 21:24:18 +00001491 // Set the lexical context. If the declarator has a C++
1492 // scope specifier, the lexical context will be different
1493 // from the semantic context.
1494 NewFD->setLexicalDeclContext(CurContext);
1495
Daniel Dunbarc3540ff2008-08-05 01:35:17 +00001496 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001497 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +00001498 // The parser guarantees this is a string.
1499 StringLiteral *SE = cast<StringLiteral>(E);
1500 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1501 SE->getByteLength())));
1502 }
1503
Chris Lattner3e254fb2008-04-08 04:40:51 +00001504 // Copy the parameter declarations from the declarator D to
1505 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +00001506 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001507 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1508
1509 // Create Decl objects for each parameter, adding them to the
1510 // FunctionDecl.
1511 llvm::SmallVector<ParmVarDecl*, 16> Params;
1512
1513 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1514 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +00001515 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +00001516 // We let through "const void" here because Sema::GetTypeForDeclarator
1517 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001518 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1519 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +00001520 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1521 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +00001522 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1523
Chris Lattnerda7b5f02008-04-10 02:26:16 +00001524 // In C++, the empty parameter-type-list must be spelled "void"; a
1525 // typedef of void is not permitted.
1526 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +00001527 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +00001528 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1529 }
Eli Friedman769e7302008-08-25 21:31:01 +00001530 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001531 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1532 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1533 }
1534
1535 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001536 } else if (R->getAsTypedefType()) {
1537 // When we're declaring a function with a typedef, as in the
1538 // following example, we'll need to synthesize (unnamed)
1539 // parameters for use in the declaration.
1540 //
1541 // @code
1542 // typedef void fn(int);
1543 // fn f;
1544 // @endcode
1545 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1546 if (!FT) {
1547 // This is a typedef of a function with no prototype, so we
1548 // don't need to do anything.
1549 } else if ((FT->getNumArgs() == 0) ||
1550 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1551 FT->getArgType(0)->isVoidType())) {
1552 // This is a zero-argument function. We don't need to do anything.
1553 } else {
1554 // Synthesize a parameter for each argument type.
1555 llvm::SmallVector<ParmVarDecl*, 16> Params;
1556 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1557 ArgType != FT->arg_type_end(); ++ArgType) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001558 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001559 SourceLocation(), 0,
1560 *ArgType, VarDecl::None,
1561 0, 0));
1562 }
1563
1564 NewFD->setParams(&Params[0], Params.size());
1565 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001566 }
1567
Douglas Gregor605de8d2008-12-16 21:30:33 +00001568 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1569 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00001570 else if (isa<CXXDestructorDecl>(NewFD)) {
1571 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1572 Record->setUserDeclaredDestructor(true);
1573 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1574 // user-defined destructor.
1575 Record->setPOD(false);
1576 } else if (CXXConversionDecl *Conversion =
1577 dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregorb0212bd2008-11-17 20:34:05 +00001578 ActOnConversionDeclarator(Conversion);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001579
Douglas Gregore60e5d32008-11-06 22:13:31 +00001580 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1581 if (NewFD->isOverloadedOperator() &&
1582 CheckOverloadedOperatorDeclaration(NewFD))
1583 NewFD->setInvalidDecl();
1584
Steve Narofff8a09432008-01-09 23:34:55 +00001585 // Merge the decl with the existing one if appropriate. Since C functions
1586 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001587 if (PrevDecl &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001588 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +00001589 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001590
1591 // If C++, determine whether NewFD is an overload of PrevDecl or
1592 // a declaration that requires merging. If it's an overload,
1593 // there's no more work to do here; we'll just add the new
1594 // function to the scope.
1595 OverloadedFunctionDecl::function_iterator MatchedDecl;
1596 if (!getLangOptions().CPlusPlus ||
1597 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1598 Decl *OldDecl = PrevDecl;
1599
1600 // If PrevDecl was an overloaded function, extract the
1601 // FunctionDecl that matched.
1602 if (isa<OverloadedFunctionDecl>(PrevDecl))
1603 OldDecl = *MatchedDecl;
1604
1605 // NewFD and PrevDecl represent declarations that need to be
1606 // merged.
1607 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1608
1609 if (NewFD == 0) return 0;
1610 if (Redeclaration) {
1611 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1612
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001613 // An out-of-line member function declaration must also be a
1614 // definition (C++ [dcl.meaning]p1).
1615 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1616 !InvalidDecl) {
1617 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1618 << D.getCXXScopeSpec().getRange();
1619 NewFD->setInvalidDecl();
Douglas Gregord2baafd2008-10-21 16:13:35 +00001620 }
1621 }
Douglas Gregor42214c52008-04-21 02:02:58 +00001622 }
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001623
1624 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1625 // The user tried to provide an out-of-line definition for a
1626 // member function, but there was no such member function
1627 // declared (C++ [class.mfct]p2). For example:
1628 //
1629 // class X {
1630 // void f() const;
1631 // };
1632 //
1633 // void X::f() { } // ill-formed
1634 //
1635 // Complain about this problem, and attempt to suggest close
1636 // matches (e.g., those that differ only in cv-qualifiers and
1637 // whether the parameter types are references).
1638 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1639 << cast<CXXRecordDecl>(DC)->getDeclName()
1640 << D.getCXXScopeSpec().getRange();
1641 InvalidDecl = true;
1642
1643 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1644 if (!PrevDecl) {
1645 // Nothing to suggest.
1646 } else if (OverloadedFunctionDecl *Ovl
1647 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1648 for (OverloadedFunctionDecl::function_iterator
1649 Func = Ovl->function_begin(),
1650 FuncEnd = Ovl->function_end();
1651 Func != FuncEnd; ++Func) {
1652 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1653 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1654
1655 }
1656 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1657 // Suggest this no matter how mismatched it is; it's the only
1658 // thing we have.
1659 unsigned diag;
1660 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1661 diag = diag::note_member_def_close_match;
1662 else if (Method->getBody())
1663 diag = diag::note_previous_definition;
1664 else
1665 diag = diag::note_previous_declaration;
1666 Diag(Method->getLocation(), diag);
1667 }
1668
1669 PrevDecl = 0;
1670 }
Chris Lattner4b009652007-07-25 00:24:17 +00001671 }
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00001672 // Handle attributes. We need to have merged decls when handling attributes
1673 // (for example to check for conflicts, etc).
1674 ProcessDeclAttributes(NewFD, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001675 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001676
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001677 if (getLangOptions().CPlusPlus) {
1678 // In C++, check default arguments now that we have merged decls.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001679 CheckCXXDefaultArguments(NewFD);
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001680
1681 // An out-of-line member function declaration must also be a
1682 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6e71edc2008-12-23 21:05:05 +00001683 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001684 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1685 << D.getCXXScopeSpec().getRange();
1686 InvalidDecl = true;
1687 }
1688 }
Chris Lattner4b009652007-07-25 00:24:17 +00001689 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001690 // Check that there are no default arguments (C++ only).
1691 if (getLangOptions().CPlusPlus)
1692 CheckExtraCXXDefaultArguments(D);
1693
Ted Kremenek42730c52008-01-07 19:49:32 +00001694 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner65cae292008-11-19 08:23:25 +00001695 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1696 << D.getIdentifier();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001697 InvalidDecl = true;
1698 }
Chris Lattner4b009652007-07-25 00:24:17 +00001699
1700 VarDecl *NewVD;
1701 VarDecl::StorageClass SC;
1702 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001703 default: assert(0 && "Unknown storage class!");
1704 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1705 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1706 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1707 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1708 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1709 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001710 case DeclSpec::SCS_mutable:
1711 // mutable can only appear on non-static class members, so it's always
1712 // an error here
1713 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1714 InvalidDecl = true;
Douglas Gregor538754e2008-12-01 22:46:22 +00001715 SC = VarDecl::None;
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001716 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001717 }
Douglas Gregor6704b312008-11-17 22:58:34 +00001718
1719 IdentifierInfo *II = Name.getAsIdentifierInfo();
1720 if (!II) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001721 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1722 << Name.getAsString();
Douglas Gregor6704b312008-11-17 22:58:34 +00001723 return 0;
1724 }
1725
Douglas Gregor723d3332009-01-07 00:43:41 +00001726 if (DC->isRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001727 // This is a static data member for a C++ class.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001728 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001729 D.getIdentifierLoc(), II,
1730 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001731 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001732 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001733 if (S->getFnParent() == 0) {
1734 // C99 6.9p2: The storage-class specifiers auto and register shall not
1735 // appear in the declaration specifiers in an external declaration.
1736 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattner4bfd2232008-11-24 06:25:27 +00001737 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001738 InvalidDecl = true;
1739 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001740 }
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001741 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1742 II, R, SC, LastDeclarator,
1743 // FIXME: Move to DeclGroup...
1744 D.getDeclSpec().getSourceRange().getBegin());
1745 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001746 }
Chris Lattner4b009652007-07-25 00:24:17 +00001747 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001748 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001749
Daniel Dunbarced89142008-08-06 00:03:29 +00001750 // Handle GNU asm-label extension (encoded as an attribute).
1751 if (Expr *E = (Expr*) D.getAsmLabel()) {
1752 // The parser guarantees this is a string.
1753 StringLiteral *SE = cast<StringLiteral>(E);
1754 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1755 SE->getByteLength())));
1756 }
1757
Nate Begemanea583262008-03-14 18:07:10 +00001758 // Emit an error if an address space was applied to decl with local storage.
1759 // This includes arrays of objects with address space qualifiers, but not
1760 // automatic variables that point to other address spaces.
1761 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001762 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1763 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1764 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001765 }
Steve Narofff8a09432008-01-09 23:34:55 +00001766 // Merge the decl with the existing one if appropriate. If the decl is
1767 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001768 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001769 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1770 // The user tried to define a non-static data member
1771 // out-of-line (C++ [dcl.meaning]p1).
1772 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1773 << D.getCXXScopeSpec().getRange();
1774 NewVD->Destroy(Context);
1775 return 0;
1776 }
1777
Chris Lattner4b009652007-07-25 00:24:17 +00001778 NewVD = MergeVarDecl(NewVD, PrevDecl);
1779 if (NewVD == 0) return 0;
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001780
1781 if (D.getCXXScopeSpec().isSet()) {
1782 // No previous declaration in the qualifying scope.
1783 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1784 << Name << D.getCXXScopeSpec().getRange();
1785 InvalidDecl = true;
1786 }
Chris Lattner4b009652007-07-25 00:24:17 +00001787 }
Chris Lattner4b009652007-07-25 00:24:17 +00001788 New = NewVD;
1789 }
1790
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001791 // Set the lexical context. If the declarator has a C++ scope specifier, the
1792 // lexical context will be different from the semantic context.
1793 New->setLexicalDeclContext(CurContext);
1794
Chris Lattner4b009652007-07-25 00:24:17 +00001795 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001796 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001797 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001798 // If any semantic error occurred, mark the decl as invalid.
1799 if (D.getInvalidType() || InvalidDecl)
1800 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001801
1802 return New;
1803}
1804
Steve Narofffc08f5e2008-10-27 11:34:16 +00001805void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001806 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1807 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001808}
1809
Eli Friedman02c22ce2008-05-20 13:48:25 +00001810bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1811 switch (Init->getStmtClass()) {
1812 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001813 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001814 return true;
1815 case Expr::ParenExprClass: {
1816 const ParenExpr* PE = cast<ParenExpr>(Init);
1817 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1818 }
1819 case Expr::CompoundLiteralExprClass:
1820 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor566782a2009-01-06 05:10:23 +00001821 case Expr::DeclRefExprClass:
1822 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001823 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001824 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1825 if (VD->hasGlobalStorage())
1826 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001827 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001828 return true;
1829 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001830 if (isa<FunctionDecl>(D))
1831 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001832 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001833 return true;
1834 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001835 case Expr::MemberExprClass: {
1836 const MemberExpr *M = cast<MemberExpr>(Init);
1837 if (M->isArrow())
1838 return CheckAddressConstantExpression(M->getBase());
1839 return CheckAddressConstantExpressionLValue(M->getBase());
1840 }
1841 case Expr::ArraySubscriptExprClass: {
1842 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1843 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1844 return CheckAddressConstantExpression(ASE->getBase()) ||
1845 CheckArithmeticConstantExpression(ASE->getIdx());
1846 }
1847 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001848 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001849 return false;
1850 case Expr::UnaryOperatorClass: {
1851 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1852
1853 // C99 6.6p9
1854 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001855 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001856
Steve Narofffc08f5e2008-10-27 11:34:16 +00001857 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001858 return true;
1859 }
1860 }
1861}
1862
1863bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1864 switch (Init->getStmtClass()) {
1865 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001866 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001867 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001868 case Expr::ParenExprClass:
1869 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001870 case Expr::StringLiteralClass:
1871 case Expr::ObjCStringLiteralClass:
1872 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001873 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001874 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001875 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1876 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1877 Builtin::BI__builtin___CFStringMakeConstantString)
1878 return false;
1879
Steve Narofffc08f5e2008-10-27 11:34:16 +00001880 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001881 return true;
1882
Eli Friedman02c22ce2008-05-20 13:48:25 +00001883 case Expr::UnaryOperatorClass: {
1884 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1885
1886 // C99 6.6p9
1887 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1888 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1889
1890 if (Exp->getOpcode() == UnaryOperator::Extension)
1891 return CheckAddressConstantExpression(Exp->getSubExpr());
1892
Steve Narofffc08f5e2008-10-27 11:34:16 +00001893 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001894 return true;
1895 }
1896 case Expr::BinaryOperatorClass: {
1897 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1898 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1899
1900 Expr *PExp = Exp->getLHS();
1901 Expr *IExp = Exp->getRHS();
1902 if (IExp->getType()->isPointerType())
1903 std::swap(PExp, IExp);
1904
1905 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1906 return CheckAddressConstantExpression(PExp) ||
1907 CheckArithmeticConstantExpression(IExp);
1908 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001909 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001910 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001911 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001912 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1913 // Check for implicit promotion
1914 if (SubExpr->getType()->isFunctionType() ||
1915 SubExpr->getType()->isArrayType())
1916 return CheckAddressConstantExpressionLValue(SubExpr);
1917 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001918
1919 // Check for pointer->pointer cast
1920 if (SubExpr->getType()->isPointerType())
1921 return CheckAddressConstantExpression(SubExpr);
1922
Eli Friedman1fad3c62008-08-25 20:46:57 +00001923 if (SubExpr->getType()->isIntegralType()) {
1924 // Check for the special-case of a pointer->int->pointer cast;
1925 // this isn't standard, but some code requires it. See
1926 // PR2720 for an example.
1927 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1928 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1929 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1930 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1931 if (IntWidth >= PointerWidth) {
1932 return CheckAddressConstantExpression(SubCast->getSubExpr());
1933 }
1934 }
1935 }
1936 }
1937 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001938 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001939 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001940
Steve Narofffc08f5e2008-10-27 11:34:16 +00001941 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001942 return true;
1943 }
1944 case Expr::ConditionalOperatorClass: {
1945 // FIXME: Should we pedwarn here?
1946 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1947 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001948 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001949 return true;
1950 }
1951 if (CheckArithmeticConstantExpression(Exp->getCond()))
1952 return true;
1953 if (Exp->getLHS() &&
1954 CheckAddressConstantExpression(Exp->getLHS()))
1955 return true;
1956 return CheckAddressConstantExpression(Exp->getRHS());
1957 }
1958 case Expr::AddrLabelExprClass:
1959 return false;
1960 }
1961}
1962
Eli Friedman998dffb2008-06-09 05:05:07 +00001963static const Expr* FindExpressionBaseAddress(const Expr* E);
1964
1965static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1966 switch (E->getStmtClass()) {
1967 default:
1968 return E;
1969 case Expr::ParenExprClass: {
1970 const ParenExpr* PE = cast<ParenExpr>(E);
1971 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1972 }
1973 case Expr::MemberExprClass: {
1974 const MemberExpr *M = cast<MemberExpr>(E);
1975 if (M->isArrow())
1976 return FindExpressionBaseAddress(M->getBase());
1977 return FindExpressionBaseAddressLValue(M->getBase());
1978 }
1979 case Expr::ArraySubscriptExprClass: {
1980 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1981 return FindExpressionBaseAddress(ASE->getBase());
1982 }
1983 case Expr::UnaryOperatorClass: {
1984 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1985
1986 if (Exp->getOpcode() == UnaryOperator::Deref)
1987 return FindExpressionBaseAddress(Exp->getSubExpr());
1988
1989 return E;
1990 }
1991 }
1992}
1993
1994static const Expr* FindExpressionBaseAddress(const Expr* E) {
1995 switch (E->getStmtClass()) {
1996 default:
1997 return E;
1998 case Expr::ParenExprClass: {
1999 const ParenExpr* PE = cast<ParenExpr>(E);
2000 return FindExpressionBaseAddress(PE->getSubExpr());
2001 }
2002 case Expr::UnaryOperatorClass: {
2003 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2004
2005 // C99 6.6p9
2006 if (Exp->getOpcode() == UnaryOperator::AddrOf)
2007 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
2008
2009 if (Exp->getOpcode() == UnaryOperator::Extension)
2010 return FindExpressionBaseAddress(Exp->getSubExpr());
2011
2012 return E;
2013 }
2014 case Expr::BinaryOperatorClass: {
2015 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2016
2017 Expr *PExp = Exp->getLHS();
2018 Expr *IExp = Exp->getRHS();
2019 if (IExp->getType()->isPointerType())
2020 std::swap(PExp, IExp);
2021
2022 return FindExpressionBaseAddress(PExp);
2023 }
2024 case Expr::ImplicitCastExprClass: {
2025 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2026
2027 // Check for implicit promotion
2028 if (SubExpr->getType()->isFunctionType() ||
2029 SubExpr->getType()->isArrayType())
2030 return FindExpressionBaseAddressLValue(SubExpr);
2031
2032 // Check for pointer->pointer cast
2033 if (SubExpr->getType()->isPointerType())
2034 return FindExpressionBaseAddress(SubExpr);
2035
2036 // We assume that we have an arithmetic expression here;
2037 // if we don't, we'll figure it out later
2038 return 0;
2039 }
Douglas Gregor035d0882008-10-28 15:36:24 +00002040 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00002041 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2042
2043 // Check for pointer->pointer cast
2044 if (SubExpr->getType()->isPointerType())
2045 return FindExpressionBaseAddress(SubExpr);
2046
2047 // We assume that we have an arithmetic expression here;
2048 // if we don't, we'll figure it out later
2049 return 0;
2050 }
2051 }
2052}
2053
Anders Carlssone8bd9f22008-11-22 21:04:56 +00002054bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002055 switch (Init->getStmtClass()) {
2056 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002057 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002058 return true;
2059 case Expr::ParenExprClass: {
2060 const ParenExpr* PE = cast<ParenExpr>(Init);
2061 return CheckArithmeticConstantExpression(PE->getSubExpr());
2062 }
2063 case Expr::FloatingLiteralClass:
2064 case Expr::IntegerLiteralClass:
2065 case Expr::CharacterLiteralClass:
2066 case Expr::ImaginaryLiteralClass:
2067 case Expr::TypesCompatibleExprClass:
2068 case Expr::CXXBoolLiteralExprClass:
2069 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00002070 case Expr::CallExprClass:
2071 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002072 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002073
2074 // Allow any constant foldable calls to builtins.
2075 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002076 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002077
Steve Narofffc08f5e2008-10-27 11:34:16 +00002078 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002079 return true;
2080 }
Douglas Gregor566782a2009-01-06 05:10:23 +00002081 case Expr::DeclRefExprClass:
2082 case Expr::QualifiedDeclRefExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00002083 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2084 if (isa<EnumConstantDecl>(D))
2085 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002086 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002087 return true;
2088 }
2089 case Expr::CompoundLiteralExprClass:
2090 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2091 // but vectors are allowed to be magic.
2092 if (Init->getType()->isVectorType())
2093 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002094 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002095 return true;
2096 case Expr::UnaryOperatorClass: {
2097 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2098
2099 switch (Exp->getOpcode()) {
2100 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2101 // See C99 6.6p3.
2102 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00002103 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002104 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002105 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00002106 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2107 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00002108 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002109 return true;
2110 case UnaryOperator::Extension:
2111 case UnaryOperator::LNot:
2112 case UnaryOperator::Plus:
2113 case UnaryOperator::Minus:
2114 case UnaryOperator::Not:
2115 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2116 }
2117 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002118 case Expr::SizeOfAlignOfExprClass: {
2119 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002120 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002121 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00002122 return false;
2123 // alignof always evaluates to a constant.
2124 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00002125 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00002126 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002127 return true;
2128 }
2129 return false;
2130 }
2131 case Expr::BinaryOperatorClass: {
2132 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2133
2134 if (Exp->getLHS()->getType()->isArithmeticType() &&
2135 Exp->getRHS()->getType()->isArithmeticType()) {
2136 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2137 CheckArithmeticConstantExpression(Exp->getRHS());
2138 }
2139
Eli Friedman998dffb2008-06-09 05:05:07 +00002140 if (Exp->getLHS()->getType()->isPointerType() &&
2141 Exp->getRHS()->getType()->isPointerType()) {
2142 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2143 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2144
2145 // Only allow a null (constant integer) base; we could
2146 // allow some additional cases if necessary, but this
2147 // is sufficient to cover offsetof-like constructs.
2148 if (!LHSBase && !RHSBase) {
2149 return CheckAddressConstantExpression(Exp->getLHS()) ||
2150 CheckAddressConstantExpression(Exp->getRHS());
2151 }
2152 }
2153
Steve Narofffc08f5e2008-10-27 11:34:16 +00002154 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002155 return true;
2156 }
2157 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00002158 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002159 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00002160 if (SubExpr->getType()->isArithmeticType())
2161 return CheckArithmeticConstantExpression(SubExpr);
2162
Eli Friedman266df142008-09-02 09:37:00 +00002163 if (SubExpr->getType()->isPointerType()) {
2164 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2165 // If the pointer has a null base, this is an offsetof-like construct
2166 if (!Base)
2167 return CheckAddressConstantExpression(SubExpr);
2168 }
2169
Steve Narofffc08f5e2008-10-27 11:34:16 +00002170 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00002171 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002172 }
2173 case Expr::ConditionalOperatorClass: {
2174 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00002175
2176 // If GNU extensions are disabled, we require all operands to be arithmetic
2177 // constant expressions.
2178 if (getLangOptions().NoExtensions) {
2179 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2180 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2181 CheckArithmeticConstantExpression(Exp->getRHS());
2182 }
2183
2184 // Otherwise, we have to emulate some of the behavior of fold here.
2185 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2186 // because it can constant fold things away. To retain compatibility with
2187 // GCC code, we see if we can fold the condition to a constant (which we
2188 // should always be able to do in theory). If so, we only require the
2189 // specified arm of the conditional to be a constant. This is a horrible
2190 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00002191 Expr::EvalResult EvalResult;
2192 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2193 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00002194 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00002195 // won't be able to either. Use it to emit the diagnostic though.
2196 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00002197 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00002198 return Res;
2199 }
2200
2201 // Verify that the side following the condition is also a constant.
2202 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00002203 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00002204 std::swap(TrueSide, FalseSide);
2205
2206 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00002207 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00002208
2209 // Okay, the evaluated side evaluates to a constant, so we accept this.
2210 // Check to see if the other side is obviously not a constant. If so,
2211 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00002212 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00002213 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00002214 diag::ext_typecheck_expression_not_constant_but_accepted)
2215 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00002216 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00002217 }
2218 }
2219}
2220
2221bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlssonf6791c62008-12-05 05:09:56 +00002222 Expr::EvalResult Result;
2223
Nuno Lopese7280452008-07-07 16:46:50 +00002224 Init = Init->IgnoreParens();
2225
Anders Carlssonf6791c62008-12-05 05:09:56 +00002226 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2227 return false;
2228
Eli Friedman02c22ce2008-05-20 13:48:25 +00002229 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2230 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2231 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2232
Nuno Lopese7280452008-07-07 16:46:50 +00002233 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2234 return CheckForConstantInitializer(e->getInitializer(), DclT);
2235
Eli Friedman02c22ce2008-05-20 13:48:25 +00002236 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2237 unsigned numInits = Exp->getNumInits();
2238 for (unsigned i = 0; i < numInits; i++) {
2239 // FIXME: Need to get the type of the declaration for C++,
2240 // because it could be a reference?
2241 if (CheckForConstantInitializer(Exp->getInit(i),
2242 Exp->getInit(i)->getType()))
2243 return true;
2244 }
2245 return false;
2246 }
2247
Anders Carlssonf6791c62008-12-05 05:09:56 +00002248 // FIXME: We can probably remove some of this code below, now that
2249 // Expr::Evaluate is doing the heavy lifting for scalars.
2250
Eli Friedman02c22ce2008-05-20 13:48:25 +00002251 if (Init->isNullPointerConstant(Context))
2252 return false;
2253 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00002254 QualType InitTy = Context.getCanonicalType(Init->getType())
2255 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00002256 if (InitTy == Context.BoolTy) {
2257 // Special handling for pointers implicitly cast to bool;
2258 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2259 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2260 Expr* SubE = ICE->getSubExpr();
2261 if (SubE->getType()->isPointerType() ||
2262 SubE->getType()->isArrayType() ||
2263 SubE->getType()->isFunctionType()) {
2264 return CheckAddressConstantExpression(Init);
2265 }
2266 }
2267 } else if (InitTy->isIntegralType()) {
2268 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00002269 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00002270 SubE = CE->getSubExpr();
2271 // Special check for pointer cast to int; we allow as an extension
2272 // an address constant cast to an integer if the integer
2273 // is of an appropriate width (this sort of code is apparently used
2274 // in some places).
2275 // FIXME: Add pedwarn?
2276 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2277 if (SubE && (SubE->getType()->isPointerType() ||
2278 SubE->getType()->isArrayType() ||
2279 SubE->getType()->isFunctionType())) {
2280 unsigned IntWidth = Context.getTypeSize(Init->getType());
2281 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2282 if (IntWidth >= PointerWidth)
2283 return CheckAddressConstantExpression(Init);
2284 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00002285 }
2286
2287 return CheckArithmeticConstantExpression(Init);
2288 }
2289
2290 if (Init->getType()->isPointerType())
2291 return CheckAddressConstantExpression(Init);
2292
Eli Friedman25086f02008-05-30 18:14:48 +00002293 // An array type at the top level that isn't an init-list must
2294 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00002295 if (Init->getType()->isArrayType())
2296 return false;
2297
Nuno Lopes1dc26762008-09-01 18:42:41 +00002298 if (Init->getType()->isFunctionType())
2299 return false;
2300
Steve Naroffdff3fb22008-10-02 17:12:56 +00002301 // Allow block exprs at top level.
2302 if (Init->getType()->isBlockPointerType())
2303 return false;
2304
Steve Narofffc08f5e2008-10-27 11:34:16 +00002305 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002306 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002307}
2308
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002309void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002310 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002311 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002312 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002313
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002314 // If there is no declaration, there was an error parsing it. Just ignore
2315 // the initializer.
2316 if (RealDecl == 0) {
2317 delete Init;
2318 return;
2319 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002320
Steve Naroff420d0f52007-09-12 20:13:48 +00002321 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2322 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00002323 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2324 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002325 RealDecl->setInvalidDecl();
2326 return;
2327 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002328 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002329 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002330 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002331 if (VDecl->isBlockVarDecl()) {
2332 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002333 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002334 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002335 VDecl->setInvalidDecl();
2336 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002337 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002338 VDecl->getDeclName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002339 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002340
2341 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2342 if (!getLangOptions().CPlusPlus) {
2343 if (SC == VarDecl::Static) // C99 6.7.8p4.
2344 CheckForConstantInitializer(Init, DclT);
2345 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002346 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002347 } else if (VDecl->isFileVarDecl()) {
2348 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002349 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002350 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002351 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002352 VDecl->getDeclName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002353 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002354
Anders Carlssonea7140a2008-08-22 05:00:02 +00002355 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2356 if (!getLangOptions().CPlusPlus) {
2357 // C99 6.7.8p4. All file scoped initializers need to be constant.
2358 CheckForConstantInitializer(Init, DclT);
2359 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002360 }
2361 // If the type changed, it means we had an incomplete type that was
2362 // completed by the initializer. For example:
2363 // int ary[] = { 1, 3, 5 };
2364 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002365 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002366 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002367 Init->setType(DclT);
2368 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002369
2370 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002371 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002372 return;
2373}
2374
Douglas Gregor81c29152008-10-29 00:13:59 +00002375void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2376 Decl *RealDecl = static_cast<Decl *>(dcl);
2377
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002378 // If there is no declaration, there was an error parsing it. Just ignore it.
2379 if (RealDecl == 0)
2380 return;
2381
Douglas Gregor81c29152008-10-29 00:13:59 +00002382 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2383 QualType Type = Var->getType();
2384 // C++ [dcl.init.ref]p3:
2385 // The initializer can be omitted for a reference only in a
2386 // parameter declaration (8.3.5), in the declaration of a
2387 // function return type, in the declaration of a class member
2388 // within its class declaration (9.2), and where the extern
2389 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002390 if (Type->isReferenceType() &&
2391 Var->getStorageClass() != VarDecl::Extern &&
2392 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002393 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002394 << Var->getDeclName()
2395 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002396 Var->setInvalidDecl();
2397 return;
2398 }
2399
2400 // C++ [dcl.init]p9:
2401 //
2402 // If no initializer is specified for an object, and the object
2403 // is of (possibly cv-qualified) non-POD class type (or array
2404 // thereof), the object shall be default-initialized; if the
2405 // object is of const-qualified type, the underlying class type
2406 // shall have a user-declared default constructor.
2407 if (getLangOptions().CPlusPlus) {
2408 QualType InitType = Type;
2409 if (const ArrayType *Array = Context.getAsArrayType(Type))
2410 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002411 if (Var->getStorageClass() != VarDecl::Extern &&
2412 Var->getStorageClass() != VarDecl::PrivateExtern &&
2413 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002414 const CXXConstructorDecl *Constructor
2415 = PerformInitializationByConstructor(InitType, 0, 0,
2416 Var->getLocation(),
2417 SourceRange(Var->getLocation(),
2418 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002419 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002420 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002421 if (!Constructor)
2422 Var->setInvalidDecl();
2423 }
2424 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002425
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002426#if 0
2427 // FIXME: Temporarily disabled because we are not properly parsing
2428 // linkage specifications on declarations, e.g.,
2429 //
2430 // extern "C" const CGPoint CGPointerZero;
2431 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002432 // C++ [dcl.init]p9:
2433 //
2434 // If no initializer is specified for an object, and the
2435 // object is of (possibly cv-qualified) non-POD class type (or
2436 // array thereof), the object shall be default-initialized; if
2437 // the object is of const-qualified type, the underlying class
2438 // type shall have a user-declared default
2439 // constructor. Otherwise, if no initializer is specified for
2440 // an object, the object and its subobjects, if any, have an
2441 // indeterminate initial value; if the object or any of its
2442 // subobjects are of const-qualified type, the program is
2443 // ill-formed.
2444 //
2445 // This isn't technically an error in C, so we don't diagnose it.
2446 //
2447 // FIXME: Actually perform the POD/user-defined default
2448 // constructor check.
2449 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002450 Context.getCanonicalType(Type).isConstQualified() &&
2451 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002452 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2453 << Var->getName()
2454 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002455#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002456 }
2457}
2458
Chris Lattner4b009652007-07-25 00:24:17 +00002459/// The declarators are chained together backwards, reverse the list.
2460Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2461 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002462 Decl *GroupDecl = static_cast<Decl*>(group);
2463 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002464 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002465
2466 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2467 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002468 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002469 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002470 else { // reverse the list.
2471 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00002472 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002473 Group->setNextDeclarator(NewGroup);
2474 NewGroup = Group;
2475 Group = Next;
2476 }
2477 }
2478 // Perform semantic analysis that depends on having fully processed both
2479 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002480 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002481 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2482 if (!IDecl)
2483 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002484 QualType T = IDecl->getType();
2485
Anders Carlsson68adbd12008-12-07 00:20:55 +00002486 if (T->isVariableArrayType()) {
Anders Carlssonef2f7df2008-12-20 21:51:53 +00002487 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002488
2489 // FIXME: This won't give the correct result for
2490 // int a[10][n];
2491 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002492 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002493 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2494 SizeRange;
2495
Eli Friedman8ff07782008-02-15 18:16:39 +00002496 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002497 } else {
2498 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2499 // static storage duration, it shall not have a variable length array.
2500 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002501 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2502 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002503 IDecl->setInvalidDecl();
2504 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002505 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2506 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002507 IDecl->setInvalidDecl();
2508 }
2509 }
2510 } else if (T->isVariablyModifiedType()) {
2511 if (IDecl->isFileVarDecl()) {
2512 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2513 IDecl->setInvalidDecl();
2514 } else {
2515 if (IDecl->getStorageClass() == VarDecl::Extern) {
2516 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2517 IDecl->setInvalidDecl();
2518 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002519 }
2520 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002521
Steve Naroff6a0e2092007-09-12 14:07:44 +00002522 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2523 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002524 if (IDecl->isBlockVarDecl() &&
2525 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002526 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner271d4c22008-11-24 05:29:24 +00002527 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002528 IDecl->setInvalidDecl();
2529 }
2530 }
2531 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2532 // object that has file scope without an initializer, and without a
2533 // storage-class specifier or with the storage-class specifier "static",
2534 // constitutes a tentative definition. Note: A tentative definition with
2535 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002536 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002537 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002538 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2539 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002540 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00002541 // C99 6.9.2p3: If the declaration of an identifier for an object is
2542 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2543 // declared type shall not be an incomplete type.
Chris Lattner271d4c22008-11-24 05:29:24 +00002544 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002545 IDecl->setInvalidDecl();
2546 }
2547 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002548 if (IDecl->isFileVarDecl())
2549 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002550 }
2551 return NewGroup;
2552}
Steve Naroff91b03f72007-08-28 03:03:08 +00002553
Chris Lattner3e254fb2008-04-08 04:40:51 +00002554/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2555/// to introduce parameters into function prototype scope.
2556Sema::DeclTy *
2557Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002558 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002559
Chris Lattner3e254fb2008-04-08 04:40:51 +00002560 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002561 VarDecl::StorageClass StorageClass = VarDecl::None;
2562 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2563 StorageClass = VarDecl::Register;
2564 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002565 Diag(DS.getStorageClassSpecLoc(),
2566 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002567 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002568 }
2569 if (DS.isThreadSpecified()) {
2570 Diag(DS.getThreadSpecLoc(),
2571 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002572 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002573 }
2574
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002575 // Check that there are no default arguments inside the type of this
2576 // parameter (C++ only).
2577 if (getLangOptions().CPlusPlus)
2578 CheckExtraCXXDefaultArguments(D);
2579
Chris Lattner3e254fb2008-04-08 04:40:51 +00002580 // In this context, we *do not* check D.getInvalidType(). If the declarator
2581 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2582 // though it will not reflect the user specified type.
2583 QualType parmDeclType = GetTypeForDeclarator(D, S);
2584
2585 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2586
Chris Lattner4b009652007-07-25 00:24:17 +00002587 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2588 // Can this happen for params? We already checked that they don't conflict
2589 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002590 IdentifierInfo *II = D.getIdentifier();
2591 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002592 if (PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002593 // Maybe we will complain about the shadowed template parameter.
2594 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2595 // Just pretend that we didn't see the previous declaration.
2596 PrevDecl = 0;
2597 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002598 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002599
2600 // Recover by removing the name
2601 II = 0;
2602 D.SetIdentifier(0, D.getIdentifierLoc());
2603 }
Chris Lattner4b009652007-07-25 00:24:17 +00002604 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002605
2606 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2607 // Doing the promotion here has a win and a loss. The win is the type for
2608 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2609 // code generator). The loss is the orginal type isn't preserved. For example:
2610 //
2611 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2612 // int blockvardecl[5];
2613 // sizeof(parmvardecl); // size == 4
2614 // sizeof(blockvardecl); // size == 20
2615 // }
2616 //
2617 // For expressions, all implicit conversions are captured using the
2618 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2619 //
2620 // FIXME: If a source translation tool needs to see the original type, then
2621 // we need to consider storing both types (in ParmVarDecl)...
2622 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002623 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002624 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002625 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002626 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002627 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002628
Chris Lattner3e254fb2008-04-08 04:40:51 +00002629 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2630 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002631 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00002632 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002633
Chris Lattner3e254fb2008-04-08 04:40:51 +00002634 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002635 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002636
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002637 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2638 if (D.getCXXScopeSpec().isSet()) {
2639 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2640 << D.getCXXScopeSpec().getRange();
2641 New->setInvalidDecl();
2642 }
2643
Douglas Gregor8acb7272008-12-11 16:49:14 +00002644 // Add the parameter declaration into this scope.
2645 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002646 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002647 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002648
Chris Lattner9b384ca2008-06-29 00:02:00 +00002649 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002650 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002651
Chris Lattner4b009652007-07-25 00:24:17 +00002652}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002653
Chris Lattnerea148702007-10-09 17:14:05 +00002654Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002655 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00002656 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2657 "Not a function declarator!");
2658 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002659
Chris Lattner4b009652007-07-25 00:24:17 +00002660 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2661 // for a K&R function.
2662 if (!FTI.hasPrototype) {
2663 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002664 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002665 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2666 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002667 // Implicitly declare the argument as type 'int' for lack of a better
2668 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002669 DeclSpec DS;
2670 const char* PrevSpec; // unused
2671 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2672 PrevSpec);
2673 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2674 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2675 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002676 }
2677 }
Chris Lattner4b009652007-07-25 00:24:17 +00002678 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002679 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002680 }
2681
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002682 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002683
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002684 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002685 ActOnDeclarator(ParentScope, D, 0,
2686 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002687}
2688
2689Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2690 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002691 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002692
2693 // See if this is a redefinition.
2694 const FunctionDecl *Definition;
2695 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002696 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002697 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002698 }
2699
Douglas Gregor8acb7272008-12-11 16:49:14 +00002700 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002701
Chris Lattner3e254fb2008-04-08 04:40:51 +00002702 // Check the validity of our function parameters
2703 CheckParmsForFunctionDef(FD);
2704
2705 // Introduce our parameters into the function scope
2706 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2707 ParmVarDecl *Param = FD->getParamDecl(p);
2708 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002709 if (Param->getIdentifier())
2710 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002711 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002712
Anton Korobeynikovb27a8702008-12-26 00:52:02 +00002713 // Checking attributes of current function definition
2714 // dllimport attribute.
2715 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2716 // dllimport attribute cannot be applied to definition.
2717 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2718 Diag(FD->getLocation(),
2719 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2720 << "dllimport";
2721 FD->setInvalidDecl();
2722 return FD;
2723 } else {
2724 // If a symbol previously declared dllimport is later defined, the
2725 // attribute is ignored in subsequent references, and a warning is
2726 // emitted.
2727 Diag(FD->getLocation(),
2728 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2729 << FD->getNameAsCString() << "dllimport";
2730 }
2731 }
Chris Lattner4b009652007-07-25 00:24:17 +00002732 return FD;
2733}
2734
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002735Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002736 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002737 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002738 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002739 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002740 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002741 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002742 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002743 } else
2744 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002745 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002746 // Verify and clean out per-function state.
2747
2748 // Check goto/label use.
2749 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2750 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2751 // Verify that we have no forward references left. If so, there was a goto
2752 // or address of a label taken, but no definition of it. Label fwd
2753 // definitions are indicated with a null substmt.
2754 if (I->second->getSubStmt() == 0) {
2755 LabelStmt *L = I->second;
2756 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002757 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002758
2759 // At this point, we have gotos that use the bogus label. Stitch it into
2760 // the function body so that they aren't leaked and that the AST is well
2761 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002762 if (Body) {
2763 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002764 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002765 } else {
2766 // The whole function wasn't parsed correctly, just delete this.
2767 delete L;
2768 }
Chris Lattner4b009652007-07-25 00:24:17 +00002769 }
2770 }
2771 LabelMap.clear();
2772
Steve Naroff99ee4302007-11-11 23:20:51 +00002773 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002774}
2775
Chris Lattner4b009652007-07-25 00:24:17 +00002776/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2777/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002778ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2779 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002780 // Extension in C99. Legal in C90, but warn about it.
2781 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002782 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002783 else
Chris Lattner65cae292008-11-19 08:23:25 +00002784 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002785
2786 // FIXME: handle stuff like:
2787 // void foo() { extern float X(); }
2788 // void bar() { X(); } <-- implicit decl for X in another scope.
2789
2790 // Set a Declarator for the implicit definition: int foo();
2791 const char *Dummy;
2792 DeclSpec DS;
2793 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2794 Error = Error; // Silence warning.
2795 assert(!Error && "Error setting up implicit decl!");
2796 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002797 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002798 D.SetIdentifier(&II, Loc);
2799
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002800 // Insert this function into translation-unit scope.
2801
2802 DeclContext *PrevDC = CurContext;
2803 CurContext = Context.getTranslationUnitDecl();
2804
Steve Naroff9104f3c2008-04-04 14:32:09 +00002805 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002806 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002807 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002808
2809 CurContext = PrevDC;
2810
Steve Naroff9104f3c2008-04-04 14:32:09 +00002811 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002812}
2813
2814
Chris Lattner82bb4792007-11-14 06:34:38 +00002815TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002816 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002817 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002818 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002819
2820 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002821 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2822 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002823 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002824 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002825 if (D.getInvalidType())
2826 NewTD->setInvalidDecl();
2827 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002828}
2829
Steve Naroff0acc9c92007-09-15 18:49:24 +00002830/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002831/// former case, Name will be non-null. In the later case, Name will be null.
2832/// TagType indicates what kind of tag this is. TK indicates whether this is a
2833/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002834Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002835 SourceLocation KWLoc, const CXXScopeSpec &SS,
2836 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregor52473432008-12-24 02:52:09 +00002837 AttributeList *Attr,
2838 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregorae644892008-12-15 16:32:14 +00002839 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002840 assert((Name != 0 || TK == TK_Definition) &&
2841 "Nameless record must be a definition!");
2842
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002843 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002844 switch (TagType) {
2845 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002846 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2847 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2848 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2849 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002850 }
2851
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002852 DeclContext *DC = CurContext;
2853 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002854
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002855 if (Name && SS.isNotEmpty()) {
2856 // We have a nested-name tag ('struct foo::bar').
2857
2858 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002859 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002860 Name = 0;
2861 goto CreateNewDecl;
2862 }
2863
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002864 DC = static_cast<DeclContext*>(SS.getScopeRep());
2865 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002866 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2867
2868 // A tag 'foo::bar' must already exist.
2869 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002870 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002871 Name = 0;
2872 goto CreateNewDecl;
2873 }
2874 } else {
2875 // If this is a named struct, check to see if there was a previous forward
2876 // declaration or definition.
2877 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2878 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
Douglas Gregordb568cf2009-01-08 20:45:30 +00002879
2880 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2881 // FIXME: This makes sure that we ignore the contexts associated
2882 // with C structs, unions, and enums when looking for a matching
2883 // tag declaration or definition. See the similar lookup tweak
2884 // in Sema::LookupDecl; is there a better way to deal with this?
2885 while (isa<RecordDecl>(DC) || isa<EnumDecl>(DC))
2886 DC = DC->getParent();
2887 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002888 }
2889
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002890 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002891 // Maybe we will complain about the shadowed template parameter.
2892 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2893 // Just pretend that we didn't see the previous declaration.
2894 PrevDecl = 0;
2895 }
2896
Ted Kremenekd4434152008-09-02 21:26:19 +00002897 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002898 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2899 "unexpected Decl type");
2900 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002901 // If this is a use of a previous tag, or if the tag is already declared
2902 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002903 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002904 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002905 // Make sure that this wasn't declared as an enum and now used as a
2906 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002907 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002908 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002909 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002910 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002911 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002912 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002913 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002914 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002915
Douglas Gregorae644892008-12-15 16:32:14 +00002916 // FIXME: In the future, return a variant or some other clue
2917 // for the consumer of this Decl to know it doesn't own it.
2918 // For our current ASTs this shouldn't be a problem, but will
2919 // need to be changed with DeclGroups.
2920 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002921 return PrevDecl;
Douglas Gregorae644892008-12-15 16:32:14 +00002922
2923 // Diagnose attempts to redefine a tag.
2924 if (TK == TK_Definition) {
2925 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2926 Diag(NameLoc, diag::err_redefinition) << Name;
2927 Diag(Def->getLocation(), diag::note_previous_definition);
2928 // If this is a redefinition, recover by making this struct be
2929 // anonymous, which will make any later references get the previous
2930 // definition.
2931 Name = 0;
2932 PrevDecl = 0;
2933 }
2934 // Okay, this is definition of a previously declared or referenced
2935 // tag PrevDecl. We're going to create a new Decl for it.
2936 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002937 }
Douglas Gregorae644892008-12-15 16:32:14 +00002938 // If we get here we have (another) forward declaration or we
2939 // have a definition. Just create a new decl.
2940 } else {
2941 // If we get here, this is a definition of a new tag type in a nested
2942 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2943 // new decl/type. We set PrevDecl to NULL so that the entities
2944 // have distinct types.
2945 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002946 }
Douglas Gregorae644892008-12-15 16:32:14 +00002947 // If we get here, we're going to create a new Decl. If PrevDecl
2948 // is non-NULL, it's a definition of the tag declared by
2949 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002950 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002951 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002952 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002953 // The tag name clashes with a namespace name, issue an error and
2954 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002955 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002956 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002957 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00002958 PrevDecl = 0;
2959 } else {
2960 // The existing declaration isn't relevant to us; we're in a
2961 // new scope, so clear out the previous declaration.
2962 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002963 }
Chris Lattner4b009652007-07-25 00:24:17 +00002964 }
Chris Lattner4b009652007-07-25 00:24:17 +00002965 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002966
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002967CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002968
2969 // If there is an identifier, use the location of the identifier as the
2970 // location of the decl, otherwise use the location of the struct/union
2971 // keyword.
2972 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2973
Douglas Gregorae644892008-12-15 16:32:14 +00002974 // Otherwise, create a new declaration. If there is a previous
2975 // declaration of the same entity, the two will be linked via
2976 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00002977 TagDecl *New;
Douglas Gregor723d3332009-01-07 00:43:41 +00002978
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002979 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002980 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2981 // enum X { A, B, C } D; D should chain to X.
Douglas Gregorae644892008-12-15 16:32:14 +00002982 New = EnumDecl::Create(Context, DC, Loc, Name,
2983 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002984 // If this is an undefined enum, warn.
2985 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002986 } else {
2987 // struct/union/class
2988
Chris Lattner4b009652007-07-25 00:24:17 +00002989 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2990 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002991 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002992 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregorae644892008-12-15 16:32:14 +00002993 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2994 cast_or_null<CXXRecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002995 else
Douglas Gregorae644892008-12-15 16:32:14 +00002996 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2997 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002998 }
Douglas Gregorae644892008-12-15 16:32:14 +00002999
3000 if (Kind != TagDecl::TK_enum) {
3001 // Handle #pragma pack: if the #pragma pack stack has non-default
3002 // alignment, make up a packed attribute for this decl. These
3003 // attributes are checked when the ASTContext lays out the
3004 // structure.
3005 //
3006 // It is important for implementing the correct semantics that this
3007 // happen here (in act on tag decl). The #pragma pack stack is
3008 // maintained as a result of parser callbacks which can occur at
3009 // many points during the parsing of a struct declaration (because
3010 // the #pragma tokens are effectively skipped over during the
3011 // parsing of the struct).
3012 if (unsigned Alignment = PackContext.getAlignment())
3013 New->addAttr(new PackedAttr(Alignment * 8));
3014 }
3015
3016 if (Attr)
3017 ProcessDeclAttributeList(New, Attr);
3018
3019 // Set the lexical context. If the tag has a C++ scope specifier, the
3020 // lexical context will be different from the semantic context.
3021 New->setLexicalDeclContext(CurContext);
Chris Lattner4b009652007-07-25 00:24:17 +00003022
3023 // If this has an identifier, add it to the scope stack.
3024 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00003025 // The scope passed in may not be a decl scope. Zip up the scope tree until
3026 // we find one that is.
3027 while ((S->getFlags() & Scope::DeclScope) == 0)
3028 S = S->getParent();
3029
3030 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003031 PushOnScopeChains(New, S);
Douglas Gregor723d3332009-01-07 00:43:41 +00003032 } else if (getLangOptions().CPlusPlus) {
3033 // FIXME: We also want to do this for C, but if this tag is
3034 // defined within a structure CurContext will point to the context
3035 // enclosing the structure, and we would end up inserting the tag
3036 // type into the wrong place.
3037 CurContext->addDecl(Context, New);
Chris Lattner4b009652007-07-25 00:24:17 +00003038 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00003039
Chris Lattner4b009652007-07-25 00:24:17 +00003040 return New;
3041}
3042
Douglas Gregordb568cf2009-01-08 20:45:30 +00003043void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3044 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3045
3046 // Enter the tag context.
3047 PushDeclContext(S, Tag);
3048
3049 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3050 FieldCollector->StartClass();
3051
3052 if (Record->getIdentifier()) {
3053 // C++ [class]p2:
3054 // [...] The class-name is also inserted into the scope of the
3055 // class itself; this is known as the injected-class-name. For
3056 // purposes of access checking, the injected-class-name is treated
3057 // as if it were a public member name.
3058 RecordDecl *InjectedClassName
3059 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3060 CurContext, Record->getLocation(),
3061 Record->getIdentifier(), Record);
3062 InjectedClassName->setImplicit();
3063 PushOnScopeChains(InjectedClassName, S);
3064 }
3065 }
3066}
3067
3068void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3069 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3070
3071 if (isa<CXXRecordDecl>(Tag))
3072 FieldCollector->FinishClass();
3073
3074 // Exit this scope of this tag's definition.
3075 PopDeclContext();
3076
3077 // Notify the consumer that we've defined a tag.
3078 Consumer.HandleTagDeclDefinition(Tag);
3079}
Chris Lattner1bf58f62008-06-21 19:39:06 +00003080
Chris Lattnera73e2202008-11-12 21:17:48 +00003081/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3082/// types into constant array types in certain situations which would otherwise
3083/// be errors (for GCC compatibility).
3084static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3085 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003086 // This method tries to turn a variable array into a constant
3087 // array even when the size isn't an ICE. This is necessary
3088 // for compatibility with code that depends on gcc's buggy
3089 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003090 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3091 if (!VLATy) return QualType();
3092
Anders Carlsson8c3de802008-12-19 20:58:05 +00003093 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003094 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00003095 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003096 return QualType();
3097
Anders Carlsson8c3de802008-12-19 20:58:05 +00003098 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3099 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattnerd03be6e2008-11-12 19:48:13 +00003100 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3101 return Context.getConstantArrayType(VLATy->getElementType(),
3102 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003103 return QualType();
3104}
3105
Anders Carlsson108229a2008-12-06 20:33:04 +00003106bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00003107 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00003108 // FIXME: 6.7.2.1p4 - verify the field type.
3109
3110 llvm::APSInt Value;
3111 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3112 return true;
3113
Chris Lattner8464c372008-12-12 04:56:04 +00003114 // Zero-width bitfield is ok for anonymous field.
3115 if (Value == 0 && FieldName)
3116 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3117
3118 if (Value.isNegative())
3119 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00003120
3121 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3122 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00003123 if (TypeSize && Value.getZExtValue() > TypeSize)
3124 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3125 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00003126
3127 return false;
3128}
3129
Steve Naroff0acc9c92007-09-15 18:49:24 +00003130/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00003131/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00003132Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00003133 SourceLocation DeclStart,
3134 Declarator &D, ExprTy *BitfieldWidth) {
3135 IdentifierInfo *II = D.getIdentifier();
3136 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00003137 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00003138 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00003139 if (II) Loc = D.getIdentifierLoc();
3140
3141 // FIXME: Unnamed fields can be handled in various different ways, for
3142 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00003143
Chris Lattner4b009652007-07-25 00:24:17 +00003144 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003145 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3146 bool InvalidDecl = false;
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003147
Chris Lattner4b009652007-07-25 00:24:17 +00003148 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3149 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00003150 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00003151 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003152 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00003153 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003154 T = FixedTy;
3155 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00003156 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00003157 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00003158 InvalidDecl = true;
3159 }
Chris Lattner4b009652007-07-25 00:24:17 +00003160 }
Anders Carlsson108229a2008-12-06 20:33:04 +00003161
3162 if (BitWidth) {
3163 if (VerifyBitField(Loc, II, T, BitWidth))
3164 InvalidDecl = true;
3165 } else {
3166 // Not a bitfield.
3167
3168 // validate II.
3169
3170 }
3171
Chris Lattner4b009652007-07-25 00:24:17 +00003172 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00003173 FieldDecl *NewFD;
3174
Douglas Gregor8acb7272008-12-11 16:49:14 +00003175 NewFD = FieldDecl::Create(Context, Record,
3176 Loc, II, T, BitWidth,
3177 D.getDeclSpec().getStorageClassSpec() ==
3178 DeclSpec::SCS_mutable,
3179 /*PrevDecl=*/0);
3180
Douglas Gregordb568cf2009-01-08 20:45:30 +00003181 if (II) {
3182 Decl *PrevDecl
3183 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3184 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3185 && !isa<TagDecl>(PrevDecl)) {
3186 Diag(Loc, diag::err_duplicate_member) << II;
3187 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3188 NewFD->setInvalidDecl();
3189 Record->setInvalidDecl();
3190 }
3191 }
3192
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003193 if (getLangOptions().CPlusPlus) {
Douglas Gregor605de8d2008-12-16 21:30:33 +00003194 CheckExtraCXXDefaultArguments(D);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003195 if (!T->isPODType())
3196 cast<CXXRecordDecl>(Record)->setPOD(false);
3197 }
Douglas Gregor605de8d2008-12-16 21:30:33 +00003198
Chris Lattner9b384ca2008-06-29 00:02:00 +00003199 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00003200
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003201 if (D.getInvalidType() || InvalidDecl)
3202 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00003203
Douglas Gregordb568cf2009-01-08 20:45:30 +00003204 if (II) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003205 PushOnScopeChains(NewFD, S);
Douglas Gregordb568cf2009-01-08 20:45:30 +00003206 } else
Douglas Gregor8acb7272008-12-11 16:49:14 +00003207 Record->addDecl(Context, NewFD);
3208
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00003209 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00003210}
3211
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003212/// TranslateIvarVisibility - Translate visibility from a token ID to an
3213/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00003214static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00003215TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00003216 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00003217 default: assert(0 && "Unknown visitibility kind");
3218 case tok::objc_private: return ObjCIvarDecl::Private;
3219 case tok::objc_public: return ObjCIvarDecl::Public;
3220 case tok::objc_protected: return ObjCIvarDecl::Protected;
3221 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00003222 }
3223}
3224
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003225/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3226/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003227Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00003228 SourceLocation DeclStart,
3229 Declarator &D, ExprTy *BitfieldWidth,
3230 tok::ObjCKeywordKind Visibility) {
Douglas Gregordb568cf2009-01-08 20:45:30 +00003231
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003232 IdentifierInfo *II = D.getIdentifier();
3233 Expr *BitWidth = (Expr*)BitfieldWidth;
3234 SourceLocation Loc = DeclStart;
3235 if (II) Loc = D.getIdentifierLoc();
3236
3237 // FIXME: Unnamed fields can be handled in various different ways, for
3238 // example, unnamed unions inject all members into the struct namespace!
3239
Anders Carlsson108229a2008-12-06 20:33:04 +00003240 QualType T = GetTypeForDeclarator(D, S);
3241 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3242 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003243
3244 if (BitWidth) {
3245 // TODO: Validate.
3246 //printf("WARNING: BITFIELDS IGNORED!\n");
3247
3248 // 6.7.2.1p3
3249 // 6.7.2.1p4
3250
3251 } else {
3252 // Not a bitfield.
3253
3254 // validate II.
3255
3256 }
3257
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003258 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3259 // than a variably modified type.
3260 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00003261 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003262 InvalidDecl = true;
3263 }
3264
Ted Kremenek173dd312008-07-23 18:04:17 +00003265 // Get the visibility (access control) for this ivar.
3266 ObjCIvarDecl::AccessControl ac =
3267 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3268 : ObjCIvarDecl::None;
3269
3270 // Construct the decl.
3271 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00003272 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003273
Douglas Gregordb568cf2009-01-08 20:45:30 +00003274 if (II) {
3275 Decl *PrevDecl
3276 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3277 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3278 && !isa<TagDecl>(PrevDecl)) {
3279 Diag(Loc, diag::err_duplicate_member) << II;
3280 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3281 NewID->setInvalidDecl();
3282 }
3283 }
3284
Ted Kremenek173dd312008-07-23 18:04:17 +00003285 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00003286 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003287
3288 if (D.getInvalidType() || InvalidDecl)
3289 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00003290
Douglas Gregordb568cf2009-01-08 20:45:30 +00003291 if (II) {
3292 // FIXME: When interfaces are DeclContexts, we'll need to add
3293 // these to the interface.
3294 S->AddDecl(NewID);
3295 IdResolver.AddDecl(NewID);
3296 }
3297
Fariborz Jahanian751c6172008-04-10 23:32:45 +00003298 return NewID;
3299}
3300
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00003301void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003302 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00003303 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00003304 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00003305 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003306 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3307 assert(EnclosingDecl && "missing record or interface decl");
3308 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3309
Douglas Gregordb568cf2009-01-08 20:45:30 +00003310 if (Record) {
3311 QualType RecordType = Context.getTypeDeclType(Record);
3312 if (RecordType->getAsRecordType()->getDecl()->isDefinition()) {
3313 RecordDecl *Def = RecordType->getAsRecordType()->getDecl();
Ted Kremenek46a837c2008-09-05 17:16:31 +00003314 // Diagnose code like:
3315 // struct S { struct S {} X; };
3316 // We discover this when we complete the outer S. Reject and ignore the
3317 // outer S.
Douglas Gregordb568cf2009-01-08 20:45:30 +00003318 Diag(Def->getLocation(), diag::err_nested_redefinition)
3319 << Def->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00003320 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek46a837c2008-09-05 17:16:31 +00003321 Record->setInvalidDecl();
3322 return;
3323 }
Douglas Gregordb568cf2009-01-08 20:45:30 +00003324 }
Ted Kremenek46a837c2008-09-05 17:16:31 +00003325
Chris Lattner4b009652007-07-25 00:24:17 +00003326 // Verify that all the fields are okay.
3327 unsigned NumNamedMembers = 0;
3328 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorc7f01612009-01-07 19:46:03 +00003329
Chris Lattner4b009652007-07-25 00:24:17 +00003330 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00003331 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3332 assert(FD && "missing field decl");
3333
Chris Lattner4b009652007-07-25 00:24:17 +00003334 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00003335 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorc7f01612009-01-07 19:46:03 +00003336
Douglas Gregordb568cf2009-01-08 20:45:30 +00003337 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorc7f01612009-01-07 19:46:03 +00003338 // Remember all fields written by the user.
3339 RecFields.push_back(FD);
3340 }
Steve Naroffffeaa552007-09-14 23:09:53 +00003341
Chris Lattner4b009652007-07-25 00:24:17 +00003342 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00003343 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003344 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00003345 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003346 FD->setInvalidDecl();
3347 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003348 continue;
3349 }
Chris Lattner4b009652007-07-25 00:24:17 +00003350 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3351 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003352 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattner271d4c22008-11-24 05:29:24 +00003353 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003354 FD->setInvalidDecl();
3355 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003356 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003357 }
Chris Lattner4b009652007-07-25 00:24:17 +00003358 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003359 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00003360 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner271d4c22008-11-24 05:29:24 +00003361 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003362 FD->setInvalidDecl();
3363 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003364 continue;
3365 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003366 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003367 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003368 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003369 FD->setInvalidDecl();
3370 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003371 continue;
3372 }
Chris Lattner4b009652007-07-25 00:24:17 +00003373 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003374 if (Record)
3375 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003376 }
Chris Lattner4b009652007-07-25 00:24:17 +00003377 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3378 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00003379 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003380 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3381 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00003382 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00003383 Record->setHasFlexibleArrayMember(true);
3384 } else {
3385 // If this is a struct/class and this is not the last element, reject
3386 // it. Note that GCC supports variable sized arrays in the middle of
3387 // structures.
3388 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003389 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003390 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00003391 FD->setInvalidDecl();
3392 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003393 continue;
3394 }
Chris Lattner4b009652007-07-25 00:24:17 +00003395 // We support flexible arrays at the end of structs in other structs
3396 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003397 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00003398 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00003399 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00003400 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00003401 }
3402 }
3403 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003404 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00003405 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003406 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003407 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003408 FD->setInvalidDecl();
3409 EnclosingDecl->setInvalidDecl();
3410 continue;
3411 }
Chris Lattner4b009652007-07-25 00:24:17 +00003412 // Keep track of the number of named members.
Douglas Gregordb568cf2009-01-08 20:45:30 +00003413 if (FD->getIdentifier())
Chris Lattner4b009652007-07-25 00:24:17 +00003414 ++NumNamedMembers;
Chris Lattner4b009652007-07-25 00:24:17 +00003415 }
Sebastian Redl39c0f6f2009-01-05 20:52:13 +00003416
Chris Lattner4b009652007-07-25 00:24:17 +00003417 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003418 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003419 Record->completeDefinition(Context);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003420 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003421 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003422 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003423 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003424 // Must enforce the rule that ivars in the base classes may not be
3425 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003426 if (ID->getSuperClass()) {
3427 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3428 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3429 ObjCIvarDecl* Ivar = (*IVI);
3430 IdentifierInfo *II = Ivar->getIdentifier();
3431 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3432 if (prevIvar) {
3433 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregordb568cf2009-01-08 20:45:30 +00003434 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003435 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003436 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003437 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003438 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003439 else if (ObjCImplementationDecl *IMPDecl =
3440 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003441 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3442 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003443 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003444 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003445 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003446
3447 if (Attr)
3448 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003449}
3450
Steve Naroff0acc9c92007-09-15 18:49:24 +00003451Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003452 DeclTy *lastEnumConst,
3453 SourceLocation IdLoc, IdentifierInfo *Id,
3454 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003455 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003456 EnumConstantDecl *LastEnumConst =
3457 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3458 Expr *Val = static_cast<Expr*>(val);
3459
Chris Lattnera7549902007-08-26 06:24:45 +00003460 // The scope passed in may not be a decl scope. Zip up the scope tree until
3461 // we find one that is.
3462 while ((S->getFlags() & Scope::DeclScope) == 0)
3463 S = S->getParent();
3464
Chris Lattner4b009652007-07-25 00:24:17 +00003465 // Verify that there isn't already something declared with this name in this
3466 // scope.
Douglas Gregordd861062008-12-05 18:15:24 +00003467 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003468 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003469 // Maybe we will complain about the shadowed template parameter.
3470 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3471 // Just pretend that we didn't see the previous declaration.
3472 PrevDecl = 0;
3473 }
3474
3475 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003476 // When in C++, we may get a TagDecl with the same name; in this case the
3477 // enum constant will 'hide' the tag.
3478 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3479 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003480 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003481 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003482 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003483 else
Chris Lattner65cae292008-11-19 08:23:25 +00003484 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003485 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003486 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003487 return 0;
3488 }
3489 }
3490
3491 llvm::APSInt EnumVal(32);
3492 QualType EltTy;
3493 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003494 // Make sure to promote the operand type to int.
3495 UsualUnaryConversions(Val);
3496
Chris Lattner4b009652007-07-25 00:24:17 +00003497 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3498 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003499 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003500 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003501 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003502 } else {
3503 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003504 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003505 }
3506
3507 if (!Val) {
3508 if (LastEnumConst) {
3509 // Assign the last value + 1.
3510 EnumVal = LastEnumConst->getInitVal();
3511 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003512
3513 // Check for overflow on increment.
3514 if (EnumVal < LastEnumConst->getInitVal())
3515 Diag(IdLoc, diag::warn_enum_value_overflow);
3516
Chris Lattnere7f53a42007-08-27 17:37:24 +00003517 EltTy = LastEnumConst->getType();
3518 } else {
3519 // First value, set to zero.
3520 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003521 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003522 }
Chris Lattner4b009652007-07-25 00:24:17 +00003523 }
3524
Chris Lattnere4650482008-03-15 06:12:44 +00003525 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003526 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3527 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00003528 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00003529
3530 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003531 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003532
3533 // Add this enumerator into the enum itself.
3534 // FIXME: This means that the enumerator is stored in two
3535 // DeclContexts. This is not a long-term solution.
3536 New->setLexicalDeclContext(TheEnumDecl);
3537 TheEnumDecl->addDecl(Context, New, true);
Chris Lattner4b009652007-07-25 00:24:17 +00003538 return New;
3539}
3540
Steve Naroffb0726b82008-08-07 14:08:16 +00003541// FIXME: For consistency with ActOnFields(), we should have the parser
3542// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003543void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003544 DeclTy **Elements, unsigned NumElements) {
3545 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregord8028382009-01-05 19:45:36 +00003546 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003547
Douglas Gregord8028382009-01-05 19:45:36 +00003548 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3549 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3550 // Diagnose code like:
3551 // enum e0 {
3552 // E0 = sizeof(enum e0 { E1 })
3553 // };
3554 Diag(Def->getLocation(), diag::err_nested_redefinition)
3555 << Enum->getDeclName();
3556 Diag(Enum->getLocation(), diag::note_previous_definition);
3557 Enum->setInvalidDecl();
Douglas Gregord8028382009-01-05 19:45:36 +00003558 return;
Steve Naroffb0726b82008-08-07 14:08:16 +00003559 }
Douglas Gregord8028382009-01-05 19:45:36 +00003560
Chris Lattner435c3fd2007-08-28 05:10:31 +00003561 // TODO: If the result value doesn't fit in an int, it must be a long or long
3562 // long value. ISO C does not support this, but GCC does as an extension,
3563 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003564 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003565
Chris Lattner206754a2007-08-28 06:15:15 +00003566 // Verify that all the values are okay, compute the size of the values, and
3567 // reverse the list.
3568 unsigned NumNegativeBits = 0;
3569 unsigned NumPositiveBits = 0;
3570
3571 // Keep track of whether all elements have type int.
3572 bool AllElementsInt = true;
3573
Chris Lattner4b009652007-07-25 00:24:17 +00003574 EnumConstantDecl *EltList = 0;
3575 for (unsigned i = 0; i != NumElements; ++i) {
3576 EnumConstantDecl *ECD =
3577 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3578 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003579
3580 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003581 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003582 assert(InitVal.getBitWidth() >= IntWidth &&
3583 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003584 if (InitVal.getBitWidth() > IntWidth) {
3585 llvm::APSInt V(InitVal);
3586 V.trunc(IntWidth);
3587 V.extend(InitVal.getBitWidth());
3588 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003589 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3590 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003591 }
Chris Lattner206754a2007-08-28 06:15:15 +00003592
3593 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003594 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003595 NumPositiveBits = std::max(NumPositiveBits,
3596 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003597 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003598 NumNegativeBits = std::max(NumNegativeBits,
3599 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003600
Chris Lattner206754a2007-08-28 06:15:15 +00003601 // Keep track of whether every enum element has type int (very commmon).
3602 if (AllElementsInt)
3603 AllElementsInt = ECD->getType() == Context.IntTy;
3604
Chris Lattner4b009652007-07-25 00:24:17 +00003605 ECD->setNextDeclarator(EltList);
3606 EltList = ECD;
3607 }
3608
Chris Lattner206754a2007-08-28 06:15:15 +00003609 // Figure out the type that should be used for this enum.
3610 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3611 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003612 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003613
3614 if (NumNegativeBits) {
3615 // If there is a negative value, figure out the smallest integer type (of
3616 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003617 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003618 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003619 BestWidth = IntWidth;
3620 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003621 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003622
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003623 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003624 BestType = Context.LongTy;
3625 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003626 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003627
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003628 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003629 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3630 BestType = Context.LongLongTy;
3631 }
3632 }
3633 } else {
3634 // If there is no negative value, figure out which of uint, ulong, ulonglong
3635 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003636 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003637 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003638 BestWidth = IntWidth;
3639 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003640 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003641 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003642 } else {
3643 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003644 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003645 "How could an initializer get larger than ULL?");
3646 BestType = Context.UnsignedLongLongTy;
3647 }
3648 }
3649
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003650 // Loop over all of the enumerator constants, changing their types to match
3651 // the type of the enum if needed.
3652 for (unsigned i = 0; i != NumElements; ++i) {
3653 EnumConstantDecl *ECD =
3654 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3655 if (!ECD) continue; // Already issued a diagnostic.
3656
3657 // Standard C says the enumerators have int type, but we allow, as an
3658 // extension, the enumerators to be larger than int size. If each
3659 // enumerator value fits in an int, type it as an int, otherwise type it the
3660 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3661 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003662 if (ECD->getType() == Context.IntTy) {
3663 // Make sure the init value is signed.
3664 llvm::APSInt IV = ECD->getInitVal();
3665 IV.setIsSigned(true);
3666 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003667
3668 if (getLangOptions().CPlusPlus)
3669 // C++ [dcl.enum]p4: Following the closing brace of an
3670 // enum-specifier, each enumerator has the type of its
3671 // enumeration.
3672 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003673 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003674 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003675
3676 // Determine whether the value fits into an int.
3677 llvm::APSInt InitVal = ECD->getInitVal();
3678 bool FitsInInt;
3679 if (InitVal.isUnsigned() || !InitVal.isNegative())
3680 FitsInInt = InitVal.getActiveBits() < IntWidth;
3681 else
3682 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3683
3684 // If it fits into an integer type, force it. Otherwise force it to match
3685 // the enum decl type.
3686 QualType NewTy;
3687 unsigned NewWidth;
3688 bool NewSign;
3689 if (FitsInInt) {
3690 NewTy = Context.IntTy;
3691 NewWidth = IntWidth;
3692 NewSign = true;
3693 } else if (ECD->getType() == BestType) {
3694 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003695 if (getLangOptions().CPlusPlus)
3696 // C++ [dcl.enum]p4: Following the closing brace of an
3697 // enum-specifier, each enumerator has the type of its
3698 // enumeration.
3699 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003700 continue;
3701 } else {
3702 NewTy = BestType;
3703 NewWidth = BestWidth;
3704 NewSign = BestType->isSignedIntegerType();
3705 }
3706
3707 // Adjust the APSInt value.
3708 InitVal.extOrTrunc(NewWidth);
3709 InitVal.setIsSigned(NewSign);
3710 ECD->setInitVal(InitVal);
3711
3712 // Adjust the Expr initializer and type.
Douglas Gregor70d26122008-11-12 17:17:38 +00003713 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3714 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003715 if (getLangOptions().CPlusPlus)
3716 // C++ [dcl.enum]p4: Following the closing brace of an
3717 // enum-specifier, each enumerator has the type of its
3718 // enumeration.
3719 ECD->setType(EnumType);
3720 else
3721 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003722 }
Chris Lattner206754a2007-08-28 06:15:15 +00003723
Douglas Gregor8acb7272008-12-11 16:49:14 +00003724 Enum->completeDefinition(Context, BestType);
Chris Lattner4b009652007-07-25 00:24:17 +00003725}
3726
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003727Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003728 ExprArg expr) {
3729 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3730
Chris Lattner81db64a2008-03-16 00:16:02 +00003731 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003732}
3733
Douglas Gregorad17e372008-12-16 22:23:02 +00003734
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003735void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3736 ExprTy *alignment, SourceLocation PragmaLoc,
3737 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3738 Expr *Alignment = static_cast<Expr *>(alignment);
3739
3740 // If specified then alignment must be a "small" power of two.
3741 unsigned AlignmentVal = 0;
3742 if (Alignment) {
3743 llvm::APSInt Val;
3744 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3745 !Val.isPowerOf2() ||
3746 Val.getZExtValue() > 16) {
3747 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3748 delete Alignment;
3749 return; // Ignore
3750 }
3751
3752 AlignmentVal = (unsigned) Val.getZExtValue();
3753 }
3754
3755 switch (Kind) {
3756 case Action::PPK_Default: // pack([n])
3757 PackContext.setAlignment(AlignmentVal);
3758 break;
3759
3760 case Action::PPK_Show: // pack(show)
3761 // Show the current alignment, making sure to show the right value
3762 // for the default.
3763 AlignmentVal = PackContext.getAlignment();
3764 // FIXME: This should come from the target.
3765 if (AlignmentVal == 0)
3766 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003767 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003768 break;
3769
3770 case Action::PPK_Push: // pack(push [, id] [, [n])
3771 PackContext.push(Name);
3772 // Set the new alignment if specified.
3773 if (Alignment)
3774 PackContext.setAlignment(AlignmentVal);
3775 break;
3776
3777 case Action::PPK_Pop: // pack(pop [, id] [, n])
3778 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3779 // "#pragma pack(pop, identifier, n) is undefined"
3780 if (Alignment && Name)
3781 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3782
3783 // Do the pop.
3784 if (!PackContext.pop(Name)) {
3785 // If a name was specified then failure indicates the name
3786 // wasn't found. Otherwise failure indicates the stack was
3787 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003788 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3789 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003790
3791 // FIXME: Warn about popping named records as MSVC does.
3792 } else {
3793 // Pop succeeded, set the new alignment if specified.
3794 if (Alignment)
3795 PackContext.setAlignment(AlignmentVal);
3796 }
3797 break;
3798
3799 default:
3800 assert(0 && "Invalid #pragma pack kind.");
3801 }
3802}
3803
3804bool PragmaPackStack::pop(IdentifierInfo *Name) {
3805 if (Stack.empty())
3806 return false;
3807
3808 // If name is empty just pop top.
3809 if (!Name) {
3810 Alignment = Stack.back().first;
3811 Stack.pop_back();
3812 return true;
3813 }
3814
3815 // Otherwise, find the named record.
3816 for (unsigned i = Stack.size(); i != 0; ) {
3817 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003818 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003819 // Found it, pop up to and including this record.
3820 Alignment = Stack[i].first;
3821 Stack.erase(Stack.begin() + i, Stack.end());
3822 return true;
3823 }
3824 }
3825
3826 return false;
3827}