blob: 49719ab4f524979c414ec53cba9835d3bdf94a5b [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Douglas Gregor2def4832008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000036 DeclContext *DC = 0;
37 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
42 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000043
Douglas Gregor2ce52f32008-04-13 21:07:44 +000044 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
45 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregor72c3f312008-12-05 18:15:24 +000046 isa<TagDecl>(IIDecl) ||
47 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000048 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000049 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000050}
51
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000053 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000054 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000055 if (MD->isOutOfLineDefinition())
56 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000057
58 // A C++ inline method is parsed *after* the topmost class it was declared in
59 // is fully parsed (it's "complete").
60 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000061 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000062 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
63 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000064 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000065 DC = RD;
66
67 // Return the declaration context of the topmost class the inline method is
68 // declared in.
69 return DC;
70 }
71
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000072 if (isa<ObjCMethodDecl>(DC))
73 return Context.getTranslationUnitDecl();
74
75 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
76 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000077
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000078 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000079}
80
Douglas Gregor44b43212008-12-11 16:49:14 +000081void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000082 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000083 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000084 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +000085 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +000086}
87
Chris Lattnerb048c982008-04-06 04:47:34 +000088void Sema::PopDeclContext() {
89 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +000090
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000091 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000092}
93
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000094/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +000096 // Move up the scope chain until we find the nearest enclosing
97 // non-transparent context. The declaration will be introduced into this
98 // scope.
99 while (S->getEntity() &&
100 ((DeclContext *)S->getEntity())->isTransparentContext())
101 S = S->getParent();
102
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000103 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000104
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000105 // Add scoped declarations into their context, so that they can be
106 // found later. Declarations without a context won't be inserted
107 // into any context.
108 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
109 CurContext->addDecl(Context, SD);
110
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000111 // C++ [basic.scope]p4:
112 // -- exactly one declaration shall declare a class name or
113 // enumeration name that is not a typedef name and the other
114 // declarations shall all refer to the same object or
115 // enumerator, or all refer to functions and function templates;
116 // in this case the class name or enumeration name is hidden.
117 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
118 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000119 if (CurContext->getLookupContext()
120 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000121 // We're pushing the tag into the current context, which might
122 // require some reshuffling in the identifier resolver.
123 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000124 I = IdResolver.begin(TD->getDeclName(), CurContext,
125 false/*LookInParentCtx*/),
126 IEnd = IdResolver.end();
127 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
128 NamedDecl *PrevDecl = *I;
129 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
130 PrevDecl = *I, ++I) {
131 if (TD->declarationReplaces(*I)) {
132 // This is a redeclaration. Remove it from the chain and
133 // break out, so that we'll add in the shadowed
134 // declaration.
135 S->RemoveDecl(*I);
136 if (PrevDecl == *I) {
137 IdResolver.RemoveDecl(*I);
138 IdResolver.AddDecl(TD);
139 return;
140 } else {
141 IdResolver.RemoveDecl(*I);
142 break;
143 }
144 }
145 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000146
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000147 // There is already a declaration with the same name in the same
148 // scope, which is not a tag declaration. It must be found
149 // before we find the new declaration, so insert the new
150 // declaration at the end of the chain.
151 IdResolver.AddShadowedDecl(TD, PrevDecl);
152
153 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000154 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000155 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000156 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000157 // We are pushing the name of a function, which might be an
158 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000159 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregorce356072009-01-06 23:51:29 +0000160 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000161 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000162 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000163 false/*LookInParentCtx*/),
164 IdResolver.end(),
165 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
166 FD));
167 if (Redecl != IdResolver.end()) {
168 // There is already a declaration of a function on our
169 // IdResolver chain. Replace it with this declaration.
170 S->RemoveDecl(*Redecl);
171 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000173 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000174
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000175 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000176}
177
Steve Naroffb216c882007-10-09 22:01:59 +0000178void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000179 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000180 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
181 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
184 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000185 Decl *TmpD = static_cast<Decl*>(*I);
186 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000187
Douglas Gregor44b43212008-12-11 16:49:14 +0000188 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
189 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000190
Douglas Gregor44b43212008-12-11 16:49:14 +0000191 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000192
Douglas Gregor44b43212008-12-11 16:49:14 +0000193 // Remove this name from our lexical scope.
194 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 }
196}
197
Steve Naroffe8043c32008-04-01 23:04:06 +0000198/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
199/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000200ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000201 // The third "scope" argument is 0 since we aren't enabling lazy built-in
202 // creation from this context.
203 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000204
Steve Naroffb327ce02008-04-02 14:35:35 +0000205 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000206}
207
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000208/// MaybeConstructOverloadSet - Name lookup has determined that the
209/// elements in [I, IEnd) have the name that we are looking for, and
210/// *I is a match for the namespace. This routine returns an
211/// appropriate Decl for name lookup, which may either be *I or an
212/// OverloadeFunctionDecl that represents the overloaded functions in
213/// [I, IEnd).
214///
215/// The existance of this routine is temporary; LookupDecl should
216/// probably be able to return multiple results, to deal with cases of
217/// ambiguity and overloaded functions without needing to create a
218/// Decl node.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000219template<typename DeclIterator>
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000220static Decl *
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000221MaybeConstructOverloadSet(ASTContext &Context,
222 DeclIterator I, DeclIterator IEnd) {
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000223 assert(I != IEnd && "Iterator range cannot be empty");
224 assert(!isa<OverloadedFunctionDecl>(*I) &&
225 "Cannot have an overloaded function");
226
227 if (isa<FunctionDecl>(*I)) {
228 // If we found a function, there might be more functions. If
229 // so, collect them into an overload set.
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000230 DeclIterator Last = I;
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000231 OverloadedFunctionDecl *Ovl = 0;
232 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
233 if (!Ovl) {
234 // FIXME: We leak this overload set. Eventually, we want to
235 // stop building the declarations for these overload sets, so
236 // there will be nothing to leak.
237 Ovl = OverloadedFunctionDecl::Create(Context,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000238 cast<ScopedDecl>(*I)->getDeclContext(),
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000239 (*I)->getDeclName());
240 Ovl->addOverload(cast<FunctionDecl>(*I));
241 }
242 Ovl->addOverload(cast<FunctionDecl>(*Last));
243 }
244
245 // If we had more than one function, we built an overload
246 // set. Return it.
247 if (Ovl)
248 return Ovl;
249 }
250
251 return *I;
252}
253
Steve Naroffe8043c32008-04-01 23:04:06 +0000254/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-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 Gregor2def4832008-11-17 20:34:05 +0000259Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000260 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000261 bool enableLazyBuiltinCreation,
Douglas Gregorf780abc2008-12-30 03:27:21 +0000262 bool LookInParent,
263 bool NamespaceNameOnly) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000264 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000265 unsigned NS = NSI;
266 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
267 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000268
Douglas Gregore267ff32008-12-11 20:41:00 +0000269 if (LookupCtx == 0 &&
270 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
271 // Unqualified name lookup in C/Objective-C and name lookup for
272 // labels in C++ is purely lexical, so search in the
273 // declarations attached to the name.
274 assert(!LookupCtx && "Can't perform qualified name lookup here");
Douglas Gregorf780abc2008-12-30 03:27:21 +0000275 assert(!NamespaceNameOnly && "Can't perform namespace name lookup here");
Douglas Gregore267ff32008-12-11 20:41:00 +0000276 IdentifierResolver::iterator I
277 = IdResolver.begin(Name, CurContext, LookInParent);
278
279 // Scan up the scope chain looking for a decl that matches this
280 // identifier that is in the appropriate namespace. This search
281 // should not take long, as shadowing of names is uncommon, and
282 // deep shadowing is extremely uncommon.
283 for (; I != IdResolver.end(); ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000284 if ((*I)->isInIdentifierNamespace(NS))
Douglas Gregorf780abc2008-12-30 03:27:21 +0000285 return *I;
Douglas Gregore267ff32008-12-11 20:41:00 +0000286 } else if (LookupCtx) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000287 // Perform qualified name lookup into the LookupCtx.
288 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000289 DeclContext::lookup_const_iterator I, E;
290 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
Chris Lattner7bea7662009-01-06 07:20:03 +0000291 if ((*I)->isInIdentifierNamespace(NS)) {
292 // Ignore non-namespace names if we're only looking for namespaces.
293 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I)) continue;
294
295 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000296 }
Douglas Gregore267ff32008-12-11 20:41:00 +0000297 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000298 // Name lookup for ordinary names and tag names in C++ requires
299 // looking into scopes that aren't strictly lexical, and
300 // therefore we walk through the context as well as walking
301 // through the scopes.
302 IdentifierResolver::iterator
303 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
304 IEnd = IdResolver.end();
305 for (; S; S = S->getParent()) {
306 // Check whether the IdResolver has anything in this scope.
307 // FIXME: The isDeclScope check could be expensive. Can we do better?
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000308 for (; I != IEnd && S->isDeclScope(*I); ++I) {
Chris Lattner7bea7662009-01-06 07:20:03 +0000309 if ((*I)->isInIdentifierNamespace(NS)) {
310 // Ignore non-namespace names if we're only looking for namespaces.
311 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
312 continue;
313
314 // We found something. Look for anything else in our scope
315 // with this same name and in an acceptable identifier
316 // namespace, so that we can construct an overload set if we
317 // need to.
318 IdentifierResolver::iterator LastI = I;
319 for (++LastI; LastI != IEnd; ++LastI) {
320 if (!(*LastI)->isInIdentifierNamespace(NS) ||
321 !S->isDeclScope(*LastI))
322 break;
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000323 }
Chris Lattner7bea7662009-01-06 07:20:03 +0000324 return MaybeConstructOverloadSet(Context, I, LastI);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000325 }
326 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000327
328 // If there is an entity associated with this scope, it's a
329 // DeclContext. We might need to perform qualified lookup into
330 // it.
331 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
332 while (Ctx && Ctx->isFunctionOrMethod())
333 Ctx = Ctx->getParent();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000334 while (Ctx && (Ctx->isNamespace() || Ctx->isRecord())) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000335 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000336 DeclContext::lookup_const_iterator I, E;
337 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000338 // FIXME: Cache this result in the IdResolver
Chris Lattner7bea7662009-01-06 07:20:03 +0000339 if ((*I)->isInIdentifierNamespace(NS)) {
340 if (NamespaceNameOnly && !isa<NamespaceDecl>(*I))
341 continue;
342 return MaybeConstructOverloadSet(Context, I, E);
Douglas Gregorf780abc2008-12-30 03:27:21 +0000343 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000344 }
345
346 Ctx = Ctx->getParent();
347 }
348
Douglas Gregor074149e2009-01-05 19:45:36 +0000349 if (!LookInParent && !Ctx->isTransparentContext())
Douglas Gregor44b43212008-12-11 16:49:14 +0000350 return 0;
351 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000352 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000353
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 // If we didn't find a use of this identifier, and if the identifier
355 // corresponds to a compiler builtin, create the decl object for the builtin
356 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000357 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000358 IdentifierInfo *II = Name.getAsIdentifierInfo();
359 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000360 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000361 // If this is a builtin on this (or all) targets, create the decl.
362 if (unsigned BuiltinID = II->getBuiltinID())
363 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
364 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000365 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000366 // @interface and @compatibility_alias introduce typedef-like names.
367 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000368 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000369 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000370 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
371 if (IDI != ObjCInterfaceDecls.end())
372 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000373 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
374 if (I != ObjCAliasDecls.end())
375 return I->second->getClassInterface();
376 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 }
378 return 0;
379}
380
Chris Lattner95e2c712008-05-05 22:18:14 +0000381void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000382 if (!Context.getBuiltinVaListType().isNull())
383 return;
384
385 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000386 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000387 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000388 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
389}
390
Reid Spencer5f016e22007-07-11 17:01:13 +0000391/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
392/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000393ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
394 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000395 Builtin::ID BID = (Builtin::ID)bid;
396
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000397 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000398 InitBuiltinVaListType();
399
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000400 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000401 FunctionDecl *New = FunctionDecl::Create(Context,
402 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000403 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000404 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000405
Chris Lattner95e2c712008-05-05 22:18:14 +0000406 // Create Decl objects for each parameter, adding them to the
407 // FunctionDecl.
408 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
409 llvm::SmallVector<ParmVarDecl*, 16> Params;
410 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
411 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
412 FT->getArgType(i), VarDecl::None, 0,
413 0));
414 New->setParams(&Params[0], Params.size());
415 }
416
417
418
Chris Lattner7f925cc2008-04-11 07:00:53 +0000419 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000420 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 return New;
422}
423
Sebastian Redlc42e1182008-11-11 11:37:55 +0000424/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
425/// everything from the standard library is defined.
426NamespaceDecl *Sema::GetStdNamespace() {
427 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000428 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000429 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000430 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000431 0, Global, /*enableLazyBuiltinCreation=*/false);
432 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
433 }
434 return StdNamespace;
435}
436
Reid Spencer5f016e22007-07-11 17:01:13 +0000437/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
438/// and scope as a previous declaration 'Old'. Figure out how to resolve this
439/// situation, merging decls or emitting diagnostics as appropriate.
440///
Steve Naroffe8043c32008-04-01 23:04:06 +0000441TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000442 // Allow multiple definitions for ObjC built-in typedefs.
443 // FIXME: Verify the underlying types are equivalent!
444 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000445 const IdentifierInfo *TypeID = New->getIdentifier();
446 switch (TypeID->getLength()) {
447 default: break;
448 case 2:
449 if (!TypeID->isStr("id"))
450 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000451 Context.setObjCIdType(New);
452 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000453 case 5:
454 if (!TypeID->isStr("Class"))
455 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000456 Context.setObjCClassType(New);
457 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000458 case 3:
459 if (!TypeID->isStr("SEL"))
460 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000461 Context.setObjCSelType(New);
462 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000463 case 8:
464 if (!TypeID->isStr("Protocol"))
465 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000466 Context.setObjCProtoType(New->getUnderlyingType());
467 return New;
468 }
469 // Fall through - the typedef name was not a builtin type.
470 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 // Verify the old decl was also a typedef.
472 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
473 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000474 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000475 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000476 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000477 return New;
478 }
479
Chris Lattner99cb9972008-07-25 18:44:27 +0000480 // If the typedef types are not identical, reject them in all languages and
481 // with any extensions enabled.
482 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
483 Context.getCanonicalType(Old->getUnderlyingType()) !=
484 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000485 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000486 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000487 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner99cb9972008-07-25 18:44:27 +0000488 return Old;
489 }
490
Eli Friedman54ecfce2008-06-11 06:20:39 +0000491 if (getLangOptions().Microsoft) return New;
492
Douglas Gregorbbe27432008-11-21 16:29:06 +0000493 // C++ [dcl.typedef]p2:
494 // In a given non-class scope, a typedef specifier can be used to
495 // redefine the name of any type declared in that scope to refer
496 // to the type to which it already refers.
497 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
498 return New;
499
500 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000501 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
502 // *either* declaration is in a system header. The code below implements
503 // this adhoc compatibility rule. FIXME: The following code will not
504 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000505 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
506 SourceManager &SrcMgr = Context.getSourceManager();
507 if (SrcMgr.isInSystemHeader(Old->getLocation()))
508 return New;
509 if (SrcMgr.isInSystemHeader(New->getLocation()))
510 return New;
511 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000512
Chris Lattner08631c52008-11-23 21:45:46 +0000513 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000514 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000515 return New;
516}
517
Chris Lattner6b6b5372008-06-26 18:38:35 +0000518/// DeclhasAttr - returns true if decl Declaration already has the target
519/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000520static bool DeclHasAttr(const Decl *decl, const Attr *target) {
521 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
522 if (attr->getKind() == target->getKind())
523 return true;
524
525 return false;
526}
527
528/// MergeAttributes - append attributes from the Old decl to the New one.
529static void MergeAttributes(Decl *New, Decl *Old) {
530 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
531
Chris Lattnerddee4232008-03-03 03:28:21 +0000532 while (attr) {
533 tmp = attr;
534 attr = attr->getNext();
535
536 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000537 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000538 New->addAttr(tmp);
539 } else {
540 tmp->setNext(0);
541 delete(tmp);
542 }
543 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000544
545 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000546}
547
Chris Lattner04421082008-04-08 04:40:51 +0000548/// MergeFunctionDecl - We just parsed a function 'New' from
549/// declarator D which has the same name and scope as a previous
550/// declaration 'Old'. Figure out how to resolve this situation,
551/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000552/// Redeclaration will be set true if this New is a redeclaration OldD.
553///
554/// In C++, New and Old must be declarations that are not
555/// overloaded. Use IsOverload to determine whether New and Old are
556/// overloaded, and to select the Old declaration that New should be
557/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000558FunctionDecl *
559Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000560 assert(!isa<OverloadedFunctionDecl>(OldD) &&
561 "Cannot merge with an overloaded function declaration");
562
Douglas Gregorf0097952008-04-21 02:02:58 +0000563 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000564 // Verify the old decl was also a function.
565 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
566 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000567 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000568 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000569 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 return New;
571 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000572
573 // Determine whether the previous declaration was a definition,
574 // implicit declaration, or a declaration.
575 diag::kind PrevDiag;
576 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000577 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000578 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000579 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000580 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000581 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000582
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000583 QualType OldQType = Context.getCanonicalType(Old->getType());
584 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000585
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000586 if (getLangOptions().CPlusPlus) {
587 // (C++98 13.1p2):
588 // Certain function declarations cannot be overloaded:
589 // -- Function declarations that differ only in the return type
590 // cannot be overloaded.
591 QualType OldReturnType
592 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
593 QualType NewReturnType
594 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
595 if (OldReturnType != NewReturnType) {
596 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
597 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000598 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000599 return New;
600 }
601
602 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
603 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
604 if (OldMethod && NewMethod) {
605 // -- Member function declarations with the same name and the
606 // same parameter types cannot be overloaded if any of them
607 // is a static member function declaration.
608 if (OldMethod->isStatic() || NewMethod->isStatic()) {
609 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
610 Diag(Old->getLocation(), PrevDiag);
611 return New;
612 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000613
614 // C++ [class.mem]p1:
615 // [...] A member shall not be declared twice in the
616 // member-specification, except that a nested class or member
617 // class template can be declared and then later defined.
618 if (OldMethod->getLexicalDeclContext() ==
619 NewMethod->getLexicalDeclContext()) {
620 unsigned NewDiag;
621 if (isa<CXXConstructorDecl>(OldMethod))
622 NewDiag = diag::err_constructor_redeclared;
623 else if (isa<CXXDestructorDecl>(NewMethod))
624 NewDiag = diag::err_destructor_redeclared;
625 else if (isa<CXXConversionDecl>(NewMethod))
626 NewDiag = diag::err_conv_function_redeclared;
627 else
628 NewDiag = diag::err_member_redeclared;
629
630 Diag(New->getLocation(), NewDiag);
631 Diag(Old->getLocation(), PrevDiag);
632 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000633 }
634
635 // (C++98 8.3.5p3):
636 // All declarations for a function shall agree exactly in both the
637 // return type and the parameter-type-list.
638 if (OldQType == NewQType) {
639 // We have a redeclaration.
640 MergeAttributes(New, Old);
641 Redeclaration = true;
642 return MergeCXXFunctionDecl(New, Old);
643 }
644
645 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000646 }
Chris Lattner04421082008-04-08 04:40:51 +0000647
648 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000649 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000650 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000651 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000652 MergeAttributes(New, Old);
653 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000654 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000655 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000656
Steve Naroff837618c2008-01-16 15:01:34 +0000657 // A function that has already been declared has been redeclared or defined
658 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000659
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
661 // TODO: This is totally simplistic. It should handle merging functions
662 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000663 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000664 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000665 return New;
666}
667
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000668/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000669static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000670 if (VD->isFileVarDecl())
671 return (!VD->getInit() &&
672 (VD->getStorageClass() == VarDecl::None ||
673 VD->getStorageClass() == VarDecl::Static));
674 return false;
675}
676
677/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
678/// when dealing with C "tentative" external object definitions (C99 6.9.2).
679void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
680 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000681 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000682
Douglas Gregore21b9942009-01-07 16:34:42 +0000683 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000684 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000685 for (IdentifierResolver::iterator
686 I = IdResolver.begin(VD->getIdentifier(),
687 VD->getDeclContext(), false/*LookInParentCtx*/),
688 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000689 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000690 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
691
Steve Narofff855e6f2008-08-10 15:20:13 +0000692 // Handle the following case:
693 // int a[10];
694 // int a[]; - the code below makes sure we set the correct type.
695 // int a[11]; - this is an error, size isn't 10.
696 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
697 OldDecl->getType()->isConstantArrayType())
698 VD->setType(OldDecl->getType());
699
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000700 // Check for "tentative" definitions. We can't accomplish this in
701 // MergeVarDecl since the initializer hasn't been attached.
702 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
703 continue;
704
705 // Handle __private_extern__ just like extern.
706 if (OldDecl->getStorageClass() != VarDecl::Extern &&
707 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
708 VD->getStorageClass() != VarDecl::Extern &&
709 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000710 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000711 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000712 }
713 }
714 }
715}
716
Reid Spencer5f016e22007-07-11 17:01:13 +0000717/// MergeVarDecl - We just parsed a variable 'New' which has the same name
718/// and scope as a previous declaration 'Old'. Figure out how to resolve this
719/// situation, merging decls or emitting diagnostics as appropriate.
720///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000721/// Tentative definition rules (C99 6.9.2p2) are checked by
722/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
723/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000724///
Steve Naroffe8043c32008-04-01 23:04:06 +0000725VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000726 // Verify the old decl was also a variable.
727 VarDecl *Old = dyn_cast<VarDecl>(OldD);
728 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000729 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000730 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000731 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000732 return New;
733 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000734
735 MergeAttributes(New, Old);
736
Reid Spencer5f016e22007-07-11 17:01:13 +0000737 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000738 QualType OldCType = Context.getCanonicalType(Old->getType());
739 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000740 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000741 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000742 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000743 return New;
744 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000745 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
746 if (New->getStorageClass() == VarDecl::Static &&
747 (Old->getStorageClass() == VarDecl::None ||
748 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000749 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000750 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000751 return New;
752 }
753 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
754 if (New->getStorageClass() != VarDecl::Static &&
755 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000756 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000757 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000758 return New;
759 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000760 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
761 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000762 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000763 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000764 }
765 return New;
766}
767
Chris Lattner04421082008-04-08 04:40:51 +0000768/// CheckParmsForFunctionDef - Check that the parameters of the given
769/// function are appropriate for the definition of a function. This
770/// takes care of any checks that cannot be performed on the
771/// declaration itself, e.g., that the types of each of the function
772/// parameters are complete.
773bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
774 bool HasInvalidParm = false;
775 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
776 ParmVarDecl *Param = FD->getParamDecl(p);
777
778 // C99 6.7.5.3p4: the parameters in a parameter type list in a
779 // function declarator that is part of a function definition of
780 // that function shall not have incomplete type.
781 if (Param->getType()->isIncompleteType() &&
782 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000783 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000784 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000785 Param->setInvalidDecl();
786 HasInvalidParm = true;
787 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000788
789 // C99 6.9.1p5: If the declarator includes a parameter type list, the
790 // declaration of each parameter shall include an identifier.
791 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
792 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000793 }
794
795 return HasInvalidParm;
796}
797
Reid Spencer5f016e22007-07-11 17:01:13 +0000798/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
799/// no declarator (e.g. "struct foo;") is parsed.
800Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000801 // FIXME: Isn't that more of a parser diagnostic than a sema diagnostic?
802 if (!DS.isMissingDeclaratorOk()) {
803 // FIXME: This diagnostic is emitted even when various previous
804 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
805 // DeclSpec has no means of communicating this information, and the
806 // responsible parser functions are quite far apart.
807 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
808 << DS.getSourceRange();
809 return 0;
810 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000811
812 TagDecl *Tag
813 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
814 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
815 if (!Record->getDeclName() && Record->isDefinition() &&
816 !Record->isInvalidDecl())
817 return BuildAnonymousStructOrUnion(S, DS, Record);
818 }
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000819
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000820 return Tag;
821}
822
823/// InjectAnonymousStructOrUnionMembers - Inject the members of the
824/// anonymous struct or union AnonRecord into the owning context Owner
825/// and scope S. This routine will be invoked just after we realize
826/// that an unnamed union or struct is actually an anonymous union or
827/// struct, e.g.,
828///
829/// @code
830/// union {
831/// int i;
832/// float f;
833/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
834/// // f into the surrounding scope.x
835/// @endcode
836///
837/// This routine is recursive, injecting the names of nested anonymous
838/// structs/unions into the owning context and scope as well.
839bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
840 RecordDecl *AnonRecord) {
841 bool Invalid = false;
842 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
843 FEnd = AnonRecord->field_end();
844 F != FEnd; ++F) {
845 if ((*F)->getDeclName()) {
846 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
847 S, Owner, false, false, false);
848 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
849 // C++ [class.union]p2:
850 // The names of the members of an anonymous union shall be
851 // distinct from the names of any other entity in the
852 // scope in which the anonymous union is declared.
853 unsigned diagKind
854 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
855 : diag::err_anonymous_struct_member_redecl;
856 Diag((*F)->getLocation(), diagKind)
857 << (*F)->getDeclName();
858 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
859 Invalid = true;
860 } else {
861 // C++ [class.union]p2:
862 // For the purpose of name lookup, after the anonymous union
863 // definition, the members of the anonymous union are
864 // considered to have been defined in the scope in which the
865 // anonymous union is declared.
866 Owner->insert(Context, *F);
867 S->AddDecl(*F);
868 IdResolver.AddDecl(*F);
869 }
870 } else if (const RecordType *InnerRecordType
871 = (*F)->getType()->getAsRecordType()) {
872 RecordDecl *InnerRecord = InnerRecordType->getDecl();
873 if (InnerRecord->isAnonymousStructOrUnion())
874 Invalid = Invalid ||
875 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
876 }
877 }
878
879 return Invalid;
880}
881
882/// ActOnAnonymousStructOrUnion - Handle the declaration of an
883/// anonymous structure or union. Anonymous unions are a C++ feature
884/// (C++ [class.union]) and a GNU C extension; anonymous structures
885/// are a GNU C and GNU C++ extension.
886Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
887 RecordDecl *Record) {
888 DeclContext *Owner = Record->getDeclContext();
889
890 // Diagnose whether this anonymous struct/union is an extension.
891 if (Record->isUnion() && !getLangOptions().CPlusPlus)
892 Diag(Record->getLocation(), diag::ext_anonymous_union);
893 else if (!Record->isUnion())
894 Diag(Record->getLocation(), diag::ext_anonymous_struct);
895
896 // C and C++ require different kinds of checks for anonymous
897 // structs/unions.
898 bool Invalid = false;
899 if (getLangOptions().CPlusPlus) {
900 const char* PrevSpec = 0;
901 // C++ [class.union]p3:
902 // Anonymous unions declared in a named namespace or in the
903 // global namespace shall be declared static.
904 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
905 (isa<TranslationUnitDecl>(Owner) ||
906 (isa<NamespaceDecl>(Owner) &&
907 cast<NamespaceDecl>(Owner)->getDeclName()))) {
908 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
909 Invalid = true;
910
911 // Recover by adding 'static'.
912 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
913 }
914 // C++ [class.union]p3:
915 // A storage class is not allowed in a declaration of an
916 // anonymous union in a class scope.
917 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
918 isa<RecordDecl>(Owner)) {
919 Diag(DS.getStorageClassSpecLoc(),
920 diag::err_anonymous_union_with_storage_spec);
921 Invalid = true;
922
923 // Recover by removing the storage specifier.
924 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
925 PrevSpec);
926 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000927
928 // C++ [class.union]p2:
929 // The member-specification of an anonymous union shall only
930 // define non-static data members. [Note: nested types and
931 // functions cannot be declared within an anonymous union. ]
932 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
933 MemEnd = Record->decls_end();
934 Mem != MemEnd; ++Mem) {
935 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
936 // C++ [class.union]p3:
937 // An anonymous union shall not have private or protected
938 // members (clause 11).
939 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
940 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
941 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
942 Invalid = true;
943 }
944 } else if ((*Mem)->isImplicit()) {
945 // Any implicit members are fine.
946 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
947 if (!MemRecord->isAnonymousStructOrUnion() &&
948 MemRecord->getDeclName()) {
949 // This is a nested type declaration.
950 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
951 << (int)Record->isUnion();
952 Invalid = true;
953 }
954 } else {
955 // We have something that isn't a non-static data
956 // member. Complain about it.
957 unsigned DK = diag::err_anonymous_record_bad_member;
958 if (isa<TypeDecl>(*Mem))
959 DK = diag::err_anonymous_record_with_type;
960 else if (isa<FunctionDecl>(*Mem))
961 DK = diag::err_anonymous_record_with_function;
962 else if (isa<VarDecl>(*Mem))
963 DK = diag::err_anonymous_record_with_static;
964 Diag((*Mem)->getLocation(), DK)
965 << (int)Record->isUnion();
966 Invalid = true;
967 }
968 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000969 } else {
970 // FIXME: Check GNU C semantics
971 }
972
973 if (!Record->isUnion() && !Owner->isRecord()) {
974 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member);
975 Invalid = true;
976 }
977
978 // Create a declaration for this anonymous struct/union.
979 ScopedDecl *Anon = 0;
980 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
981 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
982 /*IdentifierInfo=*/0,
983 Context.getTypeDeclType(Record),
984 /*BitWidth=*/0, /*Mutable=*/false,
985 /*PrevDecl=*/0);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000986 Anon->setAccess(AS_public);
987 if (getLangOptions().CPlusPlus)
988 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000989 } else {
990 VarDecl::StorageClass SC;
991 switch (DS.getStorageClassSpec()) {
992 default: assert(0 && "Unknown storage class!");
993 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
994 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
995 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
996 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
997 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
998 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
999 case DeclSpec::SCS_mutable:
1000 // mutable can only appear on non-static class members, so it's always
1001 // an error here
1002 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1003 Invalid = true;
1004 SC = VarDecl::None;
1005 break;
1006 }
1007
1008 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1009 /*IdentifierInfo=*/0,
1010 Context.getTypeDeclType(Record),
1011 SC, /*FIXME:LastDeclarator=*/0,
1012 DS.getSourceRange().getBegin());
1013 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001014 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001015
1016 // Add the anonymous struct/union object to the current
1017 // context. We'll be referencing this object when we refer to one of
1018 // its members.
1019 Owner->addDecl(Context, Anon);
1020
1021 // Inject the members of the anonymous struct/union into the owning
1022 // context and into the identifier resolver chain for name lookup
1023 // purposes.
1024 Invalid = Invalid || InjectAnonymousStructOrUnionMembers(S, Owner, Record);
1025
1026 // Mark this as an anonymous struct/union type. Note that we do not
1027 // do this until after we have already checked and injected the
1028 // members of this anonymous struct/union type, because otherwise
1029 // the members could be injected twice: once by DeclContext when it
1030 // builds its lookup table, and once by
1031 // InjectAnonymousStructOrUnionMembers.
1032 Record->setAnonymousStructOrUnion(true);
1033
1034 if (Invalid)
1035 Anon->setInvalidDecl();
1036
1037 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001038}
1039
Steve Naroffd0091aa2008-01-10 22:15:12 +00001040bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +00001041 // Get the type before calling CheckSingleAssignmentConstraints(), since
1042 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001043 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +00001044
1045 if (getLangOptions().CPlusPlus)
1046 return PerformCopyInitialization(Init, DeclType, "initializing");
1047
Chris Lattner5cf216b2008-01-04 18:04:52 +00001048 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1049 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1050 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +00001051}
1052
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001053bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001054 const ArrayType *AT = Context.getAsArrayType(DeclT);
1055
1056 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001057 // C99 6.7.8p14. We have an array of character type with unknown size
1058 // being initialized to a string literal.
1059 llvm::APSInt ConstVal(32);
1060 ConstVal = strLiteral->getByteLength() + 1;
1061 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001062 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001063 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001064 } else {
1065 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001066 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001067 // FIXME: Avoid truncation for 64-bit length strings.
1068 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001069 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001070 diag::warn_initializer_string_for_char_array_too_long)
1071 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001072 }
1073 // Set type from "char *" to "constant array of char".
1074 strLiteral->setType(DeclT);
1075 // For now, we always return false (meaning success).
1076 return false;
1077}
1078
1079StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001080 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001081 if (AT && AT->getElementType()->isCharType()) {
1082 return dyn_cast<StringLiteral>(Init);
1083 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001084 return 0;
1085}
1086
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001087bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1088 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001089 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001090 if (DeclType->isDependentType() || Init->isTypeDependent())
1091 return false;
1092
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001093 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001094 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001095 // (8.3.2), shall be initialized by an object, or function, of
1096 // type T or by an object that can be converted into a T.
1097 if (DeclType->isReferenceType())
1098 return CheckReferenceInit(Init, DeclType);
1099
Steve Naroffca107302008-01-21 23:53:58 +00001100 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1101 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001102 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001103 return Diag(InitLoc, diag::err_variable_object_no_init)
1104 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001105
Steve Naroff2fdc3742007-12-10 22:44:33 +00001106 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1107 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001108 // FIXME: Handle wide strings
1109 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1110 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001111
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001112 // C++ [dcl.init]p14:
1113 // -- If the destination type is a (possibly cv-qualified) class
1114 // type:
1115 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1116 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1117 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1118
1119 // -- If the initialization is direct-initialization, or if it is
1120 // copy-initialization where the cv-unqualified version of the
1121 // source type is the same class as, or a derived class of, the
1122 // class of the destination, constructors are considered.
1123 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1124 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1125 CXXConstructorDecl *Constructor
1126 = PerformInitializationByConstructor(DeclType, &Init, 1,
1127 InitLoc, Init->getSourceRange(),
1128 InitEntity, IK_Copy);
1129 return Constructor == 0;
1130 }
1131
1132 // -- Otherwise (i.e., for the remaining copy-initialization
1133 // cases), user-defined conversion sequences that can
1134 // convert from the source type to the destination type or
1135 // (when a conversion function is used) to a derived class
1136 // thereof are enumerated as described in 13.3.1.4, and the
1137 // best one is chosen through overload resolution
1138 // (13.3). If the conversion cannot be done or is
1139 // ambiguous, the initialization is ill-formed. The
1140 // function selected is called with the initializer
1141 // expression as its argument; if the function is a
1142 // constructor, the call initializes a temporary of the
1143 // destination type.
1144 // FIXME: We're pretending to do copy elision here; return to
1145 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001146 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001147 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001148
Douglas Gregor61366e92008-12-24 00:01:03 +00001149 if (InitEntity)
1150 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1151 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1152 << Init->getType() << Init->getSourceRange();
1153 else
1154 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1155 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1156 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001157 }
1158
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001159 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001160 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001161 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1162 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001163
Steve Naroffd0091aa2008-01-10 22:15:12 +00001164 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001165 } else if (getLangOptions().CPlusPlus) {
1166 // C++ [dcl.init]p14:
1167 // [...] If the class is an aggregate (8.5.1), and the initializer
1168 // is a brace-enclosed list, see 8.5.1.
1169 //
1170 // Note: 8.5.1 is handled below; here, we diagnose the case where
1171 // we have an initializer list and a destination type that is not
1172 // an aggregate.
1173 // FIXME: In C++0x, this is yet another form of initialization.
1174 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1175 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1176 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001177 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001178 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001179 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001180 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001181
Steve Naroff0cca7492008-05-01 22:18:59 +00001182 InitListChecker CheckInitList(this, InitList, DeclType);
1183 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +00001184}
1185
Douglas Gregor10bd3682008-11-17 22:58:34 +00001186/// GetNameForDeclarator - Determine the full declaration name for the
1187/// given Declarator.
1188DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1189 switch (D.getKind()) {
1190 case Declarator::DK_Abstract:
1191 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1192 return DeclarationName();
1193
1194 case Declarator::DK_Normal:
1195 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1196 return DeclarationName(D.getIdentifier());
1197
1198 case Declarator::DK_Constructor: {
1199 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1200 Ty = Context.getCanonicalType(Ty);
1201 return Context.DeclarationNames.getCXXConstructorName(Ty);
1202 }
1203
1204 case Declarator::DK_Destructor: {
1205 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1206 Ty = Context.getCanonicalType(Ty);
1207 return Context.DeclarationNames.getCXXDestructorName(Ty);
1208 }
1209
1210 case Declarator::DK_Conversion: {
1211 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1212 Ty = Context.getCanonicalType(Ty);
1213 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1214 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001215
1216 case Declarator::DK_Operator:
1217 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1218 return Context.DeclarationNames.getCXXOperatorName(
1219 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001220 }
1221
1222 assert(false && "Unknown name kind");
1223 return DeclarationName();
1224}
1225
Douglas Gregor584049d2008-12-15 23:53:10 +00001226/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1227/// functions Declaration and Definition are "nearly" matching. This
1228/// heuristic is used to improve diagnostics in the case where an
1229/// out-of-line member function definition doesn't match any
1230/// declaration within the class.
1231static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1232 FunctionDecl *Declaration,
1233 FunctionDecl *Definition) {
1234 if (Declaration->param_size() != Definition->param_size())
1235 return false;
1236 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1237 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1238 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1239
1240 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1241 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1242 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1243 return false;
1244 }
1245
1246 return true;
1247}
1248
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001249Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001250Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1251 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +00001252 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001253 DeclarationName Name = GetNameForDeclarator(D);
1254
Chris Lattnere80a59c2007-07-25 00:24:17 +00001255 // All of these full declarators require an identifier. If it doesn't have
1256 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001257 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001258 if (!D.getInvalidType()) // Reject this if we think it is valid.
1259 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001260 diag::err_declarator_need_ident)
1261 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001262 return 0;
1263 }
1264
Chris Lattner31e05722007-08-26 06:24:45 +00001265 // The scope passed in may not be a decl scope. Zip up the scope tree until
1266 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001267 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1268 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001269 S = S->getParent();
1270
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001271 DeclContext *DC;
1272 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001273 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001274 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001275
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001276 // See if this is a redefinition of a variable in the same scope.
1277 if (!D.getCXXScopeSpec().isSet()) {
1278 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001279 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001280 } else { // Something like "int foo::x;"
1281 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001282 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001283
1284 // C++ 7.3.1.2p2:
1285 // Members (including explicit specializations of templates) of a named
1286 // namespace can also be defined outside that namespace by explicit
1287 // qualification of the name being defined, provided that the entity being
1288 // defined was already declared in the namespace and the definition appears
1289 // after the point of declaration in a namespace that encloses the
1290 // declarations namespace.
1291 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001292 // Note that we only check the context at this point. We don't yet
1293 // have enough information to make sure that PrevDecl is actually
1294 // the declaration we want to match. For example, given:
1295 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001296 // class X {
1297 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001298 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001299 // };
1300 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001301 // void X::f(int) { } // ill-formed
1302 //
1303 // In this case, PrevDecl will point to the overload set
1304 // containing the two f's declared in X, but neither of them
1305 // matches.
1306 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001307 // The qualifying scope doesn't enclose the original declaration.
1308 // Emit diagnostic based on current scope.
1309 SourceLocation L = D.getIdentifierLoc();
1310 SourceRange R = D.getCXXScopeSpec().getRange();
1311 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001312 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001313 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001314 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001315 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001316 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001317 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001318 }
1319 }
1320
Douglas Gregorf57172b2008-12-08 18:40:42 +00001321 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001322 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001323 InvalidDecl = InvalidDecl
1324 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001325 // Just pretend that we didn't see the previous declaration.
1326 PrevDecl = 0;
1327 }
1328
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001329 // In C++, the previous declaration we find might be a tag type
1330 // (class or enum). In this case, the new declaration will hide the
1331 // tag type.
1332 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1333 PrevDecl = 0;
1334
Chris Lattner41af0932007-11-14 06:34:38 +00001335 QualType R = GetTypeForDeclarator(D, S);
1336 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1337
Reid Spencer5f016e22007-07-11 17:01:13 +00001338 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001339 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1340 if (D.getCXXScopeSpec().isSet()) {
1341 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1342 << D.getCXXScopeSpec().getRange();
1343 InvalidDecl = true;
1344 // Pretend we didn't see the scope specifier.
1345 DC = 0;
1346 }
1347
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001348 // Check that there are no default arguments (C++ only).
1349 if (getLangOptions().CPlusPlus)
1350 CheckExtraCXXDefaultArguments(D);
1351
Chris Lattner41af0932007-11-14 06:34:38 +00001352 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001353 if (!NewTD) return 0;
1354
1355 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001356 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001357 // Merge the decl with the existing one if appropriate. If the decl is
1358 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001359 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001360 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1361 if (NewTD == 0) return 0;
1362 }
1363 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001364 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001365 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1366 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001367 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001368 if (NewTD->getUnderlyingType()->isVariableArrayType())
1369 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1370 else
1371 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1372
Steve Naroffd7444aa2007-08-31 17:20:07 +00001373 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001374 }
1375 }
Chris Lattner41af0932007-11-14 06:34:38 +00001376 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001377 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001378 switch (D.getDeclSpec().getStorageClassSpec()) {
1379 default: assert(0 && "Unknown storage class!");
Sebastian Redl64b45f72009-01-05 20:52:13 +00001380 case DeclSpec::SCS_auto:
Reid Spencer5f016e22007-07-11 17:01:13 +00001381 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001382 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001383 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001384 InvalidDecl = true;
1385 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001386 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1387 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1388 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001389 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001390 }
1391
Chris Lattnera98e58d2008-03-15 21:24:04 +00001392 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001393 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001394 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1395
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001396 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001397 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001398 // This is a C++ constructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001399 assert(DC->isRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001400 "Constructors can only be declared in a member context");
1401
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001402 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001403
1404 // Create the new declaration
1405 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001406 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001407 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001408 isExplicit, isInline,
1409 /*isImplicitlyDeclared=*/false);
1410
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001411 if (InvalidDecl)
Douglas Gregor42a552f2008-11-05 20:51:48 +00001412 NewFD->setInvalidDecl();
1413 } else if (D.getKind() == Declarator::DK_Destructor) {
1414 // This is a C++ destructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001415 if (DC->isRecord()) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001416 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001417
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001418 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001419 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001420 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001421 isInline,
1422 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001423
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001424 if (InvalidDecl)
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001425 NewFD->setInvalidDecl();
1426 } else {
1427 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001428
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001429 // Create a FunctionDecl to satisfy the function definition parsing
1430 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001431 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001432 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001433 // FIXME: Move to DeclGroup...
1434 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001435 InvalidDecl = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001436 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001437 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001438 } else if (D.getKind() == Declarator::DK_Conversion) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001439 if (!DC->isRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001440 Diag(D.getIdentifierLoc(),
1441 diag::err_conv_function_not_member);
1442 return 0;
1443 } else {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001444 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001445
Douglas Gregor70316a02008-12-26 15:00:45 +00001446 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001447 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001448 isInline, isExplicit);
1449
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001450 if (InvalidDecl)
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001451 NewFD->setInvalidDecl();
1452 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001453 } else if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001454 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001455 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001456 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001457 (SC == FunctionDecl::Static), isInline,
1458 LastDeclarator);
1459 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001460 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001461 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001462 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001463 // FIXME: Move to DeclGroup...
1464 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001465 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001466
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001467 // Set the lexical context. If the declarator has a C++
1468 // scope specifier, the lexical context will be different
1469 // from the semantic context.
1470 NewFD->setLexicalDeclContext(CurContext);
1471
Daniel Dunbara80f8742008-08-05 01:35:17 +00001472 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001473 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001474 // The parser guarantees this is a string.
1475 StringLiteral *SE = cast<StringLiteral>(E);
1476 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1477 SE->getByteLength())));
1478 }
1479
Chris Lattner04421082008-04-08 04:40:51 +00001480 // Copy the parameter declarations from the declarator D to
1481 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001482 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001483 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1484
1485 // Create Decl objects for each parameter, adding them to the
1486 // FunctionDecl.
1487 llvm::SmallVector<ParmVarDecl*, 16> Params;
1488
1489 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1490 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001491 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001492 // We let through "const void" here because Sema::GetTypeForDeclarator
1493 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001494 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1495 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001496 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1497 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001498 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1499
Chris Lattnerdef026a2008-04-10 02:26:16 +00001500 // In C++, the empty parameter-type-list must be spelled "void"; a
1501 // typedef of void is not permitted.
1502 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001503 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001504 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1505 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001506 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001507 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1508 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1509 }
1510
1511 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001512 } else if (R->getAsTypedefType()) {
1513 // When we're declaring a function with a typedef, as in the
1514 // following example, we'll need to synthesize (unnamed)
1515 // parameters for use in the declaration.
1516 //
1517 // @code
1518 // typedef void fn(int);
1519 // fn f;
1520 // @endcode
1521 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1522 if (!FT) {
1523 // This is a typedef of a function with no prototype, so we
1524 // don't need to do anything.
1525 } else if ((FT->getNumArgs() == 0) ||
1526 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1527 FT->getArgType(0)->isVoidType())) {
1528 // This is a zero-argument function. We don't need to do anything.
1529 } else {
1530 // Synthesize a parameter for each argument type.
1531 llvm::SmallVector<ParmVarDecl*, 16> Params;
1532 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1533 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001534 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001535 SourceLocation(), 0,
1536 *ArgType, VarDecl::None,
1537 0, 0));
1538 }
1539
1540 NewFD->setParams(&Params[0], Params.size());
1541 }
Chris Lattner04421082008-04-08 04:40:51 +00001542 }
1543
Douglas Gregor72b505b2008-12-16 21:30:33 +00001544 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1545 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001546 else if (isa<CXXDestructorDecl>(NewFD)) {
1547 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1548 Record->setUserDeclaredDestructor(true);
1549 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1550 // user-defined destructor.
1551 Record->setPOD(false);
1552 } else if (CXXConversionDecl *Conversion =
1553 dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001554 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001555
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001556 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1557 if (NewFD->isOverloadedOperator() &&
1558 CheckOverloadedOperatorDeclaration(NewFD))
1559 NewFD->setInvalidDecl();
1560
Steve Naroffffce4d52008-01-09 23:34:55 +00001561 // Merge the decl with the existing one if appropriate. Since C functions
1562 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001563 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001564 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001565 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001566
1567 // If C++, determine whether NewFD is an overload of PrevDecl or
1568 // a declaration that requires merging. If it's an overload,
1569 // there's no more work to do here; we'll just add the new
1570 // function to the scope.
1571 OverloadedFunctionDecl::function_iterator MatchedDecl;
1572 if (!getLangOptions().CPlusPlus ||
1573 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1574 Decl *OldDecl = PrevDecl;
1575
1576 // If PrevDecl was an overloaded function, extract the
1577 // FunctionDecl that matched.
1578 if (isa<OverloadedFunctionDecl>(PrevDecl))
1579 OldDecl = *MatchedDecl;
1580
1581 // NewFD and PrevDecl represent declarations that need to be
1582 // merged.
1583 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1584
1585 if (NewFD == 0) return 0;
1586 if (Redeclaration) {
1587 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1588
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001589 // An out-of-line member function declaration must also be a
1590 // definition (C++ [dcl.meaning]p1).
1591 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1592 !InvalidDecl) {
1593 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1594 << D.getCXXScopeSpec().getRange();
1595 NewFD->setInvalidDecl();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001596 }
1597 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001598 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001599
1600 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1601 // The user tried to provide an out-of-line definition for a
1602 // member function, but there was no such member function
1603 // declared (C++ [class.mfct]p2). For example:
1604 //
1605 // class X {
1606 // void f() const;
1607 // };
1608 //
1609 // void X::f() { } // ill-formed
1610 //
1611 // Complain about this problem, and attempt to suggest close
1612 // matches (e.g., those that differ only in cv-qualifiers and
1613 // whether the parameter types are references).
1614 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1615 << cast<CXXRecordDecl>(DC)->getDeclName()
1616 << D.getCXXScopeSpec().getRange();
1617 InvalidDecl = true;
1618
1619 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1620 if (!PrevDecl) {
1621 // Nothing to suggest.
1622 } else if (OverloadedFunctionDecl *Ovl
1623 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1624 for (OverloadedFunctionDecl::function_iterator
1625 Func = Ovl->function_begin(),
1626 FuncEnd = Ovl->function_end();
1627 Func != FuncEnd; ++Func) {
1628 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1629 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1630
1631 }
1632 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1633 // Suggest this no matter how mismatched it is; it's the only
1634 // thing we have.
1635 unsigned diag;
1636 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1637 diag = diag::note_member_def_close_match;
1638 else if (Method->getBody())
1639 diag = diag::note_previous_definition;
1640 else
1641 diag = diag::note_previous_declaration;
1642 Diag(Method->getLocation(), diag);
1643 }
1644
1645 PrevDecl = 0;
1646 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001647 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +00001648 // Handle attributes. We need to have merged decls when handling attributes
1649 // (for example to check for conflicts, etc).
1650 ProcessDeclAttributes(NewFD, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001651 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001652
Douglas Gregor584049d2008-12-15 23:53:10 +00001653 if (getLangOptions().CPlusPlus) {
1654 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001655 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001656
1657 // An out-of-line member function declaration must also be a
1658 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001659 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001660 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1661 << D.getCXXScopeSpec().getRange();
1662 InvalidDecl = true;
1663 }
1664 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001666 // Check that there are no default arguments (C++ only).
1667 if (getLangOptions().CPlusPlus)
1668 CheckExtraCXXDefaultArguments(D);
1669
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001670 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001671 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1672 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001673 InvalidDecl = true;
1674 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001675
1676 VarDecl *NewVD;
1677 VarDecl::StorageClass SC;
1678 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001679 default: assert(0 && "Unknown storage class!");
1680 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1681 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1682 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1683 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1684 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1685 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001686 case DeclSpec::SCS_mutable:
1687 // mutable can only appear on non-static class members, so it's always
1688 // an error here
1689 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1690 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001691 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001692 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001693 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001694
1695 IdentifierInfo *II = Name.getAsIdentifierInfo();
1696 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001697 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1698 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001699 return 0;
1700 }
1701
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001702 if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001703 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001704 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001705 D.getIdentifierLoc(), II,
1706 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001707 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001708 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001709 if (S->getFnParent() == 0) {
1710 // C99 6.9p2: The storage-class specifiers auto and register shall not
1711 // appear in the declaration specifiers in an external declaration.
1712 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001713 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001714 InvalidDecl = true;
1715 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001716 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001717 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1718 II, R, SC, LastDeclarator,
1719 // FIXME: Move to DeclGroup...
1720 D.getDeclSpec().getSourceRange().getBegin());
1721 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001722 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001723 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001724 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001725
Daniel Dunbara735ad82008-08-06 00:03:29 +00001726 // Handle GNU asm-label extension (encoded as an attribute).
1727 if (Expr *E = (Expr*) D.getAsmLabel()) {
1728 // The parser guarantees this is a string.
1729 StringLiteral *SE = cast<StringLiteral>(E);
1730 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1731 SE->getByteLength())));
1732 }
1733
Nate Begemanc8e89a82008-03-14 18:07:10 +00001734 // Emit an error if an address space was applied to decl with local storage.
1735 // This includes arrays of objects with address space qualifiers, but not
1736 // automatic variables that point to other address spaces.
1737 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001738 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1739 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1740 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001741 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001742 // Merge the decl with the existing one if appropriate. If the decl is
1743 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001744 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001745 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1746 // The user tried to define a non-static data member
1747 // out-of-line (C++ [dcl.meaning]p1).
1748 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1749 << D.getCXXScopeSpec().getRange();
1750 NewVD->Destroy(Context);
1751 return 0;
1752 }
1753
Reid Spencer5f016e22007-07-11 17:01:13 +00001754 NewVD = MergeVarDecl(NewVD, PrevDecl);
1755 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001756
1757 if (D.getCXXScopeSpec().isSet()) {
1758 // No previous declaration in the qualifying scope.
1759 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1760 << Name << D.getCXXScopeSpec().getRange();
1761 InvalidDecl = true;
1762 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001763 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001764 New = NewVD;
1765 }
1766
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001767 // Set the lexical context. If the declarator has a C++ scope specifier, the
1768 // lexical context will be different from the semantic context.
1769 New->setLexicalDeclContext(CurContext);
1770
Reid Spencer5f016e22007-07-11 17:01:13 +00001771 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001772 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001773 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001774 // If any semantic error occurred, mark the decl as invalid.
1775 if (D.getInvalidType() || InvalidDecl)
1776 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001777
1778 return New;
1779}
1780
Steve Naroff6594a702008-10-27 11:34:16 +00001781void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001782 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1783 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001784}
1785
Eli Friedmanc594b322008-05-20 13:48:25 +00001786bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1787 switch (Init->getStmtClass()) {
1788 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001789 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001790 return true;
1791 case Expr::ParenExprClass: {
1792 const ParenExpr* PE = cast<ParenExpr>(Init);
1793 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1794 }
1795 case Expr::CompoundLiteralExprClass:
1796 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001797 case Expr::DeclRefExprClass:
1798 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001799 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001800 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1801 if (VD->hasGlobalStorage())
1802 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001803 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001804 return true;
1805 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001806 if (isa<FunctionDecl>(D))
1807 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001808 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001809 return true;
1810 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001811 case Expr::MemberExprClass: {
1812 const MemberExpr *M = cast<MemberExpr>(Init);
1813 if (M->isArrow())
1814 return CheckAddressConstantExpression(M->getBase());
1815 return CheckAddressConstantExpressionLValue(M->getBase());
1816 }
1817 case Expr::ArraySubscriptExprClass: {
1818 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1819 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1820 return CheckAddressConstantExpression(ASE->getBase()) ||
1821 CheckArithmeticConstantExpression(ASE->getIdx());
1822 }
1823 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001824 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001825 return false;
1826 case Expr::UnaryOperatorClass: {
1827 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1828
1829 // C99 6.6p9
1830 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001831 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001832
Steve Naroff6594a702008-10-27 11:34:16 +00001833 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001834 return true;
1835 }
1836 }
1837}
1838
1839bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1840 switch (Init->getStmtClass()) {
1841 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001842 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001843 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001844 case Expr::ParenExprClass:
1845 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001846 case Expr::StringLiteralClass:
1847 case Expr::ObjCStringLiteralClass:
1848 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001849 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001850 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001851 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1852 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1853 Builtin::BI__builtin___CFStringMakeConstantString)
1854 return false;
1855
Steve Naroff6594a702008-10-27 11:34:16 +00001856 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001857 return true;
1858
Eli Friedmanc594b322008-05-20 13:48:25 +00001859 case Expr::UnaryOperatorClass: {
1860 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1861
1862 // C99 6.6p9
1863 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1864 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1865
1866 if (Exp->getOpcode() == UnaryOperator::Extension)
1867 return CheckAddressConstantExpression(Exp->getSubExpr());
1868
Steve Naroff6594a702008-10-27 11:34:16 +00001869 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001870 return true;
1871 }
1872 case Expr::BinaryOperatorClass: {
1873 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1874 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1875
1876 Expr *PExp = Exp->getLHS();
1877 Expr *IExp = Exp->getRHS();
1878 if (IExp->getType()->isPointerType())
1879 std::swap(PExp, IExp);
1880
1881 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1882 return CheckAddressConstantExpression(PExp) ||
1883 CheckArithmeticConstantExpression(IExp);
1884 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001885 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001886 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001887 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001888 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1889 // Check for implicit promotion
1890 if (SubExpr->getType()->isFunctionType() ||
1891 SubExpr->getType()->isArrayType())
1892 return CheckAddressConstantExpressionLValue(SubExpr);
1893 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001894
1895 // Check for pointer->pointer cast
1896 if (SubExpr->getType()->isPointerType())
1897 return CheckAddressConstantExpression(SubExpr);
1898
Eli Friedmanc3f07642008-08-25 20:46:57 +00001899 if (SubExpr->getType()->isIntegralType()) {
1900 // Check for the special-case of a pointer->int->pointer cast;
1901 // this isn't standard, but some code requires it. See
1902 // PR2720 for an example.
1903 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1904 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1905 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1906 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1907 if (IntWidth >= PointerWidth) {
1908 return CheckAddressConstantExpression(SubCast->getSubExpr());
1909 }
1910 }
1911 }
1912 }
1913 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001914 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001915 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001916
Steve Naroff6594a702008-10-27 11:34:16 +00001917 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001918 return true;
1919 }
1920 case Expr::ConditionalOperatorClass: {
1921 // FIXME: Should we pedwarn here?
1922 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1923 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001924 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001925 return true;
1926 }
1927 if (CheckArithmeticConstantExpression(Exp->getCond()))
1928 return true;
1929 if (Exp->getLHS() &&
1930 CheckAddressConstantExpression(Exp->getLHS()))
1931 return true;
1932 return CheckAddressConstantExpression(Exp->getRHS());
1933 }
1934 case Expr::AddrLabelExprClass:
1935 return false;
1936 }
1937}
1938
Eli Friedman4caf0552008-06-09 05:05:07 +00001939static const Expr* FindExpressionBaseAddress(const Expr* E);
1940
1941static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1942 switch (E->getStmtClass()) {
1943 default:
1944 return E;
1945 case Expr::ParenExprClass: {
1946 const ParenExpr* PE = cast<ParenExpr>(E);
1947 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1948 }
1949 case Expr::MemberExprClass: {
1950 const MemberExpr *M = cast<MemberExpr>(E);
1951 if (M->isArrow())
1952 return FindExpressionBaseAddress(M->getBase());
1953 return FindExpressionBaseAddressLValue(M->getBase());
1954 }
1955 case Expr::ArraySubscriptExprClass: {
1956 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1957 return FindExpressionBaseAddress(ASE->getBase());
1958 }
1959 case Expr::UnaryOperatorClass: {
1960 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1961
1962 if (Exp->getOpcode() == UnaryOperator::Deref)
1963 return FindExpressionBaseAddress(Exp->getSubExpr());
1964
1965 return E;
1966 }
1967 }
1968}
1969
1970static const Expr* FindExpressionBaseAddress(const Expr* E) {
1971 switch (E->getStmtClass()) {
1972 default:
1973 return E;
1974 case Expr::ParenExprClass: {
1975 const ParenExpr* PE = cast<ParenExpr>(E);
1976 return FindExpressionBaseAddress(PE->getSubExpr());
1977 }
1978 case Expr::UnaryOperatorClass: {
1979 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1980
1981 // C99 6.6p9
1982 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1983 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1984
1985 if (Exp->getOpcode() == UnaryOperator::Extension)
1986 return FindExpressionBaseAddress(Exp->getSubExpr());
1987
1988 return E;
1989 }
1990 case Expr::BinaryOperatorClass: {
1991 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1992
1993 Expr *PExp = Exp->getLHS();
1994 Expr *IExp = Exp->getRHS();
1995 if (IExp->getType()->isPointerType())
1996 std::swap(PExp, IExp);
1997
1998 return FindExpressionBaseAddress(PExp);
1999 }
2000 case Expr::ImplicitCastExprClass: {
2001 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2002
2003 // Check for implicit promotion
2004 if (SubExpr->getType()->isFunctionType() ||
2005 SubExpr->getType()->isArrayType())
2006 return FindExpressionBaseAddressLValue(SubExpr);
2007
2008 // Check for pointer->pointer cast
2009 if (SubExpr->getType()->isPointerType())
2010 return FindExpressionBaseAddress(SubExpr);
2011
2012 // We assume that we have an arithmetic expression here;
2013 // if we don't, we'll figure it out later
2014 return 0;
2015 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002016 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00002017 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2018
2019 // Check for pointer->pointer cast
2020 if (SubExpr->getType()->isPointerType())
2021 return FindExpressionBaseAddress(SubExpr);
2022
2023 // We assume that we have an arithmetic expression here;
2024 // if we don't, we'll figure it out later
2025 return 0;
2026 }
2027 }
2028}
2029
Anders Carlsson51fe9962008-11-22 21:04:56 +00002030bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002031 switch (Init->getStmtClass()) {
2032 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002033 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002034 return true;
2035 case Expr::ParenExprClass: {
2036 const ParenExpr* PE = cast<ParenExpr>(Init);
2037 return CheckArithmeticConstantExpression(PE->getSubExpr());
2038 }
2039 case Expr::FloatingLiteralClass:
2040 case Expr::IntegerLiteralClass:
2041 case Expr::CharacterLiteralClass:
2042 case Expr::ImaginaryLiteralClass:
2043 case Expr::TypesCompatibleExprClass:
2044 case Expr::CXXBoolLiteralExprClass:
2045 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002046 case Expr::CallExprClass:
2047 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002048 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002049
2050 // Allow any constant foldable calls to builtins.
2051 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002052 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002053
Steve Naroff6594a702008-10-27 11:34:16 +00002054 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002055 return true;
2056 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002057 case Expr::DeclRefExprClass:
2058 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002059 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2060 if (isa<EnumConstantDecl>(D))
2061 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002062 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002063 return true;
2064 }
2065 case Expr::CompoundLiteralExprClass:
2066 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2067 // but vectors are allowed to be magic.
2068 if (Init->getType()->isVectorType())
2069 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002070 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002071 return true;
2072 case Expr::UnaryOperatorClass: {
2073 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2074
2075 switch (Exp->getOpcode()) {
2076 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2077 // See C99 6.6p3.
2078 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002079 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002080 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002081 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002082 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2083 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002084 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002085 return true;
2086 case UnaryOperator::Extension:
2087 case UnaryOperator::LNot:
2088 case UnaryOperator::Plus:
2089 case UnaryOperator::Minus:
2090 case UnaryOperator::Not:
2091 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2092 }
2093 }
Sebastian Redl05189992008-11-11 17:56:53 +00002094 case Expr::SizeOfAlignOfExprClass: {
2095 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002096 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002097 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002098 return false;
2099 // alignof always evaluates to a constant.
2100 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002101 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002102 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002103 return true;
2104 }
2105 return false;
2106 }
2107 case Expr::BinaryOperatorClass: {
2108 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2109
2110 if (Exp->getLHS()->getType()->isArithmeticType() &&
2111 Exp->getRHS()->getType()->isArithmeticType()) {
2112 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2113 CheckArithmeticConstantExpression(Exp->getRHS());
2114 }
2115
Eli Friedman4caf0552008-06-09 05:05:07 +00002116 if (Exp->getLHS()->getType()->isPointerType() &&
2117 Exp->getRHS()->getType()->isPointerType()) {
2118 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2119 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2120
2121 // Only allow a null (constant integer) base; we could
2122 // allow some additional cases if necessary, but this
2123 // is sufficient to cover offsetof-like constructs.
2124 if (!LHSBase && !RHSBase) {
2125 return CheckAddressConstantExpression(Exp->getLHS()) ||
2126 CheckAddressConstantExpression(Exp->getRHS());
2127 }
2128 }
2129
Steve Naroff6594a702008-10-27 11:34:16 +00002130 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002131 return true;
2132 }
2133 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002134 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002135 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002136 if (SubExpr->getType()->isArithmeticType())
2137 return CheckArithmeticConstantExpression(SubExpr);
2138
Eli Friedmanb529d832008-09-02 09:37:00 +00002139 if (SubExpr->getType()->isPointerType()) {
2140 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2141 // If the pointer has a null base, this is an offsetof-like construct
2142 if (!Base)
2143 return CheckAddressConstantExpression(SubExpr);
2144 }
2145
Steve Naroff6594a702008-10-27 11:34:16 +00002146 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002147 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002148 }
2149 case Expr::ConditionalOperatorClass: {
2150 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002151
2152 // If GNU extensions are disabled, we require all operands to be arithmetic
2153 // constant expressions.
2154 if (getLangOptions().NoExtensions) {
2155 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2156 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2157 CheckArithmeticConstantExpression(Exp->getRHS());
2158 }
2159
2160 // Otherwise, we have to emulate some of the behavior of fold here.
2161 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2162 // because it can constant fold things away. To retain compatibility with
2163 // GCC code, we see if we can fold the condition to a constant (which we
2164 // should always be able to do in theory). If so, we only require the
2165 // specified arm of the conditional to be a constant. This is a horrible
2166 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002167 Expr::EvalResult EvalResult;
2168 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2169 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002170 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002171 // won't be able to either. Use it to emit the diagnostic though.
2172 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002173 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002174 return Res;
2175 }
2176
2177 // Verify that the side following the condition is also a constant.
2178 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002179 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002180 std::swap(TrueSide, FalseSide);
2181
2182 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002183 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002184
2185 // Okay, the evaluated side evaluates to a constant, so we accept this.
2186 // Check to see if the other side is obviously not a constant. If so,
2187 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002188 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002189 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002190 diag::ext_typecheck_expression_not_constant_but_accepted)
2191 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002192 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002193 }
2194 }
2195}
2196
2197bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002198 Expr::EvalResult Result;
2199
Nuno Lopes9a979c32008-07-07 16:46:50 +00002200 Init = Init->IgnoreParens();
2201
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002202 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2203 return false;
2204
Eli Friedmanc594b322008-05-20 13:48:25 +00002205 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2206 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2207 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2208
Nuno Lopes9a979c32008-07-07 16:46:50 +00002209 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2210 return CheckForConstantInitializer(e->getInitializer(), DclT);
2211
Eli Friedmanc594b322008-05-20 13:48:25 +00002212 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2213 unsigned numInits = Exp->getNumInits();
2214 for (unsigned i = 0; i < numInits; i++) {
2215 // FIXME: Need to get the type of the declaration for C++,
2216 // because it could be a reference?
2217 if (CheckForConstantInitializer(Exp->getInit(i),
2218 Exp->getInit(i)->getType()))
2219 return true;
2220 }
2221 return false;
2222 }
2223
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002224 // FIXME: We can probably remove some of this code below, now that
2225 // Expr::Evaluate is doing the heavy lifting for scalars.
2226
Eli Friedmanc594b322008-05-20 13:48:25 +00002227 if (Init->isNullPointerConstant(Context))
2228 return false;
2229 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002230 QualType InitTy = Context.getCanonicalType(Init->getType())
2231 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002232 if (InitTy == Context.BoolTy) {
2233 // Special handling for pointers implicitly cast to bool;
2234 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2235 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2236 Expr* SubE = ICE->getSubExpr();
2237 if (SubE->getType()->isPointerType() ||
2238 SubE->getType()->isArrayType() ||
2239 SubE->getType()->isFunctionType()) {
2240 return CheckAddressConstantExpression(Init);
2241 }
2242 }
2243 } else if (InitTy->isIntegralType()) {
2244 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002245 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002246 SubE = CE->getSubExpr();
2247 // Special check for pointer cast to int; we allow as an extension
2248 // an address constant cast to an integer if the integer
2249 // is of an appropriate width (this sort of code is apparently used
2250 // in some places).
2251 // FIXME: Add pedwarn?
2252 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2253 if (SubE && (SubE->getType()->isPointerType() ||
2254 SubE->getType()->isArrayType() ||
2255 SubE->getType()->isFunctionType())) {
2256 unsigned IntWidth = Context.getTypeSize(Init->getType());
2257 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2258 if (IntWidth >= PointerWidth)
2259 return CheckAddressConstantExpression(Init);
2260 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002261 }
2262
2263 return CheckArithmeticConstantExpression(Init);
2264 }
2265
2266 if (Init->getType()->isPointerType())
2267 return CheckAddressConstantExpression(Init);
2268
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002269 // An array type at the top level that isn't an init-list must
2270 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002271 if (Init->getType()->isArrayType())
2272 return false;
2273
Nuno Lopes73419bf2008-09-01 18:42:41 +00002274 if (Init->getType()->isFunctionType())
2275 return false;
2276
Steve Naroff8af6a452008-10-02 17:12:56 +00002277 // Allow block exprs at top level.
2278 if (Init->getType()->isBlockPointerType())
2279 return false;
2280
Steve Naroff6594a702008-10-27 11:34:16 +00002281 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002282 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002283}
2284
Sebastian Redl798d1192008-12-13 16:23:55 +00002285void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002286 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002287 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002288 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002289
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002290 // If there is no declaration, there was an error parsing it. Just ignore
2291 // the initializer.
2292 if (RealDecl == 0) {
2293 delete Init;
2294 return;
2295 }
Steve Naroffbb204692007-09-12 14:07:44 +00002296
Steve Naroff410e3e22007-09-12 20:13:48 +00002297 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2298 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002299 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2300 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002301 RealDecl->setInvalidDecl();
2302 return;
2303 }
Steve Naroffbb204692007-09-12 14:07:44 +00002304 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002305 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002306 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002307 if (VDecl->isBlockVarDecl()) {
2308 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002309 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002310 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002311 VDecl->setInvalidDecl();
2312 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002313 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002314 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002315 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002316
2317 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2318 if (!getLangOptions().CPlusPlus) {
2319 if (SC == VarDecl::Static) // C99 6.7.8p4.
2320 CheckForConstantInitializer(Init, DclT);
2321 }
Steve Naroffbb204692007-09-12 14:07:44 +00002322 }
Steve Naroff248a7532008-04-15 22:42:06 +00002323 } else if (VDecl->isFileVarDecl()) {
2324 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002325 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002326 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002327 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002328 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002329 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002330
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002331 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2332 if (!getLangOptions().CPlusPlus) {
2333 // C99 6.7.8p4. All file scoped initializers need to be constant.
2334 CheckForConstantInitializer(Init, DclT);
2335 }
Steve Naroffbb204692007-09-12 14:07:44 +00002336 }
2337 // If the type changed, it means we had an incomplete type that was
2338 // completed by the initializer. For example:
2339 // int ary[] = { 1, 3, 5 };
2340 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002341 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002342 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002343 Init->setType(DclT);
2344 }
Steve Naroffbb204692007-09-12 14:07:44 +00002345
2346 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002347 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002348 return;
2349}
2350
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002351void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2352 Decl *RealDecl = static_cast<Decl *>(dcl);
2353
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002354 // If there is no declaration, there was an error parsing it. Just ignore it.
2355 if (RealDecl == 0)
2356 return;
2357
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002358 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2359 QualType Type = Var->getType();
2360 // C++ [dcl.init.ref]p3:
2361 // The initializer can be omitted for a reference only in a
2362 // parameter declaration (8.3.5), in the declaration of a
2363 // function return type, in the declaration of a class member
2364 // within its class declaration (9.2), and where the extern
2365 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002366 if (Type->isReferenceType() &&
2367 Var->getStorageClass() != VarDecl::Extern &&
2368 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002369 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002370 << Var->getDeclName()
2371 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002372 Var->setInvalidDecl();
2373 return;
2374 }
2375
2376 // C++ [dcl.init]p9:
2377 //
2378 // If no initializer is specified for an object, and the object
2379 // is of (possibly cv-qualified) non-POD class type (or array
2380 // thereof), the object shall be default-initialized; if the
2381 // object is of const-qualified type, the underlying class type
2382 // shall have a user-declared default constructor.
2383 if (getLangOptions().CPlusPlus) {
2384 QualType InitType = Type;
2385 if (const ArrayType *Array = Context.getAsArrayType(Type))
2386 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002387 if (Var->getStorageClass() != VarDecl::Extern &&
2388 Var->getStorageClass() != VarDecl::PrivateExtern &&
2389 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002390 const CXXConstructorDecl *Constructor
2391 = PerformInitializationByConstructor(InitType, 0, 0,
2392 Var->getLocation(),
2393 SourceRange(Var->getLocation(),
2394 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002395 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002396 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002397 if (!Constructor)
2398 Var->setInvalidDecl();
2399 }
2400 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002401
Douglas Gregor818ce482008-10-29 13:50:18 +00002402#if 0
2403 // FIXME: Temporarily disabled because we are not properly parsing
2404 // linkage specifications on declarations, e.g.,
2405 //
2406 // extern "C" const CGPoint CGPointerZero;
2407 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002408 // C++ [dcl.init]p9:
2409 //
2410 // If no initializer is specified for an object, and the
2411 // object is of (possibly cv-qualified) non-POD class type (or
2412 // array thereof), the object shall be default-initialized; if
2413 // the object is of const-qualified type, the underlying class
2414 // type shall have a user-declared default
2415 // constructor. Otherwise, if no initializer is specified for
2416 // an object, the object and its subobjects, if any, have an
2417 // indeterminate initial value; if the object or any of its
2418 // subobjects are of const-qualified type, the program is
2419 // ill-formed.
2420 //
2421 // This isn't technically an error in C, so we don't diagnose it.
2422 //
2423 // FIXME: Actually perform the POD/user-defined default
2424 // constructor check.
2425 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002426 Context.getCanonicalType(Type).isConstQualified() &&
2427 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002428 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2429 << Var->getName()
2430 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002431#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002432 }
2433}
2434
Reid Spencer5f016e22007-07-11 17:01:13 +00002435/// The declarators are chained together backwards, reverse the list.
2436Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2437 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002438 Decl *GroupDecl = static_cast<Decl*>(group);
2439 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002440 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002441
2442 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2443 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002444 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002445 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002446 else { // reverse the list.
2447 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002448 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002449 Group->setNextDeclarator(NewGroup);
2450 NewGroup = Group;
2451 Group = Next;
2452 }
2453 }
2454 // Perform semantic analysis that depends on having fully processed both
2455 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002456 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002457 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2458 if (!IDecl)
2459 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002460 QualType T = IDecl->getType();
2461
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002462 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002463 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002464
2465 // FIXME: This won't give the correct result for
2466 // int a[10][n];
2467 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002468 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002469 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2470 SizeRange;
2471
Eli Friedmanc5773c42008-02-15 18:16:39 +00002472 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002473 } else {
2474 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2475 // static storage duration, it shall not have a variable length array.
2476 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002477 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2478 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002479 IDecl->setInvalidDecl();
2480 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002481 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2482 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002483 IDecl->setInvalidDecl();
2484 }
2485 }
2486 } else if (T->isVariablyModifiedType()) {
2487 if (IDecl->isFileVarDecl()) {
2488 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2489 IDecl->setInvalidDecl();
2490 } else {
2491 if (IDecl->getStorageClass() == VarDecl::Extern) {
2492 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2493 IDecl->setInvalidDecl();
2494 }
Steve Naroffbb204692007-09-12 14:07:44 +00002495 }
2496 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002497
Steve Naroffbb204692007-09-12 14:07:44 +00002498 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2499 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002500 if (IDecl->isBlockVarDecl() &&
2501 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002502 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002503 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002504 IDecl->setInvalidDecl();
2505 }
2506 }
2507 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2508 // object that has file scope without an initializer, and without a
2509 // storage-class specifier or with the storage-class specifier "static",
2510 // constitutes a tentative definition. Note: A tentative definition with
2511 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002512 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002513 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002514 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2515 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002516 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002517 // C99 6.9.2p3: If the declaration of an identifier for an object is
2518 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2519 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002520 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002521 IDecl->setInvalidDecl();
2522 }
2523 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002524 if (IDecl->isFileVarDecl())
2525 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002526 }
2527 return NewGroup;
2528}
Steve Naroffe1223f72007-08-28 03:03:08 +00002529
Chris Lattner04421082008-04-08 04:40:51 +00002530/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2531/// to introduce parameters into function prototype scope.
2532Sema::DeclTy *
2533Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002534 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002535
Chris Lattner04421082008-04-08 04:40:51 +00002536 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002537 VarDecl::StorageClass StorageClass = VarDecl::None;
2538 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2539 StorageClass = VarDecl::Register;
2540 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002541 Diag(DS.getStorageClassSpecLoc(),
2542 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002543 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002544 }
2545 if (DS.isThreadSpecified()) {
2546 Diag(DS.getThreadSpecLoc(),
2547 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002548 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002549 }
2550
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002551 // Check that there are no default arguments inside the type of this
2552 // parameter (C++ only).
2553 if (getLangOptions().CPlusPlus)
2554 CheckExtraCXXDefaultArguments(D);
2555
Chris Lattner04421082008-04-08 04:40:51 +00002556 // In this context, we *do not* check D.getInvalidType(). If the declarator
2557 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2558 // though it will not reflect the user specified type.
2559 QualType parmDeclType = GetTypeForDeclarator(D, S);
2560
2561 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2562
Reid Spencer5f016e22007-07-11 17:01:13 +00002563 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2564 // Can this happen for params? We already checked that they don't conflict
2565 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002566 IdentifierInfo *II = D.getIdentifier();
2567 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002568 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002569 // Maybe we will complain about the shadowed template parameter.
2570 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2571 // Just pretend that we didn't see the previous declaration.
2572 PrevDecl = 0;
2573 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002574 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002575
2576 // Recover by removing the name
2577 II = 0;
2578 D.SetIdentifier(0, D.getIdentifierLoc());
2579 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002580 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002581
2582 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2583 // Doing the promotion here has a win and a loss. The win is the type for
2584 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2585 // code generator). The loss is the orginal type isn't preserved. For example:
2586 //
2587 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2588 // int blockvardecl[5];
2589 // sizeof(parmvardecl); // size == 4
2590 // sizeof(blockvardecl); // size == 20
2591 // }
2592 //
2593 // For expressions, all implicit conversions are captured using the
2594 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2595 //
2596 // FIXME: If a source translation tool needs to see the original type, then
2597 // we need to consider storing both types (in ParmVarDecl)...
2598 //
Chris Lattnere6327742008-04-02 05:18:44 +00002599 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002600 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002601 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002602 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002603 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002604
Chris Lattner04421082008-04-08 04:40:51 +00002605 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2606 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002607 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002608 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002609
Chris Lattner04421082008-04-08 04:40:51 +00002610 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002611 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002612
Douglas Gregor584049d2008-12-15 23:53:10 +00002613 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2614 if (D.getCXXScopeSpec().isSet()) {
2615 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2616 << D.getCXXScopeSpec().getRange();
2617 New->setInvalidDecl();
2618 }
2619
Douglas Gregor44b43212008-12-11 16:49:14 +00002620 // Add the parameter declaration into this scope.
2621 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002622 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002623 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002624
Chris Lattner3ff30c82008-06-29 00:02:00 +00002625 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002627
Reid Spencer5f016e22007-07-11 17:01:13 +00002628}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002629
Chris Lattnerb652cea2007-10-09 17:14:05 +00002630Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002631 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2633 "Not a function declarator!");
2634 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002635
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2637 // for a K&R function.
2638 if (!FTI.hasPrototype) {
2639 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002640 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002641 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2642 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 // Implicitly declare the argument as type 'int' for lack of a better
2644 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002645 DeclSpec DS;
2646 const char* PrevSpec; // unused
2647 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2648 PrevSpec);
2649 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2650 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2651 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 }
2653 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002655 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 }
2657
Douglas Gregor584049d2008-12-15 23:53:10 +00002658 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002659
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002660 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002661 ActOnDeclarator(ParentScope, D, 0,
2662 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002663}
2664
2665Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2666 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002667 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002668
2669 // See if this is a redefinition.
2670 const FunctionDecl *Definition;
2671 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002672 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002673 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002674 }
2675
Douglas Gregor44b43212008-12-11 16:49:14 +00002676 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002677
Chris Lattner04421082008-04-08 04:40:51 +00002678 // Check the validity of our function parameters
2679 CheckParmsForFunctionDef(FD);
2680
2681 // Introduce our parameters into the function scope
2682 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2683 ParmVarDecl *Param = FD->getParamDecl(p);
2684 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002685 if (Param->getIdentifier())
2686 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002687 }
Chris Lattner04421082008-04-08 04:40:51 +00002688
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002689 // Checking attributes of current function definition
2690 // dllimport attribute.
2691 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2692 // dllimport attribute cannot be applied to definition.
2693 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2694 Diag(FD->getLocation(),
2695 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2696 << "dllimport";
2697 FD->setInvalidDecl();
2698 return FD;
2699 } else {
2700 // If a symbol previously declared dllimport is later defined, the
2701 // attribute is ignored in subsequent references, and a warning is
2702 // emitted.
2703 Diag(FD->getLocation(),
2704 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2705 << FD->getNameAsCString() << "dllimport";
2706 }
2707 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002708 return FD;
2709}
2710
Sebastian Redl798d1192008-12-13 16:23:55 +00002711Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002712 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002713 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002714 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002715 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002716 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002717 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002718 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002719 } else
2720 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002721 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 // Verify and clean out per-function state.
2723
2724 // Check goto/label use.
2725 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2726 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2727 // Verify that we have no forward references left. If so, there was a goto
2728 // or address of a label taken, but no definition of it. Label fwd
2729 // definitions are indicated with a null substmt.
2730 if (I->second->getSubStmt() == 0) {
2731 LabelStmt *L = I->second;
2732 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002733 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002734
2735 // At this point, we have gotos that use the bogus label. Stitch it into
2736 // the function body so that they aren't leaked and that the AST is well
2737 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002738 if (Body) {
2739 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002740 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002741 } else {
2742 // The whole function wasn't parsed correctly, just delete this.
2743 delete L;
2744 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 }
2746 }
2747 LabelMap.clear();
2748
Steve Naroffd6d054d2007-11-11 23:20:51 +00002749 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002750}
2751
Reid Spencer5f016e22007-07-11 17:01:13 +00002752/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2753/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002754ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2755 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002756 // Extension in C99. Legal in C90, but warn about it.
2757 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002758 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002759 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002760 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002761
2762 // FIXME: handle stuff like:
2763 // void foo() { extern float X(); }
2764 // void bar() { X(); } <-- implicit decl for X in another scope.
2765
2766 // Set a Declarator for the implicit definition: int foo();
2767 const char *Dummy;
2768 DeclSpec DS;
2769 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2770 Error = Error; // Silence warning.
2771 assert(!Error && "Error setting up implicit decl!");
2772 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002773 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002774 D.SetIdentifier(&II, Loc);
2775
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002776 // Insert this function into translation-unit scope.
2777
2778 DeclContext *PrevDC = CurContext;
2779 CurContext = Context.getTranslationUnitDecl();
2780
Steve Naroffe2ef8152008-04-04 14:32:09 +00002781 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002782 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002783 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002784
2785 CurContext = PrevDC;
2786
Steve Naroffe2ef8152008-04-04 14:32:09 +00002787 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002788}
2789
2790
Chris Lattner41af0932007-11-14 06:34:38 +00002791TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002792 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002794 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002795
2796 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002797 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2798 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002799 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002800 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002801 if (D.getInvalidType())
2802 NewTD->setInvalidDecl();
2803 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002804}
2805
Steve Naroff08d92e42007-09-15 18:49:24 +00002806/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002807/// former case, Name will be non-null. In the later case, Name will be null.
2808/// TagType indicates what kind of tag this is. TK indicates whether this is a
2809/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002810Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002811 SourceLocation KWLoc, const CXXScopeSpec &SS,
2812 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002813 AttributeList *Attr,
2814 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002815 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002816 assert((Name != 0 || TK == TK_Definition) &&
2817 "Nameless record must be a definition!");
2818
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002819 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 switch (TagType) {
2821 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002822 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2823 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2824 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2825 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002826 }
2827
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002828 DeclContext *DC = CurContext;
2829 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002830
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002831 if (Name && SS.isNotEmpty()) {
2832 // We have a nested-name tag ('struct foo::bar').
2833
2834 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002835 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002836 Name = 0;
2837 goto CreateNewDecl;
2838 }
2839
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002840 DC = static_cast<DeclContext*>(SS.getScopeRep());
2841 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002842 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2843
2844 // A tag 'foo::bar' must already exist.
2845 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002846 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002847 Name = 0;
2848 goto CreateNewDecl;
2849 }
2850 } else {
2851 // If this is a named struct, check to see if there was a previous forward
2852 // declaration or definition.
2853 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2854 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2855 }
2856
Douglas Gregorf57172b2008-12-08 18:40:42 +00002857 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002858 // Maybe we will complain about the shadowed template parameter.
2859 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2860 // Just pretend that we didn't see the previous declaration.
2861 PrevDecl = 0;
2862 }
2863
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002864 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002865 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2866 "unexpected Decl type");
2867 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002868 // If this is a use of a previous tag, or if the tag is already declared
2869 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002870 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002871 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002872 // Make sure that this wasn't declared as an enum and now used as a
2873 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002874 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002875 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002876 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002877 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002878 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002879 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002880 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002881 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002882
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002883 // FIXME: In the future, return a variant or some other clue
2884 // for the consumer of this Decl to know it doesn't own it.
2885 // For our current ASTs this shouldn't be a problem, but will
2886 // need to be changed with DeclGroups.
2887 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002888 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002889
2890 // Diagnose attempts to redefine a tag.
2891 if (TK == TK_Definition) {
2892 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2893 Diag(NameLoc, diag::err_redefinition) << Name;
2894 Diag(Def->getLocation(), diag::note_previous_definition);
2895 // If this is a redefinition, recover by making this struct be
2896 // anonymous, which will make any later references get the previous
2897 // definition.
2898 Name = 0;
2899 PrevDecl = 0;
2900 }
2901 // Okay, this is definition of a previously declared or referenced
2902 // tag PrevDecl. We're going to create a new Decl for it.
2903 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002904 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002905 // If we get here we have (another) forward declaration or we
2906 // have a definition. Just create a new decl.
2907 } else {
2908 // If we get here, this is a definition of a new tag type in a nested
2909 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2910 // new decl/type. We set PrevDecl to NULL so that the entities
2911 // have distinct types.
2912 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002913 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002914 // If we get here, we're going to create a new Decl. If PrevDecl
2915 // is non-NULL, it's a definition of the tag declared by
2916 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002917 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002918 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002919 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002920 // The tag name clashes with a namespace name, issue an error and
2921 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002922 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002923 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002924 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002925 PrevDecl = 0;
2926 } else {
2927 // The existing declaration isn't relevant to us; we're in a
2928 // new scope, so clear out the previous declaration.
2929 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002930 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002931 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002932 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002933
Chris Lattnercc98eac2008-12-17 07:13:27 +00002934CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002935
2936 // If there is an identifier, use the location of the identifier as the
2937 // location of the decl, otherwise use the location of the struct/union
2938 // keyword.
2939 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2940
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002941 // Otherwise, create a new declaration. If there is a previous
2942 // declaration of the same entity, the two will be linked via
2943 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002944 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002945
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002946 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002947 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2948 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002949 New = EnumDecl::Create(Context, DC, Loc, Name,
2950 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002951 // If this is an undefined enum, warn.
2952 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002953 } else {
2954 // struct/union/class
2955
Reid Spencer5f016e22007-07-11 17:01:13 +00002956 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2957 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002958 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002959 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002960 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2961 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002962 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002963 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2964 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002965 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002966
2967 if (Kind != TagDecl::TK_enum) {
2968 // Handle #pragma pack: if the #pragma pack stack has non-default
2969 // alignment, make up a packed attribute for this decl. These
2970 // attributes are checked when the ASTContext lays out the
2971 // structure.
2972 //
2973 // It is important for implementing the correct semantics that this
2974 // happen here (in act on tag decl). The #pragma pack stack is
2975 // maintained as a result of parser callbacks which can occur at
2976 // many points during the parsing of a struct declaration (because
2977 // the #pragma tokens are effectively skipped over during the
2978 // parsing of the struct).
2979 if (unsigned Alignment = PackContext.getAlignment())
2980 New->addAttr(new PackedAttr(Alignment * 8));
2981 }
2982
2983 if (Attr)
2984 ProcessDeclAttributeList(New, Attr);
2985
2986 // Set the lexical context. If the tag has a C++ scope specifier, the
2987 // lexical context will be different from the semantic context.
2988 New->setLexicalDeclContext(CurContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002989
2990 // If this has an identifier, add it to the scope stack.
2991 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002992 // The scope passed in may not be a decl scope. Zip up the scope tree until
2993 // we find one that is.
2994 while ((S->getFlags() & Scope::DeclScope) == 0)
2995 S = S->getParent();
2996
2997 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002998 PushOnScopeChains(New, S);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002999 } else if (getLangOptions().CPlusPlus) {
3000 // FIXME: We also want to do this for C, but if this tag is
3001 // defined within a structure CurContext will point to the context
3002 // enclosing the structure, and we would end up inserting the tag
3003 // type into the wrong place.
3004 CurContext->addDecl(Context, New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003005 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003006
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 return New;
3008}
3009
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003010
Chris Lattner1d353ba2008-11-12 21:17:48 +00003011/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3012/// types into constant array types in certain situations which would otherwise
3013/// be errors (for GCC compatibility).
3014static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3015 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003016 // This method tries to turn a variable array into a constant
3017 // array even when the size isn't an ICE. This is necessary
3018 // for compatibility with code that depends on gcc's buggy
3019 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003020 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3021 if (!VLATy) return QualType();
3022
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003023 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003024 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003025 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003026 return QualType();
3027
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003028 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3029 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00003030 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3031 return Context.getConstantArrayType(VLATy->getElementType(),
3032 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003033 return QualType();
3034}
3035
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003036bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003037 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003038 // FIXME: 6.7.2.1p4 - verify the field type.
3039
3040 llvm::APSInt Value;
3041 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3042 return true;
3043
Chris Lattnercd087072008-12-12 04:56:04 +00003044 // Zero-width bitfield is ok for anonymous field.
3045 if (Value == 0 && FieldName)
3046 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3047
3048 if (Value.isNegative())
3049 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003050
3051 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3052 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003053 if (TypeSize && Value.getZExtValue() > TypeSize)
3054 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3055 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003056
3057 return false;
3058}
3059
Steve Naroff08d92e42007-09-15 18:49:24 +00003060/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003061/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003062Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003063 SourceLocation DeclStart,
3064 Declarator &D, ExprTy *BitfieldWidth) {
3065 IdentifierInfo *II = D.getIdentifier();
3066 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003067 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003068 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003069 if (II) Loc = D.getIdentifierLoc();
3070
3071 // FIXME: Unnamed fields can be handled in various different ways, for
3072 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003073
Reid Spencer5f016e22007-07-11 17:01:13 +00003074 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003075 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3076 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003077
Reid Spencer5f016e22007-07-11 17:01:13 +00003078 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3079 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003080 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003081 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003082 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003083 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003084 T = FixedTy;
3085 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003086 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003087 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003088 InvalidDecl = true;
3089 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003090 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003091
3092 if (BitWidth) {
3093 if (VerifyBitField(Loc, II, T, BitWidth))
3094 InvalidDecl = true;
3095 } else {
3096 // Not a bitfield.
3097
3098 // validate II.
3099
3100 }
3101
Reid Spencer5f016e22007-07-11 17:01:13 +00003102 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003103 FieldDecl *NewFD;
3104
Douglas Gregor44b43212008-12-11 16:49:14 +00003105 NewFD = FieldDecl::Create(Context, Record,
3106 Loc, II, T, BitWidth,
3107 D.getDeclSpec().getStorageClassSpec() ==
3108 DeclSpec::SCS_mutable,
3109 /*PrevDecl=*/0);
3110
Sebastian Redl64b45f72009-01-05 20:52:13 +00003111 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003112 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003113 if (!T->isPODType())
3114 cast<CXXRecordDecl>(Record)->setPOD(false);
3115 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003116
Chris Lattner3ff30c82008-06-29 00:02:00 +00003117 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003118
Steve Naroff5912a352007-08-28 20:14:24 +00003119 if (D.getInvalidType() || InvalidDecl)
3120 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003121
3122 if (II && getLangOptions().CPlusPlus)
3123 PushOnScopeChains(NewFD, S);
3124 else
3125 Record->addDecl(Context, NewFD);
3126
Steve Naroff5912a352007-08-28 20:14:24 +00003127 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003128}
3129
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003130/// TranslateIvarVisibility - Translate visibility from a token ID to an
3131/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003132static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003133TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003134 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003135 default: assert(0 && "Unknown visitibility kind");
3136 case tok::objc_private: return ObjCIvarDecl::Private;
3137 case tok::objc_public: return ObjCIvarDecl::Public;
3138 case tok::objc_protected: return ObjCIvarDecl::Protected;
3139 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003140 }
3141}
3142
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003143/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3144/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003145Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003146 SourceLocation DeclStart,
3147 Declarator &D, ExprTy *BitfieldWidth,
3148 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003149 IdentifierInfo *II = D.getIdentifier();
3150 Expr *BitWidth = (Expr*)BitfieldWidth;
3151 SourceLocation Loc = DeclStart;
3152 if (II) Loc = D.getIdentifierLoc();
3153
3154 // FIXME: Unnamed fields can be handled in various different ways, for
3155 // example, unnamed unions inject all members into the struct namespace!
3156
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003157 QualType T = GetTypeForDeclarator(D, S);
3158 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3159 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003160
3161 if (BitWidth) {
3162 // TODO: Validate.
3163 //printf("WARNING: BITFIELDS IGNORED!\n");
3164
3165 // 6.7.2.1p3
3166 // 6.7.2.1p4
3167
3168 } else {
3169 // Not a bitfield.
3170
3171 // validate II.
3172
3173 }
3174
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003175 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3176 // than a variably modified type.
3177 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003178 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003179 InvalidDecl = true;
3180 }
3181
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003182 // Get the visibility (access control) for this ivar.
3183 ObjCIvarDecl::AccessControl ac =
3184 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3185 : ObjCIvarDecl::None;
3186
3187 // Construct the decl.
3188 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003189 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003190
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003191 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003192 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003193
3194 if (D.getInvalidType() || InvalidDecl)
3195 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003196
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003197 return NewID;
3198}
3199
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003200void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003201 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003202 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003203 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003204 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003205 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3206 assert(EnclosingDecl && "missing record or interface decl");
3207 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3208
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003209 if (Record)
3210 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
3211 // Diagnose code like:
3212 // struct S { struct S {} X; };
3213 // We discover this when we complete the outer S. Reject and ignore the
3214 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003215 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003216 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003217 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003218 Record->setInvalidDecl();
3219 return;
3220 }
3221
Reid Spencer5f016e22007-07-11 17:01:13 +00003222 // Verify that all the fields are okay.
3223 unsigned NumNamedMembers = 0;
3224 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003225
3226 // FIXME: Eventually, we'd like to eliminate this in favor of
3227 // checking for redeclarations on-the-fly.
3228 llvm::DenseMap<const IdentifierInfo*, FieldDecl *> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00003229
Reid Spencer5f016e22007-07-11 17:01:13 +00003230 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003231 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3232 assert(FD && "missing field decl");
3233
Reid Spencer5f016e22007-07-11 17:01:13 +00003234 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003235 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003236
3237 if (FD->isAnonymousStructOrUnion()) {
3238 // We have found a field that represents an anonymous struct
3239 // or union. Introduce all of the inner fields (recursively)
3240 // into the list of fields we know about, so that we can produce
3241 // an appropriate error message in cases like:
3242 //
3243 // struct X {
3244 // union {
3245 // int x;
3246 // float f;
3247 // };
3248 // double x;
3249 // };
3250 llvm::SmallVector<FieldDecl *, 4> AnonStructUnionFields;
3251 AnonStructUnionFields.push_back(FD);
3252 while (!AnonStructUnionFields.empty()) {
3253 FieldDecl *AnonField = AnonStructUnionFields.back();
3254 AnonStructUnionFields.pop_back();
3255
3256 RecordDecl *AnonRecord
3257 = AnonField->getType()->getAsRecordType()->getDecl();
3258 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
3259 FEnd = AnonRecord->field_end();
3260 F != FEnd; ++F) {
3261 if ((*F)->isAnonymousStructOrUnion())
3262 AnonStructUnionFields.push_back(*F);
3263 else if (const IdentifierInfo *II = (*F)->getIdentifier())
3264 FieldIDs[II] = *F;
3265 }
3266 }
3267 } else {
3268 // Remember all fields written by the user.
3269 RecFields.push_back(FD);
3270 }
Steve Narofff13271f2007-09-14 23:09:53 +00003271
Reid Spencer5f016e22007-07-11 17:01:13 +00003272 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003273 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003274 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003275 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003276 FD->setInvalidDecl();
3277 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003278 continue;
3279 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003280 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3281 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003282 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003283 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003284 FD->setInvalidDecl();
3285 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003286 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003287 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003288 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003289 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003290 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003291 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003292 FD->setInvalidDecl();
3293 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003294 continue;
3295 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003296 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003297 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003298 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003299 FD->setInvalidDecl();
3300 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003301 continue;
3302 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003303 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003304 if (Record)
3305 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003306 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003307 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3308 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003309 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003310 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3311 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003312 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003313 Record->setHasFlexibleArrayMember(true);
3314 } else {
3315 // If this is a struct/class and this is not the last element, reject
3316 // it. Note that GCC supports variable sized arrays in the middle of
3317 // structures.
3318 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003319 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003320 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003321 FD->setInvalidDecl();
3322 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003323 continue;
3324 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003325 // We support flexible arrays at the end of structs in other structs
3326 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003327 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003328 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003329 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003330 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003331 }
3332 }
3333 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003334 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003335 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003336 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003337 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003338 FD->setInvalidDecl();
3339 EnclosingDecl->setInvalidDecl();
3340 continue;
3341 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003342 // Keep track of the number of named members.
3343 if (IdentifierInfo *II = FD->getIdentifier()) {
3344 // Detect duplicate member names.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003345 if (FieldIDs[II]) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003346 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003347 // Find the previous decl.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003348 Diag(FieldIDs[II]->getLocation(), diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003349 FD->setInvalidDecl();
3350 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003351 continue;
3352 }
3353 ++NumNamedMembers;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003354 FieldIDs[II] = FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003355 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003356 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003357
Reid Spencer5f016e22007-07-11 17:01:13 +00003358 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003359 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003360 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003361 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3362 // Sema::ActOnFinishCXXClassDef.
3363 if (!isa<CXXRecordDecl>(Record))
3364 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003365 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003366 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003367 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003368 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003369 // Must enforce the rule that ivars in the base classes may not be
3370 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003371 if (ID->getSuperClass()) {
3372 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3373 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3374 ObjCIvarDecl* Ivar = (*IVI);
3375 IdentifierInfo *II = Ivar->getIdentifier();
3376 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3377 if (prevIvar) {
3378 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3379 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003380 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003381 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003382 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003383 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003384 else if (ObjCImplementationDecl *IMPDecl =
3385 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003386 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3387 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003388 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003389 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003390 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003391
3392 if (Attr)
3393 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003394}
3395
Douglas Gregor074149e2009-01-05 19:45:36 +00003396void Sema::ActOnEnumStartDefinition(Scope *S, DeclTy *EnumD) {
Douglas Gregor4f3b8f82009-01-06 07:17:58 +00003397 EnumDecl *Enum = cast<EnumDecl>((Decl *)EnumD);
Douglas Gregor074149e2009-01-05 19:45:36 +00003398
Douglas Gregor4f3b8f82009-01-06 07:17:58 +00003399 // Enter the enumeration context.
3400 PushDeclContext(S, Enum);
Douglas Gregor074149e2009-01-05 19:45:36 +00003401}
3402
Steve Naroff08d92e42007-09-15 18:49:24 +00003403Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003404 DeclTy *lastEnumConst,
3405 SourceLocation IdLoc, IdentifierInfo *Id,
3406 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003407 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003408 EnumConstantDecl *LastEnumConst =
3409 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3410 Expr *Val = static_cast<Expr*>(val);
3411
Chris Lattner31e05722007-08-26 06:24:45 +00003412 // The scope passed in may not be a decl scope. Zip up the scope tree until
3413 // we find one that is.
3414 while ((S->getFlags() & Scope::DeclScope) == 0)
3415 S = S->getParent();
3416
Reid Spencer5f016e22007-07-11 17:01:13 +00003417 // Verify that there isn't already something declared with this name in this
3418 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003419 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003420 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003421 // Maybe we will complain about the shadowed template parameter.
3422 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3423 // Just pretend that we didn't see the previous declaration.
3424 PrevDecl = 0;
3425 }
3426
3427 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003428 // When in C++, we may get a TagDecl with the same name; in this case the
3429 // enum constant will 'hide' the tag.
3430 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3431 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003432 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003433 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003434 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003435 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003436 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003437 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003438 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003439 return 0;
3440 }
3441 }
3442
3443 llvm::APSInt EnumVal(32);
3444 QualType EltTy;
3445 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003446 // Make sure to promote the operand type to int.
3447 UsualUnaryConversions(Val);
3448
Reid Spencer5f016e22007-07-11 17:01:13 +00003449 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3450 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003451 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003452 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003453 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003454 } else {
3455 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003456 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003457 }
3458
3459 if (!Val) {
3460 if (LastEnumConst) {
3461 // Assign the last value + 1.
3462 EnumVal = LastEnumConst->getInitVal();
3463 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003464
3465 // Check for overflow on increment.
3466 if (EnumVal < LastEnumConst->getInitVal())
3467 Diag(IdLoc, diag::warn_enum_value_overflow);
3468
Chris Lattnerb7416f92007-08-27 17:37:24 +00003469 EltTy = LastEnumConst->getType();
3470 } else {
3471 // First value, set to zero.
3472 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003473 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003474 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003475 }
3476
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003477 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003478 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3479 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003480 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003481
3482 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003483 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003484
3485 // Add this enumerator into the enum itself.
3486 // FIXME: This means that the enumerator is stored in two
3487 // DeclContexts. This is not a long-term solution.
3488 New->setLexicalDeclContext(TheEnumDecl);
3489 TheEnumDecl->addDecl(Context, New, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003490 return New;
3491}
3492
Steve Naroff02408c62008-08-07 14:08:16 +00003493// FIXME: For consistency with ActOnFields(), we should have the parser
3494// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003495void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003496 DeclTy **Elements, unsigned NumElements) {
3497 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003498 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003499
Douglas Gregor074149e2009-01-05 19:45:36 +00003500 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3501 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3502 // Diagnose code like:
3503 // enum e0 {
3504 // E0 = sizeof(enum e0 { E1 })
3505 // };
3506 Diag(Def->getLocation(), diag::err_nested_redefinition)
3507 << Enum->getDeclName();
3508 Diag(Enum->getLocation(), diag::note_previous_definition);
3509 Enum->setInvalidDecl();
3510 PopDeclContext();
3511 return;
Steve Naroff02408c62008-08-07 14:08:16 +00003512 }
Douglas Gregor074149e2009-01-05 19:45:36 +00003513
Chris Lattnere37f0be2007-08-28 05:10:31 +00003514 // TODO: If the result value doesn't fit in an int, it must be a long or long
3515 // long value. ISO C does not support this, but GCC does as an extension,
3516 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003517 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003518
Chris Lattnerac609682007-08-28 06:15:15 +00003519 // Verify that all the values are okay, compute the size of the values, and
3520 // reverse the list.
3521 unsigned NumNegativeBits = 0;
3522 unsigned NumPositiveBits = 0;
3523
3524 // Keep track of whether all elements have type int.
3525 bool AllElementsInt = true;
3526
Reid Spencer5f016e22007-07-11 17:01:13 +00003527 EnumConstantDecl *EltList = 0;
3528 for (unsigned i = 0; i != NumElements; ++i) {
3529 EnumConstantDecl *ECD =
3530 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3531 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003532
3533 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003534 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003535 assert(InitVal.getBitWidth() >= IntWidth &&
3536 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003537 if (InitVal.getBitWidth() > IntWidth) {
3538 llvm::APSInt V(InitVal);
3539 V.trunc(IntWidth);
3540 V.extend(InitVal.getBitWidth());
3541 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003542 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3543 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003544 }
Chris Lattnerac609682007-08-28 06:15:15 +00003545
3546 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003547 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003548 NumPositiveBits = std::max(NumPositiveBits,
3549 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003550 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003551 NumNegativeBits = std::max(NumNegativeBits,
3552 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003553
Chris Lattnerac609682007-08-28 06:15:15 +00003554 // Keep track of whether every enum element has type int (very commmon).
3555 if (AllElementsInt)
3556 AllElementsInt = ECD->getType() == Context.IntTy;
3557
Reid Spencer5f016e22007-07-11 17:01:13 +00003558 ECD->setNextDeclarator(EltList);
3559 EltList = ECD;
3560 }
3561
Chris Lattnerac609682007-08-28 06:15:15 +00003562 // Figure out the type that should be used for this enum.
3563 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3564 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003565 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003566
3567 if (NumNegativeBits) {
3568 // If there is a negative value, figure out the smallest integer type (of
3569 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003570 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003571 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003572 BestWidth = IntWidth;
3573 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003574 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003575
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003576 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003577 BestType = Context.LongTy;
3578 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003579 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003580
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003581 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003582 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3583 BestType = Context.LongLongTy;
3584 }
3585 }
3586 } else {
3587 // If there is no negative value, figure out which of uint, ulong, ulonglong
3588 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003589 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003590 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003591 BestWidth = IntWidth;
3592 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003593 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003594 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003595 } else {
3596 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003597 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003598 "How could an initializer get larger than ULL?");
3599 BestType = Context.UnsignedLongLongTy;
3600 }
3601 }
3602
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003603 // Loop over all of the enumerator constants, changing their types to match
3604 // the type of the enum if needed.
3605 for (unsigned i = 0; i != NumElements; ++i) {
3606 EnumConstantDecl *ECD =
3607 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3608 if (!ECD) continue; // Already issued a diagnostic.
3609
3610 // Standard C says the enumerators have int type, but we allow, as an
3611 // extension, the enumerators to be larger than int size. If each
3612 // enumerator value fits in an int, type it as an int, otherwise type it the
3613 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3614 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003615 if (ECD->getType() == Context.IntTy) {
3616 // Make sure the init value is signed.
3617 llvm::APSInt IV = ECD->getInitVal();
3618 IV.setIsSigned(true);
3619 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003620
3621 if (getLangOptions().CPlusPlus)
3622 // C++ [dcl.enum]p4: Following the closing brace of an
3623 // enum-specifier, each enumerator has the type of its
3624 // enumeration.
3625 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003626 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003627 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003628
3629 // Determine whether the value fits into an int.
3630 llvm::APSInt InitVal = ECD->getInitVal();
3631 bool FitsInInt;
3632 if (InitVal.isUnsigned() || !InitVal.isNegative())
3633 FitsInInt = InitVal.getActiveBits() < IntWidth;
3634 else
3635 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3636
3637 // If it fits into an integer type, force it. Otherwise force it to match
3638 // the enum decl type.
3639 QualType NewTy;
3640 unsigned NewWidth;
3641 bool NewSign;
3642 if (FitsInInt) {
3643 NewTy = Context.IntTy;
3644 NewWidth = IntWidth;
3645 NewSign = true;
3646 } else if (ECD->getType() == BestType) {
3647 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003648 if (getLangOptions().CPlusPlus)
3649 // C++ [dcl.enum]p4: Following the closing brace of an
3650 // enum-specifier, each enumerator has the type of its
3651 // enumeration.
3652 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003653 continue;
3654 } else {
3655 NewTy = BestType;
3656 NewWidth = BestWidth;
3657 NewSign = BestType->isSignedIntegerType();
3658 }
3659
3660 // Adjust the APSInt value.
3661 InitVal.extOrTrunc(NewWidth);
3662 InitVal.setIsSigned(NewSign);
3663 ECD->setInitVal(InitVal);
3664
3665 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003666 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3667 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003668 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);
3673 else
3674 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003675 }
Chris Lattnerac609682007-08-28 06:15:15 +00003676
Douglas Gregor44b43212008-12-11 16:49:14 +00003677 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003678 Consumer.HandleTagDeclDefinition(Enum);
Douglas Gregor074149e2009-01-05 19:45:36 +00003679
3680 // Leave the context of the enumeration.
3681 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00003682}
3683
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003684Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003685 ExprArg expr) {
3686 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3687
Chris Lattner8e25d862008-03-16 00:16:02 +00003688 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003689}
3690
Douglas Gregorf44515a2008-12-16 22:23:02 +00003691
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003692void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3693 ExprTy *alignment, SourceLocation PragmaLoc,
3694 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3695 Expr *Alignment = static_cast<Expr *>(alignment);
3696
3697 // If specified then alignment must be a "small" power of two.
3698 unsigned AlignmentVal = 0;
3699 if (Alignment) {
3700 llvm::APSInt Val;
3701 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3702 !Val.isPowerOf2() ||
3703 Val.getZExtValue() > 16) {
3704 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3705 delete Alignment;
3706 return; // Ignore
3707 }
3708
3709 AlignmentVal = (unsigned) Val.getZExtValue();
3710 }
3711
3712 switch (Kind) {
3713 case Action::PPK_Default: // pack([n])
3714 PackContext.setAlignment(AlignmentVal);
3715 break;
3716
3717 case Action::PPK_Show: // pack(show)
3718 // Show the current alignment, making sure to show the right value
3719 // for the default.
3720 AlignmentVal = PackContext.getAlignment();
3721 // FIXME: This should come from the target.
3722 if (AlignmentVal == 0)
3723 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003724 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003725 break;
3726
3727 case Action::PPK_Push: // pack(push [, id] [, [n])
3728 PackContext.push(Name);
3729 // Set the new alignment if specified.
3730 if (Alignment)
3731 PackContext.setAlignment(AlignmentVal);
3732 break;
3733
3734 case Action::PPK_Pop: // pack(pop [, id] [, n])
3735 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3736 // "#pragma pack(pop, identifier, n) is undefined"
3737 if (Alignment && Name)
3738 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3739
3740 // Do the pop.
3741 if (!PackContext.pop(Name)) {
3742 // If a name was specified then failure indicates the name
3743 // wasn't found. Otherwise failure indicates the stack was
3744 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003745 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3746 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003747
3748 // FIXME: Warn about popping named records as MSVC does.
3749 } else {
3750 // Pop succeeded, set the new alignment if specified.
3751 if (Alignment)
3752 PackContext.setAlignment(AlignmentVal);
3753 }
3754 break;
3755
3756 default:
3757 assert(0 && "Invalid #pragma pack kind.");
3758 }
3759}
3760
3761bool PragmaPackStack::pop(IdentifierInfo *Name) {
3762 if (Stack.empty())
3763 return false;
3764
3765 // If name is empty just pop top.
3766 if (!Name) {
3767 Alignment = Stack.back().first;
3768 Stack.pop_back();
3769 return true;
3770 }
3771
3772 // Otherwise, find the named record.
3773 for (unsigned i = Stack.size(); i != 0; ) {
3774 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003775 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003776 // Found it, pop up to and including this record.
3777 Alignment = Stack[i].first;
3778 Stack.erase(Stack.begin() + i, Stack.end());
3779 return true;
3780 }
3781 }
3782
3783 return false;
3784}